babylonjs.loaders.js 244 KB

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