babylonjs.loaders.js 265 KB

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