babylon.glTFFileLoader.js 192 KB

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