babylon.glTFFileLoader.js 184 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. var GLTFFileLoader = (function () {
  5. function GLTFFileLoader() {
  6. this.extensions = {
  7. ".gltf": { isBinary: false },
  8. ".glb": { isBinary: true }
  9. };
  10. }
  11. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onError) {
  12. var loaderData = GLTFFileLoader._parse(data);
  13. var loader = this._getLoader(loaderData);
  14. if (!loader) {
  15. onError();
  16. return;
  17. }
  18. loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onError);
  19. };
  20. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onError) {
  21. var loaderData = GLTFFileLoader._parse(data);
  22. var loader = this._getLoader(loaderData);
  23. if (!loader) {
  24. onError();
  25. return;
  26. }
  27. return loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onError);
  28. };
  29. GLTFFileLoader._parse = function (data) {
  30. if (data instanceof ArrayBuffer) {
  31. return GLTFFileLoader._parseBinary(data);
  32. }
  33. return {
  34. json: JSON.parse(data),
  35. bin: null
  36. };
  37. };
  38. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  39. var loaderVersion = { major: 2, minor: 0 };
  40. var asset = loaderData.json.asset || {};
  41. var version = GLTFFileLoader._parseVersion(asset.version);
  42. if (!version) {
  43. BABYLON.Tools.Error("Invalid version");
  44. return null;
  45. }
  46. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  47. if (minVersion) {
  48. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  49. BABYLON.Tools.Error("Incompatible version");
  50. return null;
  51. }
  52. }
  53. var loaders = {
  54. 1: GLTFFileLoader.GLTFLoaderV1,
  55. 2: GLTFFileLoader.GLTFLoaderV2
  56. };
  57. var loader = loaders[version.major];
  58. if (loader === undefined) {
  59. BABYLON.Tools.Error("Unsupported version");
  60. return null;
  61. }
  62. if (loader === null) {
  63. BABYLON.Tools.Error("v" + version.major + " loader is not available");
  64. return null;
  65. }
  66. return loader;
  67. };
  68. GLTFFileLoader._parseBinary = function (data) {
  69. var Binary = {
  70. Magic: 0x46546C67
  71. };
  72. var binaryReader = new BinaryReader(data);
  73. var magic = binaryReader.readUint32();
  74. if (magic !== Binary.Magic) {
  75. BABYLON.Tools.Error("Unexpected magic: " + magic);
  76. return null;
  77. }
  78. var version = binaryReader.readUint32();
  79. switch (version) {
  80. case 1: return GLTFFileLoader._parseV1(binaryReader);
  81. case 2: return GLTFFileLoader._parseV2(binaryReader);
  82. }
  83. BABYLON.Tools.Error("Unsupported version: " + version);
  84. return null;
  85. };
  86. GLTFFileLoader._parseV1 = function (binaryReader) {
  87. var ContentFormat = {
  88. JSON: 0
  89. };
  90. var length = binaryReader.readUint32();
  91. if (length != binaryReader.getLength()) {
  92. BABYLON.Tools.Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  93. return null;
  94. }
  95. var contentLength = binaryReader.readUint32();
  96. var contentFormat = binaryReader.readUint32();
  97. var content;
  98. switch (contentFormat) {
  99. case ContentFormat.JSON:
  100. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  101. break;
  102. default:
  103. BABYLON.Tools.Error("Unexpected content format: " + contentFormat);
  104. return null;
  105. }
  106. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  107. var body = binaryReader.readUint8Array(bytesRemaining);
  108. return {
  109. json: content,
  110. bin: body
  111. };
  112. };
  113. GLTFFileLoader._parseV2 = function (binaryReader) {
  114. var ChunkFormat = {
  115. JSON: 0x4E4F534A,
  116. BIN: 0x004E4942
  117. };
  118. var length = binaryReader.readUint32();
  119. if (length !== binaryReader.getLength()) {
  120. BABYLON.Tools.Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  121. return null;
  122. }
  123. // JSON chunk
  124. var chunkLength = binaryReader.readUint32();
  125. var chunkFormat = binaryReader.readUint32();
  126. if (chunkFormat !== ChunkFormat.JSON) {
  127. BABYLON.Tools.Error("First chunk format is not JSON");
  128. return null;
  129. }
  130. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  131. // Look for BIN chunk
  132. var bin = null;
  133. while (binaryReader.getPosition() < binaryReader.getLength()) {
  134. chunkLength = binaryReader.readUint32();
  135. chunkFormat = binaryReader.readUint32();
  136. switch (chunkFormat) {
  137. case ChunkFormat.JSON:
  138. BABYLON.Tools.Error("Unexpected JSON chunk");
  139. return null;
  140. case ChunkFormat.BIN:
  141. bin = binaryReader.readUint8Array(chunkLength);
  142. break;
  143. default:
  144. // ignore unrecognized chunkFormat
  145. binaryReader.skipBytes(chunkLength);
  146. break;
  147. }
  148. }
  149. return {
  150. json: json,
  151. bin: bin
  152. };
  153. };
  154. GLTFFileLoader._parseVersion = function (version) {
  155. if (!version) {
  156. return null;
  157. }
  158. var parts = version.split(".");
  159. if (parts.length === 0) {
  160. return null;
  161. }
  162. var major = parseInt(parts[0]);
  163. if (major > 1 && parts.length != 2) {
  164. return null;
  165. }
  166. var minor = parseInt(parts[1]);
  167. return {
  168. major: major,
  169. minor: parseInt(parts[0])
  170. };
  171. };
  172. GLTFFileLoader._compareVersion = function (a, b) {
  173. if (a.major > b.major)
  174. return 1;
  175. if (a.major < b.major)
  176. return -1;
  177. if (a.minor > b.minor)
  178. return 1;
  179. if (a.minor < b.minor)
  180. return -1;
  181. return 0;
  182. };
  183. GLTFFileLoader._decodeBufferToText = function (view) {
  184. var result = "";
  185. var length = view.byteLength;
  186. for (var i = 0; i < length; ++i) {
  187. result += String.fromCharCode(view[i]);
  188. }
  189. return result;
  190. };
  191. return GLTFFileLoader;
  192. }());
  193. GLTFFileLoader.GLTFLoaderV1 = null;
  194. GLTFFileLoader.GLTFLoaderV2 = null;
  195. GLTFFileLoader.HomogeneousCoordinates = false;
  196. GLTFFileLoader.IncrementalLoading = true;
  197. BABYLON.GLTFFileLoader = GLTFFileLoader;
  198. var BinaryReader = (function () {
  199. function BinaryReader(arrayBuffer) {
  200. this._arrayBuffer = arrayBuffer;
  201. this._dataView = new DataView(arrayBuffer);
  202. this._byteOffset = 0;
  203. }
  204. BinaryReader.prototype.getPosition = function () {
  205. return this._byteOffset;
  206. };
  207. BinaryReader.prototype.getLength = function () {
  208. return this._arrayBuffer.byteLength;
  209. };
  210. BinaryReader.prototype.readUint32 = function () {
  211. var value = this._dataView.getUint32(this._byteOffset, true);
  212. this._byteOffset += 4;
  213. return value;
  214. };
  215. BinaryReader.prototype.readUint8Array = function (length) {
  216. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  217. this._byteOffset += length;
  218. return value;
  219. };
  220. BinaryReader.prototype.skipBytes = function (length) {
  221. this._byteOffset += length;
  222. };
  223. return BinaryReader;
  224. }());
  225. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  226. })(BABYLON || (BABYLON = {}));
  227. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  228. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  229. var BABYLON;
  230. (function (BABYLON) {
  231. var GLTF1;
  232. (function (GLTF1) {
  233. /**
  234. * Enums
  235. */
  236. var EComponentType;
  237. (function (EComponentType) {
  238. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  239. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  240. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  241. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  242. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  243. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  244. var EShaderType;
  245. (function (EShaderType) {
  246. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  247. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  248. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  249. var EParameterType;
  250. (function (EParameterType) {
  251. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  252. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  253. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  254. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  255. EParameterType[EParameterType["INT"] = 5124] = "INT";
  256. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  257. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  258. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  259. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  260. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  261. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  262. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  263. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  264. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  265. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  266. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  267. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  268. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  269. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  270. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  271. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  272. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  273. var ETextureWrapMode;
  274. (function (ETextureWrapMode) {
  275. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  276. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  277. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  278. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  279. var ETextureFilterType;
  280. (function (ETextureFilterType) {
  281. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  282. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  283. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  284. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  285. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  286. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  287. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  288. var ETextureFormat;
  289. (function (ETextureFormat) {
  290. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  291. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  292. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  293. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  294. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  295. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  296. var ECullingType;
  297. (function (ECullingType) {
  298. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  299. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  300. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  301. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  302. var EBlendingFunction;
  303. (function (EBlendingFunction) {
  304. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  305. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  306. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  307. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  308. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  309. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  310. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  311. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  312. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  313. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  314. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  315. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  316. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  317. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  318. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  319. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  320. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  321. })(BABYLON || (BABYLON = {}));
  322. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  323. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  324. var BABYLON;
  325. (function (BABYLON) {
  326. var GLTF1;
  327. (function (GLTF1) {
  328. /**
  329. * Tokenizer. Used for shaders compatibility
  330. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  331. */
  332. var ETokenType;
  333. (function (ETokenType) {
  334. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  335. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  336. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  337. })(ETokenType || (ETokenType = {}));
  338. var Tokenizer = (function () {
  339. function Tokenizer(toParse) {
  340. this._pos = 0;
  341. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  342. this._toParse = toParse;
  343. this._maxPos = toParse.length;
  344. }
  345. Tokenizer.prototype.getNextToken = function () {
  346. if (this.isEnd())
  347. return ETokenType.END_OF_INPUT;
  348. this.currentString = this.read();
  349. this.currentToken = ETokenType.UNKNOWN;
  350. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  351. this.currentToken = ETokenType.IDENTIFIER;
  352. this.currentIdentifier = this.currentString;
  353. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  354. this.currentIdentifier += this.currentString;
  355. this.forward();
  356. }
  357. }
  358. return this.currentToken;
  359. };
  360. Tokenizer.prototype.peek = function () {
  361. return this._toParse[this._pos];
  362. };
  363. Tokenizer.prototype.read = function () {
  364. return this._toParse[this._pos++];
  365. };
  366. Tokenizer.prototype.forward = function () {
  367. this._pos++;
  368. };
  369. Tokenizer.prototype.isEnd = function () {
  370. return this._pos >= this._maxPos;
  371. };
  372. return Tokenizer;
  373. }());
  374. /**
  375. * Values
  376. */
  377. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  378. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  379. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  380. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  381. /**
  382. * Parse
  383. */
  384. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  385. for (var buf in parsedBuffers) {
  386. var parsedBuffer = parsedBuffers[buf];
  387. gltfRuntime.buffers[buf] = parsedBuffer;
  388. gltfRuntime.buffersCount++;
  389. }
  390. };
  391. var parseShaders = function (parsedShaders, gltfRuntime) {
  392. for (var sha in parsedShaders) {
  393. var parsedShader = parsedShaders[sha];
  394. gltfRuntime.shaders[sha] = parsedShader;
  395. gltfRuntime.shaderscount++;
  396. }
  397. };
  398. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  399. for (var object in parsedObjects) {
  400. var parsedObject = parsedObjects[object];
  401. gltfRuntime[runtimeProperty][object] = parsedObject;
  402. }
  403. };
  404. /**
  405. * Utils
  406. */
  407. var normalizeUVs = function (buffer) {
  408. if (!buffer) {
  409. return;
  410. }
  411. for (var i = 0; i < buffer.length / 2; i++) {
  412. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  413. }
  414. };
  415. var replaceInString = function (str, searchValue, replaceValue) {
  416. while (str.indexOf(searchValue) !== -1) {
  417. str = str.replace(searchValue, replaceValue);
  418. }
  419. return str;
  420. };
  421. var getAttribute = function (attributeParameter) {
  422. if (attributeParameter.semantic === "NORMAL") {
  423. return "normal";
  424. }
  425. else if (attributeParameter.semantic === "POSITION") {
  426. return "position";
  427. }
  428. else if (attributeParameter.semantic === "JOINT") {
  429. return "matricesIndices";
  430. }
  431. else if (attributeParameter.semantic === "WEIGHT") {
  432. return "matricesWeights";
  433. }
  434. else if (attributeParameter.semantic === "COLOR") {
  435. return "color";
  436. }
  437. else if (attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  438. var channel = Number(attributeParameter.semantic.split("_")[1]);
  439. return "uv" + (channel === 0 ? "" : channel + 1);
  440. }
  441. };
  442. /**
  443. * Returns the animation path (glTF -> Babylon)
  444. */
  445. var getAnimationPath = function (path) {
  446. var index = glTFAnimationPaths.indexOf(path);
  447. if (index !== -1) {
  448. return babylonAnimationPaths[index];
  449. }
  450. return path;
  451. };
  452. /**
  453. * Loads and creates animations
  454. */
  455. var loadAnimations = function (gltfRuntime) {
  456. for (var anim in gltfRuntime.animations) {
  457. var animation = gltfRuntime.animations[anim];
  458. var lastAnimation = null;
  459. for (var i = 0; i < animation.channels.length; i++) {
  460. // Get parameters and load buffers
  461. var channel = animation.channels[i];
  462. var sampler = animation.samplers[channel.sampler];
  463. if (!sampler) {
  464. continue;
  465. }
  466. var inputData = null;
  467. var outputData = null;
  468. if (animation.parameters) {
  469. inputData = animation.parameters[sampler.input];
  470. outputData = animation.parameters[sampler.output];
  471. }
  472. else {
  473. inputData = sampler.input;
  474. outputData = sampler.output;
  475. }
  476. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  477. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  478. var targetID = channel.target.id;
  479. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  480. if (targetNode === null) {
  481. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  482. }
  483. if (targetNode === null) {
  484. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  485. continue;
  486. }
  487. var isBone = targetNode instanceof BABYLON.Bone;
  488. // Get target path (position, rotation or scaling)
  489. var targetPath = channel.target.path;
  490. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  491. if (targetPathIndex !== -1) {
  492. targetPath = babylonAnimationPaths[targetPathIndex];
  493. }
  494. // Determine animation type
  495. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  496. if (!isBone) {
  497. if (targetPath === "rotationQuaternion") {
  498. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  499. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  500. }
  501. else {
  502. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  503. }
  504. }
  505. // Create animation and key frames
  506. var babylonAnimation = null;
  507. var keys = [];
  508. var arrayOffset = 0;
  509. var modifyKey = false;
  510. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  511. babylonAnimation = lastAnimation;
  512. modifyKey = true;
  513. }
  514. if (!modifyKey) {
  515. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  516. }
  517. // For each frame
  518. for (var j = 0; j < bufferInput.length; j++) {
  519. var value = null;
  520. if (targetPath === "rotationQuaternion") {
  521. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  522. arrayOffset += 4;
  523. }
  524. else {
  525. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  526. arrayOffset += 3;
  527. }
  528. if (isBone) {
  529. var bone = targetNode;
  530. var translation = BABYLON.Vector3.Zero();
  531. var rotationQuaternion = new BABYLON.Quaternion();
  532. var scaling = BABYLON.Vector3.Zero();
  533. // Warning on decompose
  534. var mat = bone.getBaseMatrix();
  535. if (modifyKey) {
  536. mat = lastAnimation.getKeys()[j].value;
  537. }
  538. mat.decompose(scaling, rotationQuaternion, translation);
  539. if (targetPath === "position") {
  540. translation = value;
  541. }
  542. else if (targetPath === "rotationQuaternion") {
  543. rotationQuaternion = value;
  544. }
  545. else {
  546. scaling = value;
  547. }
  548. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  549. }
  550. if (!modifyKey) {
  551. keys.push({
  552. frame: bufferInput[j],
  553. value: value
  554. });
  555. }
  556. else {
  557. lastAnimation.getKeys()[j].value = value;
  558. }
  559. }
  560. // Finish
  561. if (!modifyKey) {
  562. babylonAnimation.setKeys(keys);
  563. targetNode.animations.push(babylonAnimation);
  564. }
  565. lastAnimation = babylonAnimation;
  566. gltfRuntime.scene.stopAnimation(targetNode);
  567. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  568. }
  569. }
  570. };
  571. /**
  572. * Returns the bones transformation matrix
  573. */
  574. var configureBoneTransformation = function (node) {
  575. var mat = null;
  576. if (node.translation || node.rotation || node.scale) {
  577. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  578. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  579. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  580. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  581. }
  582. else {
  583. mat = BABYLON.Matrix.FromArray(node.matrix);
  584. }
  585. return mat;
  586. };
  587. /**
  588. * Returns the parent bone
  589. */
  590. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  591. // Try to find
  592. for (var i = 0; i < newSkeleton.bones.length; i++) {
  593. if (newSkeleton.bones[i].name === jointName) {
  594. return newSkeleton.bones[i];
  595. }
  596. }
  597. // Not found, search in gltf nodes
  598. var nodes = gltfRuntime.nodes;
  599. for (var nde in nodes) {
  600. var node = nodes[nde];
  601. if (!node.jointName) {
  602. continue;
  603. }
  604. var children = node.children;
  605. for (var i = 0; i < children.length; i++) {
  606. var child = gltfRuntime.nodes[children[i]];
  607. if (!child.jointName) {
  608. continue;
  609. }
  610. if (child.jointName === jointName) {
  611. var mat = configureBoneTransformation(node);
  612. var bone = new BABYLON.Bone(node.name, newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  613. bone.id = nde;
  614. return bone;
  615. }
  616. }
  617. }
  618. return null;
  619. };
  620. /**
  621. * Returns the appropriate root node
  622. */
  623. var getNodeToRoot = function (nodesToRoot, id) {
  624. for (var i = 0; i < nodesToRoot.length; i++) {
  625. var nodeToRoot = nodesToRoot[i];
  626. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  627. var child = nodeToRoot.node.children[j];
  628. if (child === id) {
  629. return nodeToRoot.bone;
  630. }
  631. }
  632. }
  633. return null;
  634. };
  635. /**
  636. * Returns the node with the joint name
  637. */
  638. var getJointNode = function (gltfRuntime, jointName) {
  639. var nodes = gltfRuntime.nodes;
  640. var node = nodes[jointName];
  641. if (node) {
  642. return {
  643. node: node,
  644. id: jointName
  645. };
  646. }
  647. for (var nde in nodes) {
  648. node = nodes[nde];
  649. if (node.jointName === jointName) {
  650. return {
  651. node: node,
  652. id: nde
  653. };
  654. }
  655. }
  656. return null;
  657. };
  658. /**
  659. * Checks if a nodes is in joints
  660. */
  661. var nodeIsInJoints = function (skins, id) {
  662. for (var i = 0; i < skins.jointNames.length; i++) {
  663. if (skins.jointNames[i] === id) {
  664. return true;
  665. }
  666. }
  667. return false;
  668. };
  669. /**
  670. * Fills the nodes to root for bones and builds hierarchy
  671. */
  672. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  673. // Creates nodes for root
  674. for (var nde in gltfRuntime.nodes) {
  675. var node = gltfRuntime.nodes[nde];
  676. var id = nde;
  677. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  678. continue;
  679. }
  680. // Create node to root bone
  681. var mat = configureBoneTransformation(node);
  682. var bone = new BABYLON.Bone(node.name, newSkeleton, null, mat);
  683. bone.id = id;
  684. nodesToRoot.push({ bone: bone, node: node, id: id });
  685. }
  686. // Parenting
  687. for (var i = 0; i < nodesToRoot.length; i++) {
  688. var nodeToRoot = nodesToRoot[i];
  689. var children = nodeToRoot.node.children;
  690. for (var j = 0; j < children.length; j++) {
  691. var child = null;
  692. for (var k = 0; k < nodesToRoot.length; k++) {
  693. if (nodesToRoot[k].id === children[j]) {
  694. child = nodesToRoot[k];
  695. break;
  696. }
  697. }
  698. if (child) {
  699. child.bone._parent = nodeToRoot.bone;
  700. nodeToRoot.bone.children.push(child.bone);
  701. }
  702. }
  703. }
  704. };
  705. var printMat = function (m) {
  706. console.log(m[0] + "\t" + m[1] + "\t" + m[2] + "\t" + m[3] + "\n" +
  707. m[4] + "\t" + m[5] + "\t" + m[6] + "\t" + m[7] + "\n" +
  708. m[8] + "\t" + m[9] + "\t" + m[10] + "\t" + m[11] + "\n" +
  709. m[12] + "\t" + m[13] + "\t" + m[14] + "\t" + m[15] + "\n");
  710. };
  711. /**
  712. * Imports a skeleton
  713. */
  714. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  715. if (!newSkeleton) {
  716. newSkeleton = new BABYLON.Skeleton(skins.name, "", gltfRuntime.scene);
  717. }
  718. if (!skins.babylonSkeleton) {
  719. return newSkeleton;
  720. }
  721. // Matrices
  722. var accessor = gltfRuntime.accessors[skins.inverseBindMatrices];
  723. var buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  724. var bindShapeMatrix = BABYLON.Matrix.FromArray(skins.bindShapeMatrix);
  725. // Find the root bones
  726. var nodesToRoot = [];
  727. var nodesToRootToAdd = [];
  728. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  729. newSkeleton.bones = [];
  730. // Joints
  731. for (var i = 0; i < skins.jointNames.length; i++) {
  732. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  733. var node = jointNode.node;
  734. if (!node) {
  735. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  736. continue;
  737. }
  738. var id = jointNode.id;
  739. // Optimize, if the bone already exists...
  740. var existingBone = gltfRuntime.scene.getBoneByID(id);
  741. if (existingBone) {
  742. newSkeleton.bones.push(existingBone);
  743. continue;
  744. }
  745. // Search for parent bone
  746. var foundBone = false;
  747. var parentBone = null;
  748. for (var j = 0; j < i; j++) {
  749. var joint = getJointNode(gltfRuntime, skins.jointNames[j]).node;
  750. if (!joint) {
  751. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  752. continue;
  753. }
  754. var children = joint.children;
  755. foundBone = false;
  756. for (var k = 0; k < children.length; k++) {
  757. if (children[k] === id) {
  758. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  759. foundBone = true;
  760. break;
  761. }
  762. }
  763. if (foundBone) {
  764. break;
  765. }
  766. }
  767. // Create bone
  768. var mat = configureBoneTransformation(node);
  769. if (!parentBone && nodesToRoot.length > 0) {
  770. parentBone = getNodeToRoot(nodesToRoot, id);
  771. if (parentBone) {
  772. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  773. nodesToRootToAdd.push(parentBone);
  774. }
  775. }
  776. }
  777. var bone = new BABYLON.Bone(node.jointName, newSkeleton, parentBone, mat);
  778. bone.id = id;
  779. }
  780. // Polish
  781. var bones = newSkeleton.bones;
  782. newSkeleton.bones = [];
  783. for (var i = 0; i < skins.jointNames.length; i++) {
  784. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  785. if (!jointNode) {
  786. continue;
  787. }
  788. for (var j = 0; j < bones.length; j++) {
  789. if (bones[j].id === jointNode.id) {
  790. newSkeleton.bones.push(bones[j]);
  791. break;
  792. }
  793. }
  794. }
  795. newSkeleton.prepare();
  796. // Finish
  797. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  798. newSkeleton.bones.push(nodesToRootToAdd[i]);
  799. }
  800. return newSkeleton;
  801. };
  802. /**
  803. * Imports a mesh and its geometries
  804. */
  805. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  806. if (!newMesh) {
  807. newMesh = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  808. newMesh.id = id;
  809. }
  810. if (!node.babylonNode) {
  811. return newMesh;
  812. }
  813. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  814. if (!newMesh.material) {
  815. newMesh.material = multiMat;
  816. }
  817. var vertexData = new BABYLON.VertexData();
  818. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  819. var verticesStarts = [];
  820. var verticesCounts = [];
  821. var indexStarts = [];
  822. var indexCounts = [];
  823. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  824. var meshID = meshes[meshIndex];
  825. var mesh = gltfRuntime.meshes[meshID];
  826. if (!mesh) {
  827. continue;
  828. }
  829. // Positions, normals and UVs
  830. for (var i = 0; i < mesh.primitives.length; i++) {
  831. // Temporary vertex data
  832. var tempVertexData = new BABYLON.VertexData();
  833. var primitive = mesh.primitives[i];
  834. if (primitive.mode !== 4) {
  835. // continue;
  836. }
  837. var attributes = primitive.attributes;
  838. var accessor = null;
  839. var buffer = null;
  840. // Set positions, normal and uvs
  841. for (var semantic in attributes) {
  842. // Link accessor and buffer view
  843. accessor = gltfRuntime.accessors[attributes[semantic]];
  844. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  845. if (semantic === "NORMAL") {
  846. tempVertexData.normals = new Float32Array(buffer.length);
  847. tempVertexData.normals.set(buffer);
  848. }
  849. else if (semantic === "POSITION") {
  850. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  851. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  852. for (var j = 0; j < buffer.length; j += 4) {
  853. tempVertexData.positions[j] = buffer[j];
  854. tempVertexData.positions[j + 1] = buffer[j + 1];
  855. tempVertexData.positions[j + 2] = buffer[j + 2];
  856. }
  857. }
  858. else {
  859. tempVertexData.positions = new Float32Array(buffer.length);
  860. tempVertexData.positions.set(buffer);
  861. }
  862. verticesCounts.push(tempVertexData.positions.length);
  863. }
  864. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  865. var channel = Number(semantic.split("_")[1]);
  866. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  867. var uvs = new Float32Array(buffer.length);
  868. uvs.set(buffer);
  869. normalizeUVs(uvs);
  870. tempVertexData.set(uvs, uvKind);
  871. }
  872. else if (semantic === "JOINT") {
  873. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  874. tempVertexData.matricesIndices.set(buffer);
  875. }
  876. else if (semantic === "WEIGHT") {
  877. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  878. tempVertexData.matricesWeights.set(buffer);
  879. }
  880. else if (semantic === "COLOR") {
  881. tempVertexData.colors = new Float32Array(buffer.length);
  882. tempVertexData.colors.set(buffer);
  883. }
  884. }
  885. // Indices
  886. accessor = gltfRuntime.accessors[primitive.indices];
  887. if (accessor) {
  888. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  889. tempVertexData.indices = new Int32Array(buffer.length);
  890. tempVertexData.indices.set(buffer);
  891. indexCounts.push(tempVertexData.indices.length);
  892. }
  893. else {
  894. // Set indices on the fly
  895. var indices = [];
  896. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  897. indices.push(j);
  898. }
  899. tempVertexData.indices = new Int32Array(indices);
  900. indexCounts.push(tempVertexData.indices.length);
  901. }
  902. vertexData.merge(tempVertexData);
  903. tempVertexData = undefined;
  904. // Sub material
  905. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  906. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  907. // Update vertices start and index start
  908. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  909. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  910. }
  911. }
  912. // Apply geometry
  913. geometry.setAllVerticesData(vertexData, false);
  914. newMesh.computeWorldMatrix(true);
  915. // Apply submeshes
  916. newMesh.subMeshes = [];
  917. var index = 0;
  918. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  919. var meshID = meshes[meshIndex];
  920. var mesh = gltfRuntime.meshes[meshID];
  921. if (!mesh) {
  922. continue;
  923. }
  924. for (var i = 0; i < mesh.primitives.length; i++) {
  925. if (mesh.primitives[i].mode !== 4) {
  926. //continue;
  927. }
  928. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  929. index++;
  930. }
  931. }
  932. // Finish
  933. return newMesh;
  934. };
  935. /**
  936. * Configure node transformation from position, rotation and scaling
  937. */
  938. var configureNode = function (newNode, position, rotation, scaling) {
  939. if (newNode.position) {
  940. newNode.position = position;
  941. }
  942. if (newNode.rotationQuaternion || newNode.rotation) {
  943. newNode.rotationQuaternion = rotation;
  944. }
  945. if (newNode.scaling) {
  946. newNode.scaling = scaling;
  947. }
  948. };
  949. /**
  950. * Configures node from transformation matrix
  951. */
  952. var configureNodeFromMatrix = function (newNode, node, parent) {
  953. if (node.matrix) {
  954. var position = new BABYLON.Vector3(0, 0, 0);
  955. var rotation = new BABYLON.Quaternion();
  956. var scaling = new BABYLON.Vector3(0, 0, 0);
  957. var mat = BABYLON.Matrix.FromArray(node.matrix);
  958. mat.decompose(scaling, rotation, position);
  959. configureNode(newNode, position, rotation, scaling);
  960. }
  961. else {
  962. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  963. }
  964. newNode.computeWorldMatrix(true);
  965. };
  966. /**
  967. * Imports a node
  968. */
  969. var importNode = function (gltfRuntime, node, id, parent) {
  970. var lastNode = null;
  971. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  972. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  973. return null;
  974. }
  975. }
  976. // Meshes
  977. if (node.skin) {
  978. if (node.meshes) {
  979. var skin = gltfRuntime.skins[node.skin];
  980. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  981. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  982. if (newMesh.skeleton === null) {
  983. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  984. if (!skin.babylonSkeleton) {
  985. skin.babylonSkeleton = newMesh.skeleton;
  986. }
  987. }
  988. lastNode = newMesh;
  989. }
  990. }
  991. else if (node.meshes) {
  992. /**
  993. * Improve meshes property
  994. */
  995. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  996. lastNode = newMesh;
  997. }
  998. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  999. var light = gltfRuntime.lights[node.light];
  1000. if (light) {
  1001. if (light.type === "ambient") {
  1002. var ambienLight = light[light.type];
  1003. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1004. hemiLight.name = node.name;
  1005. if (ambienLight.color) {
  1006. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  1007. }
  1008. lastNode = hemiLight;
  1009. }
  1010. else if (light.type === "directional") {
  1011. var directionalLight = light[light.type];
  1012. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1013. dirLight.name = node.name;
  1014. if (directionalLight.color) {
  1015. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  1016. }
  1017. lastNode = dirLight;
  1018. }
  1019. else if (light.type === "point") {
  1020. var pointLight = light[light.type];
  1021. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1022. ptLight.name = node.name;
  1023. if (pointLight.color) {
  1024. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  1025. }
  1026. lastNode = ptLight;
  1027. }
  1028. else if (light.type === "spot") {
  1029. var spotLight = light[light.type];
  1030. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  1031. spLight.name = node.name;
  1032. if (spotLight.color) {
  1033. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  1034. }
  1035. if (spotLight.fallOfAngle) {
  1036. spLight.angle = spotLight.fallOfAngle;
  1037. }
  1038. if (spotLight.fallOffExponent) {
  1039. spLight.exponent = spotLight.fallOffExponent;
  1040. }
  1041. lastNode = spLight;
  1042. }
  1043. }
  1044. }
  1045. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1046. var camera = gltfRuntime.cameras[node.camera];
  1047. if (camera) {
  1048. if (camera.type === "orthographic") {
  1049. var orthographicCamera = camera[camera.type];
  1050. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1051. orthoCamera.name = node.name;
  1052. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  1053. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1054. lastNode = orthoCamera;
  1055. }
  1056. else if (camera.type === "perspective") {
  1057. var perspectiveCamera = camera[camera.type];
  1058. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1059. persCamera.name = node.name;
  1060. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1061. if (!perspectiveCamera.aspectRatio) {
  1062. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  1063. }
  1064. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  1065. persCamera.maxZ = perspectiveCamera.zfar;
  1066. persCamera.minZ = perspectiveCamera.znear;
  1067. }
  1068. lastNode = persCamera;
  1069. }
  1070. }
  1071. }
  1072. // Empty node
  1073. if (!node.jointName) {
  1074. if (node.babylonNode) {
  1075. return node.babylonNode;
  1076. }
  1077. else if (lastNode === null) {
  1078. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  1079. node.babylonNode = dummy;
  1080. lastNode = dummy;
  1081. }
  1082. }
  1083. if (lastNode !== null) {
  1084. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  1085. configureNodeFromMatrix(lastNode, node, parent);
  1086. }
  1087. else {
  1088. var translation = node.translation || [0, 0, 0];
  1089. var rotation = node.rotation || [0, 0, 0, 1];
  1090. var scale = node.scale || [1, 1, 1];
  1091. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  1092. }
  1093. lastNode.updateCache(true);
  1094. node.babylonNode = lastNode;
  1095. }
  1096. return lastNode;
  1097. };
  1098. /**
  1099. * Traverses nodes and creates them
  1100. */
  1101. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  1102. var node = gltfRuntime.nodes[id];
  1103. var newNode = null;
  1104. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  1105. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  1106. meshIncluded = true;
  1107. }
  1108. else {
  1109. meshIncluded = false;
  1110. }
  1111. }
  1112. else {
  1113. meshIncluded = true;
  1114. }
  1115. if (!node.jointName && meshIncluded) {
  1116. newNode = importNode(gltfRuntime, node, id, parent);
  1117. if (newNode !== null) {
  1118. newNode.id = id;
  1119. newNode.parent = parent;
  1120. }
  1121. }
  1122. if (node.children) {
  1123. for (var i = 0; i < node.children.length; i++) {
  1124. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  1125. }
  1126. }
  1127. };
  1128. /**
  1129. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  1130. */
  1131. var postLoad = function (gltfRuntime) {
  1132. // Nodes
  1133. var currentScene = gltfRuntime.currentScene;
  1134. if (currentScene) {
  1135. for (var i = 0; i < currentScene.nodes.length; i++) {
  1136. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1137. }
  1138. }
  1139. else {
  1140. for (var thing in gltfRuntime.scenes) {
  1141. currentScene = gltfRuntime.scenes[thing];
  1142. for (var i = 0; i < currentScene.nodes.length; i++) {
  1143. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1144. }
  1145. }
  1146. }
  1147. // Set animations
  1148. loadAnimations(gltfRuntime);
  1149. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  1150. var skeleton = gltfRuntime.scene.skeletons[i];
  1151. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  1152. }
  1153. };
  1154. /**
  1155. * onBind shaderrs callback to set uniforms and matrices
  1156. */
  1157. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  1158. var materialValues = material.values || technique.parameters;
  1159. for (var unif in unTreatedUniforms) {
  1160. var uniform = unTreatedUniforms[unif];
  1161. var type = uniform.type;
  1162. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  1163. if (uniform.semantic && !uniform.source && !uniform.node) {
  1164. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  1165. }
  1166. else if (uniform.semantic && (uniform.source || uniform.node)) {
  1167. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  1168. if (source === null) {
  1169. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  1170. }
  1171. if (source === null) {
  1172. continue;
  1173. }
  1174. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  1175. }
  1176. }
  1177. else {
  1178. var value = materialValues[technique.uniforms[unif]];
  1179. if (!value) {
  1180. continue;
  1181. }
  1182. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1183. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  1184. if (texture === null || texture === undefined) {
  1185. continue;
  1186. }
  1187. shaderMaterial.getEffect().setTexture(unif, texture);
  1188. }
  1189. else {
  1190. GLTF1.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  1191. }
  1192. }
  1193. }
  1194. onSuccess(shaderMaterial);
  1195. };
  1196. /**
  1197. * Prepare uniforms to send the only one time
  1198. * Loads the appropriate textures
  1199. */
  1200. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  1201. var materialValues = material.values || technique.parameters;
  1202. var techniqueUniforms = technique.uniforms;
  1203. /**
  1204. * Prepare values here (not matrices)
  1205. */
  1206. for (var unif in unTreatedUniforms) {
  1207. var uniform = unTreatedUniforms[unif];
  1208. var type = uniform.type;
  1209. var value = materialValues[techniqueUniforms[unif]];
  1210. if (value === undefined) {
  1211. // In case the value is the same for all materials
  1212. value = uniform.value;
  1213. }
  1214. if (!value) {
  1215. continue;
  1216. }
  1217. var onLoadTexture = function (uniformName) {
  1218. return function (texture) {
  1219. if (uniform.value) {
  1220. // Static uniform
  1221. shaderMaterial.setTexture(uniformName, texture);
  1222. delete unTreatedUniforms[uniformName];
  1223. }
  1224. };
  1225. };
  1226. // Texture (sampler2D)
  1227. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1228. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  1229. }
  1230. else {
  1231. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  1232. // Static uniform
  1233. delete unTreatedUniforms[unif];
  1234. }
  1235. }
  1236. }
  1237. };
  1238. /**
  1239. * Shader compilation failed
  1240. */
  1241. var onShaderCompileError = function (program, shaderMaterial, onError) {
  1242. return function (effect, error) {
  1243. BABYLON.Tools.Error("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1244. shaderMaterial.dispose(true);
  1245. onError();
  1246. };
  1247. };
  1248. /**
  1249. * Shader compilation success
  1250. */
  1251. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1252. return function (_) {
  1253. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1254. shaderMaterial.onBind = function (mesh) {
  1255. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1256. };
  1257. };
  1258. };
  1259. /**
  1260. * Returns the appropriate uniform if already handled by babylon
  1261. */
  1262. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1263. for (var unif in technique.uniforms) {
  1264. var uniform = technique.uniforms[unif];
  1265. var uniformParameter = technique.parameters[uniform];
  1266. if (tokenizer.currentIdentifier === unif) {
  1267. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1268. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1269. if (transformIndex !== -1) {
  1270. delete unTreatedUniforms[unif];
  1271. return babylonTransforms[transformIndex];
  1272. }
  1273. }
  1274. }
  1275. }
  1276. return tokenizer.currentIdentifier;
  1277. };
  1278. /**
  1279. * All shaders loaded. Create materials one by one
  1280. */
  1281. var importMaterials = function (gltfRuntime) {
  1282. // Create materials
  1283. for (var mat in gltfRuntime.materials) {
  1284. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1285. }
  1286. };
  1287. /**
  1288. * Implementation of the base glTF spec
  1289. */
  1290. var GLTFLoaderBase = (function () {
  1291. function GLTFLoaderBase() {
  1292. }
  1293. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1294. var gltfRuntime = {
  1295. extensions: {},
  1296. accessors: {},
  1297. buffers: {},
  1298. bufferViews: {},
  1299. meshes: {},
  1300. lights: {},
  1301. cameras: {},
  1302. nodes: {},
  1303. images: {},
  1304. textures: {},
  1305. shaders: {},
  1306. programs: {},
  1307. samplers: {},
  1308. techniques: {},
  1309. materials: {},
  1310. animations: {},
  1311. skins: {},
  1312. extensionsUsed: [],
  1313. scenes: {},
  1314. buffersCount: 0,
  1315. shaderscount: 0,
  1316. scene: scene,
  1317. rootUrl: rootUrl,
  1318. loadedBufferCount: 0,
  1319. loadedBufferViews: {},
  1320. loadedShaderCount: 0,
  1321. importOnlyMeshes: false,
  1322. dummyNodes: []
  1323. };
  1324. // Parse
  1325. if (parsedData.extensions) {
  1326. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  1327. }
  1328. if (parsedData.extensionsUsed) {
  1329. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1330. }
  1331. if (parsedData.buffers) {
  1332. parseBuffers(parsedData.buffers, gltfRuntime);
  1333. }
  1334. if (parsedData.bufferViews) {
  1335. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1336. }
  1337. if (parsedData.accessors) {
  1338. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1339. }
  1340. if (parsedData.meshes) {
  1341. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1342. }
  1343. if (parsedData.lights) {
  1344. parseObject(parsedData.lights, "lights", gltfRuntime);
  1345. }
  1346. if (parsedData.cameras) {
  1347. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1348. }
  1349. if (parsedData.nodes) {
  1350. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1351. }
  1352. if (parsedData.images) {
  1353. parseObject(parsedData.images, "images", gltfRuntime);
  1354. }
  1355. if (parsedData.textures) {
  1356. parseObject(parsedData.textures, "textures", gltfRuntime);
  1357. }
  1358. if (parsedData.shaders) {
  1359. parseShaders(parsedData.shaders, gltfRuntime);
  1360. }
  1361. if (parsedData.programs) {
  1362. parseObject(parsedData.programs, "programs", gltfRuntime);
  1363. }
  1364. if (parsedData.samplers) {
  1365. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1366. }
  1367. if (parsedData.techniques) {
  1368. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1369. }
  1370. if (parsedData.materials) {
  1371. parseObject(parsedData.materials, "materials", gltfRuntime);
  1372. }
  1373. if (parsedData.animations) {
  1374. parseObject(parsedData.animations, "animations", gltfRuntime);
  1375. }
  1376. if (parsedData.skins) {
  1377. parseObject(parsedData.skins, "skins", gltfRuntime);
  1378. }
  1379. if (parsedData.scenes) {
  1380. gltfRuntime.scenes = parsedData.scenes;
  1381. }
  1382. if (parsedData.scene && parsedData.scenes) {
  1383. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1384. }
  1385. return gltfRuntime;
  1386. };
  1387. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1388. var buffer = gltfRuntime.buffers[id];
  1389. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  1390. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  1391. }
  1392. else {
  1393. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, null, true, onError);
  1394. }
  1395. };
  1396. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1397. var texture = gltfRuntime.textures[id];
  1398. if (!texture || !texture.source) {
  1399. onError();
  1400. return;
  1401. }
  1402. if (texture.babylonTexture) {
  1403. onSuccess(null);
  1404. return;
  1405. }
  1406. var source = gltfRuntime.images[texture.source];
  1407. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  1408. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  1409. }
  1410. else {
  1411. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, onError);
  1412. }
  1413. };
  1414. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1415. var texture = gltfRuntime.textures[id];
  1416. if (texture.babylonTexture) {
  1417. onSuccess(texture.babylonTexture);
  1418. return;
  1419. }
  1420. var sampler = gltfRuntime.samplers[texture.sampler];
  1421. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1422. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1423. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1424. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1425. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1426. var blob = new Blob([buffer]);
  1427. var blobURL = URL.createObjectURL(blob);
  1428. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1429. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1430. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  1431. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  1432. newTexture.name = id;
  1433. texture.babylonTexture = newTexture;
  1434. onSuccess(newTexture);
  1435. };
  1436. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1437. var shader = gltfRuntime.shaders[id];
  1438. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  1439. var shaderString = atob(shader.uri.split(",")[1]);
  1440. onSuccess(shaderString);
  1441. }
  1442. else {
  1443. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, onError);
  1444. }
  1445. };
  1446. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1447. var material = gltfRuntime.materials[id];
  1448. var technique = gltfRuntime.techniques[material.technique];
  1449. if (!technique) {
  1450. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  1451. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  1452. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1453. onSuccess(defaultMaterial);
  1454. return;
  1455. }
  1456. var program = gltfRuntime.programs[technique.program];
  1457. var states = technique.states;
  1458. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1459. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1460. var newVertexShader = "";
  1461. var newPixelShader = "";
  1462. var vertexTokenizer = new Tokenizer(vertexShader);
  1463. var pixelTokenizer = new Tokenizer(pixelShader);
  1464. var unTreatedUniforms = {};
  1465. var uniforms = [];
  1466. var attributes = [];
  1467. var samplers = [];
  1468. // Fill uniform, sampler2D and attributes
  1469. for (var unif in technique.uniforms) {
  1470. var uniform = technique.uniforms[unif];
  1471. var uniformParameter = technique.parameters[uniform];
  1472. unTreatedUniforms[unif] = uniformParameter;
  1473. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1474. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1475. if (transformIndex !== -1) {
  1476. uniforms.push(babylonTransforms[transformIndex]);
  1477. delete unTreatedUniforms[unif];
  1478. }
  1479. else {
  1480. uniforms.push(unif);
  1481. }
  1482. }
  1483. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  1484. samplers.push(unif);
  1485. }
  1486. else {
  1487. uniforms.push(unif);
  1488. }
  1489. }
  1490. for (var attr in technique.attributes) {
  1491. var attribute = technique.attributes[attr];
  1492. var attributeParameter = technique.parameters[attribute];
  1493. if (attributeParameter.semantic) {
  1494. attributes.push(getAttribute(attributeParameter));
  1495. }
  1496. }
  1497. // Configure vertex shader
  1498. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1499. var tokenType = vertexTokenizer.currentToken;
  1500. if (tokenType !== ETokenType.IDENTIFIER) {
  1501. newVertexShader += vertexTokenizer.currentString;
  1502. continue;
  1503. }
  1504. var foundAttribute = false;
  1505. for (var attr in technique.attributes) {
  1506. var attribute = technique.attributes[attr];
  1507. var attributeParameter = technique.parameters[attribute];
  1508. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1509. newVertexShader += getAttribute(attributeParameter);
  1510. foundAttribute = true;
  1511. break;
  1512. }
  1513. }
  1514. if (foundAttribute) {
  1515. continue;
  1516. }
  1517. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1518. }
  1519. // Configure pixel shader
  1520. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1521. var tokenType = pixelTokenizer.currentToken;
  1522. if (tokenType !== ETokenType.IDENTIFIER) {
  1523. newPixelShader += pixelTokenizer.currentString;
  1524. continue;
  1525. }
  1526. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1527. }
  1528. // Create shader material
  1529. var shaderPath = {
  1530. vertex: program.vertexShader + id,
  1531. fragment: program.fragmentShader + id
  1532. };
  1533. var options = {
  1534. attributes: attributes,
  1535. uniforms: uniforms,
  1536. samplers: samplers,
  1537. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  1538. };
  1539. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1540. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1541. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1542. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1543. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1544. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1545. if (states && states.functions) {
  1546. var functions = states.functions;
  1547. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  1548. shaderMaterial.backFaceCulling = false;
  1549. }
  1550. var blendFunc = functions.blendFuncSeparate;
  1551. if (blendFunc) {
  1552. 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) {
  1553. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1554. }
  1555. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1556. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  1557. }
  1558. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1559. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  1560. }
  1561. 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) {
  1562. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  1563. }
  1564. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1565. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  1566. }
  1567. 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) {
  1568. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  1569. }
  1570. }
  1571. }
  1572. };
  1573. return GLTFLoaderBase;
  1574. }());
  1575. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  1576. /**
  1577. * glTF V1 Loader
  1578. */
  1579. var GLTFLoader = (function () {
  1580. function GLTFLoader() {
  1581. }
  1582. GLTFLoader.RegisterExtension = function (extension) {
  1583. if (GLTFLoader.Extensions[extension.name]) {
  1584. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1585. return;
  1586. }
  1587. GLTFLoader.Extensions[extension.name] = extension;
  1588. };
  1589. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onError, onProgress) {
  1590. var _this = this;
  1591. scene.useRightHandedSystem = true;
  1592. var gltfRuntime = GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1593. gltfRuntime.importOnlyMeshes = true;
  1594. if (meshesNames === "") {
  1595. gltfRuntime.importMeshesNames = [];
  1596. }
  1597. else if (typeof meshesNames === "string") {
  1598. gltfRuntime.importMeshesNames = [meshesNames];
  1599. }
  1600. else if (meshesNames && !(meshesNames instanceof Array)) {
  1601. gltfRuntime.importMeshesNames = [meshesNames];
  1602. }
  1603. else {
  1604. gltfRuntime.importMeshesNames = [];
  1605. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1606. }
  1607. // Create nodes
  1608. _this._createNodes(gltfRuntime);
  1609. var meshes = [];
  1610. var skeletons = [];
  1611. // Fill arrays of meshes and skeletons
  1612. for (var nde in gltfRuntime.nodes) {
  1613. var node = gltfRuntime.nodes[nde];
  1614. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  1615. meshes.push(node.babylonNode);
  1616. }
  1617. }
  1618. for (var skl in gltfRuntime.skins) {
  1619. var skin = gltfRuntime.skins[skl];
  1620. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  1621. skeletons.push(skin.babylonSkeleton);
  1622. }
  1623. }
  1624. // Load buffers, shaders, materials, etc.
  1625. _this._loadBuffersAsync(gltfRuntime, function () {
  1626. _this._loadShadersAsync(gltfRuntime, function () {
  1627. importMaterials(gltfRuntime);
  1628. postLoad(gltfRuntime);
  1629. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1630. onSuccess(meshes, null, skeletons);
  1631. }
  1632. });
  1633. }, onProgress);
  1634. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1635. onSuccess(meshes, null, skeletons);
  1636. }
  1637. }, onError);
  1638. return true;
  1639. };
  1640. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1641. var _this = this;
  1642. scene.useRightHandedSystem = true;
  1643. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1644. // Load runtime extensios
  1645. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  1646. // Create nodes
  1647. _this._createNodes(gltfRuntime);
  1648. // Load buffers, shaders, materials, etc.
  1649. _this._loadBuffersAsync(gltfRuntime, function () {
  1650. _this._loadShadersAsync(gltfRuntime, function () {
  1651. importMaterials(gltfRuntime);
  1652. postLoad(gltfRuntime);
  1653. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  1654. onSuccess();
  1655. }
  1656. });
  1657. });
  1658. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  1659. onSuccess();
  1660. }
  1661. }, onError);
  1662. }, onError);
  1663. };
  1664. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  1665. var hasShaders = false;
  1666. var processShader = function (sha, shader) {
  1667. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  1668. gltfRuntime.loadedShaderCount++;
  1669. if (shaderString) {
  1670. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1671. }
  1672. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1673. onload();
  1674. }
  1675. }, function () {
  1676. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1677. });
  1678. };
  1679. for (var sha in gltfRuntime.shaders) {
  1680. hasShaders = true;
  1681. var shader = gltfRuntime.shaders[sha];
  1682. if (shader) {
  1683. processShader.bind(this, sha, shader)();
  1684. }
  1685. else {
  1686. BABYLON.Tools.Error("No shader named: " + sha);
  1687. }
  1688. }
  1689. if (!hasShaders) {
  1690. onload();
  1691. }
  1692. };
  1693. ;
  1694. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onload, onProgress) {
  1695. var hasBuffers = false;
  1696. var processBuffer = function (buf, buffer) {
  1697. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  1698. gltfRuntime.loadedBufferCount++;
  1699. if (bufferView) {
  1700. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  1701. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  1702. }
  1703. gltfRuntime.loadedBufferViews[buf] = bufferView;
  1704. }
  1705. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  1706. onload();
  1707. }
  1708. }, function () {
  1709. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  1710. });
  1711. };
  1712. for (var buf in gltfRuntime.buffers) {
  1713. hasBuffers = true;
  1714. var buffer = gltfRuntime.buffers[buf];
  1715. if (buffer) {
  1716. processBuffer.bind(this, buf, buffer)();
  1717. }
  1718. else {
  1719. BABYLON.Tools.Error("No buffer named: " + buf);
  1720. }
  1721. }
  1722. if (!hasBuffers) {
  1723. onload();
  1724. }
  1725. };
  1726. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  1727. var currentScene = gltfRuntime.currentScene;
  1728. if (currentScene) {
  1729. // Only one scene even if multiple scenes are defined
  1730. for (var i = 0; i < currentScene.nodes.length; i++) {
  1731. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1732. }
  1733. }
  1734. else {
  1735. // Load all scenes
  1736. for (var thing in gltfRuntime.scenes) {
  1737. currentScene = gltfRuntime.scenes[thing];
  1738. for (var i = 0; i < currentScene.nodes.length; i++) {
  1739. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1740. }
  1741. }
  1742. }
  1743. };
  1744. return GLTFLoader;
  1745. }());
  1746. GLTFLoader.Extensions = {};
  1747. GLTF1.GLTFLoader = GLTFLoader;
  1748. ;
  1749. BABYLON.GLTFFileLoader.GLTFLoaderV1 = new GLTFLoader();
  1750. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  1751. })(BABYLON || (BABYLON = {}));
  1752. //# sourceMappingURL=babylon.glTFLoader.js.map
  1753. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1754. var BABYLON;
  1755. (function (BABYLON) {
  1756. var GLTF1;
  1757. (function (GLTF1) {
  1758. /**
  1759. * Utils functions for GLTF
  1760. */
  1761. var GLTFUtils = (function () {
  1762. function GLTFUtils() {
  1763. }
  1764. /**
  1765. * Sets the given "parameter" matrix
  1766. * @param scene: the {BABYLON.Scene} object
  1767. * @param source: the source node where to pick the matrix
  1768. * @param parameter: the GLTF technique parameter
  1769. * @param uniformName: the name of the shader's uniform
  1770. * @param shaderMaterial: the shader material
  1771. */
  1772. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  1773. var mat = null;
  1774. if (parameter.semantic === "MODEL") {
  1775. mat = source.getWorldMatrix();
  1776. }
  1777. else if (parameter.semantic === "PROJECTION") {
  1778. mat = scene.getProjectionMatrix();
  1779. }
  1780. else if (parameter.semantic === "VIEW") {
  1781. mat = scene.getViewMatrix();
  1782. }
  1783. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  1784. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  1785. }
  1786. else if (parameter.semantic === "MODELVIEW") {
  1787. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  1788. }
  1789. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  1790. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  1791. }
  1792. else if (parameter.semantic === "MODELINVERSE") {
  1793. mat = source.getWorldMatrix().invert();
  1794. }
  1795. else if (parameter.semantic === "VIEWINVERSE") {
  1796. mat = scene.getViewMatrix().invert();
  1797. }
  1798. else if (parameter.semantic === "PROJECTIONINVERSE") {
  1799. mat = scene.getProjectionMatrix().invert();
  1800. }
  1801. else if (parameter.semantic === "MODELVIEWINVERSE") {
  1802. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  1803. }
  1804. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  1805. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  1806. }
  1807. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  1808. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  1809. }
  1810. else {
  1811. debugger;
  1812. }
  1813. switch (parameter.type) {
  1814. case GLTF1.EParameterType.FLOAT_MAT2:
  1815. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  1816. break;
  1817. case GLTF1.EParameterType.FLOAT_MAT3:
  1818. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  1819. break;
  1820. case GLTF1.EParameterType.FLOAT_MAT4:
  1821. shaderMaterial.setMatrix(uniformName, mat);
  1822. break;
  1823. default: break;
  1824. }
  1825. };
  1826. /**
  1827. * Sets the given "parameter" matrix
  1828. * @param shaderMaterial: the shader material
  1829. * @param uniform: the name of the shader's uniform
  1830. * @param value: the value of the uniform
  1831. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  1832. */
  1833. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  1834. switch (type) {
  1835. case GLTF1.EParameterType.FLOAT:
  1836. shaderMaterial.setFloat(uniform, value);
  1837. return true;
  1838. case GLTF1.EParameterType.FLOAT_VEC2:
  1839. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  1840. return true;
  1841. case GLTF1.EParameterType.FLOAT_VEC3:
  1842. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  1843. return true;
  1844. case GLTF1.EParameterType.FLOAT_VEC4:
  1845. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  1846. return true;
  1847. default: return false;
  1848. }
  1849. };
  1850. /**
  1851. * If the uri is a base64 string
  1852. * @param uri: the uri to test
  1853. */
  1854. GLTFUtils.IsBase64 = function (uri) {
  1855. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1856. };
  1857. /**
  1858. * Decode the base64 uri
  1859. * @param uri: the uri to decode
  1860. */
  1861. GLTFUtils.DecodeBase64 = function (uri) {
  1862. var decodedString = atob(uri.split(",")[1]);
  1863. var bufferLength = decodedString.length;
  1864. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1865. for (var i = 0; i < bufferLength; i++) {
  1866. bufferView[i] = decodedString.charCodeAt(i);
  1867. }
  1868. return bufferView.buffer;
  1869. };
  1870. /**
  1871. * Returns the wrap mode of the texture
  1872. * @param mode: the mode value
  1873. */
  1874. GLTFUtils.GetWrapMode = function (mode) {
  1875. switch (mode) {
  1876. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1877. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1878. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1879. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1880. }
  1881. };
  1882. /**
  1883. * Returns the byte stride giving an accessor
  1884. * @param accessor: the GLTF accessor objet
  1885. */
  1886. GLTFUtils.GetByteStrideFromType = function (accessor) {
  1887. // Needs this function since "byteStride" isn't requiered in glTF format
  1888. var type = accessor.type;
  1889. switch (type) {
  1890. case "VEC2": return 2;
  1891. case "VEC3": return 3;
  1892. case "VEC4": return 4;
  1893. case "MAT2": return 4;
  1894. case "MAT3": return 9;
  1895. case "MAT4": return 16;
  1896. default: return 1;
  1897. }
  1898. };
  1899. /**
  1900. * Returns the texture filter mode giving a mode value
  1901. * @param mode: the filter mode value
  1902. */
  1903. GLTFUtils.GetTextureFilterMode = function (mode) {
  1904. switch (mode) {
  1905. case GLTF1.ETextureFilterType.LINEAR:
  1906. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  1907. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1908. case GLTF1.ETextureFilterType.NEAREST:
  1909. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  1910. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1911. }
  1912. };
  1913. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  1914. var byteOffset = bufferView.byteOffset + byteOffset;
  1915. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  1916. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  1917. throw new Error("Buffer access is out of range");
  1918. }
  1919. var buffer = loadedBufferView.buffer;
  1920. byteOffset += loadedBufferView.byteOffset;
  1921. switch (componentType) {
  1922. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  1923. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  1924. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  1925. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  1926. default: return new Float32Array(buffer, byteOffset, byteLength);
  1927. }
  1928. };
  1929. /**
  1930. * Returns a buffer from its accessor
  1931. * @param gltfRuntime: the GLTF runtime
  1932. * @param accessor: the GLTF accessor
  1933. */
  1934. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  1935. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  1936. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  1937. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  1938. };
  1939. /**
  1940. * Decodes a buffer view into a string
  1941. * @param view: the buffer view
  1942. */
  1943. GLTFUtils.DecodeBufferToText = function (view) {
  1944. var result = "";
  1945. var length = view.byteLength;
  1946. for (var i = 0; i < length; ++i) {
  1947. result += String.fromCharCode(view[i]);
  1948. }
  1949. return result;
  1950. };
  1951. /**
  1952. * Returns the default material of gltf. Related to
  1953. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  1954. * @param scene: the Babylon.js scene
  1955. */
  1956. GLTFUtils.GetDefaultMaterial = function (scene) {
  1957. if (!GLTFUtils._DefaultMaterial) {
  1958. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  1959. "precision highp float;",
  1960. "",
  1961. "uniform mat4 worldView;",
  1962. "uniform mat4 projection;",
  1963. "",
  1964. "attribute vec3 position;",
  1965. "",
  1966. "void main(void)",
  1967. "{",
  1968. " gl_Position = projection * worldView * vec4(position, 1.0);",
  1969. "}"
  1970. ].join("\n");
  1971. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  1972. "precision highp float;",
  1973. "",
  1974. "uniform vec4 u_emission;",
  1975. "",
  1976. "void main(void)",
  1977. "{",
  1978. " gl_FragColor = u_emission;",
  1979. "}"
  1980. ].join("\n");
  1981. var shaderPath = {
  1982. vertex: "GLTFDefaultMaterial",
  1983. fragment: "GLTFDefaultMaterial"
  1984. };
  1985. var options = {
  1986. attributes: ["position"],
  1987. uniforms: ["worldView", "projection", "u_emission"],
  1988. samplers: [],
  1989. needAlphaBlending: false
  1990. };
  1991. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  1992. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  1993. }
  1994. return GLTFUtils._DefaultMaterial;
  1995. };
  1996. return GLTFUtils;
  1997. }());
  1998. // The GLTF default material
  1999. GLTFUtils._DefaultMaterial = null;
  2000. GLTF1.GLTFUtils = GLTFUtils;
  2001. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2002. })(BABYLON || (BABYLON = {}));
  2003. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  2004. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2005. var BABYLON;
  2006. (function (BABYLON) {
  2007. var GLTF1;
  2008. (function (GLTF1) {
  2009. var GLTFLoaderExtension = (function () {
  2010. function GLTFLoaderExtension(name) {
  2011. this._name = name;
  2012. }
  2013. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  2014. get: function () {
  2015. return this._name;
  2016. },
  2017. enumerable: true,
  2018. configurable: true
  2019. });
  2020. /**
  2021. * Defines an override for loading the runtime
  2022. * Return true to stop further extensions from loading the runtime
  2023. */
  2024. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2025. return false;
  2026. };
  2027. /**
  2028. * Defines an onverride for creating gltf runtime
  2029. * Return true to stop further extensions from creating the runtime
  2030. */
  2031. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2032. return false;
  2033. };
  2034. /**
  2035. * Defines an override for loading buffers
  2036. * Return true to stop further extensions from loading this buffer
  2037. */
  2038. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2039. return false;
  2040. };
  2041. /**
  2042. * Defines an override for loading texture buffers
  2043. * Return true to stop further extensions from loading this texture data
  2044. */
  2045. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2046. return false;
  2047. };
  2048. /**
  2049. * Defines an override for creating textures
  2050. * Return true to stop further extensions from loading this texture
  2051. */
  2052. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2053. return false;
  2054. };
  2055. /**
  2056. * Defines an override for loading shader strings
  2057. * Return true to stop further extensions from loading this shader data
  2058. */
  2059. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2060. return false;
  2061. };
  2062. /**
  2063. * Defines an override for loading materials
  2064. * Return true to stop further extensions from loading this material
  2065. */
  2066. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2067. return false;
  2068. };
  2069. // ---------
  2070. // Utilities
  2071. // ---------
  2072. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2073. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2074. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  2075. }, function () {
  2076. setTimeout(function () {
  2077. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2078. });
  2079. });
  2080. };
  2081. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2082. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2083. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  2084. }, function () {
  2085. setTimeout(function () {
  2086. onSuccess();
  2087. });
  2088. });
  2089. };
  2090. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2091. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2092. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2093. }, function () {
  2094. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2095. });
  2096. };
  2097. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  2098. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  2099. };
  2100. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2101. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2102. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2103. }, function () {
  2104. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2105. });
  2106. };
  2107. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2108. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2109. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2110. }, function () {
  2111. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2112. });
  2113. };
  2114. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2115. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2116. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2117. }, function () {
  2118. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2119. });
  2120. };
  2121. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2122. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2123. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2124. }, function () {
  2125. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2126. });
  2127. };
  2128. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  2129. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  2130. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  2131. if (func(loaderExtension)) {
  2132. return;
  2133. }
  2134. }
  2135. defaultFunc();
  2136. };
  2137. return GLTFLoaderExtension;
  2138. }());
  2139. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  2140. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2141. })(BABYLON || (BABYLON = {}));
  2142. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  2143. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2144. var __extends = (this && this.__extends) || (function () {
  2145. var extendStatics = Object.setPrototypeOf ||
  2146. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2147. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2148. return function (d, b) {
  2149. extendStatics(d, b);
  2150. function __() { this.constructor = d; }
  2151. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2152. };
  2153. })();
  2154. var BABYLON;
  2155. (function (BABYLON) {
  2156. var GLTF1;
  2157. (function (GLTF1) {
  2158. var BinaryExtensionBufferName = "binary_glTF";
  2159. var EContentFormat;
  2160. (function (EContentFormat) {
  2161. EContentFormat[EContentFormat["JSON"] = 0] = "JSON";
  2162. })(EContentFormat || (EContentFormat = {}));
  2163. ;
  2164. ;
  2165. ;
  2166. var GLTFBinaryExtension = (function (_super) {
  2167. __extends(GLTFBinaryExtension, _super);
  2168. function GLTFBinaryExtension() {
  2169. return _super.call(this, "KHR_binary_glTF") || this;
  2170. }
  2171. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2172. var extensionsUsed = data.json.extensionsUsed;
  2173. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1) {
  2174. return false;
  2175. }
  2176. this._bin = data.bin;
  2177. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2178. return true;
  2179. };
  2180. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2181. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  2182. return false;
  2183. }
  2184. if (id !== BinaryExtensionBufferName) {
  2185. return false;
  2186. }
  2187. onSuccess(this._bin);
  2188. return true;
  2189. };
  2190. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2191. var texture = gltfRuntime.textures[id];
  2192. var source = gltfRuntime.images[texture.source];
  2193. if (!source.extensions || !(this.name in source.extensions)) {
  2194. return false;
  2195. }
  2196. var sourceExt = source.extensions[this.name];
  2197. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  2198. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2199. onSuccess(buffer);
  2200. return true;
  2201. };
  2202. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2203. var shader = gltfRuntime.shaders[id];
  2204. if (!shader.extensions || !(this.name in shader.extensions)) {
  2205. return false;
  2206. }
  2207. var binaryExtensionShader = shader.extensions[this.name];
  2208. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  2209. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2210. setTimeout(function () {
  2211. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  2212. onSuccess(shaderString);
  2213. });
  2214. return true;
  2215. };
  2216. return GLTFBinaryExtension;
  2217. }(GLTF1.GLTFLoaderExtension));
  2218. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  2219. var BinaryReader = (function () {
  2220. function BinaryReader(arrayBuffer) {
  2221. this._arrayBuffer = arrayBuffer;
  2222. this._dataView = new DataView(arrayBuffer);
  2223. this._byteOffset = 0;
  2224. }
  2225. BinaryReader.prototype.getUint32 = function () {
  2226. var value = this._dataView.getUint32(this._byteOffset, true);
  2227. this._byteOffset += 4;
  2228. return value;
  2229. };
  2230. BinaryReader.prototype.getUint8Array = function (length) {
  2231. if (!length) {
  2232. length = this._arrayBuffer.byteLength - this._byteOffset;
  2233. }
  2234. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  2235. this._byteOffset += length;
  2236. return value;
  2237. };
  2238. return BinaryReader;
  2239. }());
  2240. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  2241. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2242. })(BABYLON || (BABYLON = {}));
  2243. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  2244. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2245. var __extends = (this && this.__extends) || (function () {
  2246. var extendStatics = Object.setPrototypeOf ||
  2247. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2248. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2249. return function (d, b) {
  2250. extendStatics(d, b);
  2251. function __() { this.constructor = d; }
  2252. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2253. };
  2254. })();
  2255. var BABYLON;
  2256. (function (BABYLON) {
  2257. var GLTF1;
  2258. (function (GLTF1) {
  2259. ;
  2260. ;
  2261. ;
  2262. var GLTFMaterialsCommonExtension = (function (_super) {
  2263. __extends(GLTFMaterialsCommonExtension, _super);
  2264. function GLTFMaterialsCommonExtension() {
  2265. return _super.call(this, "KHR_materials_common") || this;
  2266. }
  2267. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2268. if (!gltfRuntime.extensions)
  2269. return false;
  2270. var extension = gltfRuntime.extensions[this.name];
  2271. if (!extension)
  2272. return false;
  2273. // Create lights
  2274. var lights = extension.lights;
  2275. if (lights) {
  2276. for (var thing in lights) {
  2277. var light = lights[thing];
  2278. switch (light.type) {
  2279. case "ambient":
  2280. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  2281. var ambient = light.ambient;
  2282. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  2283. break;
  2284. case "point":
  2285. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  2286. var point = light.point;
  2287. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  2288. break;
  2289. case "directional":
  2290. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  2291. var directional = light.directional;
  2292. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  2293. break;
  2294. case "spot":
  2295. var spot = light.spot;
  2296. 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);
  2297. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  2298. break;
  2299. default:
  2300. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  2301. break;
  2302. }
  2303. }
  2304. }
  2305. return false;
  2306. };
  2307. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2308. var material = gltfRuntime.materials[id];
  2309. if (!material || !material.extensions)
  2310. return false;
  2311. var extension = material.extensions[this.name];
  2312. if (!extension)
  2313. return false;
  2314. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  2315. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2316. if (extension.technique === "CONSTANT") {
  2317. standardMaterial.disableLighting = true;
  2318. }
  2319. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  2320. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  2321. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  2322. // Ambient
  2323. if (typeof extension.values.ambient === "string") {
  2324. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  2325. }
  2326. else {
  2327. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  2328. }
  2329. // Diffuse
  2330. if (typeof extension.values.diffuse === "string") {
  2331. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  2332. }
  2333. else {
  2334. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  2335. }
  2336. // Emission
  2337. if (typeof extension.values.emission === "string") {
  2338. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  2339. }
  2340. else {
  2341. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  2342. }
  2343. // Specular
  2344. if (typeof extension.values.specular === "string") {
  2345. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  2346. }
  2347. else {
  2348. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  2349. }
  2350. return true;
  2351. };
  2352. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  2353. // Create buffer from texture url
  2354. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2355. // Create texture from buffer
  2356. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  2357. }, onError);
  2358. };
  2359. return GLTFMaterialsCommonExtension;
  2360. }(GLTF1.GLTFLoaderExtension));
  2361. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  2362. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  2363. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2364. })(BABYLON || (BABYLON = {}));
  2365. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  2366. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2367. var BABYLON;
  2368. (function (BABYLON) {
  2369. var GLTF2;
  2370. (function (GLTF2) {
  2371. /**
  2372. * Enums
  2373. */
  2374. var EBufferViewTarget;
  2375. (function (EBufferViewTarget) {
  2376. EBufferViewTarget[EBufferViewTarget["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER";
  2377. EBufferViewTarget[EBufferViewTarget["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER";
  2378. })(EBufferViewTarget = GLTF2.EBufferViewTarget || (GLTF2.EBufferViewTarget = {}));
  2379. var EComponentType;
  2380. (function (EComponentType) {
  2381. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  2382. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  2383. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  2384. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  2385. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  2386. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  2387. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  2388. var EMeshPrimitiveMode;
  2389. (function (EMeshPrimitiveMode) {
  2390. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  2391. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  2392. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  2393. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  2394. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  2395. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  2396. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  2397. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  2398. var EParameterType;
  2399. (function (EParameterType) {
  2400. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  2401. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  2402. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  2403. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  2404. EParameterType[EParameterType["INT"] = 5124] = "INT";
  2405. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  2406. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  2407. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  2408. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  2409. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  2410. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  2411. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  2412. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  2413. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  2414. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  2415. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  2416. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  2417. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  2418. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  2419. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  2420. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  2421. })(EParameterType = GLTF2.EParameterType || (GLTF2.EParameterType = {}));
  2422. var ETextureMagFilter;
  2423. (function (ETextureMagFilter) {
  2424. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  2425. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  2426. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  2427. var ETextureMinFilter;
  2428. (function (ETextureMinFilter) {
  2429. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  2430. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  2431. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  2432. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  2433. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  2434. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  2435. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  2436. var ETextureFormat;
  2437. (function (ETextureFormat) {
  2438. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  2439. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  2440. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  2441. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  2442. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  2443. })(ETextureFormat = GLTF2.ETextureFormat || (GLTF2.ETextureFormat = {}));
  2444. var ETextureTarget;
  2445. (function (ETextureTarget) {
  2446. ETextureTarget[ETextureTarget["TEXTURE_2D"] = 3553] = "TEXTURE_2D";
  2447. })(ETextureTarget = GLTF2.ETextureTarget || (GLTF2.ETextureTarget = {}));
  2448. var ETextureType;
  2449. (function (ETextureType) {
  2450. ETextureType[ETextureType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  2451. ETextureType[ETextureType["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5";
  2452. ETextureType[ETextureType["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4";
  2453. ETextureType[ETextureType["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1";
  2454. })(ETextureType = GLTF2.ETextureType || (GLTF2.ETextureType = {}));
  2455. var ETextureWrapMode;
  2456. (function (ETextureWrapMode) {
  2457. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  2458. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  2459. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  2460. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  2461. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2462. })(BABYLON || (BABYLON = {}));
  2463. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  2464. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2465. var BABYLON;
  2466. (function (BABYLON) {
  2467. var GLTF2;
  2468. (function (GLTF2) {
  2469. /**
  2470. * Values
  2471. */
  2472. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  2473. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  2474. /**
  2475. * Utils
  2476. */
  2477. var normalizeUVs = function (buffer) {
  2478. if (!buffer) {
  2479. return;
  2480. }
  2481. for (var i = 0; i < buffer.length / 2; i++) {
  2482. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  2483. }
  2484. };
  2485. var createStringId = function (index) {
  2486. return "node" + index;
  2487. };
  2488. /**
  2489. * Returns the animation path (glTF -> Babylon)
  2490. */
  2491. var getAnimationPath = function (path) {
  2492. var index = glTFAnimationPaths.indexOf(path);
  2493. if (index !== -1) {
  2494. return babylonAnimationPaths[index];
  2495. }
  2496. return path;
  2497. };
  2498. /**
  2499. * Loads and creates animations
  2500. */
  2501. var loadAnimations = function (runtime) {
  2502. var animations = runtime.gltf.animations;
  2503. if (!animations) {
  2504. return;
  2505. }
  2506. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  2507. var animation = animations[animationIndex];
  2508. if (!animation || !animation.channels || !animation.samplers) {
  2509. continue;
  2510. }
  2511. var lastAnimation = null;
  2512. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  2513. var channel = animation.channels[channelIndex];
  2514. if (!channel) {
  2515. continue;
  2516. }
  2517. var sampler = animation.samplers[channel.sampler];
  2518. if (!sampler) {
  2519. continue;
  2520. }
  2521. var inputData = sampler.input;
  2522. var outputData = sampler.output;
  2523. var bufferInput = GLTF2.GLTFUtils.GetBufferFromAccessor(runtime, runtime.gltf.accessors[inputData]);
  2524. var bufferOutput = GLTF2.GLTFUtils.GetBufferFromAccessor(runtime, runtime.gltf.accessors[outputData]);
  2525. var targetID = channel.target.node;
  2526. var targetNode = runtime.babylonScene.getNodeByID(createStringId(targetID));
  2527. if (targetNode === null) {
  2528. BABYLON.Tools.Warn("Creating animation index " + animationIndex + " but cannot find node index " + targetID + " to attach to");
  2529. continue;
  2530. }
  2531. var isBone = targetNode instanceof BABYLON.Bone;
  2532. // Get target path (position, rotation or scaling)
  2533. var targetPath = channel.target.path;
  2534. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  2535. if (targetPathIndex !== -1) {
  2536. targetPath = babylonAnimationPaths[targetPathIndex];
  2537. }
  2538. // Determine animation type
  2539. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  2540. if (!isBone) {
  2541. if (targetPath === "rotationQuaternion") {
  2542. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  2543. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  2544. }
  2545. else {
  2546. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  2547. }
  2548. }
  2549. // Create animation and key frames
  2550. var babylonAnimation = null;
  2551. var keys = [];
  2552. var arrayOffset = 0;
  2553. var modifyKey = false;
  2554. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  2555. babylonAnimation = lastAnimation;
  2556. modifyKey = true;
  2557. }
  2558. if (!modifyKey) {
  2559. var animationName = animation.name || "anim" + animationIndex;
  2560. babylonAnimation = new BABYLON.Animation(animationName, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  2561. }
  2562. // For each frame
  2563. for (var j = 0; j < bufferInput.length; j++) {
  2564. var value = null;
  2565. if (targetPath === "rotationQuaternion") {
  2566. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  2567. arrayOffset += 4;
  2568. }
  2569. else {
  2570. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  2571. arrayOffset += 3;
  2572. }
  2573. if (isBone) {
  2574. var bone = targetNode;
  2575. var translation = BABYLON.Vector3.Zero();
  2576. var rotationQuaternion = new BABYLON.Quaternion();
  2577. var scaling = BABYLON.Vector3.Zero();
  2578. // Warning on decompose
  2579. var mat = bone.getBaseMatrix();
  2580. if (modifyKey) {
  2581. mat = lastAnimation.getKeys()[j].value;
  2582. }
  2583. mat.decompose(scaling, rotationQuaternion, translation);
  2584. if (targetPath === "position") {
  2585. translation = value;
  2586. }
  2587. else if (targetPath === "rotationQuaternion") {
  2588. rotationQuaternion = value;
  2589. }
  2590. else {
  2591. scaling = value;
  2592. }
  2593. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  2594. }
  2595. if (!modifyKey) {
  2596. keys.push({
  2597. frame: bufferInput[j],
  2598. value: value
  2599. });
  2600. }
  2601. else {
  2602. lastAnimation.getKeys()[j].value = value;
  2603. }
  2604. }
  2605. // Finish
  2606. if (!modifyKey) {
  2607. babylonAnimation.setKeys(keys);
  2608. targetNode.animations.push(babylonAnimation);
  2609. }
  2610. lastAnimation = babylonAnimation;
  2611. runtime.babylonScene.stopAnimation(targetNode);
  2612. runtime.babylonScene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  2613. }
  2614. }
  2615. };
  2616. /**
  2617. * Returns the bones transformation matrix
  2618. */
  2619. var configureBoneTransformation = function (node) {
  2620. var mat = null;
  2621. if (node.translation || node.rotation || node.scale) {
  2622. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  2623. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  2624. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  2625. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  2626. }
  2627. else {
  2628. mat = node.matrix ? BABYLON.Matrix.FromArray(node.matrix) : BABYLON.Matrix.Identity();
  2629. }
  2630. return mat;
  2631. };
  2632. /**
  2633. * Returns the parent bone
  2634. */
  2635. var getParentBone = function (runtime, skin, index, newSkeleton) {
  2636. // Try to find
  2637. var nodeStringID = createStringId(index);
  2638. for (var i = 0; i < newSkeleton.bones.length; i++) {
  2639. if (newSkeleton.bones[i].id === nodeStringID) {
  2640. return newSkeleton.bones[i].getParent();
  2641. }
  2642. }
  2643. // Not found, search in gltf nodes
  2644. var joints = skin.joints;
  2645. for (var j = 0; j < joints.length; j++) {
  2646. var parentID = joints[j];
  2647. var parent = runtime.gltf.nodes[parentID];
  2648. var children = parent.children;
  2649. for (var i = 0; i < children.length; i++) {
  2650. var childID = children[i];
  2651. var child = runtime.gltf.nodes[childID];
  2652. if (!nodeIsInJoints(skin, childID)) {
  2653. continue;
  2654. }
  2655. if (childID === index) {
  2656. var mat = configureBoneTransformation(parent);
  2657. var bone = new BABYLON.Bone(parent.name || createStringId(parentID), newSkeleton, getParentBone(runtime, skin, parentID, newSkeleton), mat);
  2658. bone.id = createStringId(parentID);
  2659. return bone;
  2660. }
  2661. }
  2662. }
  2663. return null;
  2664. };
  2665. /**
  2666. * Returns the appropriate root node
  2667. */
  2668. var getNodeToRoot = function (nodesToRoot, index) {
  2669. for (var i = 0; i < nodesToRoot.length; i++) {
  2670. var nodeToRoot = nodesToRoot[i];
  2671. if (nodeToRoot.node.children) {
  2672. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  2673. var child = nodeToRoot.node.children[j];
  2674. if (child === index) {
  2675. return nodeToRoot.bone;
  2676. }
  2677. }
  2678. }
  2679. }
  2680. return null;
  2681. };
  2682. /**
  2683. * Returns the node with the node index
  2684. */
  2685. var getJointNode = function (runtime, index) {
  2686. var node = runtime.gltf.nodes[index];
  2687. if (node) {
  2688. return {
  2689. node: node,
  2690. index: index
  2691. };
  2692. }
  2693. return null;
  2694. };
  2695. /**
  2696. * Checks if a nodes is in joints
  2697. */
  2698. var nodeIsInJoints = function (skin, index) {
  2699. for (var i = 0; i < skin.joints.length; i++) {
  2700. if (skin.joints[i] === index) {
  2701. return true;
  2702. }
  2703. }
  2704. return false;
  2705. };
  2706. /**
  2707. * Fills the nodes to root for bones and builds hierarchy
  2708. */
  2709. var getNodesToRoot = function (runtime, newSkeleton, skin, nodesToRoot) {
  2710. // Creates nodes for root
  2711. for (var i = 0; i < runtime.gltf.nodes.length; i++) {
  2712. var node = runtime.gltf.nodes[i];
  2713. if (nodeIsInJoints(skin, i)) {
  2714. continue;
  2715. }
  2716. // Create node to root bone
  2717. var mat = configureBoneTransformation(node);
  2718. var bone = new BABYLON.Bone(node.name || createStringId(i), newSkeleton, null, mat);
  2719. bone.id = createStringId(i);
  2720. nodesToRoot.push({ bone: bone, node: node, index: i });
  2721. }
  2722. // Parenting
  2723. for (var i = 0; i < nodesToRoot.length; i++) {
  2724. var nodeToRoot = nodesToRoot[i];
  2725. var children = nodeToRoot.node.children;
  2726. if (children) {
  2727. for (var j = 0; j < children.length; j++) {
  2728. var child = null;
  2729. for (var k = 0; k < nodesToRoot.length; k++) {
  2730. if (nodesToRoot[k].index === children[j]) {
  2731. child = nodesToRoot[k];
  2732. break;
  2733. }
  2734. }
  2735. if (child) {
  2736. child.bone._parent = nodeToRoot.bone;
  2737. nodeToRoot.bone.children.push(child.bone);
  2738. }
  2739. }
  2740. }
  2741. }
  2742. };
  2743. /**
  2744. * Imports a skeleton
  2745. */
  2746. var importSkeleton = function (runtime, skinNode, skin) {
  2747. var name = skin.name || "skin" + skinNode.skin;
  2748. var babylonSkeleton = skin.babylonSkeleton;
  2749. if (!babylonSkeleton) {
  2750. babylonSkeleton = new BABYLON.Skeleton(name, "skin" + skinNode.skin, runtime.babylonScene);
  2751. }
  2752. if (!skin.babylonSkeleton) {
  2753. return babylonSkeleton;
  2754. }
  2755. // Matrices
  2756. var accessor = runtime.gltf.accessors[skin.inverseBindMatrices];
  2757. var buffer = GLTF2.GLTFUtils.GetBufferFromAccessor(runtime, accessor);
  2758. // Find the root bones
  2759. var nodesToRoot = [];
  2760. var nodesToRootToAdd = [];
  2761. getNodesToRoot(runtime, babylonSkeleton, skin, nodesToRoot);
  2762. babylonSkeleton.bones = [];
  2763. // Joints
  2764. for (var i = 0; i < skin.joints.length; i++) {
  2765. var jointNode = getJointNode(runtime, skin.joints[i]);
  2766. var node = jointNode.node;
  2767. if (!node) {
  2768. BABYLON.Tools.Warn("Joint index " + skin.joints[i] + " does not exist");
  2769. continue;
  2770. }
  2771. var index = jointNode.index;
  2772. var stringID = createStringId(index);
  2773. // Optimize, if the bone already exists...
  2774. var existingBone = runtime.babylonScene.getBoneByID(stringID);
  2775. if (existingBone) {
  2776. babylonSkeleton.bones.push(existingBone);
  2777. continue;
  2778. }
  2779. // Search for parent bone
  2780. var foundBone = false;
  2781. var parentBone = null;
  2782. for (var j = 0; j < i; j++) {
  2783. var joint = getJointNode(runtime, skin.joints[j]).node;
  2784. if (!joint) {
  2785. BABYLON.Tools.Warn("Joint index " + skin.joints[j] + " does not exist when looking for parent");
  2786. continue;
  2787. }
  2788. var children = joint.children;
  2789. foundBone = false;
  2790. for (var k = 0; k < children.length; k++) {
  2791. if (children[k] === index) {
  2792. parentBone = getParentBone(runtime, skin, skin.joints[j], babylonSkeleton);
  2793. foundBone = true;
  2794. break;
  2795. }
  2796. }
  2797. if (foundBone) {
  2798. break;
  2799. }
  2800. }
  2801. // Create bone
  2802. var mat = configureBoneTransformation(node);
  2803. if (!parentBone && nodesToRoot.length > 0) {
  2804. parentBone = getNodeToRoot(nodesToRoot, index);
  2805. if (parentBone) {
  2806. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  2807. nodesToRootToAdd.push(parentBone);
  2808. }
  2809. }
  2810. }
  2811. var bone = new BABYLON.Bone(node.name || stringID, babylonSkeleton, parentBone, mat);
  2812. bone.id = stringID;
  2813. }
  2814. // Polish
  2815. var bones = babylonSkeleton.bones;
  2816. babylonSkeleton.bones = [];
  2817. for (var i = 0; i < skin.joints.length; i++) {
  2818. var jointNode = getJointNode(runtime, skin.joints[i]);
  2819. if (!jointNode) {
  2820. continue;
  2821. }
  2822. var jointNodeStringId = createStringId(jointNode.index);
  2823. for (var j = 0; j < bones.length; j++) {
  2824. if (bones[j].id === jointNodeStringId) {
  2825. babylonSkeleton.bones.push(bones[j]);
  2826. break;
  2827. }
  2828. }
  2829. }
  2830. babylonSkeleton.prepare();
  2831. // Finish
  2832. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  2833. babylonSkeleton.bones.push(nodesToRootToAdd[i]);
  2834. }
  2835. return babylonSkeleton;
  2836. };
  2837. /**
  2838. * Gets a material
  2839. */
  2840. var getMaterial = function (runtime, index) {
  2841. if (index === undefined) {
  2842. return GLTF2.GLTFUtils.GetDefaultMaterial(runtime);
  2843. }
  2844. var materials = runtime.gltf.materials;
  2845. if (!materials || index < 0 || index >= materials.length) {
  2846. BABYLON.Tools.Error("Invalid material index");
  2847. return GLTF2.GLTFUtils.GetDefaultMaterial(runtime);
  2848. }
  2849. var material = runtime.gltf.materials[index].babylonMaterial;
  2850. if (!material) {
  2851. return GLTF2.GLTFUtils.GetDefaultMaterial(runtime);
  2852. }
  2853. return material;
  2854. };
  2855. /**
  2856. * Imports a mesh and its geometries
  2857. */
  2858. var importMesh = function (runtime, node, mesh) {
  2859. var name = mesh.name || node.name || "mesh" + node.mesh;
  2860. var babylonMesh = node.babylonNode;
  2861. if (!babylonMesh) {
  2862. babylonMesh = new BABYLON.Mesh(name, runtime.babylonScene);
  2863. }
  2864. if (!node.babylonNode) {
  2865. return babylonMesh;
  2866. }
  2867. var multiMat = new BABYLON.MultiMaterial(name, runtime.babylonScene);
  2868. if (!babylonMesh.material) {
  2869. babylonMesh.material = multiMat;
  2870. }
  2871. var vertexData = new BABYLON.VertexData();
  2872. var geometry = new BABYLON.Geometry(name, runtime.babylonScene, vertexData, false, babylonMesh);
  2873. var verticesStarts = [];
  2874. var verticesCounts = [];
  2875. var indexStarts = [];
  2876. var indexCounts = [];
  2877. // Positions, normals and UVs
  2878. for (var index = 0; index < mesh.primitives.length; index++) {
  2879. // Temporary vertex data
  2880. var tempVertexData = new BABYLON.VertexData();
  2881. var primitive = mesh.primitives[index];
  2882. if (primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  2883. // continue;
  2884. }
  2885. var attributes = primitive.attributes;
  2886. var accessor = null;
  2887. var buffer = null;
  2888. // Set positions, normal and uvs
  2889. for (var semantic in attributes) {
  2890. // Link accessor and buffer view
  2891. accessor = runtime.gltf.accessors[attributes[semantic]];
  2892. buffer = GLTF2.GLTFUtils.GetBufferFromAccessor(runtime, accessor);
  2893. if (semantic === "NORMAL") {
  2894. tempVertexData.normals = new Float32Array(buffer.length);
  2895. tempVertexData.normals.set(buffer);
  2896. }
  2897. else if (semantic === "POSITION") {
  2898. tempVertexData.positions = new Float32Array(buffer.length);
  2899. tempVertexData.positions.set(buffer);
  2900. verticesCounts.push(tempVertexData.positions.length);
  2901. }
  2902. else if (semantic === "TANGENT") {
  2903. tempVertexData.tangents = new Float32Array(buffer.length);
  2904. tempVertexData.tangents.set(buffer);
  2905. }
  2906. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  2907. var channel = Number(semantic.split("_")[1]);
  2908. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  2909. var uvs = new Float32Array(buffer.length);
  2910. uvs.set(buffer);
  2911. normalizeUVs(uvs);
  2912. tempVertexData.set(uvs, uvKind);
  2913. }
  2914. else if (semantic === "JOINT") {
  2915. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  2916. tempVertexData.matricesIndices.set(buffer);
  2917. }
  2918. else if (semantic === "WEIGHT") {
  2919. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  2920. tempVertexData.matricesWeights.set(buffer);
  2921. }
  2922. else if (semantic === "COLOR_0") {
  2923. tempVertexData.colors = new Float32Array(buffer.length);
  2924. tempVertexData.colors.set(buffer);
  2925. }
  2926. else {
  2927. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  2928. }
  2929. }
  2930. // Indices
  2931. accessor = runtime.gltf.accessors[primitive.indices];
  2932. if (accessor) {
  2933. buffer = GLTF2.GLTFUtils.GetBufferFromAccessor(runtime, accessor);
  2934. tempVertexData.indices = new Int32Array(buffer.length);
  2935. tempVertexData.indices.set(buffer);
  2936. indexCounts.push(tempVertexData.indices.length);
  2937. }
  2938. else {
  2939. // Set indices on the fly
  2940. var indices = [];
  2941. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  2942. indices.push(j);
  2943. }
  2944. tempVertexData.indices = new Int32Array(indices);
  2945. indexCounts.push(tempVertexData.indices.length);
  2946. }
  2947. vertexData.merge(tempVertexData);
  2948. tempVertexData = undefined;
  2949. // Sub material
  2950. var material = getMaterial(runtime, primitive.material);
  2951. multiMat.subMaterials.push(material);
  2952. // Update vertices start and index start
  2953. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  2954. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  2955. }
  2956. // Apply geometry
  2957. geometry.setAllVerticesData(vertexData, false);
  2958. babylonMesh.computeWorldMatrix(true);
  2959. // Apply submeshes
  2960. babylonMesh.subMeshes = [];
  2961. for (var index = 0; index < mesh.primitives.length; index++) {
  2962. if (mesh.primitives[index].mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  2963. //continue;
  2964. }
  2965. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], babylonMesh, babylonMesh, true);
  2966. }
  2967. // Finish
  2968. return babylonMesh;
  2969. };
  2970. /**
  2971. * Configures node transformation
  2972. */
  2973. var configureNode = function (babylonNode, node) {
  2974. var position = BABYLON.Vector3.Zero();
  2975. var rotation = BABYLON.Quaternion.Identity();
  2976. var scaling = new BABYLON.Vector3(1, 1, 1);
  2977. if (node.matrix) {
  2978. var mat = BABYLON.Matrix.FromArray(node.matrix);
  2979. mat.decompose(scaling, rotation, position);
  2980. }
  2981. else {
  2982. if (node.translation) {
  2983. position = BABYLON.Vector3.FromArray(node.translation);
  2984. }
  2985. if (node.rotation) {
  2986. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  2987. }
  2988. if (node.scale) {
  2989. scaling = BABYLON.Vector3.FromArray(node.scale);
  2990. }
  2991. }
  2992. babylonNode.position = position;
  2993. babylonNode.rotationQuaternion = rotation;
  2994. if (babylonNode instanceof BABYLON.Mesh) {
  2995. var mesh = babylonNode;
  2996. mesh.scaling = scaling;
  2997. }
  2998. };
  2999. /**
  3000. * Imports a node
  3001. */
  3002. var importNode = function (runtime, node) {
  3003. var babylonNode = null;
  3004. if (runtime.importOnlyMeshes && (node.skin !== undefined || node.mesh !== undefined)) {
  3005. if (runtime.importMeshesNames.length > 0 && runtime.importMeshesNames.indexOf(node.name) === -1) {
  3006. return null;
  3007. }
  3008. }
  3009. // Meshes
  3010. if (node.skin !== undefined) {
  3011. if (node.mesh !== undefined) {
  3012. var skin = runtime.gltf.skins[node.skin];
  3013. var newMesh = importMesh(runtime, node, runtime.gltf.meshes[node.mesh]);
  3014. var newSkeleton = importSkeleton(runtime, node, skin);
  3015. if (newSkeleton) {
  3016. newMesh.skeleton = newSkeleton;
  3017. skin.babylonSkeleton = newSkeleton;
  3018. }
  3019. babylonNode = newMesh;
  3020. }
  3021. }
  3022. else if (node.mesh !== undefined) {
  3023. babylonNode = importMesh(runtime, node, runtime.gltf.meshes[node.mesh]);
  3024. }
  3025. else if (node.camera !== undefined && !node.babylonNode && !runtime.importOnlyMeshes) {
  3026. var camera = runtime.gltf.cameras[node.camera];
  3027. if (camera !== undefined) {
  3028. if (camera.type === "orthographic") {
  3029. var orthographicCamera = camera.orthographic;
  3030. var orthoCamera = new BABYLON.FreeCamera(node.name || "camera" + node.camera, BABYLON.Vector3.Zero(), runtime.babylonScene);
  3031. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  3032. orthoCamera.attachControl(runtime.babylonScene.getEngine().getRenderingCanvas());
  3033. babylonNode = orthoCamera;
  3034. }
  3035. else if (camera.type === "perspective") {
  3036. var perspectiveCamera = camera.perspective;
  3037. var persCamera = new BABYLON.FreeCamera(node.name || "camera" + node.camera, BABYLON.Vector3.Zero(), runtime.babylonScene);
  3038. persCamera.attachControl(runtime.babylonScene.getEngine().getRenderingCanvas());
  3039. if (!perspectiveCamera.aspectRatio) {
  3040. perspectiveCamera.aspectRatio = runtime.babylonScene.getEngine().getRenderWidth() / runtime.babylonScene.getEngine().getRenderHeight();
  3041. }
  3042. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  3043. persCamera.maxZ = perspectiveCamera.zfar;
  3044. persCamera.minZ = perspectiveCamera.znear;
  3045. }
  3046. babylonNode = persCamera;
  3047. }
  3048. }
  3049. }
  3050. // Empty node
  3051. if (node.babylonNode) {
  3052. return node.babylonNode;
  3053. }
  3054. else if (babylonNode === null) {
  3055. var dummy = new BABYLON.Mesh(node.name || "mesh" + node.mesh, runtime.babylonScene);
  3056. node.babylonNode = dummy;
  3057. babylonNode = dummy;
  3058. }
  3059. if (babylonNode !== null) {
  3060. configureNode(babylonNode, node);
  3061. babylonNode.updateCache(true);
  3062. node.babylonNode = babylonNode;
  3063. }
  3064. return babylonNode;
  3065. };
  3066. /**
  3067. * Traverses nodes and creates them
  3068. */
  3069. var traverseNodes = function (runtime, index, parent, meshIncluded) {
  3070. var node = runtime.gltf.nodes[index];
  3071. var newNode = null;
  3072. if (runtime.importOnlyMeshes && !meshIncluded) {
  3073. if (runtime.importMeshesNames.indexOf(node.name) !== -1 || runtime.importMeshesNames.length === 0) {
  3074. meshIncluded = true;
  3075. }
  3076. else {
  3077. meshIncluded = false;
  3078. }
  3079. }
  3080. else {
  3081. meshIncluded = true;
  3082. }
  3083. if (meshIncluded) {
  3084. newNode = importNode(runtime, node);
  3085. if (newNode !== null) {
  3086. newNode.id = createStringId(index);
  3087. newNode.parent = parent;
  3088. }
  3089. }
  3090. if (node.children) {
  3091. for (var i = 0; i < node.children.length; i++) {
  3092. traverseNodes(runtime, node.children[i], newNode, meshIncluded);
  3093. }
  3094. }
  3095. };
  3096. var importScene = function (runtime) {
  3097. var scene = runtime.gltf.scene || 0;
  3098. var scenes = runtime.gltf.scenes;
  3099. if (scenes) {
  3100. var nodes = scenes[scene].nodes;
  3101. for (var i = 0; i < nodes.length; i++) {
  3102. traverseNodes(runtime, nodes[i], null);
  3103. }
  3104. }
  3105. else {
  3106. for (var i = 0; i < runtime.gltf.nodes.length; i++) {
  3107. traverseNodes(runtime, i, null);
  3108. }
  3109. }
  3110. };
  3111. /**
  3112. * do stuff after buffers are loaded (e.g. hook up materials, load animations, etc.)
  3113. */
  3114. var postLoad = function (runtime) {
  3115. importScene(runtime);
  3116. // Set animations
  3117. loadAnimations(runtime);
  3118. for (var i = 0; i < runtime.babylonScene.skeletons.length; i++) {
  3119. var skeleton = runtime.babylonScene.skeletons[i];
  3120. runtime.babylonScene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  3121. }
  3122. // Revoke object urls created during load
  3123. if (runtime.gltf.textures) {
  3124. for (var i = 0; i < runtime.gltf.textures.length; i++) {
  3125. var texture = runtime.gltf.textures[i];
  3126. if (texture.blobURL) {
  3127. URL.revokeObjectURL(texture.blobURL);
  3128. }
  3129. }
  3130. }
  3131. };
  3132. var BinaryReader = (function () {
  3133. function BinaryReader(arrayBuffer) {
  3134. this._arrayBuffer = arrayBuffer;
  3135. this._dataView = new DataView(arrayBuffer);
  3136. this._byteOffset = 0;
  3137. }
  3138. BinaryReader.prototype.getPosition = function () {
  3139. return this._byteOffset;
  3140. };
  3141. BinaryReader.prototype.getLength = function () {
  3142. return this._arrayBuffer.byteLength;
  3143. };
  3144. BinaryReader.prototype.readUint32 = function () {
  3145. var value = this._dataView.getUint32(this._byteOffset, true);
  3146. this._byteOffset += 4;
  3147. return value;
  3148. };
  3149. BinaryReader.prototype.readUint8Array = function (length) {
  3150. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  3151. this._byteOffset += length;
  3152. return value;
  3153. };
  3154. BinaryReader.prototype.skipBytes = function (length) {
  3155. this._byteOffset += length;
  3156. };
  3157. return BinaryReader;
  3158. }());
  3159. /**
  3160. * glTF File Loader Plugin
  3161. */
  3162. var GLTFLoader = (function () {
  3163. function GLTFLoader() {
  3164. }
  3165. GLTFLoader.RegisterExtension = function (extension) {
  3166. if (GLTFLoader.Extensions[extension.name]) {
  3167. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  3168. return;
  3169. }
  3170. GLTFLoader.Extensions[extension.name] = extension;
  3171. };
  3172. GLTFLoader.LoadMaterial = function (runtime, index) {
  3173. var material = runtime.gltf.materials[index];
  3174. if (!material)
  3175. return null;
  3176. material.babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + index, runtime.babylonScene);
  3177. material.babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  3178. material.babylonMaterial.useScalarInLinearSpace = true;
  3179. return material;
  3180. };
  3181. GLTFLoader.LoadMetallicRoughnessMaterialPropertiesAsync = function (runtime, material, onSuccess, onError) {
  3182. // Ensure metallic workflow
  3183. material.babylonMaterial.metallic = 1;
  3184. material.babylonMaterial.roughness = 1;
  3185. var properties = material.pbrMetallicRoughness;
  3186. if (!properties) {
  3187. onSuccess();
  3188. return;
  3189. }
  3190. //
  3191. // Load Factors
  3192. //
  3193. material.babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  3194. material.babylonMaterial.metallic = properties.metallicFactor || 1;
  3195. material.babylonMaterial.roughness = properties.roughnessFactor || 1;
  3196. //
  3197. // Load Textures
  3198. //
  3199. if (!properties.baseColorTexture && !properties.metallicRoughnessTexture) {
  3200. onSuccess();
  3201. return;
  3202. }
  3203. var checkSuccess = function () {
  3204. if ((!properties.baseColorTexture || material.babylonMaterial.albedoTexture) &&
  3205. (!properties.metallicRoughnessTexture || material.babylonMaterial.metallicTexture)) {
  3206. onSuccess();
  3207. }
  3208. };
  3209. if (properties.baseColorTexture) {
  3210. GLTFLoader.LoadTextureAsync(runtime, properties.baseColorTexture, function (texture) {
  3211. material.babylonMaterial.albedoTexture = texture;
  3212. GLTFLoader.LoadAlphaProperties(runtime, material);
  3213. checkSuccess();
  3214. }, function () {
  3215. BABYLON.Tools.Error("Failed to load base color texture");
  3216. onError();
  3217. });
  3218. }
  3219. if (properties.metallicRoughnessTexture) {
  3220. GLTFLoader.LoadTextureAsync(runtime, properties.metallicRoughnessTexture, function (texture) {
  3221. material.babylonMaterial.metallicTexture = texture;
  3222. material.babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  3223. material.babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  3224. material.babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  3225. checkSuccess();
  3226. }, function () {
  3227. BABYLON.Tools.Error("Failed to load metallic roughness texture");
  3228. onError();
  3229. });
  3230. }
  3231. };
  3232. GLTFLoader.LoadCommonMaterialPropertiesAsync = function (runtime, material, onSuccess, onError) {
  3233. //
  3234. // Load Factors
  3235. //
  3236. material.babylonMaterial.useEmissiveAsIllumination = (material.emissiveFactor || material.emissiveTexture) ? true : false;
  3237. material.babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  3238. if (material.doubleSided) {
  3239. material.babylonMaterial.backFaceCulling = false;
  3240. material.babylonMaterial.twoSidedLighting = true;
  3241. }
  3242. //
  3243. // Load Textures
  3244. //
  3245. if (!material.normalTexture && !material.occlusionTexture && !material.emissiveTexture) {
  3246. onSuccess();
  3247. return;
  3248. }
  3249. var checkSuccess = function () {
  3250. if ((!material.normalTexture || material.babylonMaterial.bumpTexture) &&
  3251. (!material.occlusionTexture || material.babylonMaterial.ambientTexture) &&
  3252. (!material.emissiveTexture || material.babylonMaterial.emissiveTexture)) {
  3253. onSuccess();
  3254. }
  3255. };
  3256. if (material.normalTexture) {
  3257. GLTFLoader.LoadTextureAsync(runtime, material.normalTexture, function (babylonTexture) {
  3258. material.babylonMaterial.bumpTexture = babylonTexture;
  3259. if (material.normalTexture.scale !== undefined) {
  3260. material.babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  3261. }
  3262. checkSuccess();
  3263. }, function () {
  3264. BABYLON.Tools.Error("Failed to load normal texture");
  3265. onError();
  3266. });
  3267. }
  3268. if (material.occlusionTexture) {
  3269. GLTFLoader.LoadTextureAsync(runtime, material.occlusionTexture, function (babylonTexture) {
  3270. material.babylonMaterial.ambientTexture = babylonTexture;
  3271. material.babylonMaterial.useAmbientInGrayScale = true;
  3272. if (material.occlusionTexture.strength !== undefined) {
  3273. material.babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  3274. }
  3275. checkSuccess();
  3276. }, function () {
  3277. BABYLON.Tools.Error("Failed to load occlusion texture");
  3278. onError();
  3279. });
  3280. }
  3281. if (material.emissiveTexture) {
  3282. GLTFLoader.LoadTextureAsync(runtime, material.emissiveTexture, function (babylonTexture) {
  3283. material.babylonMaterial.emissiveTexture = babylonTexture;
  3284. checkSuccess();
  3285. }, function () {
  3286. BABYLON.Tools.Error("Failed to load emissive texture");
  3287. onError();
  3288. });
  3289. }
  3290. };
  3291. GLTFLoader.LoadAlphaProperties = function (runtime, material) {
  3292. var alphaMode = material.alphaMode || "OPAQUE";
  3293. switch (alphaMode) {
  3294. case "OPAQUE":
  3295. // default is opaque
  3296. break;
  3297. case "MASK":
  3298. material.babylonMaterial.albedoTexture.hasAlpha = true;
  3299. material.babylonMaterial.useAlphaFromAlbedoTexture = false;
  3300. material.babylonMaterial.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  3301. break;
  3302. case "BLEND":
  3303. material.babylonMaterial.albedoTexture.hasAlpha = true;
  3304. material.babylonMaterial.useAlphaFromAlbedoTexture = true;
  3305. material.babylonMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  3306. break;
  3307. default:
  3308. BABYLON.Tools.Error("Invalid alpha mode '" + material.alphaMode + "'");
  3309. }
  3310. };
  3311. GLTFLoader.LoadTextureAsync = function (runtime, textureInfo, onSuccess, onError) {
  3312. var texture = runtime.gltf.textures[textureInfo.index];
  3313. var texCoord = textureInfo.texCoord || 0;
  3314. if (!texture || texture.source === undefined) {
  3315. onError();
  3316. return;
  3317. }
  3318. if (texture.babylonTextures) {
  3319. var babylonTexture = texture.babylonTextures[texCoord];
  3320. if (!babylonTexture) {
  3321. for (var i = 0; i < texture.babylonTextures.length; i++) {
  3322. babylonTexture = texture.babylonTextures[i];
  3323. if (babylonTexture) {
  3324. babylonTexture = babylonTexture.clone();
  3325. babylonTexture.coordinatesIndex = texCoord;
  3326. break;
  3327. }
  3328. }
  3329. }
  3330. onSuccess(babylonTexture);
  3331. return;
  3332. }
  3333. var source = runtime.gltf.images[texture.source];
  3334. var sourceURL = runtime.rootUrl + source.uri;
  3335. if (texture.blobURL) {
  3336. sourceURL = texture.blobURL;
  3337. }
  3338. else {
  3339. if (source.uri === undefined) {
  3340. var bufferView = runtime.gltf.bufferViews[source.bufferView];
  3341. var buffer = GLTF2.GLTFUtils.GetBufferFromBufferView(runtime, bufferView, 0, bufferView.byteLength, GLTF2.EComponentType.UNSIGNED_BYTE);
  3342. texture.blobURL = URL.createObjectURL(new Blob([buffer], { type: source.mimeType }));
  3343. sourceURL = texture.blobURL;
  3344. }
  3345. else if (GLTF2.GLTFUtils.IsBase64(source.uri)) {
  3346. var decodedBuffer = new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(source.uri));
  3347. texture.blobURL = URL.createObjectURL(new Blob([decodedBuffer], { type: source.mimeType }));
  3348. sourceURL = texture.blobURL;
  3349. }
  3350. }
  3351. GLTFLoader._createTextureAsync(runtime, texture, texCoord, sourceURL, onSuccess, onError);
  3352. };
  3353. GLTFLoader._createTextureAsync = function (runtime, texture, texCoord, url, onSuccess, onError) {
  3354. var sampler = texture.sampler ? runtime.gltf.samplers[texture.sampler] : {};
  3355. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  3356. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  3357. var babylonTexture = new BABYLON.Texture(url, runtime.babylonScene, noMipMaps, true, samplingMode, function () {
  3358. onSuccess(babylonTexture);
  3359. }, onError);
  3360. babylonTexture.coordinatesIndex = texCoord;
  3361. babylonTexture.wrapU = GLTF2.GLTFUtils.GetWrapMode(sampler.wrapS);
  3362. babylonTexture.wrapV = GLTF2.GLTFUtils.GetWrapMode(sampler.wrapT);
  3363. babylonTexture.name = texture.name;
  3364. // Cache the texture
  3365. texture.babylonTextures = texture.babylonTextures || [];
  3366. texture.babylonTextures[texCoord] = babylonTexture;
  3367. };
  3368. /**
  3369. * Import meshes
  3370. */
  3371. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onError) {
  3372. scene.useRightHandedSystem = true;
  3373. var runtime = GLTFLoader._createRuntime(scene, data, rootUrl, true);
  3374. if (!runtime) {
  3375. onError();
  3376. return;
  3377. }
  3378. if (meshesNames === "") {
  3379. runtime.importMeshesNames = [];
  3380. }
  3381. else if (typeof meshesNames === "string") {
  3382. runtime.importMeshesNames = [meshesNames];
  3383. }
  3384. else if (meshesNames && !(meshesNames instanceof Array)) {
  3385. runtime.importMeshesNames = [meshesNames];
  3386. }
  3387. else {
  3388. runtime.importMeshesNames = [];
  3389. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  3390. }
  3391. // Load scene
  3392. importScene(runtime);
  3393. var meshes = [];
  3394. var skeletons = [];
  3395. // Fill arrays of meshes and skeletons
  3396. for (var i = 0; i < runtime.gltf.nodes.length; i++) {
  3397. var node = runtime.gltf.nodes[i];
  3398. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  3399. meshes.push(node.babylonNode);
  3400. }
  3401. }
  3402. for (var i = 0; i < runtime.gltf.skins.length; i++) {
  3403. var skin = runtime.gltf.skins[i];
  3404. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  3405. skeletons.push(skin.babylonSkeleton);
  3406. }
  3407. }
  3408. // Load buffers, materials, etc.
  3409. GLTFLoader._loadBuffersAsync(runtime, function () {
  3410. GLTFLoader._loadMaterialsAsync(runtime, function () {
  3411. postLoad(runtime);
  3412. onSuccess(meshes, null, skeletons);
  3413. }, onError);
  3414. }, onError);
  3415. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  3416. onSuccess(meshes, null, skeletons);
  3417. }
  3418. };
  3419. /**
  3420. * Load scene
  3421. */
  3422. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onError) {
  3423. scene.useRightHandedSystem = true;
  3424. var runtime = GLTFLoader._createRuntime(scene, data, rootUrl, false);
  3425. if (!runtime) {
  3426. onError();
  3427. return;
  3428. }
  3429. importScene(runtime);
  3430. GLTFLoader._loadBuffersAsync(runtime, function () {
  3431. GLTFLoader._loadMaterialsAsync(runtime, function () {
  3432. postLoad(runtime);
  3433. onSuccess();
  3434. }, onError);
  3435. }, onError);
  3436. };
  3437. GLTFLoader._loadBuffersAsync = function (runtime, onSuccess, onError) {
  3438. var _this = this;
  3439. if (runtime.gltf.buffers.length == 0) {
  3440. onSuccess();
  3441. return;
  3442. }
  3443. var successCount = 0;
  3444. runtime.gltf.buffers.forEach(function (buffer, index) {
  3445. _this._loadBufferAsync(runtime, index, function () {
  3446. if (++successCount === runtime.gltf.buffers.length) {
  3447. onSuccess();
  3448. }
  3449. }, onError);
  3450. });
  3451. };
  3452. GLTFLoader._loadBufferAsync = function (runtime, index, onSuccess, onError) {
  3453. var buffer = runtime.gltf.buffers[index];
  3454. if (buffer.uri === undefined) {
  3455. // buffer.loadedBufferView should already be set
  3456. onSuccess();
  3457. }
  3458. else if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  3459. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  3460. setTimeout(function () {
  3461. buffer.loadedBufferView = new Uint8Array(data);
  3462. onSuccess();
  3463. });
  3464. }
  3465. else {
  3466. BABYLON.Tools.LoadFile(runtime.rootUrl + buffer.uri, function (data) {
  3467. buffer.loadedBufferView = new Uint8Array(data);
  3468. onSuccess();
  3469. }, null, null, true, onError);
  3470. }
  3471. };
  3472. GLTFLoader._loadMaterialsAsync = function (runtime, onSuccess, onError) {
  3473. var materials = runtime.gltf.materials;
  3474. if (!materials) {
  3475. onSuccess();
  3476. return;
  3477. }
  3478. var successCount = 0;
  3479. for (var i = 0; i < materials.length; i++) {
  3480. GLTF2.GLTFLoaderExtension.LoadMaterialAsync(runtime, i, function () {
  3481. if (++successCount === materials.length) {
  3482. onSuccess();
  3483. }
  3484. }, onError);
  3485. }
  3486. };
  3487. GLTFLoader._createRuntime = function (scene, data, rootUrl, importOnlyMeshes) {
  3488. var runtime = {
  3489. gltf: data.json,
  3490. babylonScene: scene,
  3491. rootUrl: rootUrl,
  3492. importOnlyMeshes: importOnlyMeshes,
  3493. };
  3494. var binaryBuffer;
  3495. var buffers = runtime.gltf.buffers;
  3496. if (buffers.length > 0 && buffers[0].uri === undefined) {
  3497. binaryBuffer = buffers[0];
  3498. }
  3499. if (data.bin) {
  3500. if (!binaryBuffer) {
  3501. BABYLON.Tools.Error("Unexpected BIN chunk");
  3502. return null;
  3503. }
  3504. if (binaryBuffer.byteLength != data.bin.byteLength) {
  3505. BABYLON.Tools.Error("Binary buffer length from JSON does not match chunk length");
  3506. return null;
  3507. }
  3508. binaryBuffer.loadedBufferView = data.bin;
  3509. }
  3510. GLTF2.GLTFLoaderExtension.PostCreateRuntime(runtime);
  3511. return runtime;
  3512. };
  3513. return GLTFLoader;
  3514. }());
  3515. GLTFLoader.Extensions = {};
  3516. GLTF2.GLTFLoader = GLTFLoader;
  3517. BABYLON.GLTFFileLoader.GLTFLoaderV2 = new GLTFLoader();
  3518. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3519. })(BABYLON || (BABYLON = {}));
  3520. //# sourceMappingURL=babylon.glTFLoader.js.map
  3521. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  3522. var BABYLON;
  3523. (function (BABYLON) {
  3524. var GLTF2;
  3525. (function (GLTF2) {
  3526. /**
  3527. * Utils functions for GLTF
  3528. */
  3529. var GLTFUtils = (function () {
  3530. function GLTFUtils() {
  3531. }
  3532. /**
  3533. * If the uri is a base64 string
  3534. * @param uri: the uri to test
  3535. */
  3536. GLTFUtils.IsBase64 = function (uri) {
  3537. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  3538. };
  3539. /**
  3540. * Decode the base64 uri
  3541. * @param uri: the uri to decode
  3542. */
  3543. GLTFUtils.DecodeBase64 = function (uri) {
  3544. var decodedString = atob(uri.split(",")[1]);
  3545. var bufferLength = decodedString.length;
  3546. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  3547. for (var i = 0; i < bufferLength; i++) {
  3548. bufferView[i] = decodedString.charCodeAt(i);
  3549. }
  3550. return bufferView.buffer;
  3551. };
  3552. /**
  3553. * Returns the wrap mode of the texture
  3554. * @param mode: the mode value
  3555. */
  3556. GLTFUtils.GetWrapMode = function (mode) {
  3557. switch (mode) {
  3558. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  3559. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  3560. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  3561. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  3562. }
  3563. };
  3564. /**
  3565. * Returns the byte stride giving an accessor
  3566. * @param accessor: the GLTF accessor objet
  3567. */
  3568. GLTFUtils.GetByteStrideFromType = function (accessor) {
  3569. // Needs this function since "byteStride" isn't requiered in glTF format
  3570. var type = accessor.type;
  3571. switch (type) {
  3572. case "VEC2": return 2;
  3573. case "VEC3": return 3;
  3574. case "VEC4": return 4;
  3575. case "MAT2": return 4;
  3576. case "MAT3": return 9;
  3577. case "MAT4": return 16;
  3578. default: return 1;
  3579. }
  3580. };
  3581. /**
  3582. * Returns the texture filter mode giving a mode value
  3583. * @param mode: the filter mode value
  3584. */
  3585. GLTFUtils.GetTextureFilterMode = function (mode) {
  3586. switch (mode) {
  3587. case GLTF2.ETextureMinFilter.LINEAR:
  3588. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST:
  3589. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3590. case GLTF2.ETextureMinFilter.NEAREST:
  3591. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  3592. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  3593. }
  3594. };
  3595. GLTFUtils.GetBufferFromBufferView = function (runtime, bufferView, byteOffset, byteLength, componentType) {
  3596. var byteOffset = bufferView.byteOffset + byteOffset;
  3597. var loadedBufferView = runtime.gltf.buffers[bufferView.buffer].loadedBufferView;
  3598. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  3599. throw new Error("Buffer access is out of range");
  3600. }
  3601. var buffer = loadedBufferView.buffer;
  3602. byteOffset += loadedBufferView.byteOffset;
  3603. switch (componentType) {
  3604. case GLTF2.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  3605. case GLTF2.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  3606. case GLTF2.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  3607. case GLTF2.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  3608. case GLTF2.EComponentType.UNSIGNED_INT: return new Uint32Array(buffer, byteOffset, byteLength);
  3609. default: return new Float32Array(buffer, byteOffset, byteLength);
  3610. }
  3611. };
  3612. /**
  3613. * Returns a buffer from its accessor
  3614. * @param runtime: the GLTF runtime
  3615. * @param accessor: the GLTF accessor
  3616. */
  3617. GLTFUtils.GetBufferFromAccessor = function (runtime, accessor) {
  3618. var bufferView = runtime.gltf.bufferViews[accessor.bufferView];
  3619. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  3620. return GLTFUtils.GetBufferFromBufferView(runtime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  3621. };
  3622. /**
  3623. * Decodes a buffer view into a string
  3624. * @param view: the buffer view
  3625. */
  3626. GLTFUtils.DecodeBufferToText = function (view) {
  3627. var result = "";
  3628. var length = view.byteLength;
  3629. for (var i = 0; i < length; ++i) {
  3630. result += String.fromCharCode(view[i]);
  3631. }
  3632. return result;
  3633. };
  3634. /**
  3635. * Returns the default material of gltf.
  3636. * @param scene: the Babylon.js scene
  3637. */
  3638. GLTFUtils.GetDefaultMaterial = function (runtime) {
  3639. if (!runtime.defaultMaterial) {
  3640. var material = new BABYLON.PBRMaterial("gltf_default", runtime.babylonScene);
  3641. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  3642. material.metallic = 1;
  3643. material.roughness = 1;
  3644. runtime.defaultMaterial = material;
  3645. }
  3646. return runtime.defaultMaterial;
  3647. };
  3648. return GLTFUtils;
  3649. }());
  3650. GLTF2.GLTFUtils = GLTFUtils;
  3651. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3652. })(BABYLON || (BABYLON = {}));
  3653. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  3654. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  3655. var BABYLON;
  3656. (function (BABYLON) {
  3657. var GLTF2;
  3658. (function (GLTF2) {
  3659. var GLTFLoaderExtension = (function () {
  3660. function GLTFLoaderExtension(name) {
  3661. this._name = name;
  3662. }
  3663. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  3664. get: function () {
  3665. return this._name;
  3666. },
  3667. enumerable: true,
  3668. configurable: true
  3669. });
  3670. GLTFLoaderExtension.prototype.postCreateRuntime = function (runtime) { };
  3671. // Return true to stop other extensions from loading materials.
  3672. GLTFLoaderExtension.prototype.loadMaterialAsync = function (runtime, index, onSuccess, onError) { return false; };
  3673. // ---------
  3674. // Utilities
  3675. // ---------
  3676. GLTFLoaderExtension.PostCreateRuntime = function (runtime) {
  3677. for (var extensionName in GLTF2.GLTFLoader.Extensions) {
  3678. var extension = GLTF2.GLTFLoader.Extensions[extensionName];
  3679. extension.postCreateRuntime(runtime);
  3680. }
  3681. };
  3682. GLTFLoaderExtension.LoadMaterialAsync = function (runtime, index, onSuccess, onError) {
  3683. for (var extensionName in GLTF2.GLTFLoader.Extensions) {
  3684. var extension = GLTF2.GLTFLoader.Extensions[extensionName];
  3685. if (extension.loadMaterialAsync(runtime, index, onSuccess, onError)) {
  3686. return;
  3687. }
  3688. }
  3689. var material = GLTF2.GLTFLoader.LoadMaterial(runtime, index);
  3690. if (!material) {
  3691. onSuccess();
  3692. return;
  3693. }
  3694. var metallicRoughnessPropertiesSuccess = false;
  3695. var commonPropertiesSuccess = false;
  3696. var checkSuccess = function () {
  3697. if (metallicRoughnessPropertiesSuccess && commonPropertiesSuccess) {
  3698. onSuccess();
  3699. }
  3700. };
  3701. GLTF2.GLTFLoader.LoadMetallicRoughnessMaterialPropertiesAsync(runtime, material, function () {
  3702. metallicRoughnessPropertiesSuccess = true;
  3703. checkSuccess();
  3704. }, onError);
  3705. GLTF2.GLTFLoader.LoadCommonMaterialPropertiesAsync(runtime, material, function () {
  3706. commonPropertiesSuccess = true;
  3707. checkSuccess();
  3708. }, onError);
  3709. };
  3710. return GLTFLoaderExtension;
  3711. }());
  3712. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  3713. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3714. })(BABYLON || (BABYLON = {}));
  3715. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  3716. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  3717. var __extends = (this && this.__extends) || (function () {
  3718. var extendStatics = Object.setPrototypeOf ||
  3719. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  3720. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  3721. return function (d, b) {
  3722. extendStatics(d, b);
  3723. function __() { this.constructor = d; }
  3724. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3725. };
  3726. })();
  3727. var BABYLON;
  3728. (function (BABYLON) {
  3729. var GLTF2;
  3730. (function (GLTF2) {
  3731. var GLTFMaterialsPbrSpecularGlossinessExtension = (function (_super) {
  3732. __extends(GLTFMaterialsPbrSpecularGlossinessExtension, _super);
  3733. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  3734. return _super.call(this, "KHR_materials_pbrSpecularGlossiness") || this;
  3735. }
  3736. GLTFMaterialsPbrSpecularGlossinessExtension.prototype.loadMaterialAsync = function (runtime, index, onSuccess, onError) {
  3737. var material = GLTF2.GLTFLoader.LoadMaterial(runtime, index);
  3738. if (!material || !material.extensions)
  3739. return false;
  3740. var properties = material.extensions[this.name];
  3741. if (!properties)
  3742. return false;
  3743. //
  3744. // Load Factors
  3745. //
  3746. material.babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  3747. material.babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  3748. material.babylonMaterial.microSurface = properties.glossinessFactor === undefined ? 1 : properties.glossinessFactor;
  3749. //
  3750. // Load Textures
  3751. //
  3752. var commonMaterialPropertiesSuccess = false;
  3753. var checkSuccess = function () {
  3754. if ((!properties.diffuseTexture || material.babylonMaterial.albedoTexture) &&
  3755. (!properties.specularGlossinessTexture || material.babylonMaterial.reflectivityTexture) &&
  3756. commonMaterialPropertiesSuccess) {
  3757. onSuccess();
  3758. }
  3759. };
  3760. if (properties.diffuseTexture) {
  3761. GLTF2.GLTFLoader.LoadTextureAsync(runtime, properties.diffuseTexture, function (texture) {
  3762. material.babylonMaterial.albedoTexture = texture;
  3763. GLTF2.GLTFLoader.LoadAlphaProperties(runtime, material);
  3764. checkSuccess();
  3765. }, function () {
  3766. BABYLON.Tools.Warn("Failed to load diffuse texture");
  3767. onError();
  3768. });
  3769. }
  3770. if (properties.specularGlossinessTexture) {
  3771. GLTF2.GLTFLoader.LoadTextureAsync(runtime, properties.specularGlossinessTexture, function (texture) {
  3772. material.babylonMaterial.reflectivityTexture = texture;
  3773. material.babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  3774. checkSuccess();
  3775. }, function () {
  3776. BABYLON.Tools.Warn("Failed to load metallic roughness texture");
  3777. onError();
  3778. });
  3779. }
  3780. GLTF2.GLTFLoader.LoadCommonMaterialPropertiesAsync(runtime, material, function () {
  3781. commonMaterialPropertiesSuccess = true;
  3782. checkSuccess();
  3783. }, onError);
  3784. return true;
  3785. };
  3786. return GLTFMaterialsPbrSpecularGlossinessExtension;
  3787. }(GLTF2.GLTFLoaderExtension));
  3788. GLTF2.GLTFMaterialsPbrSpecularGlossinessExtension = GLTFMaterialsPbrSpecularGlossinessExtension;
  3789. GLTF2.GLTFLoader.RegisterExtension(new GLTFMaterialsPbrSpecularGlossinessExtension());
  3790. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3791. })(BABYLON || (BABYLON = {}));
  3792. //# sourceMappingURL=babylon.glTFMaterialsPbrSpecularGlossinessExtension.js.map