babylonjs.loaders.js 269 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339
  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.onParsedObservable.clear();
  1170. this.onMeshLoadedObservable.clear();
  1171. this.onTextureLoadedObservable.clear();
  1172. this.onMaterialLoadedObservable.clear();
  1173. this.onCompleteObservable.clear();
  1174. this.onDisposeObservable.notifyObservers(this);
  1175. this.onDisposeObservable.clear();
  1176. };
  1177. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  1178. var _this = this;
  1179. return Promise.resolve().then(function () {
  1180. var loaderData = _this._parse(data);
  1181. _this._loader = _this._getLoader(loaderData);
  1182. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  1183. });
  1184. };
  1185. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  1186. var _this = this;
  1187. return Promise.resolve().then(function () {
  1188. var loaderData = _this._parse(data);
  1189. _this._loader = _this._getLoader(loaderData);
  1190. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  1191. });
  1192. };
  1193. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  1194. var _this = this;
  1195. return Promise.resolve().then(function () {
  1196. var loaderData = _this._parse(data);
  1197. _this._loader = _this._getLoader(loaderData);
  1198. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  1199. var container = new BABYLON.AssetContainer(scene);
  1200. Array.prototype.push.apply(container.meshes, result.meshes);
  1201. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  1202. Array.prototype.push.apply(container.skeletons, result.skeletons);
  1203. container.removeAllFromScene();
  1204. return container;
  1205. });
  1206. });
  1207. };
  1208. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  1209. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  1210. };
  1211. GLTFFileLoader.prototype.createPlugin = function () {
  1212. return new GLTFFileLoader();
  1213. };
  1214. GLTFFileLoader.prototype._parse = function (data) {
  1215. var parsedData;
  1216. if (data instanceof ArrayBuffer) {
  1217. parsedData = GLTFFileLoader._parseBinary(data);
  1218. }
  1219. else {
  1220. parsedData = {
  1221. json: JSON.parse(data),
  1222. bin: null
  1223. };
  1224. }
  1225. this.onParsedObservable.notifyObservers(parsedData);
  1226. return parsedData;
  1227. };
  1228. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  1229. var _this = this;
  1230. var loaderVersion = { major: 2, minor: 0 };
  1231. var asset = loaderData.json.asset || {};
  1232. var version = GLTFFileLoader._parseVersion(asset.version);
  1233. if (!version) {
  1234. throw new Error("Invalid version: " + asset.version);
  1235. }
  1236. if (asset.minVersion !== undefined) {
  1237. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  1238. if (!minVersion) {
  1239. throw new Error("Invalid minimum version: " + asset.minVersion);
  1240. }
  1241. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  1242. throw new Error("Incompatible minimum version: " + asset.minVersion);
  1243. }
  1244. }
  1245. var createLoaders = {
  1246. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  1247. 2: GLTFFileLoader.CreateGLTFLoaderV2
  1248. };
  1249. var createLoader = createLoaders[version.major];
  1250. if (!createLoader) {
  1251. throw new Error("Unsupported version: " + asset.version);
  1252. }
  1253. var loader = createLoader();
  1254. loader.coordinateSystemMode = this.coordinateSystemMode;
  1255. loader.animationStartMode = this.animationStartMode;
  1256. loader.compileMaterials = this.compileMaterials;
  1257. loader.useClipPlane = this.useClipPlane;
  1258. loader.compileShadowGenerators = this.compileShadowGenerators;
  1259. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  1260. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  1261. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  1262. loader.onCompleteObservable.add(function () { return _this.onCompleteObservable.notifyObservers(_this); });
  1263. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  1264. return loader;
  1265. };
  1266. GLTFFileLoader._parseBinary = function (data) {
  1267. var Binary = {
  1268. Magic: 0x46546C67
  1269. };
  1270. var binaryReader = new BinaryReader(data);
  1271. var magic = binaryReader.readUint32();
  1272. if (magic !== Binary.Magic) {
  1273. throw new Error("Unexpected magic: " + magic);
  1274. }
  1275. var version = binaryReader.readUint32();
  1276. switch (version) {
  1277. case 1: return GLTFFileLoader._parseV1(binaryReader);
  1278. case 2: return GLTFFileLoader._parseV2(binaryReader);
  1279. }
  1280. throw new Error("Unsupported version: " + version);
  1281. };
  1282. GLTFFileLoader._parseV1 = function (binaryReader) {
  1283. var ContentFormat = {
  1284. JSON: 0
  1285. };
  1286. var length = binaryReader.readUint32();
  1287. if (length != binaryReader.getLength()) {
  1288. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  1289. }
  1290. var contentLength = binaryReader.readUint32();
  1291. var contentFormat = binaryReader.readUint32();
  1292. var content;
  1293. switch (contentFormat) {
  1294. case ContentFormat.JSON: {
  1295. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  1296. break;
  1297. }
  1298. default: {
  1299. throw new Error("Unexpected content format: " + contentFormat);
  1300. }
  1301. }
  1302. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  1303. var body = binaryReader.readUint8Array(bytesRemaining);
  1304. return {
  1305. json: content,
  1306. bin: body
  1307. };
  1308. };
  1309. GLTFFileLoader._parseV2 = function (binaryReader) {
  1310. var ChunkFormat = {
  1311. JSON: 0x4E4F534A,
  1312. BIN: 0x004E4942
  1313. };
  1314. var length = binaryReader.readUint32();
  1315. if (length !== binaryReader.getLength()) {
  1316. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  1317. }
  1318. // JSON chunk
  1319. var chunkLength = binaryReader.readUint32();
  1320. var chunkFormat = binaryReader.readUint32();
  1321. if (chunkFormat !== ChunkFormat.JSON) {
  1322. throw new Error("First chunk format is not JSON");
  1323. }
  1324. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  1325. // Look for BIN chunk
  1326. var bin = null;
  1327. while (binaryReader.getPosition() < binaryReader.getLength()) {
  1328. var chunkLength_1 = binaryReader.readUint32();
  1329. var chunkFormat_1 = binaryReader.readUint32();
  1330. switch (chunkFormat_1) {
  1331. case ChunkFormat.JSON: {
  1332. throw new Error("Unexpected JSON chunk");
  1333. }
  1334. case ChunkFormat.BIN: {
  1335. bin = binaryReader.readUint8Array(chunkLength_1);
  1336. break;
  1337. }
  1338. default: {
  1339. // ignore unrecognized chunkFormat
  1340. binaryReader.skipBytes(chunkLength_1);
  1341. break;
  1342. }
  1343. }
  1344. }
  1345. return {
  1346. json: json,
  1347. bin: bin
  1348. };
  1349. };
  1350. GLTFFileLoader._parseVersion = function (version) {
  1351. if (version === "1.0" || version === "1.0.1") {
  1352. return {
  1353. major: 1,
  1354. minor: 0
  1355. };
  1356. }
  1357. var match = (version + "").match(/^(\d+)\.(\d+)/);
  1358. if (!match) {
  1359. return null;
  1360. }
  1361. return {
  1362. major: parseInt(match[1]),
  1363. minor: parseInt(match[2])
  1364. };
  1365. };
  1366. GLTFFileLoader._compareVersion = function (a, b) {
  1367. if (a.major > b.major)
  1368. return 1;
  1369. if (a.major < b.major)
  1370. return -1;
  1371. if (a.minor > b.minor)
  1372. return 1;
  1373. if (a.minor < b.minor)
  1374. return -1;
  1375. return 0;
  1376. };
  1377. GLTFFileLoader._decodeBufferToText = function (buffer) {
  1378. var result = "";
  1379. var length = buffer.byteLength;
  1380. for (var i = 0; i < length; i++) {
  1381. result += String.fromCharCode(buffer[i]);
  1382. }
  1383. return result;
  1384. };
  1385. // #endregion
  1386. // #region V1 options
  1387. GLTFFileLoader.IncrementalLoading = true;
  1388. GLTFFileLoader.HomogeneousCoordinates = false;
  1389. return GLTFFileLoader;
  1390. }());
  1391. BABYLON.GLTFFileLoader = GLTFFileLoader;
  1392. var BinaryReader = /** @class */ (function () {
  1393. function BinaryReader(arrayBuffer) {
  1394. this._arrayBuffer = arrayBuffer;
  1395. this._dataView = new DataView(arrayBuffer);
  1396. this._byteOffset = 0;
  1397. }
  1398. BinaryReader.prototype.getPosition = function () {
  1399. return this._byteOffset;
  1400. };
  1401. BinaryReader.prototype.getLength = function () {
  1402. return this._arrayBuffer.byteLength;
  1403. };
  1404. BinaryReader.prototype.readUint32 = function () {
  1405. var value = this._dataView.getUint32(this._byteOffset, true);
  1406. this._byteOffset += 4;
  1407. return value;
  1408. };
  1409. BinaryReader.prototype.readUint8Array = function (length) {
  1410. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  1411. this._byteOffset += length;
  1412. return value;
  1413. };
  1414. BinaryReader.prototype.skipBytes = function (length) {
  1415. this._byteOffset += length;
  1416. };
  1417. return BinaryReader;
  1418. }());
  1419. if (BABYLON.SceneLoader) {
  1420. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  1421. }
  1422. })(BABYLON || (BABYLON = {}));
  1423. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  1424. var BABYLON;
  1425. (function (BABYLON) {
  1426. var GLTF1;
  1427. (function (GLTF1) {
  1428. /**
  1429. * Enums
  1430. */
  1431. var EComponentType;
  1432. (function (EComponentType) {
  1433. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  1434. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  1435. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  1436. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  1437. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  1438. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  1439. var EShaderType;
  1440. (function (EShaderType) {
  1441. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  1442. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  1443. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  1444. var EParameterType;
  1445. (function (EParameterType) {
  1446. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  1447. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  1448. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  1449. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  1450. EParameterType[EParameterType["INT"] = 5124] = "INT";
  1451. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  1452. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  1453. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  1454. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  1455. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  1456. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  1457. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  1458. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  1459. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  1460. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  1461. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  1462. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  1463. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  1464. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  1465. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  1466. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  1467. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  1468. var ETextureWrapMode;
  1469. (function (ETextureWrapMode) {
  1470. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  1471. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  1472. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  1473. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  1474. var ETextureFilterType;
  1475. (function (ETextureFilterType) {
  1476. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  1477. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  1478. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  1479. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  1480. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  1481. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  1482. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  1483. var ETextureFormat;
  1484. (function (ETextureFormat) {
  1485. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  1486. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  1487. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  1488. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  1489. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  1490. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  1491. var ECullingType;
  1492. (function (ECullingType) {
  1493. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  1494. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  1495. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  1496. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  1497. var EBlendingFunction;
  1498. (function (EBlendingFunction) {
  1499. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  1500. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  1501. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  1502. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  1503. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  1504. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  1505. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  1506. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  1507. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  1508. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  1509. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  1510. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  1511. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  1512. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  1513. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  1514. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  1515. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  1516. })(BABYLON || (BABYLON = {}));
  1517. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  1518. var BABYLON;
  1519. (function (BABYLON) {
  1520. var GLTF1;
  1521. (function (GLTF1) {
  1522. /**
  1523. * Tokenizer. Used for shaders compatibility
  1524. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  1525. */
  1526. var ETokenType;
  1527. (function (ETokenType) {
  1528. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  1529. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  1530. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  1531. })(ETokenType || (ETokenType = {}));
  1532. var Tokenizer = /** @class */ (function () {
  1533. function Tokenizer(toParse) {
  1534. this._pos = 0;
  1535. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  1536. this._toParse = toParse;
  1537. this._maxPos = toParse.length;
  1538. }
  1539. Tokenizer.prototype.getNextToken = function () {
  1540. if (this.isEnd())
  1541. return ETokenType.END_OF_INPUT;
  1542. this.currentString = this.read();
  1543. this.currentToken = ETokenType.UNKNOWN;
  1544. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  1545. this.currentToken = ETokenType.IDENTIFIER;
  1546. this.currentIdentifier = this.currentString;
  1547. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  1548. this.currentIdentifier += this.currentString;
  1549. this.forward();
  1550. }
  1551. }
  1552. return this.currentToken;
  1553. };
  1554. Tokenizer.prototype.peek = function () {
  1555. return this._toParse[this._pos];
  1556. };
  1557. Tokenizer.prototype.read = function () {
  1558. return this._toParse[this._pos++];
  1559. };
  1560. Tokenizer.prototype.forward = function () {
  1561. this._pos++;
  1562. };
  1563. Tokenizer.prototype.isEnd = function () {
  1564. return this._pos >= this._maxPos;
  1565. };
  1566. return Tokenizer;
  1567. }());
  1568. /**
  1569. * Values
  1570. */
  1571. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  1572. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  1573. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  1574. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  1575. /**
  1576. * Parse
  1577. */
  1578. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  1579. for (var buf in parsedBuffers) {
  1580. var parsedBuffer = parsedBuffers[buf];
  1581. gltfRuntime.buffers[buf] = parsedBuffer;
  1582. gltfRuntime.buffersCount++;
  1583. }
  1584. };
  1585. var parseShaders = function (parsedShaders, gltfRuntime) {
  1586. for (var sha in parsedShaders) {
  1587. var parsedShader = parsedShaders[sha];
  1588. gltfRuntime.shaders[sha] = parsedShader;
  1589. gltfRuntime.shaderscount++;
  1590. }
  1591. };
  1592. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  1593. for (var object in parsedObjects) {
  1594. var parsedObject = parsedObjects[object];
  1595. gltfRuntime[runtimeProperty][object] = parsedObject;
  1596. }
  1597. };
  1598. /**
  1599. * Utils
  1600. */
  1601. var normalizeUVs = function (buffer) {
  1602. if (!buffer) {
  1603. return;
  1604. }
  1605. for (var i = 0; i < buffer.length / 2; i++) {
  1606. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  1607. }
  1608. };
  1609. var getAttribute = function (attributeParameter) {
  1610. if (attributeParameter.semantic === "NORMAL") {
  1611. return "normal";
  1612. }
  1613. else if (attributeParameter.semantic === "POSITION") {
  1614. return "position";
  1615. }
  1616. else if (attributeParameter.semantic === "JOINT") {
  1617. return "matricesIndices";
  1618. }
  1619. else if (attributeParameter.semantic === "WEIGHT") {
  1620. return "matricesWeights";
  1621. }
  1622. else if (attributeParameter.semantic === "COLOR") {
  1623. return "color";
  1624. }
  1625. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  1626. var channel = Number(attributeParameter.semantic.split("_")[1]);
  1627. return "uv" + (channel === 0 ? "" : channel + 1);
  1628. }
  1629. return null;
  1630. };
  1631. /**
  1632. * Loads and creates animations
  1633. */
  1634. var loadAnimations = function (gltfRuntime) {
  1635. for (var anim in gltfRuntime.animations) {
  1636. var animation = gltfRuntime.animations[anim];
  1637. if (!animation.channels || !animation.samplers) {
  1638. continue;
  1639. }
  1640. var lastAnimation = null;
  1641. for (var i = 0; i < animation.channels.length; i++) {
  1642. // Get parameters and load buffers
  1643. var channel = animation.channels[i];
  1644. var sampler = animation.samplers[channel.sampler];
  1645. if (!sampler) {
  1646. continue;
  1647. }
  1648. var inputData = null;
  1649. var outputData = null;
  1650. if (animation.parameters) {
  1651. inputData = animation.parameters[sampler.input];
  1652. outputData = animation.parameters[sampler.output];
  1653. }
  1654. else {
  1655. inputData = sampler.input;
  1656. outputData = sampler.output;
  1657. }
  1658. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  1659. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  1660. var targetID = channel.target.id;
  1661. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  1662. if (targetNode === null) {
  1663. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  1664. }
  1665. if (targetNode === null) {
  1666. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  1667. continue;
  1668. }
  1669. var isBone = targetNode instanceof BABYLON.Bone;
  1670. // Get target path (position, rotation or scaling)
  1671. var targetPath = channel.target.path;
  1672. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  1673. if (targetPathIndex !== -1) {
  1674. targetPath = babylonAnimationPaths[targetPathIndex];
  1675. }
  1676. // Determine animation type
  1677. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  1678. if (!isBone) {
  1679. if (targetPath === "rotationQuaternion") {
  1680. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  1681. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  1682. }
  1683. else {
  1684. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  1685. }
  1686. }
  1687. // Create animation and key frames
  1688. var babylonAnimation = null;
  1689. var keys = [];
  1690. var arrayOffset = 0;
  1691. var modifyKey = false;
  1692. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  1693. babylonAnimation = lastAnimation;
  1694. modifyKey = true;
  1695. }
  1696. if (!modifyKey) {
  1697. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  1698. }
  1699. // For each frame
  1700. for (var j = 0; j < bufferInput.length; j++) {
  1701. var value = null;
  1702. if (targetPath === "rotationQuaternion") {
  1703. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  1704. arrayOffset += 4;
  1705. }
  1706. else {
  1707. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  1708. arrayOffset += 3;
  1709. }
  1710. if (isBone) {
  1711. var bone = targetNode;
  1712. var translation = BABYLON.Vector3.Zero();
  1713. var rotationQuaternion = new BABYLON.Quaternion();
  1714. var scaling = BABYLON.Vector3.Zero();
  1715. // Warning on decompose
  1716. var mat = bone.getBaseMatrix();
  1717. if (modifyKey && lastAnimation) {
  1718. mat = lastAnimation.getKeys()[j].value;
  1719. }
  1720. mat.decompose(scaling, rotationQuaternion, translation);
  1721. if (targetPath === "position") {
  1722. translation = value;
  1723. }
  1724. else if (targetPath === "rotationQuaternion") {
  1725. rotationQuaternion = value;
  1726. }
  1727. else {
  1728. scaling = value;
  1729. }
  1730. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  1731. }
  1732. if (!modifyKey) {
  1733. keys.push({
  1734. frame: bufferInput[j],
  1735. value: value
  1736. });
  1737. }
  1738. else if (lastAnimation) {
  1739. lastAnimation.getKeys()[j].value = value;
  1740. }
  1741. }
  1742. // Finish
  1743. if (!modifyKey && babylonAnimation) {
  1744. babylonAnimation.setKeys(keys);
  1745. targetNode.animations.push(babylonAnimation);
  1746. }
  1747. lastAnimation = babylonAnimation;
  1748. gltfRuntime.scene.stopAnimation(targetNode);
  1749. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  1750. }
  1751. }
  1752. };
  1753. /**
  1754. * Returns the bones transformation matrix
  1755. */
  1756. var configureBoneTransformation = function (node) {
  1757. var mat = null;
  1758. if (node.translation || node.rotation || node.scale) {
  1759. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  1760. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  1761. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  1762. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  1763. }
  1764. else {
  1765. mat = BABYLON.Matrix.FromArray(node.matrix);
  1766. }
  1767. return mat;
  1768. };
  1769. /**
  1770. * Returns the parent bone
  1771. */
  1772. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  1773. // Try to find
  1774. for (var i = 0; i < newSkeleton.bones.length; i++) {
  1775. if (newSkeleton.bones[i].name === jointName) {
  1776. return newSkeleton.bones[i];
  1777. }
  1778. }
  1779. // Not found, search in gltf nodes
  1780. var nodes = gltfRuntime.nodes;
  1781. for (var nde in nodes) {
  1782. var node = nodes[nde];
  1783. if (!node.jointName) {
  1784. continue;
  1785. }
  1786. var children = node.children;
  1787. for (var i = 0; i < children.length; i++) {
  1788. var child = gltfRuntime.nodes[children[i]];
  1789. if (!child.jointName) {
  1790. continue;
  1791. }
  1792. if (child.jointName === jointName) {
  1793. var mat = configureBoneTransformation(node);
  1794. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  1795. bone.id = nde;
  1796. return bone;
  1797. }
  1798. }
  1799. }
  1800. return null;
  1801. };
  1802. /**
  1803. * Returns the appropriate root node
  1804. */
  1805. var getNodeToRoot = function (nodesToRoot, id) {
  1806. for (var i = 0; i < nodesToRoot.length; i++) {
  1807. var nodeToRoot = nodesToRoot[i];
  1808. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  1809. var child = nodeToRoot.node.children[j];
  1810. if (child === id) {
  1811. return nodeToRoot.bone;
  1812. }
  1813. }
  1814. }
  1815. return null;
  1816. };
  1817. /**
  1818. * Returns the node with the joint name
  1819. */
  1820. var getJointNode = function (gltfRuntime, jointName) {
  1821. var nodes = gltfRuntime.nodes;
  1822. var node = nodes[jointName];
  1823. if (node) {
  1824. return {
  1825. node: node,
  1826. id: jointName
  1827. };
  1828. }
  1829. for (var nde in nodes) {
  1830. node = nodes[nde];
  1831. if (node.jointName === jointName) {
  1832. return {
  1833. node: node,
  1834. id: nde
  1835. };
  1836. }
  1837. }
  1838. return null;
  1839. };
  1840. /**
  1841. * Checks if a nodes is in joints
  1842. */
  1843. var nodeIsInJoints = function (skins, id) {
  1844. for (var i = 0; i < skins.jointNames.length; i++) {
  1845. if (skins.jointNames[i] === id) {
  1846. return true;
  1847. }
  1848. }
  1849. return false;
  1850. };
  1851. /**
  1852. * Fills the nodes to root for bones and builds hierarchy
  1853. */
  1854. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  1855. // Creates nodes for root
  1856. for (var nde in gltfRuntime.nodes) {
  1857. var node = gltfRuntime.nodes[nde];
  1858. var id = nde;
  1859. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  1860. continue;
  1861. }
  1862. // Create node to root bone
  1863. var mat = configureBoneTransformation(node);
  1864. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  1865. bone.id = id;
  1866. nodesToRoot.push({ bone: bone, node: node, id: id });
  1867. }
  1868. // Parenting
  1869. for (var i = 0; i < nodesToRoot.length; i++) {
  1870. var nodeToRoot = nodesToRoot[i];
  1871. var children = nodeToRoot.node.children;
  1872. for (var j = 0; j < children.length; j++) {
  1873. var child = null;
  1874. for (var k = 0; k < nodesToRoot.length; k++) {
  1875. if (nodesToRoot[k].id === children[j]) {
  1876. child = nodesToRoot[k];
  1877. break;
  1878. }
  1879. }
  1880. if (child) {
  1881. child.bone._parent = nodeToRoot.bone;
  1882. nodeToRoot.bone.children.push(child.bone);
  1883. }
  1884. }
  1885. }
  1886. };
  1887. /**
  1888. * Imports a skeleton
  1889. */
  1890. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  1891. if (!newSkeleton) {
  1892. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  1893. }
  1894. if (!skins.babylonSkeleton) {
  1895. return newSkeleton;
  1896. }
  1897. // Find the root bones
  1898. var nodesToRoot = [];
  1899. var nodesToRootToAdd = [];
  1900. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  1901. newSkeleton.bones = [];
  1902. // Joints
  1903. for (var i = 0; i < skins.jointNames.length; i++) {
  1904. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  1905. if (!jointNode) {
  1906. continue;
  1907. }
  1908. var node = jointNode.node;
  1909. if (!node) {
  1910. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  1911. continue;
  1912. }
  1913. var id = jointNode.id;
  1914. // Optimize, if the bone already exists...
  1915. var existingBone = gltfRuntime.scene.getBoneByID(id);
  1916. if (existingBone) {
  1917. newSkeleton.bones.push(existingBone);
  1918. continue;
  1919. }
  1920. // Search for parent bone
  1921. var foundBone = false;
  1922. var parentBone = null;
  1923. for (var j = 0; j < i; j++) {
  1924. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  1925. if (!jointNode_1) {
  1926. continue;
  1927. }
  1928. var joint = jointNode_1.node;
  1929. if (!joint) {
  1930. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  1931. continue;
  1932. }
  1933. var children = joint.children;
  1934. if (!children) {
  1935. continue;
  1936. }
  1937. foundBone = false;
  1938. for (var k = 0; k < children.length; k++) {
  1939. if (children[k] === id) {
  1940. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  1941. foundBone = true;
  1942. break;
  1943. }
  1944. }
  1945. if (foundBone) {
  1946. break;
  1947. }
  1948. }
  1949. // Create bone
  1950. var mat = configureBoneTransformation(node);
  1951. if (!parentBone && nodesToRoot.length > 0) {
  1952. parentBone = getNodeToRoot(nodesToRoot, id);
  1953. if (parentBone) {
  1954. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  1955. nodesToRootToAdd.push(parentBone);
  1956. }
  1957. }
  1958. }
  1959. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  1960. bone.id = id;
  1961. }
  1962. // Polish
  1963. var bones = newSkeleton.bones;
  1964. newSkeleton.bones = [];
  1965. for (var i = 0; i < skins.jointNames.length; i++) {
  1966. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  1967. if (!jointNode) {
  1968. continue;
  1969. }
  1970. for (var j = 0; j < bones.length; j++) {
  1971. if (bones[j].id === jointNode.id) {
  1972. newSkeleton.bones.push(bones[j]);
  1973. break;
  1974. }
  1975. }
  1976. }
  1977. newSkeleton.prepare();
  1978. // Finish
  1979. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  1980. newSkeleton.bones.push(nodesToRootToAdd[i]);
  1981. }
  1982. return newSkeleton;
  1983. };
  1984. /**
  1985. * Imports a mesh and its geometries
  1986. */
  1987. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  1988. if (!newMesh) {
  1989. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  1990. newMesh.id = id;
  1991. }
  1992. if (!node.babylonNode) {
  1993. return newMesh;
  1994. }
  1995. var subMaterials = [];
  1996. var vertexData = null;
  1997. var verticesStarts = new Array();
  1998. var verticesCounts = new Array();
  1999. var indexStarts = new Array();
  2000. var indexCounts = new Array();
  2001. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  2002. var meshID = meshes[meshIndex];
  2003. var mesh = gltfRuntime.meshes[meshID];
  2004. if (!mesh) {
  2005. continue;
  2006. }
  2007. // Positions, normals and UVs
  2008. for (var i = 0; i < mesh.primitives.length; i++) {
  2009. // Temporary vertex data
  2010. var tempVertexData = new BABYLON.VertexData();
  2011. var primitive = mesh.primitives[i];
  2012. if (primitive.mode !== 4) {
  2013. // continue;
  2014. }
  2015. var attributes = primitive.attributes;
  2016. var accessor = null;
  2017. var buffer = null;
  2018. // Set positions, normal and uvs
  2019. for (var semantic in attributes) {
  2020. // Link accessor and buffer view
  2021. accessor = gltfRuntime.accessors[attributes[semantic]];
  2022. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  2023. if (semantic === "NORMAL") {
  2024. tempVertexData.normals = new Float32Array(buffer.length);
  2025. tempVertexData.normals.set(buffer);
  2026. }
  2027. else if (semantic === "POSITION") {
  2028. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  2029. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  2030. for (var j = 0; j < buffer.length; j += 4) {
  2031. tempVertexData.positions[j] = buffer[j];
  2032. tempVertexData.positions[j + 1] = buffer[j + 1];
  2033. tempVertexData.positions[j + 2] = buffer[j + 2];
  2034. }
  2035. }
  2036. else {
  2037. tempVertexData.positions = new Float32Array(buffer.length);
  2038. tempVertexData.positions.set(buffer);
  2039. }
  2040. verticesCounts.push(tempVertexData.positions.length);
  2041. }
  2042. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  2043. var channel = Number(semantic.split("_")[1]);
  2044. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  2045. var uvs = new Float32Array(buffer.length);
  2046. uvs.set(buffer);
  2047. normalizeUVs(uvs);
  2048. tempVertexData.set(uvs, uvKind);
  2049. }
  2050. else if (semantic === "JOINT") {
  2051. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  2052. tempVertexData.matricesIndices.set(buffer);
  2053. }
  2054. else if (semantic === "WEIGHT") {
  2055. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  2056. tempVertexData.matricesWeights.set(buffer);
  2057. }
  2058. else if (semantic === "COLOR") {
  2059. tempVertexData.colors = new Float32Array(buffer.length);
  2060. tempVertexData.colors.set(buffer);
  2061. }
  2062. }
  2063. // Indices
  2064. accessor = gltfRuntime.accessors[primitive.indices];
  2065. if (accessor) {
  2066. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  2067. tempVertexData.indices = new Int32Array(buffer.length);
  2068. tempVertexData.indices.set(buffer);
  2069. indexCounts.push(tempVertexData.indices.length);
  2070. }
  2071. else {
  2072. // Set indices on the fly
  2073. var indices = [];
  2074. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  2075. indices.push(j);
  2076. }
  2077. tempVertexData.indices = new Int32Array(indices);
  2078. indexCounts.push(tempVertexData.indices.length);
  2079. }
  2080. if (!vertexData) {
  2081. vertexData = tempVertexData;
  2082. }
  2083. else {
  2084. vertexData.merge(tempVertexData);
  2085. }
  2086. // Sub material
  2087. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  2088. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  2089. // Update vertices start and index start
  2090. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  2091. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  2092. }
  2093. }
  2094. var material;
  2095. if (subMaterials.length > 1) {
  2096. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  2097. material.subMaterials = subMaterials;
  2098. }
  2099. else {
  2100. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  2101. }
  2102. if (subMaterials.length === 1) {
  2103. material = subMaterials[0];
  2104. }
  2105. if (!newMesh.material) {
  2106. newMesh.material = material;
  2107. }
  2108. // Apply geometry
  2109. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  2110. newMesh.computeWorldMatrix(true);
  2111. // Apply submeshes
  2112. newMesh.subMeshes = [];
  2113. var index = 0;
  2114. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  2115. var meshID = meshes[meshIndex];
  2116. var mesh = gltfRuntime.meshes[meshID];
  2117. if (!mesh) {
  2118. continue;
  2119. }
  2120. for (var i = 0; i < mesh.primitives.length; i++) {
  2121. if (mesh.primitives[i].mode !== 4) {
  2122. //continue;
  2123. }
  2124. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  2125. index++;
  2126. }
  2127. }
  2128. // Finish
  2129. return newMesh;
  2130. };
  2131. /**
  2132. * Configure node transformation from position, rotation and scaling
  2133. */
  2134. var configureNode = function (newNode, position, rotation, scaling) {
  2135. if (newNode.position) {
  2136. newNode.position = position;
  2137. }
  2138. if (newNode.rotationQuaternion || newNode.rotation) {
  2139. newNode.rotationQuaternion = rotation;
  2140. }
  2141. if (newNode.scaling) {
  2142. newNode.scaling = scaling;
  2143. }
  2144. };
  2145. /**
  2146. * Configures node from transformation matrix
  2147. */
  2148. var configureNodeFromMatrix = function (newNode, node, parent) {
  2149. if (node.matrix) {
  2150. var position = new BABYLON.Vector3(0, 0, 0);
  2151. var rotation = new BABYLON.Quaternion();
  2152. var scaling = new BABYLON.Vector3(0, 0, 0);
  2153. var mat = BABYLON.Matrix.FromArray(node.matrix);
  2154. mat.decompose(scaling, rotation, position);
  2155. configureNode(newNode, position, rotation, scaling);
  2156. }
  2157. else if (node.translation && node.rotation && node.scale) {
  2158. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  2159. }
  2160. newNode.computeWorldMatrix(true);
  2161. };
  2162. /**
  2163. * Imports a node
  2164. */
  2165. var importNode = function (gltfRuntime, node, id, parent) {
  2166. var lastNode = null;
  2167. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  2168. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  2169. return null;
  2170. }
  2171. }
  2172. // Meshes
  2173. if (node.skin) {
  2174. if (node.meshes) {
  2175. var skin = gltfRuntime.skins[node.skin];
  2176. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  2177. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  2178. if (newMesh.skeleton === null) {
  2179. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  2180. if (!skin.babylonSkeleton) {
  2181. skin.babylonSkeleton = newMesh.skeleton;
  2182. }
  2183. }
  2184. lastNode = newMesh;
  2185. }
  2186. }
  2187. else if (node.meshes) {
  2188. /**
  2189. * Improve meshes property
  2190. */
  2191. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  2192. lastNode = newMesh;
  2193. }
  2194. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  2195. var light = gltfRuntime.lights[node.light];
  2196. if (light) {
  2197. if (light.type === "ambient") {
  2198. var ambienLight = light[light.type];
  2199. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  2200. hemiLight.name = node.name || "";
  2201. if (ambienLight.color) {
  2202. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  2203. }
  2204. lastNode = hemiLight;
  2205. }
  2206. else if (light.type === "directional") {
  2207. var directionalLight = light[light.type];
  2208. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  2209. dirLight.name = node.name || "";
  2210. if (directionalLight.color) {
  2211. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  2212. }
  2213. lastNode = dirLight;
  2214. }
  2215. else if (light.type === "point") {
  2216. var pointLight = light[light.type];
  2217. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  2218. ptLight.name = node.name || "";
  2219. if (pointLight.color) {
  2220. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  2221. }
  2222. lastNode = ptLight;
  2223. }
  2224. else if (light.type === "spot") {
  2225. var spotLight = light[light.type];
  2226. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  2227. spLight.name = node.name || "";
  2228. if (spotLight.color) {
  2229. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  2230. }
  2231. if (spotLight.fallOfAngle) {
  2232. spLight.angle = spotLight.fallOfAngle;
  2233. }
  2234. if (spotLight.fallOffExponent) {
  2235. spLight.exponent = spotLight.fallOffExponent;
  2236. }
  2237. lastNode = spLight;
  2238. }
  2239. }
  2240. }
  2241. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  2242. var camera = gltfRuntime.cameras[node.camera];
  2243. if (camera) {
  2244. if (camera.type === "orthographic") {
  2245. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  2246. orthoCamera.name = node.name || "";
  2247. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  2248. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  2249. lastNode = orthoCamera;
  2250. }
  2251. else if (camera.type === "perspective") {
  2252. var perspectiveCamera = camera[camera.type];
  2253. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  2254. persCamera.name = node.name || "";
  2255. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  2256. if (!perspectiveCamera.aspectRatio) {
  2257. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  2258. }
  2259. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  2260. persCamera.maxZ = perspectiveCamera.zfar;
  2261. persCamera.minZ = perspectiveCamera.znear;
  2262. }
  2263. lastNode = persCamera;
  2264. }
  2265. }
  2266. }
  2267. // Empty node
  2268. if (!node.jointName) {
  2269. if (node.babylonNode) {
  2270. return node.babylonNode;
  2271. }
  2272. else if (lastNode === null) {
  2273. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  2274. node.babylonNode = dummy;
  2275. lastNode = dummy;
  2276. }
  2277. }
  2278. if (lastNode !== null) {
  2279. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  2280. configureNodeFromMatrix(lastNode, node, parent);
  2281. }
  2282. else {
  2283. var translation = node.translation || [0, 0, 0];
  2284. var rotation = node.rotation || [0, 0, 0, 1];
  2285. var scale = node.scale || [1, 1, 1];
  2286. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  2287. }
  2288. lastNode.updateCache(true);
  2289. node.babylonNode = lastNode;
  2290. }
  2291. return lastNode;
  2292. };
  2293. /**
  2294. * Traverses nodes and creates them
  2295. */
  2296. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  2297. if (meshIncluded === void 0) { meshIncluded = false; }
  2298. var node = gltfRuntime.nodes[id];
  2299. var newNode = null;
  2300. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  2301. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  2302. meshIncluded = true;
  2303. }
  2304. else {
  2305. meshIncluded = false;
  2306. }
  2307. }
  2308. else {
  2309. meshIncluded = true;
  2310. }
  2311. if (!node.jointName && meshIncluded) {
  2312. newNode = importNode(gltfRuntime, node, id, parent);
  2313. if (newNode !== null) {
  2314. newNode.id = id;
  2315. newNode.parent = parent;
  2316. }
  2317. }
  2318. if (node.children) {
  2319. for (var i = 0; i < node.children.length; i++) {
  2320. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  2321. }
  2322. }
  2323. };
  2324. /**
  2325. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  2326. */
  2327. var postLoad = function (gltfRuntime) {
  2328. // Nodes
  2329. var currentScene = gltfRuntime.currentScene;
  2330. if (currentScene) {
  2331. for (var i = 0; i < currentScene.nodes.length; i++) {
  2332. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2333. }
  2334. }
  2335. else {
  2336. for (var thing in gltfRuntime.scenes) {
  2337. currentScene = gltfRuntime.scenes[thing];
  2338. for (var i = 0; i < currentScene.nodes.length; i++) {
  2339. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2340. }
  2341. }
  2342. }
  2343. // Set animations
  2344. loadAnimations(gltfRuntime);
  2345. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  2346. var skeleton = gltfRuntime.scene.skeletons[i];
  2347. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  2348. }
  2349. };
  2350. /**
  2351. * onBind shaderrs callback to set uniforms and matrices
  2352. */
  2353. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  2354. var materialValues = material.values || technique.parameters;
  2355. for (var unif in unTreatedUniforms) {
  2356. var uniform = unTreatedUniforms[unif];
  2357. var type = uniform.type;
  2358. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  2359. if (uniform.semantic && !uniform.source && !uniform.node) {
  2360. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  2361. }
  2362. else if (uniform.semantic && (uniform.source || uniform.node)) {
  2363. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  2364. if (source === null) {
  2365. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  2366. }
  2367. if (source === null) {
  2368. continue;
  2369. }
  2370. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  2371. }
  2372. }
  2373. else {
  2374. var value = materialValues[technique.uniforms[unif]];
  2375. if (!value) {
  2376. continue;
  2377. }
  2378. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  2379. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  2380. if (texture === null || texture === undefined) {
  2381. continue;
  2382. }
  2383. shaderMaterial.getEffect().setTexture(unif, texture);
  2384. }
  2385. else {
  2386. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  2387. }
  2388. }
  2389. }
  2390. onSuccess(shaderMaterial);
  2391. };
  2392. /**
  2393. * Prepare uniforms to send the only one time
  2394. * Loads the appropriate textures
  2395. */
  2396. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  2397. var materialValues = material.values || technique.parameters;
  2398. var techniqueUniforms = technique.uniforms;
  2399. /**
  2400. * Prepare values here (not matrices)
  2401. */
  2402. for (var unif in unTreatedUniforms) {
  2403. var uniform = unTreatedUniforms[unif];
  2404. var type = uniform.type;
  2405. var value = materialValues[techniqueUniforms[unif]];
  2406. if (value === undefined) {
  2407. // In case the value is the same for all materials
  2408. value = uniform.value;
  2409. }
  2410. if (!value) {
  2411. continue;
  2412. }
  2413. var onLoadTexture = function (uniformName) {
  2414. return function (texture) {
  2415. if (uniform.value && uniformName) {
  2416. // Static uniform
  2417. shaderMaterial.setTexture(uniformName, texture);
  2418. delete unTreatedUniforms[uniformName];
  2419. }
  2420. };
  2421. };
  2422. // Texture (sampler2D)
  2423. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  2424. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  2425. }
  2426. else {
  2427. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  2428. // Static uniform
  2429. delete unTreatedUniforms[unif];
  2430. }
  2431. }
  2432. }
  2433. };
  2434. /**
  2435. * Shader compilation failed
  2436. */
  2437. var onShaderCompileError = function (program, shaderMaterial, onError) {
  2438. return function (effect, error) {
  2439. shaderMaterial.dispose(true);
  2440. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  2441. };
  2442. };
  2443. /**
  2444. * Shader compilation success
  2445. */
  2446. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  2447. return function (_) {
  2448. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  2449. shaderMaterial.onBind = function (mesh) {
  2450. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  2451. };
  2452. };
  2453. };
  2454. /**
  2455. * Returns the appropriate uniform if already handled by babylon
  2456. */
  2457. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  2458. for (var unif in technique.uniforms) {
  2459. var uniform = technique.uniforms[unif];
  2460. var uniformParameter = technique.parameters[uniform];
  2461. if (tokenizer.currentIdentifier === unif) {
  2462. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  2463. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  2464. if (transformIndex !== -1) {
  2465. delete unTreatedUniforms[unif];
  2466. return babylonTransforms[transformIndex];
  2467. }
  2468. }
  2469. }
  2470. }
  2471. return tokenizer.currentIdentifier;
  2472. };
  2473. /**
  2474. * All shaders loaded. Create materials one by one
  2475. */
  2476. var importMaterials = function (gltfRuntime) {
  2477. // Create materials
  2478. for (var mat in gltfRuntime.materials) {
  2479. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  2480. }
  2481. };
  2482. /**
  2483. * Implementation of the base glTF spec
  2484. */
  2485. var GLTFLoaderBase = /** @class */ (function () {
  2486. function GLTFLoaderBase() {
  2487. }
  2488. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  2489. var gltfRuntime = {
  2490. extensions: {},
  2491. accessors: {},
  2492. buffers: {},
  2493. bufferViews: {},
  2494. meshes: {},
  2495. lights: {},
  2496. cameras: {},
  2497. nodes: {},
  2498. images: {},
  2499. textures: {},
  2500. shaders: {},
  2501. programs: {},
  2502. samplers: {},
  2503. techniques: {},
  2504. materials: {},
  2505. animations: {},
  2506. skins: {},
  2507. extensionsUsed: [],
  2508. scenes: {},
  2509. buffersCount: 0,
  2510. shaderscount: 0,
  2511. scene: scene,
  2512. rootUrl: rootUrl,
  2513. loadedBufferCount: 0,
  2514. loadedBufferViews: {},
  2515. loadedShaderCount: 0,
  2516. importOnlyMeshes: false,
  2517. dummyNodes: []
  2518. };
  2519. // Parse
  2520. if (parsedData.extensions) {
  2521. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  2522. }
  2523. if (parsedData.extensionsUsed) {
  2524. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  2525. }
  2526. if (parsedData.buffers) {
  2527. parseBuffers(parsedData.buffers, gltfRuntime);
  2528. }
  2529. if (parsedData.bufferViews) {
  2530. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  2531. }
  2532. if (parsedData.accessors) {
  2533. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  2534. }
  2535. if (parsedData.meshes) {
  2536. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  2537. }
  2538. if (parsedData.lights) {
  2539. parseObject(parsedData.lights, "lights", gltfRuntime);
  2540. }
  2541. if (parsedData.cameras) {
  2542. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  2543. }
  2544. if (parsedData.nodes) {
  2545. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  2546. }
  2547. if (parsedData.images) {
  2548. parseObject(parsedData.images, "images", gltfRuntime);
  2549. }
  2550. if (parsedData.textures) {
  2551. parseObject(parsedData.textures, "textures", gltfRuntime);
  2552. }
  2553. if (parsedData.shaders) {
  2554. parseShaders(parsedData.shaders, gltfRuntime);
  2555. }
  2556. if (parsedData.programs) {
  2557. parseObject(parsedData.programs, "programs", gltfRuntime);
  2558. }
  2559. if (parsedData.samplers) {
  2560. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  2561. }
  2562. if (parsedData.techniques) {
  2563. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  2564. }
  2565. if (parsedData.materials) {
  2566. parseObject(parsedData.materials, "materials", gltfRuntime);
  2567. }
  2568. if (parsedData.animations) {
  2569. parseObject(parsedData.animations, "animations", gltfRuntime);
  2570. }
  2571. if (parsedData.skins) {
  2572. parseObject(parsedData.skins, "skins", gltfRuntime);
  2573. }
  2574. if (parsedData.scenes) {
  2575. gltfRuntime.scenes = parsedData.scenes;
  2576. }
  2577. if (parsedData.scene && parsedData.scenes) {
  2578. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  2579. }
  2580. return gltfRuntime;
  2581. };
  2582. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2583. var buffer = gltfRuntime.buffers[id];
  2584. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  2585. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  2586. }
  2587. else {
  2588. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  2589. if (request) {
  2590. onError(request.status + " " + request.statusText);
  2591. }
  2592. });
  2593. }
  2594. };
  2595. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2596. var texture = gltfRuntime.textures[id];
  2597. if (!texture || !texture.source) {
  2598. onError("");
  2599. return;
  2600. }
  2601. if (texture.babylonTexture) {
  2602. onSuccess(null);
  2603. return;
  2604. }
  2605. var source = gltfRuntime.images[texture.source];
  2606. if (BABYLON.Tools.IsBase64(source.uri)) {
  2607. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  2608. }
  2609. else {
  2610. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  2611. if (request) {
  2612. onError(request.status + " " + request.statusText);
  2613. }
  2614. });
  2615. }
  2616. };
  2617. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2618. var texture = gltfRuntime.textures[id];
  2619. if (texture.babylonTexture) {
  2620. onSuccess(texture.babylonTexture);
  2621. return;
  2622. }
  2623. var sampler = gltfRuntime.samplers[texture.sampler];
  2624. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  2625. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  2626. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  2627. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  2628. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  2629. var blob = new Blob([buffer]);
  2630. var blobURL = URL.createObjectURL(blob);
  2631. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  2632. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  2633. if (sampler.wrapS !== undefined) {
  2634. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  2635. }
  2636. if (sampler.wrapT !== undefined) {
  2637. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  2638. }
  2639. newTexture.name = id;
  2640. texture.babylonTexture = newTexture;
  2641. onSuccess(newTexture);
  2642. };
  2643. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2644. var shader = gltfRuntime.shaders[id];
  2645. if (BABYLON.Tools.IsBase64(shader.uri)) {
  2646. var shaderString = atob(shader.uri.split(",")[1]);
  2647. onSuccess(shaderString);
  2648. }
  2649. else {
  2650. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  2651. if (request) {
  2652. onError(request.status + " " + request.statusText);
  2653. }
  2654. });
  2655. }
  2656. };
  2657. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2658. var material = gltfRuntime.materials[id];
  2659. if (!material.technique) {
  2660. if (onError) {
  2661. onError("No technique found.");
  2662. }
  2663. return;
  2664. }
  2665. var technique = gltfRuntime.techniques[material.technique];
  2666. if (!technique) {
  2667. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  2668. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  2669. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2670. onSuccess(defaultMaterial);
  2671. return;
  2672. }
  2673. var program = gltfRuntime.programs[technique.program];
  2674. var states = technique.states;
  2675. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  2676. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  2677. var newVertexShader = "";
  2678. var newPixelShader = "";
  2679. var vertexTokenizer = new Tokenizer(vertexShader);
  2680. var pixelTokenizer = new Tokenizer(pixelShader);
  2681. var unTreatedUniforms = {};
  2682. var uniforms = [];
  2683. var attributes = [];
  2684. var samplers = [];
  2685. // Fill uniform, sampler2D and attributes
  2686. for (var unif in technique.uniforms) {
  2687. var uniform = technique.uniforms[unif];
  2688. var uniformParameter = technique.parameters[uniform];
  2689. unTreatedUniforms[unif] = uniformParameter;
  2690. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  2691. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  2692. if (transformIndex !== -1) {
  2693. uniforms.push(babylonTransforms[transformIndex]);
  2694. delete unTreatedUniforms[unif];
  2695. }
  2696. else {
  2697. uniforms.push(unif);
  2698. }
  2699. }
  2700. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  2701. samplers.push(unif);
  2702. }
  2703. else {
  2704. uniforms.push(unif);
  2705. }
  2706. }
  2707. for (var attr in technique.attributes) {
  2708. var attribute = technique.attributes[attr];
  2709. var attributeParameter = technique.parameters[attribute];
  2710. if (attributeParameter.semantic) {
  2711. attributes.push(getAttribute(attributeParameter));
  2712. }
  2713. }
  2714. // Configure vertex shader
  2715. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  2716. var tokenType = vertexTokenizer.currentToken;
  2717. if (tokenType !== ETokenType.IDENTIFIER) {
  2718. newVertexShader += vertexTokenizer.currentString;
  2719. continue;
  2720. }
  2721. var foundAttribute = false;
  2722. for (var attr in technique.attributes) {
  2723. var attribute = technique.attributes[attr];
  2724. var attributeParameter = technique.parameters[attribute];
  2725. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  2726. newVertexShader += getAttribute(attributeParameter);
  2727. foundAttribute = true;
  2728. break;
  2729. }
  2730. }
  2731. if (foundAttribute) {
  2732. continue;
  2733. }
  2734. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  2735. }
  2736. // Configure pixel shader
  2737. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  2738. var tokenType = pixelTokenizer.currentToken;
  2739. if (tokenType !== ETokenType.IDENTIFIER) {
  2740. newPixelShader += pixelTokenizer.currentString;
  2741. continue;
  2742. }
  2743. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  2744. }
  2745. // Create shader material
  2746. var shaderPath = {
  2747. vertex: program.vertexShader + id,
  2748. fragment: program.fragmentShader + id
  2749. };
  2750. var options = {
  2751. attributes: attributes,
  2752. uniforms: uniforms,
  2753. samplers: samplers,
  2754. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  2755. };
  2756. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  2757. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  2758. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  2759. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  2760. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  2761. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2762. if (states && states.functions) {
  2763. var functions = states.functions;
  2764. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  2765. shaderMaterial.backFaceCulling = false;
  2766. }
  2767. var blendFunc = functions.blendFuncSeparate;
  2768. if (blendFunc) {
  2769. 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) {
  2770. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  2771. }
  2772. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2773. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  2774. }
  2775. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2776. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  2777. }
  2778. 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) {
  2779. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  2780. }
  2781. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2782. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  2783. }
  2784. 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) {
  2785. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  2786. }
  2787. }
  2788. }
  2789. };
  2790. return GLTFLoaderBase;
  2791. }());
  2792. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  2793. /**
  2794. * glTF V1 Loader
  2795. */
  2796. var GLTFLoader = /** @class */ (function () {
  2797. function GLTFLoader() {
  2798. // #region Stubs for IGLTFLoader interface
  2799. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  2800. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  2801. this.compileMaterials = false;
  2802. this.useClipPlane = false;
  2803. this.compileShadowGenerators = false;
  2804. this.onDisposeObservable = new BABYLON.Observable();
  2805. this.onMeshLoadedObservable = new BABYLON.Observable();
  2806. this.onTextureLoadedObservable = new BABYLON.Observable();
  2807. this.onMaterialLoadedObservable = new BABYLON.Observable();
  2808. this.onCompleteObservable = new BABYLON.Observable();
  2809. this.onExtensionLoadedObservable = new BABYLON.Observable();
  2810. this.state = null;
  2811. }
  2812. GLTFLoader.RegisterExtension = function (extension) {
  2813. if (GLTFLoader.Extensions[extension.name]) {
  2814. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  2815. return;
  2816. }
  2817. GLTFLoader.Extensions[extension.name] = extension;
  2818. };
  2819. GLTFLoader.prototype.dispose = function () { };
  2820. // #endregion
  2821. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  2822. var _this = this;
  2823. scene.useRightHandedSystem = true;
  2824. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  2825. gltfRuntime.importOnlyMeshes = true;
  2826. if (meshesNames === "") {
  2827. gltfRuntime.importMeshesNames = [];
  2828. }
  2829. else if (typeof meshesNames === "string") {
  2830. gltfRuntime.importMeshesNames = [meshesNames];
  2831. }
  2832. else if (meshesNames && !(meshesNames instanceof Array)) {
  2833. gltfRuntime.importMeshesNames = [meshesNames];
  2834. }
  2835. else {
  2836. gltfRuntime.importMeshesNames = [];
  2837. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  2838. }
  2839. // Create nodes
  2840. _this._createNodes(gltfRuntime);
  2841. var meshes = new Array();
  2842. var skeletons = new Array();
  2843. // Fill arrays of meshes and skeletons
  2844. for (var nde in gltfRuntime.nodes) {
  2845. var node = gltfRuntime.nodes[nde];
  2846. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  2847. meshes.push(node.babylonNode);
  2848. }
  2849. }
  2850. for (var skl in gltfRuntime.skins) {
  2851. var skin = gltfRuntime.skins[skl];
  2852. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  2853. skeletons.push(skin.babylonSkeleton);
  2854. }
  2855. }
  2856. // Load buffers, shaders, materials, etc.
  2857. _this._loadBuffersAsync(gltfRuntime, function () {
  2858. _this._loadShadersAsync(gltfRuntime, function () {
  2859. importMaterials(gltfRuntime);
  2860. postLoad(gltfRuntime);
  2861. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  2862. onSuccess(meshes, [], skeletons);
  2863. }
  2864. });
  2865. }, onProgress);
  2866. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  2867. onSuccess(meshes, [], skeletons);
  2868. }
  2869. }, onError);
  2870. return true;
  2871. };
  2872. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  2873. var _this = this;
  2874. return new Promise(function (resolve, reject) {
  2875. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  2876. resolve({
  2877. meshes: meshes,
  2878. particleSystems: particleSystems,
  2879. skeletons: skeletons
  2880. });
  2881. }, onProgress, function (message) {
  2882. reject(new Error(message));
  2883. });
  2884. });
  2885. };
  2886. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  2887. var _this = this;
  2888. scene.useRightHandedSystem = true;
  2889. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  2890. // Load runtime extensios
  2891. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  2892. // Create nodes
  2893. _this._createNodes(gltfRuntime);
  2894. // Load buffers, shaders, materials, etc.
  2895. _this._loadBuffersAsync(gltfRuntime, function () {
  2896. _this._loadShadersAsync(gltfRuntime, function () {
  2897. importMaterials(gltfRuntime);
  2898. postLoad(gltfRuntime);
  2899. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  2900. onSuccess();
  2901. }
  2902. });
  2903. });
  2904. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  2905. onSuccess();
  2906. }
  2907. }, onError);
  2908. }, onError);
  2909. };
  2910. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  2911. var _this = this;
  2912. return new Promise(function (resolve, reject) {
  2913. _this._loadAsync(scene, data, rootUrl, function () {
  2914. resolve();
  2915. }, onProgress, function (message) {
  2916. reject(new Error(message));
  2917. });
  2918. });
  2919. };
  2920. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  2921. var hasShaders = false;
  2922. var processShader = function (sha, shader) {
  2923. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  2924. gltfRuntime.loadedShaderCount++;
  2925. if (shaderString) {
  2926. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  2927. }
  2928. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  2929. onload();
  2930. }
  2931. }, function () {
  2932. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  2933. });
  2934. };
  2935. for (var sha in gltfRuntime.shaders) {
  2936. hasShaders = true;
  2937. var shader = gltfRuntime.shaders[sha];
  2938. if (shader) {
  2939. processShader.bind(this, sha, shader)();
  2940. }
  2941. else {
  2942. BABYLON.Tools.Error("No shader named: " + sha);
  2943. }
  2944. }
  2945. if (!hasShaders) {
  2946. onload();
  2947. }
  2948. };
  2949. ;
  2950. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  2951. var hasBuffers = false;
  2952. var processBuffer = function (buf, buffer) {
  2953. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  2954. gltfRuntime.loadedBufferCount++;
  2955. if (bufferView) {
  2956. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  2957. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  2958. }
  2959. gltfRuntime.loadedBufferViews[buf] = bufferView;
  2960. }
  2961. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  2962. onLoad();
  2963. }
  2964. }, function () {
  2965. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  2966. });
  2967. };
  2968. for (var buf in gltfRuntime.buffers) {
  2969. hasBuffers = true;
  2970. var buffer = gltfRuntime.buffers[buf];
  2971. if (buffer) {
  2972. processBuffer.bind(this, buf, buffer)();
  2973. }
  2974. else {
  2975. BABYLON.Tools.Error("No buffer named: " + buf);
  2976. }
  2977. }
  2978. if (!hasBuffers) {
  2979. onLoad();
  2980. }
  2981. };
  2982. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  2983. var currentScene = gltfRuntime.currentScene;
  2984. if (currentScene) {
  2985. // Only one scene even if multiple scenes are defined
  2986. for (var i = 0; i < currentScene.nodes.length; i++) {
  2987. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2988. }
  2989. }
  2990. else {
  2991. // Load all scenes
  2992. for (var thing in gltfRuntime.scenes) {
  2993. currentScene = gltfRuntime.scenes[thing];
  2994. for (var i = 0; i < currentScene.nodes.length; i++) {
  2995. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2996. }
  2997. }
  2998. }
  2999. };
  3000. GLTFLoader.Extensions = {};
  3001. return GLTFLoader;
  3002. }());
  3003. GLTF1.GLTFLoader = GLTFLoader;
  3004. ;
  3005. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  3006. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  3007. })(BABYLON || (BABYLON = {}));
  3008. //# sourceMappingURL=babylon.glTFLoader.js.map
  3009. var BABYLON;
  3010. (function (BABYLON) {
  3011. var GLTF1;
  3012. (function (GLTF1) {
  3013. /**
  3014. * Utils functions for GLTF
  3015. */
  3016. var GLTFUtils = /** @class */ (function () {
  3017. function GLTFUtils() {
  3018. }
  3019. /**
  3020. * Sets the given "parameter" matrix
  3021. * @param scene: the {BABYLON.Scene} object
  3022. * @param source: the source node where to pick the matrix
  3023. * @param parameter: the GLTF technique parameter
  3024. * @param uniformName: the name of the shader's uniform
  3025. * @param shaderMaterial: the shader material
  3026. */
  3027. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  3028. var mat = null;
  3029. if (parameter.semantic === "MODEL") {
  3030. mat = source.getWorldMatrix();
  3031. }
  3032. else if (parameter.semantic === "PROJECTION") {
  3033. mat = scene.getProjectionMatrix();
  3034. }
  3035. else if (parameter.semantic === "VIEW") {
  3036. mat = scene.getViewMatrix();
  3037. }
  3038. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  3039. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  3040. }
  3041. else if (parameter.semantic === "MODELVIEW") {
  3042. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  3043. }
  3044. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  3045. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  3046. }
  3047. else if (parameter.semantic === "MODELINVERSE") {
  3048. mat = source.getWorldMatrix().invert();
  3049. }
  3050. else if (parameter.semantic === "VIEWINVERSE") {
  3051. mat = scene.getViewMatrix().invert();
  3052. }
  3053. else if (parameter.semantic === "PROJECTIONINVERSE") {
  3054. mat = scene.getProjectionMatrix().invert();
  3055. }
  3056. else if (parameter.semantic === "MODELVIEWINVERSE") {
  3057. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  3058. }
  3059. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  3060. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  3061. }
  3062. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  3063. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  3064. }
  3065. else {
  3066. debugger;
  3067. }
  3068. if (mat) {
  3069. switch (parameter.type) {
  3070. case GLTF1.EParameterType.FLOAT_MAT2:
  3071. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  3072. break;
  3073. case GLTF1.EParameterType.FLOAT_MAT3:
  3074. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  3075. break;
  3076. case GLTF1.EParameterType.FLOAT_MAT4:
  3077. shaderMaterial.setMatrix(uniformName, mat);
  3078. break;
  3079. default: break;
  3080. }
  3081. }
  3082. };
  3083. /**
  3084. * Sets the given "parameter" matrix
  3085. * @param shaderMaterial: the shader material
  3086. * @param uniform: the name of the shader's uniform
  3087. * @param value: the value of the uniform
  3088. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  3089. */
  3090. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  3091. switch (type) {
  3092. case GLTF1.EParameterType.FLOAT:
  3093. shaderMaterial.setFloat(uniform, value);
  3094. return true;
  3095. case GLTF1.EParameterType.FLOAT_VEC2:
  3096. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  3097. return true;
  3098. case GLTF1.EParameterType.FLOAT_VEC3:
  3099. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  3100. return true;
  3101. case GLTF1.EParameterType.FLOAT_VEC4:
  3102. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  3103. return true;
  3104. default: return false;
  3105. }
  3106. };
  3107. /**
  3108. * Returns the wrap mode of the texture
  3109. * @param mode: the mode value
  3110. */
  3111. GLTFUtils.GetWrapMode = function (mode) {
  3112. switch (mode) {
  3113. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  3114. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  3115. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  3116. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  3117. }
  3118. };
  3119. /**
  3120. * Returns the byte stride giving an accessor
  3121. * @param accessor: the GLTF accessor objet
  3122. */
  3123. GLTFUtils.GetByteStrideFromType = function (accessor) {
  3124. // Needs this function since "byteStride" isn't requiered in glTF format
  3125. var type = accessor.type;
  3126. switch (type) {
  3127. case "VEC2": return 2;
  3128. case "VEC3": return 3;
  3129. case "VEC4": return 4;
  3130. case "MAT2": return 4;
  3131. case "MAT3": return 9;
  3132. case "MAT4": return 16;
  3133. default: return 1;
  3134. }
  3135. };
  3136. /**
  3137. * Returns the texture filter mode giving a mode value
  3138. * @param mode: the filter mode value
  3139. */
  3140. GLTFUtils.GetTextureFilterMode = function (mode) {
  3141. switch (mode) {
  3142. case GLTF1.ETextureFilterType.LINEAR:
  3143. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  3144. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3145. case GLTF1.ETextureFilterType.NEAREST:
  3146. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  3147. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  3148. }
  3149. };
  3150. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  3151. var byteOffset = bufferView.byteOffset + byteOffset;
  3152. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  3153. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  3154. throw new Error("Buffer access is out of range");
  3155. }
  3156. var buffer = loadedBufferView.buffer;
  3157. byteOffset += loadedBufferView.byteOffset;
  3158. switch (componentType) {
  3159. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  3160. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  3161. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  3162. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  3163. default: return new Float32Array(buffer, byteOffset, byteLength);
  3164. }
  3165. };
  3166. /**
  3167. * Returns a buffer from its accessor
  3168. * @param gltfRuntime: the GLTF runtime
  3169. * @param accessor: the GLTF accessor
  3170. */
  3171. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  3172. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  3173. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  3174. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  3175. };
  3176. /**
  3177. * Decodes a buffer view into a string
  3178. * @param view: the buffer view
  3179. */
  3180. GLTFUtils.DecodeBufferToText = function (view) {
  3181. var result = "";
  3182. var length = view.byteLength;
  3183. for (var i = 0; i < length; ++i) {
  3184. result += String.fromCharCode(view[i]);
  3185. }
  3186. return result;
  3187. };
  3188. /**
  3189. * Returns the default material of gltf. Related to
  3190. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  3191. * @param scene: the Babylon.js scene
  3192. */
  3193. GLTFUtils.GetDefaultMaterial = function (scene) {
  3194. if (!GLTFUtils._DefaultMaterial) {
  3195. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  3196. "precision highp float;",
  3197. "",
  3198. "uniform mat4 worldView;",
  3199. "uniform mat4 projection;",
  3200. "",
  3201. "attribute vec3 position;",
  3202. "",
  3203. "void main(void)",
  3204. "{",
  3205. " gl_Position = projection * worldView * vec4(position, 1.0);",
  3206. "}"
  3207. ].join("\n");
  3208. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  3209. "precision highp float;",
  3210. "",
  3211. "uniform vec4 u_emission;",
  3212. "",
  3213. "void main(void)",
  3214. "{",
  3215. " gl_FragColor = u_emission;",
  3216. "}"
  3217. ].join("\n");
  3218. var shaderPath = {
  3219. vertex: "GLTFDefaultMaterial",
  3220. fragment: "GLTFDefaultMaterial"
  3221. };
  3222. var options = {
  3223. attributes: ["position"],
  3224. uniforms: ["worldView", "projection", "u_emission"],
  3225. samplers: new Array(),
  3226. needAlphaBlending: false
  3227. };
  3228. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  3229. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  3230. }
  3231. return GLTFUtils._DefaultMaterial;
  3232. };
  3233. // The GLTF default material
  3234. GLTFUtils._DefaultMaterial = null;
  3235. return GLTFUtils;
  3236. }());
  3237. GLTF1.GLTFUtils = GLTFUtils;
  3238. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  3239. })(BABYLON || (BABYLON = {}));
  3240. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  3241. var BABYLON;
  3242. (function (BABYLON) {
  3243. var GLTF1;
  3244. (function (GLTF1) {
  3245. var GLTFLoaderExtension = /** @class */ (function () {
  3246. function GLTFLoaderExtension(name) {
  3247. this._name = name;
  3248. }
  3249. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  3250. get: function () {
  3251. return this._name;
  3252. },
  3253. enumerable: true,
  3254. configurable: true
  3255. });
  3256. /**
  3257. * Defines an override for loading the runtime
  3258. * Return true to stop further extensions from loading the runtime
  3259. */
  3260. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  3261. return false;
  3262. };
  3263. /**
  3264. * Defines an onverride for creating gltf runtime
  3265. * Return true to stop further extensions from creating the runtime
  3266. */
  3267. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  3268. return false;
  3269. };
  3270. /**
  3271. * Defines an override for loading buffers
  3272. * Return true to stop further extensions from loading this buffer
  3273. */
  3274. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  3275. return false;
  3276. };
  3277. /**
  3278. * Defines an override for loading texture buffers
  3279. * Return true to stop further extensions from loading this texture data
  3280. */
  3281. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  3282. return false;
  3283. };
  3284. /**
  3285. * Defines an override for creating textures
  3286. * Return true to stop further extensions from loading this texture
  3287. */
  3288. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  3289. return false;
  3290. };
  3291. /**
  3292. * Defines an override for loading shader strings
  3293. * Return true to stop further extensions from loading this shader data
  3294. */
  3295. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  3296. return false;
  3297. };
  3298. /**
  3299. * Defines an override for loading materials
  3300. * Return true to stop further extensions from loading this material
  3301. */
  3302. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  3303. return false;
  3304. };
  3305. // ---------
  3306. // Utilities
  3307. // ---------
  3308. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  3309. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3310. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  3311. }, function () {
  3312. setTimeout(function () {
  3313. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  3314. });
  3315. });
  3316. };
  3317. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  3318. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3319. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  3320. }, function () {
  3321. setTimeout(function () {
  3322. onSuccess();
  3323. });
  3324. });
  3325. };
  3326. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  3327. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3328. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  3329. }, function () {
  3330. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  3331. });
  3332. };
  3333. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  3334. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  3335. };
  3336. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  3337. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3338. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  3339. }, function () {
  3340. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  3341. });
  3342. };
  3343. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  3344. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3345. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  3346. }, function () {
  3347. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  3348. });
  3349. };
  3350. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  3351. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3352. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  3353. }, function () {
  3354. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  3355. });
  3356. };
  3357. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  3358. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3359. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  3360. }, function () {
  3361. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  3362. });
  3363. };
  3364. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  3365. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  3366. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  3367. if (func(loaderExtension)) {
  3368. return;
  3369. }
  3370. }
  3371. defaultFunc();
  3372. };
  3373. return GLTFLoaderExtension;
  3374. }());
  3375. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  3376. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  3377. })(BABYLON || (BABYLON = {}));
  3378. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  3379. var BABYLON;
  3380. (function (BABYLON) {
  3381. var GLTF1;
  3382. (function (GLTF1) {
  3383. var BinaryExtensionBufferName = "binary_glTF";
  3384. ;
  3385. ;
  3386. var GLTFBinaryExtension = /** @class */ (function (_super) {
  3387. __extends(GLTFBinaryExtension, _super);
  3388. function GLTFBinaryExtension() {
  3389. return _super.call(this, "KHR_binary_glTF") || this;
  3390. }
  3391. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  3392. var extensionsUsed = data.json.extensionsUsed;
  3393. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  3394. return false;
  3395. }
  3396. this._bin = data.bin;
  3397. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  3398. return true;
  3399. };
  3400. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  3401. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  3402. return false;
  3403. }
  3404. if (id !== BinaryExtensionBufferName) {
  3405. return false;
  3406. }
  3407. onSuccess(this._bin);
  3408. return true;
  3409. };
  3410. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  3411. var texture = gltfRuntime.textures[id];
  3412. var source = gltfRuntime.images[texture.source];
  3413. if (!source.extensions || !(this.name in source.extensions)) {
  3414. return false;
  3415. }
  3416. var sourceExt = source.extensions[this.name];
  3417. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  3418. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  3419. onSuccess(buffer);
  3420. return true;
  3421. };
  3422. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  3423. var shader = gltfRuntime.shaders[id];
  3424. if (!shader.extensions || !(this.name in shader.extensions)) {
  3425. return false;
  3426. }
  3427. var binaryExtensionShader = shader.extensions[this.name];
  3428. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  3429. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  3430. setTimeout(function () {
  3431. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  3432. onSuccess(shaderString);
  3433. });
  3434. return true;
  3435. };
  3436. return GLTFBinaryExtension;
  3437. }(GLTF1.GLTFLoaderExtension));
  3438. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  3439. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  3440. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  3441. })(BABYLON || (BABYLON = {}));
  3442. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  3443. var BABYLON;
  3444. (function (BABYLON) {
  3445. var GLTF1;
  3446. (function (GLTF1) {
  3447. ;
  3448. ;
  3449. ;
  3450. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  3451. __extends(GLTFMaterialsCommonExtension, _super);
  3452. function GLTFMaterialsCommonExtension() {
  3453. return _super.call(this, "KHR_materials_common") || this;
  3454. }
  3455. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  3456. if (!gltfRuntime.extensions)
  3457. return false;
  3458. var extension = gltfRuntime.extensions[this.name];
  3459. if (!extension)
  3460. return false;
  3461. // Create lights
  3462. var lights = extension.lights;
  3463. if (lights) {
  3464. for (var thing in lights) {
  3465. var light = lights[thing];
  3466. switch (light.type) {
  3467. case "ambient":
  3468. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  3469. var ambient = light.ambient;
  3470. if (ambient) {
  3471. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  3472. }
  3473. break;
  3474. case "point":
  3475. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  3476. var point = light.point;
  3477. if (point) {
  3478. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  3479. }
  3480. break;
  3481. case "directional":
  3482. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  3483. var directional = light.directional;
  3484. if (directional) {
  3485. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  3486. }
  3487. break;
  3488. case "spot":
  3489. var spot = light.spot;
  3490. if (spot) {
  3491. 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);
  3492. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  3493. }
  3494. break;
  3495. default:
  3496. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  3497. break;
  3498. }
  3499. }
  3500. }
  3501. return false;
  3502. };
  3503. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  3504. var material = gltfRuntime.materials[id];
  3505. if (!material || !material.extensions)
  3506. return false;
  3507. var extension = material.extensions[this.name];
  3508. if (!extension)
  3509. return false;
  3510. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  3511. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  3512. if (extension.technique === "CONSTANT") {
  3513. standardMaterial.disableLighting = true;
  3514. }
  3515. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  3516. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  3517. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  3518. // Ambient
  3519. if (typeof extension.values.ambient === "string") {
  3520. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  3521. }
  3522. else {
  3523. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  3524. }
  3525. // Diffuse
  3526. if (typeof extension.values.diffuse === "string") {
  3527. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  3528. }
  3529. else {
  3530. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  3531. }
  3532. // Emission
  3533. if (typeof extension.values.emission === "string") {
  3534. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  3535. }
  3536. else {
  3537. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  3538. }
  3539. // Specular
  3540. if (typeof extension.values.specular === "string") {
  3541. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  3542. }
  3543. else {
  3544. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  3545. }
  3546. return true;
  3547. };
  3548. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  3549. // Create buffer from texture url
  3550. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  3551. // Create texture from buffer
  3552. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  3553. }, onError);
  3554. };
  3555. return GLTFMaterialsCommonExtension;
  3556. }(GLTF1.GLTFLoaderExtension));
  3557. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  3558. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  3559. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  3560. })(BABYLON || (BABYLON = {}));
  3561. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  3562. var BABYLON;
  3563. (function (BABYLON) {
  3564. var GLTF2;
  3565. (function (GLTF2) {
  3566. var ArrayItem = /** @class */ (function () {
  3567. function ArrayItem() {
  3568. }
  3569. ArrayItem.Assign = function (values) {
  3570. if (values) {
  3571. for (var index = 0; index < values.length; index++) {
  3572. values[index]._index = index;
  3573. }
  3574. }
  3575. };
  3576. return ArrayItem;
  3577. }());
  3578. GLTF2.ArrayItem = ArrayItem;
  3579. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3580. })(BABYLON || (BABYLON = {}));
  3581. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  3582. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  3583. var BABYLON;
  3584. (function (BABYLON) {
  3585. var GLTF2;
  3586. (function (GLTF2) {
  3587. var GLTFLoader = /** @class */ (function () {
  3588. function GLTFLoader() {
  3589. this._completePromises = new Array();
  3590. this._disposed = false;
  3591. this._state = null;
  3592. this._extensions = {};
  3593. this._defaultSampler = {};
  3594. this._requests = new Array();
  3595. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  3596. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  3597. this.compileMaterials = false;
  3598. this.useClipPlane = false;
  3599. this.compileShadowGenerators = false;
  3600. this.onDisposeObservable = new BABYLON.Observable();
  3601. this.onMeshLoadedObservable = new BABYLON.Observable();
  3602. this.onTextureLoadedObservable = new BABYLON.Observable();
  3603. this.onMaterialLoadedObservable = new BABYLON.Observable();
  3604. this.onExtensionLoadedObservable = new BABYLON.Observable();
  3605. this.onCompleteObservable = new BABYLON.Observable();
  3606. }
  3607. GLTFLoader._Register = function (name, factory) {
  3608. if (GLTFLoader._Factories[name]) {
  3609. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  3610. return;
  3611. }
  3612. GLTFLoader._Factories[name] = factory;
  3613. // Keep the order of registration so that extensions registered first are called first.
  3614. GLTFLoader._Names.push(name);
  3615. };
  3616. Object.defineProperty(GLTFLoader.prototype, "state", {
  3617. get: function () {
  3618. return this._state;
  3619. },
  3620. enumerable: true,
  3621. configurable: true
  3622. });
  3623. GLTFLoader.prototype.dispose = function () {
  3624. if (this._disposed) {
  3625. return;
  3626. }
  3627. this._disposed = true;
  3628. this._abortRequests();
  3629. this._releaseResources();
  3630. this.onDisposeObservable.notifyObservers(this);
  3631. };
  3632. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  3633. var _this = this;
  3634. return Promise.resolve().then(function () {
  3635. var nodes = null;
  3636. if (meshesNames) {
  3637. var nodeMap_1 = {};
  3638. if (_this._gltf.nodes) {
  3639. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  3640. var node = _a[_i];
  3641. if (node.name) {
  3642. nodeMap_1[node.name] = node;
  3643. }
  3644. }
  3645. }
  3646. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  3647. nodes = names.map(function (name) {
  3648. var node = nodeMap_1[name];
  3649. if (!node) {
  3650. throw new Error("Failed to find node " + name);
  3651. }
  3652. return node;
  3653. });
  3654. }
  3655. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  3656. return {
  3657. meshes: _this._getMeshes(),
  3658. particleSystems: [],
  3659. skeletons: _this._getSkeletons(),
  3660. };
  3661. });
  3662. });
  3663. };
  3664. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  3665. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  3666. };
  3667. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  3668. var _this = this;
  3669. return Promise.resolve().then(function () {
  3670. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  3671. var name_1 = _a[_i];
  3672. var extension = GLTFLoader._Factories[name_1](_this);
  3673. _this._extensions[name_1] = extension;
  3674. _this.onExtensionLoadedObservable.notifyObservers(extension);
  3675. }
  3676. _this._babylonScene = scene;
  3677. _this._rootUrl = rootUrl;
  3678. _this._progressCallback = onProgress;
  3679. _this._state = BABYLON.GLTFLoaderState.Loading;
  3680. _this._loadData(data);
  3681. var promises = new Array();
  3682. if (nodes) {
  3683. promises.push(_this._loadNodesAsync(nodes));
  3684. }
  3685. else {
  3686. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  3687. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  3688. }
  3689. if (_this.compileMaterials) {
  3690. promises.push(_this._compileMaterialsAsync());
  3691. }
  3692. if (_this.compileShadowGenerators) {
  3693. promises.push(_this._compileShadowGeneratorsAsync());
  3694. }
  3695. return Promise.all(promises).then(function () {
  3696. _this._state = BABYLON.GLTFLoaderState.Ready;
  3697. _this._startAnimations();
  3698. BABYLON.Tools.SetImmediate(function () {
  3699. if (!_this._disposed) {
  3700. Promise.all(_this._completePromises).then(function () {
  3701. _this._releaseResources();
  3702. _this._state = BABYLON.GLTFLoaderState.Complete;
  3703. _this.onCompleteObservable.notifyObservers(_this);
  3704. }).catch(function (error) {
  3705. BABYLON.Tools.Error("glTF Loader: " + error.message);
  3706. _this.dispose();
  3707. });
  3708. }
  3709. });
  3710. });
  3711. }).catch(function (error) {
  3712. BABYLON.Tools.Error("glTF Loader: " + error.message);
  3713. _this.dispose();
  3714. throw error;
  3715. });
  3716. };
  3717. GLTFLoader.prototype._loadData = function (data) {
  3718. this._gltf = data.json;
  3719. this._setupData();
  3720. if (data.bin) {
  3721. var buffers = this._gltf.buffers;
  3722. if (buffers && buffers[0] && !buffers[0].uri) {
  3723. var binaryBuffer = buffers[0];
  3724. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  3725. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  3726. }
  3727. binaryBuffer._data = Promise.resolve(data.bin);
  3728. }
  3729. else {
  3730. BABYLON.Tools.Warn("Unexpected BIN chunk");
  3731. }
  3732. }
  3733. };
  3734. GLTFLoader.prototype._setupData = function () {
  3735. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  3736. GLTF2.ArrayItem.Assign(this._gltf.animations);
  3737. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  3738. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  3739. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  3740. GLTF2.ArrayItem.Assign(this._gltf.images);
  3741. GLTF2.ArrayItem.Assign(this._gltf.materials);
  3742. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  3743. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  3744. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  3745. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  3746. GLTF2.ArrayItem.Assign(this._gltf.skins);
  3747. GLTF2.ArrayItem.Assign(this._gltf.textures);
  3748. if (this._gltf.nodes) {
  3749. var nodeParents = {};
  3750. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  3751. var node = _a[_i];
  3752. if (node.children) {
  3753. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  3754. var index = _c[_b];
  3755. nodeParents[index] = node._index;
  3756. }
  3757. }
  3758. }
  3759. var rootNode = this._createRootNode();
  3760. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  3761. var node = _e[_d];
  3762. var parentIndex = nodeParents[node._index];
  3763. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  3764. }
  3765. }
  3766. };
  3767. GLTFLoader.prototype._createRootNode = function () {
  3768. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  3769. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  3770. switch (this.coordinateSystemMode) {
  3771. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  3772. if (!this._babylonScene.useRightHandedSystem) {
  3773. rootNode.rotation = [0, 1, 0, 0];
  3774. rootNode.scale = [1, 1, -1];
  3775. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  3776. }
  3777. break;
  3778. }
  3779. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  3780. this._babylonScene.useRightHandedSystem = true;
  3781. break;
  3782. }
  3783. default: {
  3784. throw new Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  3785. }
  3786. }
  3787. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  3788. return rootNode;
  3789. };
  3790. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  3791. var promises = new Array();
  3792. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  3793. var node = nodes_1[_i];
  3794. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  3795. }
  3796. promises.push(this._loadAnimationsAsync());
  3797. return Promise.all(promises).then(function () { });
  3798. };
  3799. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  3800. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  3801. if (promise) {
  3802. return promise;
  3803. }
  3804. var promises = new Array();
  3805. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  3806. var index = _a[_i];
  3807. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  3808. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  3809. }
  3810. promises.push(this._loadAnimationsAsync());
  3811. return Promise.all(promises).then(function () { });
  3812. };
  3813. GLTFLoader.prototype._getMeshes = function () {
  3814. var meshes = new Array();
  3815. // Root mesh is always first.
  3816. meshes.push(this._rootBabylonMesh);
  3817. var nodes = this._gltf.nodes;
  3818. if (nodes) {
  3819. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  3820. var node = nodes_2[_i];
  3821. if (node._babylonMesh) {
  3822. meshes.push(node._babylonMesh);
  3823. }
  3824. }
  3825. }
  3826. return meshes;
  3827. };
  3828. GLTFLoader.prototype._getSkeletons = function () {
  3829. var skeletons = new Array();
  3830. var skins = this._gltf.skins;
  3831. if (skins) {
  3832. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  3833. var skin = skins_1[_i];
  3834. if (skin._babylonSkeleton) {
  3835. skeletons.push(skin._babylonSkeleton);
  3836. }
  3837. }
  3838. }
  3839. return skeletons;
  3840. };
  3841. GLTFLoader.prototype._startAnimations = function () {
  3842. var animations = this._gltf.animations;
  3843. if (!animations) {
  3844. return;
  3845. }
  3846. switch (this.animationStartMode) {
  3847. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  3848. // do nothing
  3849. break;
  3850. }
  3851. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  3852. var animation = animations[0];
  3853. animation._babylonAnimationGroup.start(true);
  3854. break;
  3855. }
  3856. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  3857. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  3858. var animation = animations_1[_i];
  3859. animation._babylonAnimationGroup.start(true);
  3860. }
  3861. break;
  3862. }
  3863. default: {
  3864. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  3865. return;
  3866. }
  3867. }
  3868. };
  3869. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  3870. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  3871. if (promise) {
  3872. return promise;
  3873. }
  3874. if (node._babylonMesh) {
  3875. throw new Error(context + ": Invalid recursive node hierarchy");
  3876. }
  3877. var promises = new Array();
  3878. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  3879. node._babylonMesh = babylonMesh;
  3880. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  3881. node._babylonAnimationTargets.push(babylonMesh);
  3882. GLTFLoader._LoadTransform(node, babylonMesh);
  3883. if (node.mesh != undefined) {
  3884. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  3885. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh));
  3886. }
  3887. if (node.children) {
  3888. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  3889. var index = _a[_i];
  3890. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  3891. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  3892. }
  3893. }
  3894. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  3895. return Promise.all(promises).then(function () { });
  3896. };
  3897. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh) {
  3898. // TODO: instancing
  3899. var promises = new Array();
  3900. var primitives = mesh.primitives;
  3901. if (!primitives || primitives.length === 0) {
  3902. throw new Error(context + ": Primitives are missing");
  3903. }
  3904. GLTF2.ArrayItem.Assign(primitives);
  3905. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  3906. var primitive = primitives_1[_i];
  3907. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive));
  3908. }
  3909. if (node.skin != undefined) {
  3910. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  3911. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  3912. }
  3913. return Promise.all(promises).then(function () {
  3914. if (node._primitiveBabylonMeshes) {
  3915. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  3916. var primitiveBabylonMesh = _a[_i];
  3917. primitiveBabylonMesh._refreshBoundingInfo(true);
  3918. }
  3919. }
  3920. });
  3921. };
  3922. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive) {
  3923. var _this = this;
  3924. var promises = new Array();
  3925. var babylonMesh = new BABYLON.Mesh((mesh.name || node._babylonMesh.name) + "_" + primitive._index, this._babylonScene, node._babylonMesh);
  3926. babylonMesh.setEnabled(false);
  3927. node._primitiveBabylonMeshes = node._primitiveBabylonMeshes || [];
  3928. node._primitiveBabylonMeshes[primitive._index] = babylonMesh;
  3929. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  3930. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  3931. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  3932. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  3933. }));
  3934. if (primitive.material == undefined) {
  3935. babylonMesh.material = this._getDefaultMaterial();
  3936. }
  3937. else {
  3938. var material = GLTFLoader._GetProperty(context + "/material", this._gltf.materials, primitive.material);
  3939. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh));
  3940. }
  3941. return Promise.all(promises).then(function () {
  3942. babylonMesh.setEnabled(true);
  3943. });
  3944. };
  3945. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  3946. var _this = this;
  3947. var attributes = primitive.attributes;
  3948. if (!attributes) {
  3949. throw new Error(context + ": Attributes are missing");
  3950. }
  3951. if (primitive.mode && primitive.mode !== 4 /* TRIANGLES */) {
  3952. // TODO: handle other primitive modes
  3953. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  3954. }
  3955. var promises = new Array();
  3956. var babylonVertexData = new BABYLON.VertexData();
  3957. if (primitive.indices == undefined) {
  3958. var positionAccessorIndex = attributes["POSITION"];
  3959. if (positionAccessorIndex != undefined) {
  3960. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  3961. babylonVertexData.indices = new Uint32Array(accessor.count);
  3962. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  3963. babylonVertexData.indices[i] = i;
  3964. }
  3965. }
  3966. }
  3967. else {
  3968. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  3969. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  3970. babylonVertexData.indices = data;
  3971. }));
  3972. }
  3973. var loadAttribute = function (attribute, kind) {
  3974. if (attributes[attribute] == undefined) {
  3975. return;
  3976. }
  3977. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  3978. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  3979. babylonMesh._delayInfo.push(kind);
  3980. }
  3981. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  3982. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  3983. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  3984. if (attribute === "COLOR_0") {
  3985. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  3986. babylonMesh.hasVertexAlpha = true;
  3987. if (accessor.type === "VEC3") {
  3988. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  3989. }
  3990. }
  3991. babylonVertexData.set(attributeData, kind);
  3992. }));
  3993. };
  3994. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  3995. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  3996. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  3997. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  3998. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  3999. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  4000. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  4001. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  4002. return Promise.all(promises).then(function () {
  4003. return babylonVertexData;
  4004. });
  4005. };
  4006. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  4007. if (!primitive.targets) {
  4008. return;
  4009. }
  4010. if (node._numMorphTargets == undefined) {
  4011. node._numMorphTargets = primitive.targets.length;
  4012. }
  4013. else if (primitive.targets.length !== node._numMorphTargets) {
  4014. throw new Error(context + ": Primitives do not have the same number of targets");
  4015. }
  4016. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  4017. for (var index = 0; index < primitive.targets.length; index++) {
  4018. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  4019. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  4020. // TODO: tell the target whether it has positions, normals, tangents
  4021. }
  4022. };
  4023. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  4024. if (!primitive.targets) {
  4025. return Promise.resolve();
  4026. }
  4027. var promises = new Array();
  4028. var morphTargetManager = babylonMesh.morphTargetManager;
  4029. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  4030. var babylonMorphTarget = morphTargetManager.getTarget(index);
  4031. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  4032. }
  4033. return Promise.all(promises).then(function () { });
  4034. };
  4035. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  4036. var _this = this;
  4037. var promises = new Array();
  4038. var loadAttribute = function (attribute, setData) {
  4039. if (attributes[attribute] == undefined) {
  4040. return;
  4041. }
  4042. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  4043. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  4044. setData(data);
  4045. }));
  4046. };
  4047. loadAttribute("POSITION", function (data) {
  4048. if (babylonVertexData.positions) {
  4049. for (var i = 0; i < data.length; i++) {
  4050. data[i] += babylonVertexData.positions[i];
  4051. }
  4052. babylonMorphTarget.setPositions(data);
  4053. }
  4054. });
  4055. loadAttribute("NORMAL", function (data) {
  4056. if (babylonVertexData.normals) {
  4057. for (var i = 0; i < data.length; i++) {
  4058. data[i] += babylonVertexData.normals[i];
  4059. }
  4060. babylonMorphTarget.setNormals(data);
  4061. }
  4062. });
  4063. loadAttribute("TANGENT", function (data) {
  4064. if (babylonVertexData.tangents) {
  4065. // Tangent data for morph targets is stored as xyz delta.
  4066. // The vertexData.tangent is stored as xyzw.
  4067. // So we need to skip every fourth vertexData.tangent.
  4068. for (var i = 0, j = 0; i < data.length; i++) {
  4069. data[i] += babylonVertexData.tangents[j++];
  4070. if ((i + 1) % 3 == 0) {
  4071. j++;
  4072. }
  4073. }
  4074. babylonMorphTarget.setTangents(data);
  4075. }
  4076. });
  4077. return Promise.all(promises).then(function () { });
  4078. };
  4079. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  4080. if (accessor.componentType == 5126 /* FLOAT */) {
  4081. return data;
  4082. }
  4083. var factor = 1;
  4084. if (accessor.normalized) {
  4085. switch (accessor.componentType) {
  4086. case 5121 /* UNSIGNED_BYTE */: {
  4087. factor = 1 / 255;
  4088. break;
  4089. }
  4090. case 5123 /* UNSIGNED_SHORT */: {
  4091. factor = 1 / 65535;
  4092. break;
  4093. }
  4094. default: {
  4095. throw new Error(context + ": Invalid component type " + accessor.componentType);
  4096. }
  4097. }
  4098. }
  4099. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  4100. for (var i = 0; i < result.length; i++) {
  4101. result[i] = data[i] * factor;
  4102. }
  4103. return result;
  4104. };
  4105. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  4106. var result = new Float32Array(data.length / 3 * 4);
  4107. var offset = 0;
  4108. for (var i = 0; i < result.length; i++) {
  4109. if ((i + 1) % 4 === 0) {
  4110. result[i] = 1;
  4111. }
  4112. else {
  4113. result[i] = data[offset++];
  4114. }
  4115. }
  4116. return result;
  4117. };
  4118. GLTFLoader._LoadTransform = function (node, babylonNode) {
  4119. var position = BABYLON.Vector3.Zero();
  4120. var rotation = BABYLON.Quaternion.Identity();
  4121. var scaling = BABYLON.Vector3.One();
  4122. if (node.matrix) {
  4123. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  4124. matrix.decompose(scaling, rotation, position);
  4125. }
  4126. else {
  4127. if (node.translation)
  4128. position = BABYLON.Vector3.FromArray(node.translation);
  4129. if (node.rotation)
  4130. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  4131. if (node.scale)
  4132. scaling = BABYLON.Vector3.FromArray(node.scale);
  4133. }
  4134. babylonNode.position = position;
  4135. babylonNode.rotationQuaternion = rotation;
  4136. babylonNode.scaling = scaling;
  4137. };
  4138. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  4139. var _this = this;
  4140. var assignSkeleton = function () {
  4141. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  4142. var babylonMesh = _a[_i];
  4143. babylonMesh.skeleton = skin._babylonSkeleton;
  4144. }
  4145. node._babylonMesh.parent = _this._rootBabylonMesh;
  4146. node._babylonMesh.position = BABYLON.Vector3.Zero();
  4147. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  4148. node._babylonMesh.scaling = BABYLON.Vector3.One();
  4149. };
  4150. if (skin._loaded) {
  4151. assignSkeleton();
  4152. return skin._loaded;
  4153. }
  4154. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  4155. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  4156. var skeletonId = "skeleton" + skin._index;
  4157. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  4158. skin._babylonSkeleton = babylonSkeleton;
  4159. _this._loadBones(context, skin, inverseBindMatricesData);
  4160. assignSkeleton();
  4161. }));
  4162. };
  4163. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  4164. if (skin.inverseBindMatrices == undefined) {
  4165. return Promise.resolve(null);
  4166. }
  4167. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  4168. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  4169. return data;
  4170. });
  4171. };
  4172. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  4173. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  4174. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  4175. node._babylonAnimationTargets.push(babylonBone);
  4176. return babylonBone;
  4177. };
  4178. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  4179. var babylonBones = {};
  4180. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  4181. var index = _a[_i];
  4182. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  4183. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  4184. }
  4185. };
  4186. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  4187. var babylonBone = babylonBones[node._index];
  4188. if (babylonBone) {
  4189. return babylonBone;
  4190. }
  4191. var boneIndex = skin.joints.indexOf(node._index);
  4192. var baseMatrix = BABYLON.Matrix.Identity();
  4193. if (inverseBindMatricesData && boneIndex !== -1) {
  4194. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  4195. baseMatrix.invertToRef(baseMatrix);
  4196. }
  4197. var babylonParentBone = null;
  4198. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  4199. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  4200. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  4201. }
  4202. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  4203. babylonBones[node._index] = babylonBone;
  4204. return babylonBone;
  4205. };
  4206. GLTFLoader.prototype._getNodeMatrix = function (node) {
  4207. return node.matrix ?
  4208. BABYLON.Matrix.FromArray(node.matrix) :
  4209. 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());
  4210. };
  4211. GLTFLoader.prototype._loadAnimationsAsync = function () {
  4212. var animations = this._gltf.animations;
  4213. if (!animations) {
  4214. return Promise.resolve();
  4215. }
  4216. var promises = new Array();
  4217. for (var index = 0; index < animations.length; index++) {
  4218. var animation = animations[index];
  4219. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  4220. }
  4221. return Promise.all(promises).then(function () { });
  4222. };
  4223. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  4224. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  4225. animation._babylonAnimationGroup = babylonAnimationGroup;
  4226. var promises = new Array();
  4227. GLTF2.ArrayItem.Assign(animation.channels);
  4228. GLTF2.ArrayItem.Assign(animation.samplers);
  4229. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  4230. var channel = _a[_i];
  4231. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  4232. }
  4233. return Promise.all(promises).then(function () {
  4234. babylonAnimationGroup.normalize();
  4235. });
  4236. };
  4237. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  4238. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  4239. if (!targetNode._babylonMesh) {
  4240. return Promise.resolve();
  4241. }
  4242. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  4243. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  4244. var targetPath;
  4245. var animationType;
  4246. switch (channel.target.path) {
  4247. case "translation" /* TRANSLATION */: {
  4248. targetPath = "position";
  4249. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  4250. break;
  4251. }
  4252. case "rotation" /* ROTATION */: {
  4253. targetPath = "rotationQuaternion";
  4254. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  4255. break;
  4256. }
  4257. case "scale" /* SCALE */: {
  4258. targetPath = "scaling";
  4259. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  4260. break;
  4261. }
  4262. case "weights" /* WEIGHTS */: {
  4263. targetPath = "influence";
  4264. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  4265. break;
  4266. }
  4267. default: {
  4268. throw new Error(context + ": Invalid target path " + channel.target.path);
  4269. }
  4270. }
  4271. var outputBufferOffset = 0;
  4272. var getNextOutputValue;
  4273. switch (targetPath) {
  4274. case "position": {
  4275. getNextOutputValue = function () {
  4276. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  4277. outputBufferOffset += 3;
  4278. return value;
  4279. };
  4280. break;
  4281. }
  4282. case "rotationQuaternion": {
  4283. getNextOutputValue = function () {
  4284. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  4285. outputBufferOffset += 4;
  4286. return value;
  4287. };
  4288. break;
  4289. }
  4290. case "scaling": {
  4291. getNextOutputValue = function () {
  4292. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  4293. outputBufferOffset += 3;
  4294. return value;
  4295. };
  4296. break;
  4297. }
  4298. case "influence": {
  4299. getNextOutputValue = function () {
  4300. var value = new Array(targetNode._numMorphTargets);
  4301. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  4302. value[i] = data.output[outputBufferOffset++];
  4303. }
  4304. return value;
  4305. };
  4306. break;
  4307. }
  4308. }
  4309. var getNextKey;
  4310. switch (data.interpolation) {
  4311. case "STEP" /* STEP */: {
  4312. getNextKey = function (frameIndex) { return ({
  4313. frame: data.input[frameIndex],
  4314. value: getNextOutputValue(),
  4315. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  4316. }); };
  4317. break;
  4318. }
  4319. case "LINEAR" /* LINEAR */: {
  4320. getNextKey = function (frameIndex) { return ({
  4321. frame: data.input[frameIndex],
  4322. value: getNextOutputValue()
  4323. }); };
  4324. break;
  4325. }
  4326. case "CUBICSPLINE" /* CUBICSPLINE */: {
  4327. getNextKey = function (frameIndex) { return ({
  4328. frame: data.input[frameIndex],
  4329. inTangent: getNextOutputValue(),
  4330. value: getNextOutputValue(),
  4331. outTangent: getNextOutputValue()
  4332. }); };
  4333. break;
  4334. }
  4335. }
  4336. var keys;
  4337. if (data.input.length === 1) {
  4338. var key = getNextKey(0);
  4339. keys = [
  4340. { frame: key.frame, value: key.value },
  4341. { frame: key.frame + 1, value: key.value }
  4342. ];
  4343. }
  4344. else {
  4345. keys = new Array(data.input.length);
  4346. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  4347. keys[frameIndex] = getNextKey(frameIndex);
  4348. }
  4349. }
  4350. if (targetPath === "influence") {
  4351. var _loop_1 = function (targetIndex) {
  4352. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  4353. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  4354. babylonAnimation.setKeys(keys.map(function (key) { return ({
  4355. frame: key.frame,
  4356. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  4357. value: key.value[targetIndex],
  4358. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  4359. }); }));
  4360. for (var _i = 0, _a = targetNode._primitiveBabylonMeshes; _i < _a.length; _i++) {
  4361. var babylonMesh = _a[_i];
  4362. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  4363. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  4364. }
  4365. };
  4366. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  4367. _loop_1(targetIndex);
  4368. }
  4369. }
  4370. else {
  4371. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  4372. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  4373. babylonAnimation.setKeys(keys);
  4374. if (targetNode._babylonAnimationTargets) {
  4375. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  4376. var target = _a[_i];
  4377. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  4378. }
  4379. }
  4380. }
  4381. });
  4382. };
  4383. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  4384. if (sampler._data) {
  4385. return sampler._data;
  4386. }
  4387. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  4388. switch (interpolation) {
  4389. case "STEP" /* STEP */:
  4390. case "LINEAR" /* LINEAR */:
  4391. case "CUBICSPLINE" /* CUBICSPLINE */: {
  4392. break;
  4393. }
  4394. default: {
  4395. throw new Error(context + ": Invalid interpolation " + sampler.interpolation);
  4396. }
  4397. }
  4398. var inputData;
  4399. var outputData;
  4400. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  4401. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  4402. sampler._data = Promise.all([
  4403. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  4404. inputData = data;
  4405. }),
  4406. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  4407. outputData = data;
  4408. })
  4409. ]).then(function () {
  4410. return {
  4411. input: inputData,
  4412. interpolation: interpolation,
  4413. output: outputData,
  4414. };
  4415. });
  4416. return sampler._data;
  4417. };
  4418. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  4419. if (buffer._data) {
  4420. return buffer._data;
  4421. }
  4422. if (!buffer.uri) {
  4423. throw new Error(context + ": Uri is missing");
  4424. }
  4425. buffer._data = this._loadUriAsync(context, buffer.uri);
  4426. return buffer._data;
  4427. };
  4428. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  4429. if (bufferView._data) {
  4430. return bufferView._data;
  4431. }
  4432. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  4433. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  4434. try {
  4435. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  4436. }
  4437. catch (e) {
  4438. throw new Error(context + ": " + e.message);
  4439. }
  4440. });
  4441. return bufferView._data;
  4442. };
  4443. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  4444. var _this = this;
  4445. if (accessor.sparse) {
  4446. throw new Error(context + ": Sparse accessors are not currently supported");
  4447. }
  4448. if (accessor._data) {
  4449. return accessor._data;
  4450. }
  4451. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  4452. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  4453. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  4454. var byteOffset = accessor.byteOffset || 0;
  4455. var byteStride = bufferView.byteStride;
  4456. if (byteStride === 0) {
  4457. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  4458. }
  4459. try {
  4460. switch (accessor.componentType) {
  4461. case 5120 /* BYTE */: {
  4462. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  4463. }
  4464. case 5121 /* UNSIGNED_BYTE */: {
  4465. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  4466. }
  4467. case 5122 /* SHORT */: {
  4468. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  4469. }
  4470. case 5123 /* UNSIGNED_SHORT */: {
  4471. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  4472. }
  4473. case 5125 /* UNSIGNED_INT */: {
  4474. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  4475. }
  4476. case 5126 /* FLOAT */: {
  4477. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  4478. }
  4479. default: {
  4480. throw new Error(context + ": Invalid component type " + accessor.componentType);
  4481. }
  4482. }
  4483. }
  4484. catch (e) {
  4485. throw new Error(context + ": " + e);
  4486. }
  4487. });
  4488. return accessor._data;
  4489. };
  4490. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  4491. byteOffset += data.byteOffset;
  4492. var targetLength = count * numComponents;
  4493. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  4494. return new typedArray(data.buffer, byteOffset, targetLength);
  4495. }
  4496. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  4497. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  4498. var targetBuffer = new typedArray(targetLength);
  4499. var sourceIndex = 0;
  4500. var targetIndex = 0;
  4501. while (targetIndex < targetLength) {
  4502. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  4503. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  4504. targetIndex++;
  4505. }
  4506. sourceIndex += elementStride;
  4507. }
  4508. return targetBuffer;
  4509. };
  4510. GLTFLoader.prototype._getDefaultMaterial = function () {
  4511. var id = "__gltf_default";
  4512. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  4513. if (!babylonMaterial) {
  4514. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  4515. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  4516. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  4517. babylonMaterial.metallic = 1;
  4518. babylonMaterial.roughness = 1;
  4519. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  4520. }
  4521. return babylonMaterial;
  4522. };
  4523. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  4524. var promises = new Array();
  4525. var babylonMaterial = material._babylonMaterial;
  4526. // Ensure metallic workflow
  4527. babylonMaterial.metallic = 1;
  4528. babylonMaterial.roughness = 1;
  4529. var properties = material.pbrMetallicRoughness;
  4530. if (properties) {
  4531. if (properties.baseColorFactor) {
  4532. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  4533. babylonMaterial.alpha = properties.baseColorFactor[3];
  4534. }
  4535. else {
  4536. babylonMaterial.albedoColor = BABYLON.Color3.White();
  4537. }
  4538. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  4539. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  4540. if (properties.baseColorTexture) {
  4541. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  4542. babylonMaterial.albedoTexture = texture;
  4543. }));
  4544. }
  4545. if (properties.metallicRoughnessTexture) {
  4546. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  4547. babylonMaterial.metallicTexture = texture;
  4548. }));
  4549. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  4550. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  4551. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  4552. }
  4553. }
  4554. this._loadMaterialAlphaProperties(context, material);
  4555. return Promise.all(promises).then(function () { });
  4556. };
  4557. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  4558. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh);
  4559. if (promise) {
  4560. return promise;
  4561. }
  4562. material._babylonMeshes = material._babylonMeshes || [];
  4563. material._babylonMeshes.push(babylonMesh);
  4564. if (material._loaded) {
  4565. babylonMesh.material = material._babylonMaterial;
  4566. return material._loaded;
  4567. }
  4568. var promises = new Array();
  4569. var babylonMaterial = this._createMaterial(material);
  4570. material._babylonMaterial = babylonMaterial;
  4571. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  4572. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  4573. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  4574. babylonMesh.material = babylonMaterial;
  4575. return (material._loaded = Promise.all(promises).then(function () { }));
  4576. };
  4577. GLTFLoader.prototype._createMaterial = function (material) {
  4578. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  4579. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  4580. return babylonMaterial;
  4581. };
  4582. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  4583. var promises = new Array();
  4584. var babylonMaterial = material._babylonMaterial;
  4585. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  4586. if (material.doubleSided) {
  4587. babylonMaterial.backFaceCulling = false;
  4588. babylonMaterial.twoSidedLighting = true;
  4589. }
  4590. if (material.normalTexture) {
  4591. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  4592. babylonMaterial.bumpTexture = texture;
  4593. }));
  4594. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  4595. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  4596. if (material.normalTexture.scale != undefined) {
  4597. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  4598. }
  4599. }
  4600. if (material.occlusionTexture) {
  4601. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  4602. babylonMaterial.ambientTexture = texture;
  4603. }));
  4604. babylonMaterial.useAmbientInGrayScale = true;
  4605. if (material.occlusionTexture.strength != undefined) {
  4606. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  4607. }
  4608. }
  4609. if (material.emissiveTexture) {
  4610. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  4611. babylonMaterial.emissiveTexture = texture;
  4612. }));
  4613. }
  4614. return Promise.all(promises).then(function () { });
  4615. };
  4616. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  4617. var babylonMaterial = material._babylonMaterial;
  4618. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  4619. switch (alphaMode) {
  4620. case "OPAQUE" /* OPAQUE */: {
  4621. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  4622. break;
  4623. }
  4624. case "MASK" /* MASK */: {
  4625. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  4626. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  4627. if (babylonMaterial.alpha) {
  4628. if (babylonMaterial.alpha === 0) {
  4629. babylonMaterial.alphaCutOff = 1;
  4630. }
  4631. else {
  4632. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  4633. }
  4634. babylonMaterial.alpha = 1;
  4635. }
  4636. if (babylonMaterial.albedoTexture) {
  4637. babylonMaterial.albedoTexture.hasAlpha = true;
  4638. }
  4639. break;
  4640. }
  4641. case "BLEND" /* BLEND */: {
  4642. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  4643. if (babylonMaterial.albedoTexture) {
  4644. babylonMaterial.albedoTexture.hasAlpha = true;
  4645. babylonMaterial.useAlphaFromAlbedoTexture = true;
  4646. }
  4647. break;
  4648. }
  4649. default: {
  4650. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  4651. }
  4652. }
  4653. };
  4654. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  4655. var _this = this;
  4656. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  4657. context = "#/textures/" + textureInfo.index;
  4658. var promises = new Array();
  4659. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  4660. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  4661. var deferred = new BABYLON.Deferred();
  4662. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  4663. if (!_this._disposed) {
  4664. deferred.resolve();
  4665. }
  4666. }, function (message, exception) {
  4667. if (!_this._disposed) {
  4668. deferred.reject(new Error(context + ": " + (exception && exception.message) ? exception.message : message || "Failed to load texture"));
  4669. }
  4670. });
  4671. promises.push(deferred.promise);
  4672. babylonTexture.name = texture.name || "texture" + texture._index;
  4673. babylonTexture.wrapU = samplerData.wrapU;
  4674. babylonTexture.wrapV = samplerData.wrapV;
  4675. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  4676. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  4677. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  4678. babylonTexture.updateURL(objectURL);
  4679. }));
  4680. assign(babylonTexture);
  4681. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  4682. return Promise.all(promises).then(function () { });
  4683. };
  4684. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  4685. if (!sampler._data) {
  4686. sampler._data = {
  4687. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  4688. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  4689. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  4690. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  4691. };
  4692. }
  4693. ;
  4694. return sampler._data;
  4695. };
  4696. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  4697. if (image._objectURL) {
  4698. return image._objectURL;
  4699. }
  4700. var promise;
  4701. if (image.uri) {
  4702. promise = this._loadUriAsync(context, image.uri);
  4703. }
  4704. else {
  4705. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  4706. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  4707. }
  4708. image._objectURL = promise.then(function (data) {
  4709. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  4710. });
  4711. return image._objectURL;
  4712. };
  4713. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  4714. var _this = this;
  4715. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  4716. if (promise) {
  4717. return promise;
  4718. }
  4719. if (!GLTFLoader._ValidateUri(uri)) {
  4720. throw new Error(context + ": Uri '" + uri + "' is invalid");
  4721. }
  4722. if (BABYLON.Tools.IsBase64(uri)) {
  4723. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  4724. }
  4725. return new Promise(function (resolve, reject) {
  4726. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  4727. if (!_this._disposed) {
  4728. resolve(new Uint8Array(data));
  4729. }
  4730. }, function (event) {
  4731. if (!_this._disposed) {
  4732. try {
  4733. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  4734. request._lengthComputable = event.lengthComputable;
  4735. request._loaded = event.loaded;
  4736. request._total = event.total;
  4737. _this._onProgress();
  4738. }
  4739. }
  4740. catch (e) {
  4741. reject(e);
  4742. }
  4743. }
  4744. }, _this._babylonScene.database, true, function (request, exception) {
  4745. if (!_this._disposed) {
  4746. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  4747. }
  4748. });
  4749. _this._requests.push(request);
  4750. });
  4751. };
  4752. GLTFLoader.prototype._onProgress = function () {
  4753. if (!this._progressCallback) {
  4754. return;
  4755. }
  4756. var lengthComputable = true;
  4757. var loaded = 0;
  4758. var total = 0;
  4759. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  4760. var request = _a[_i];
  4761. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  4762. return;
  4763. }
  4764. lengthComputable = lengthComputable && request._lengthComputable;
  4765. loaded += request._loaded;
  4766. total += request._total;
  4767. }
  4768. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  4769. };
  4770. GLTFLoader._GetProperty = function (context, array, index) {
  4771. if (!array || index == undefined || !array[index]) {
  4772. throw new Error(context + ": Failed to find index " + index);
  4773. }
  4774. return array[index];
  4775. };
  4776. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  4777. // Set defaults if undefined
  4778. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  4779. switch (mode) {
  4780. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  4781. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  4782. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  4783. default:
  4784. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  4785. return BABYLON.Texture.WRAP_ADDRESSMODE;
  4786. }
  4787. };
  4788. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  4789. // Set defaults if undefined
  4790. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  4791. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  4792. if (magFilter === 9729 /* LINEAR */) {
  4793. switch (minFilter) {
  4794. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  4795. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  4796. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  4797. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  4798. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  4799. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  4800. default:
  4801. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  4802. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  4803. }
  4804. }
  4805. else {
  4806. if (magFilter !== 9728 /* NEAREST */) {
  4807. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  4808. }
  4809. switch (minFilter) {
  4810. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  4811. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  4812. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  4813. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  4814. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  4815. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  4816. default:
  4817. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  4818. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  4819. }
  4820. }
  4821. };
  4822. GLTFLoader._GetNumComponents = function (context, type) {
  4823. switch (type) {
  4824. case "SCALAR": return 1;
  4825. case "VEC2": return 2;
  4826. case "VEC3": return 3;
  4827. case "VEC4": return 4;
  4828. case "MAT2": return 4;
  4829. case "MAT3": return 9;
  4830. case "MAT4": return 16;
  4831. }
  4832. throw new Error(context + ": Invalid type " + type);
  4833. };
  4834. GLTFLoader._ValidateUri = function (uri) {
  4835. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  4836. };
  4837. GLTFLoader.prototype._compileMaterialsAsync = function () {
  4838. var promises = new Array();
  4839. if (this._gltf.materials) {
  4840. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  4841. var material = _a[_i];
  4842. var babylonMaterial = material._babylonMaterial;
  4843. var babylonMeshes = material._babylonMeshes;
  4844. if (babylonMaterial && babylonMeshes) {
  4845. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  4846. var babylonMesh = babylonMeshes_1[_b];
  4847. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  4848. if (this.useClipPlane) {
  4849. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  4850. }
  4851. }
  4852. }
  4853. }
  4854. }
  4855. return Promise.all(promises).then(function () { });
  4856. };
  4857. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  4858. var promises = new Array();
  4859. var lights = this._babylonScene.lights;
  4860. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  4861. var light = lights_1[_i];
  4862. var generator = light.getShadowGenerator();
  4863. if (generator) {
  4864. promises.push(generator.forceCompilationAsync());
  4865. }
  4866. }
  4867. return Promise.all(promises).then(function () { });
  4868. };
  4869. GLTFLoader.prototype._abortRequests = function () {
  4870. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  4871. var request = _a[_i];
  4872. request.abort();
  4873. }
  4874. this._requests.length = 0;
  4875. };
  4876. GLTFLoader.prototype._releaseResources = function () {
  4877. if (this._gltf.images) {
  4878. for (var _i = 0, _a = this._gltf.images; _i < _a.length; _i++) {
  4879. var image = _a[_i];
  4880. if (image._objectURL) {
  4881. image._objectURL.then(function (value) {
  4882. URL.revokeObjectURL(value);
  4883. });
  4884. image._objectURL = undefined;
  4885. }
  4886. }
  4887. }
  4888. };
  4889. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  4890. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  4891. var name_2 = _a[_i];
  4892. var extension = this._extensions[name_2];
  4893. if (extension.enabled) {
  4894. var promise = actionAsync(extension);
  4895. if (promise) {
  4896. return promise;
  4897. }
  4898. }
  4899. }
  4900. return null;
  4901. };
  4902. GLTFLoader._Names = new Array();
  4903. GLTFLoader._Factories = {};
  4904. return GLTFLoader;
  4905. }());
  4906. GLTF2.GLTFLoader = GLTFLoader;
  4907. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  4908. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4909. })(BABYLON || (BABYLON = {}));
  4910. //# sourceMappingURL=babylon.glTFLoader.js.map
  4911. var BABYLON;
  4912. (function (BABYLON) {
  4913. var GLTF2;
  4914. (function (GLTF2) {
  4915. var GLTFLoaderExtension = /** @class */ (function () {
  4916. function GLTFLoaderExtension(loader) {
  4917. this.enabled = true;
  4918. this._loader = loader;
  4919. }
  4920. // #region Overridable Methods
  4921. /** Override this method to modify the default behavior for loading scenes. */
  4922. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  4923. /** Override this method to modify the default behavior for loading nodes. */
  4924. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  4925. /** Override this method to modify the default behavior for loading materials. */
  4926. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh) { return null; };
  4927. /** Override this method to modify the default behavior for loading uris. */
  4928. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  4929. // #endregion
  4930. /** Helper method called by a loader extension to load an glTF extension. */
  4931. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  4932. var _this = this;
  4933. if (!property.extensions) {
  4934. return null;
  4935. }
  4936. var extensions = property.extensions;
  4937. var extension = extensions[this.name];
  4938. if (!extension) {
  4939. return null;
  4940. }
  4941. // Clear out the extension before executing the action to avoid recursing into the same property.
  4942. delete extensions[this.name];
  4943. return actionAsync(context + "/extensions/" + this.name, extension).then(function () {
  4944. // Restore the extension after completing the action.
  4945. extensions[_this.name] = extension;
  4946. });
  4947. };
  4948. /** Helper method called by the loader to allow extensions to override loading scenes. */
  4949. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  4950. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  4951. };
  4952. /** Helper method called by the loader to allow extensions to override loading nodes. */
  4953. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  4954. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  4955. };
  4956. /** Helper method called by the loader to allow extensions to override loading materials. */
  4957. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh) {
  4958. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh); });
  4959. };
  4960. /** Helper method called by the loader to allow extensions to override loading uris. */
  4961. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  4962. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  4963. };
  4964. return GLTFLoaderExtension;
  4965. }());
  4966. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  4967. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4968. })(BABYLON || (BABYLON = {}));
  4969. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  4970. var BABYLON;
  4971. (function (BABYLON) {
  4972. var GLTF2;
  4973. (function (GLTF2) {
  4974. var Extensions;
  4975. (function (Extensions) {
  4976. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  4977. var NAME = "MSFT_lod";
  4978. var MSFT_lod = /** @class */ (function (_super) {
  4979. __extends(MSFT_lod, _super);
  4980. function MSFT_lod() {
  4981. var _this = _super !== null && _super.apply(this, arguments) || this;
  4982. _this.name = NAME;
  4983. /**
  4984. * Maximum number of LODs to load, starting from the lowest LOD.
  4985. */
  4986. _this.maxLODsToLoad = Number.MAX_VALUE;
  4987. _this._loadingNodeLOD = null;
  4988. _this._loadNodeSignals = {};
  4989. _this._loadingMaterialLOD = null;
  4990. _this._loadMaterialSignals = {};
  4991. return _this;
  4992. }
  4993. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  4994. var _this = this;
  4995. return this._loadExtensionAsync(context, node, function (context, extension) {
  4996. var firstPromise;
  4997. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  4998. var _loop_1 = function (indexLOD) {
  4999. var nodeLOD = nodeLODs[indexLOD];
  5000. if (indexLOD !== 0) {
  5001. _this._loadingNodeLOD = nodeLOD;
  5002. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  5003. }
  5004. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  5005. if (indexLOD !== 0) {
  5006. var previousNodeLOD = nodeLODs[indexLOD - 1];
  5007. previousNodeLOD._babylonMesh.setEnabled(false);
  5008. }
  5009. if (indexLOD !== nodeLODs.length - 1) {
  5010. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  5011. _this._loadNodeSignals[nodeIndex].resolve();
  5012. delete _this._loadNodeSignals[nodeIndex];
  5013. }
  5014. });
  5015. if (indexLOD === 0) {
  5016. firstPromise = promise;
  5017. }
  5018. else {
  5019. _this._loader._completePromises.push(promise);
  5020. _this._loadingNodeLOD = null;
  5021. }
  5022. };
  5023. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  5024. _loop_1(indexLOD);
  5025. }
  5026. return firstPromise;
  5027. });
  5028. };
  5029. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  5030. var _this = this;
  5031. // Don't load material LODs if already loading a node LOD.
  5032. if (this._loadingNodeLOD) {
  5033. return null;
  5034. }
  5035. return this._loadExtensionAsync(context, material, function (context, extension) {
  5036. var firstPromise;
  5037. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  5038. var _loop_2 = function (indexLOD) {
  5039. var materialLOD = materialLODs[indexLOD];
  5040. if (indexLOD !== 0) {
  5041. _this._loadingMaterialLOD = materialLOD;
  5042. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  5043. }
  5044. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh).then(function () {
  5045. if (indexLOD !== materialLODs.length - 1) {
  5046. var materialIndex = materialLODs[indexLOD + 1]._index;
  5047. _this._loadMaterialSignals[materialIndex].resolve();
  5048. delete _this._loadMaterialSignals[materialIndex];
  5049. }
  5050. });
  5051. if (indexLOD === 0) {
  5052. firstPromise = promise;
  5053. }
  5054. else {
  5055. _this._loader._completePromises.push(promise);
  5056. _this._loadingMaterialLOD = null;
  5057. }
  5058. };
  5059. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  5060. _loop_2(indexLOD);
  5061. }
  5062. return firstPromise;
  5063. });
  5064. };
  5065. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  5066. var _this = this;
  5067. // Defer the loading of uris if loading a material or node LOD.
  5068. if (this._loadingMaterialLOD) {
  5069. var index = this._loadingMaterialLOD._index;
  5070. return this._loadMaterialSignals[index].promise.then(function () {
  5071. return _this._loader._loadUriAsync(context, uri);
  5072. });
  5073. }
  5074. else if (this._loadingNodeLOD) {
  5075. var index = this._loadingNodeLOD._index;
  5076. return this._loadNodeSignals[index].promise.then(function () {
  5077. return _this._loader._loadUriAsync(context, uri);
  5078. });
  5079. }
  5080. return null;
  5081. };
  5082. /**
  5083. * Gets an array of LOD properties from lowest to highest.
  5084. */
  5085. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  5086. if (this.maxLODsToLoad <= 0) {
  5087. throw new Error("maxLODsToLoad must be greater than zero");
  5088. }
  5089. var properties = new Array();
  5090. for (var i = ids.length - 1; i >= 0; i--) {
  5091. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  5092. if (properties.length === this.maxLODsToLoad) {
  5093. return properties;
  5094. }
  5095. }
  5096. properties.push(property);
  5097. return properties;
  5098. };
  5099. return MSFT_lod;
  5100. }(GLTF2.GLTFLoaderExtension));
  5101. Extensions.MSFT_lod = MSFT_lod;
  5102. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  5103. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  5104. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  5105. })(BABYLON || (BABYLON = {}));
  5106. //# sourceMappingURL=MSFT_lod.js.map
  5107. var BABYLON;
  5108. (function (BABYLON) {
  5109. var GLTF2;
  5110. (function (GLTF2) {
  5111. var Extensions;
  5112. (function (Extensions) {
  5113. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  5114. var NAME = "KHR_materials_pbrSpecularGlossiness";
  5115. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  5116. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  5117. function KHR_materials_pbrSpecularGlossiness() {
  5118. var _this = _super !== null && _super.apply(this, arguments) || this;
  5119. _this.name = NAME;
  5120. return _this;
  5121. }
  5122. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  5123. var _this = this;
  5124. return this._loadExtensionAsync(context, material, function (context, extension) {
  5125. material._babylonMeshes = material._babylonMeshes || [];
  5126. material._babylonMeshes.push(babylonMesh);
  5127. if (material._loaded) {
  5128. babylonMesh.material = material._babylonMaterial;
  5129. return material._loaded;
  5130. }
  5131. var promises = new Array();
  5132. var babylonMaterial = _this._loader._createMaterial(material);
  5133. material._babylonMaterial = babylonMaterial;
  5134. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  5135. promises.push(_this._loadSpecularGlossinessPropertiesAsync(_this._loader, context, material, extension));
  5136. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  5137. babylonMesh.material = babylonMaterial;
  5138. return (material._loaded = Promise.all(promises).then(function () { }));
  5139. });
  5140. };
  5141. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (loader, context, material, properties) {
  5142. var promises = new Array();
  5143. var babylonMaterial = material._babylonMaterial;
  5144. if (properties.diffuseFactor) {
  5145. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  5146. babylonMaterial.alpha = properties.diffuseFactor[3];
  5147. }
  5148. else {
  5149. babylonMaterial.albedoColor = BABYLON.Color3.White();
  5150. }
  5151. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  5152. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  5153. if (properties.diffuseTexture) {
  5154. promises.push(loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  5155. babylonMaterial.albedoTexture = texture;
  5156. }));
  5157. }
  5158. if (properties.specularGlossinessTexture) {
  5159. promises.push(loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  5160. babylonMaterial.reflectivityTexture = texture;
  5161. }));
  5162. babylonMaterial.reflectivityTexture.hasAlpha = true;
  5163. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  5164. }
  5165. loader._loadMaterialAlphaProperties(context, material);
  5166. return Promise.all(promises).then(function () { });
  5167. };
  5168. return KHR_materials_pbrSpecularGlossiness;
  5169. }(GLTF2.GLTFLoaderExtension));
  5170. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  5171. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  5172. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  5173. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  5174. })(BABYLON || (BABYLON = {}));
  5175. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  5176. var BABYLON;
  5177. (function (BABYLON) {
  5178. var GLTF2;
  5179. (function (GLTF2) {
  5180. var Extensions;
  5181. (function (Extensions) {
  5182. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  5183. var NAME = "KHR_lights";
  5184. var LightType;
  5185. (function (LightType) {
  5186. LightType["AMBIENT"] = "ambient";
  5187. LightType["DIRECTIONAL"] = "directional";
  5188. LightType["POINT"] = "point";
  5189. LightType["SPOT"] = "spot";
  5190. })(LightType || (LightType = {}));
  5191. var KHR_lights = /** @class */ (function (_super) {
  5192. __extends(KHR_lights, _super);
  5193. function KHR_lights() {
  5194. var _this = _super !== null && _super.apply(this, arguments) || this;
  5195. _this.name = NAME;
  5196. return _this;
  5197. }
  5198. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  5199. var _this = this;
  5200. return this._loadExtensionAsync(context, scene, function (context, extension) {
  5201. var promise = _this._loader._loadSceneAsync(context, scene);
  5202. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  5203. if (light.type !== LightType.AMBIENT) {
  5204. throw new Error(context + ": Only ambient lights are allowed on a scene");
  5205. }
  5206. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  5207. return promise;
  5208. });
  5209. };
  5210. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  5211. var _this = this;
  5212. return this._loadExtensionAsync(context, node, function (context, extension) {
  5213. var promise = _this._loader._loadNodeAsync(context, node);
  5214. var babylonLight;
  5215. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  5216. var name = node._babylonMesh.name;
  5217. switch (light.type) {
  5218. case LightType.AMBIENT: {
  5219. throw new Error(context + ": Ambient lights are not allowed on a node");
  5220. }
  5221. case LightType.DIRECTIONAL: {
  5222. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  5223. break;
  5224. }
  5225. case LightType.POINT: {
  5226. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  5227. break;
  5228. }
  5229. case LightType.SPOT: {
  5230. var spotLight = light;
  5231. // TODO: support inner and outer cone angles
  5232. //const innerConeAngle = spotLight.innerConeAngle || 0;
  5233. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  5234. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  5235. break;
  5236. }
  5237. default: {
  5238. throw new Error(context + ": Invalid light type " + light.type);
  5239. }
  5240. }
  5241. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  5242. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  5243. babylonLight.parent = node._babylonMesh;
  5244. return promise;
  5245. });
  5246. };
  5247. Object.defineProperty(KHR_lights.prototype, "_lights", {
  5248. get: function () {
  5249. var extensions = this._loader._gltf.extensions;
  5250. if (!extensions || !extensions[this.name]) {
  5251. throw new Error("#/extensions: " + this.name + " not found");
  5252. }
  5253. var extension = extensions[this.name];
  5254. return extension.lights;
  5255. },
  5256. enumerable: true,
  5257. configurable: true
  5258. });
  5259. return KHR_lights;
  5260. }(GLTF2.GLTFLoaderExtension));
  5261. Extensions.KHR_lights = KHR_lights;
  5262. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  5263. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  5264. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  5265. })(BABYLON || (BABYLON = {}));
  5266. //# sourceMappingURL=KHR_lights.js.map
  5267. (function universalModuleDefinition(root, factory) {
  5268. var f = factory();
  5269. if (root && root["BABYLON"]) {
  5270. return;
  5271. }
  5272. if(typeof exports === 'object' && typeof module === 'object')
  5273. module.exports = f;
  5274. else if(typeof define === 'function' && define.amd)
  5275. define(["BJSLoaders"], factory);
  5276. else if(typeof exports === 'object')
  5277. exports["BJSLoaders"] = f;
  5278. else {
  5279. root["BABYLON"] = f;
  5280. }
  5281. })(this, function() {
  5282. return BABYLON;
  5283. });