babylonjs.loaders.js 249 KB

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