babylonjs.loaders.js 262 KB

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