babylonjs.loaders.js 249 KB

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