babylon.glTFLoader.ts 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124
  1. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2. /**
  3. * Defines the module for importing and exporting glTF 2.0 assets
  4. */
  5. module BABYLON.GLTF2 {
  6. interface IFileRequestInfo extends IFileRequest {
  7. _lengthComputable?: boolean;
  8. _loaded?: number;
  9. _total?: number;
  10. }
  11. interface ILoaderProperty extends IProperty {
  12. _activeLoaderExtensions: any;
  13. }
  14. /**
  15. * Helper class for working with arrays when loading the glTF asset
  16. */
  17. export class ArrayItem {
  18. /**
  19. * Gets an item from the given array.
  20. * @param context The context when loading the asset
  21. * @param array The array to get the item from
  22. * @param index The index to the array
  23. * @returns The array item
  24. */
  25. public static Get<T>(context: string, array: ArrayLike<T> | undefined, index: number | undefined): T {
  26. if (!array || index == undefined || !array[index]) {
  27. throw new Error(`${context}: Failed to find index (${index})`);
  28. }
  29. return array[index];
  30. }
  31. /**
  32. * Assign an `index` field to each item of the given array.
  33. * @param array The array of items
  34. */
  35. public static Assign(array?: IArrayItem[]): void {
  36. if (array) {
  37. for (let index = 0; index < array.length; index++) {
  38. array[index].index = index;
  39. }
  40. }
  41. }
  42. }
  43. /**
  44. * The glTF 2.0 loader
  45. */
  46. export class GLTFLoader implements IGLTFLoader {
  47. /** The glTF object parsed from the JSON. */
  48. public gltf: ILoaderGLTF;
  49. /** The Babylon scene when loading the asset. */
  50. public babylonScene: Scene;
  51. /** @hidden */
  52. public _completePromises = new Array<Promise<any>>();
  53. private _disposed = false;
  54. private _parent: GLTFFileLoader;
  55. private _state: Nullable<GLTFLoaderState> = null;
  56. private _extensions: { [name: string]: IGLTFLoaderExtension } = {};
  57. private _rootUrl: string;
  58. private _fileName: string;
  59. private _uniqueRootUrl: string;
  60. private _rootBabylonMesh: Mesh;
  61. private _defaultBabylonMaterialData: { [drawMode: number]: Material } = {};
  62. private _progressCallback?: (event: SceneLoaderProgressEvent) => void;
  63. private _requests = new Array<IFileRequestInfo>();
  64. private static readonly _DefaultSampler: ILoaderSampler = { index: -1 };
  65. private static _ExtensionNames = new Array<string>();
  66. private static _ExtensionFactories: { [name: string]: (loader: GLTFLoader) => IGLTFLoaderExtension } = {};
  67. /**
  68. * Registers a loader extension.
  69. * @param name The name of the loader extension.
  70. * @param factory The factory function that creates the loader extension.
  71. */
  72. public static RegisterExtension(name: string, factory: (loader: GLTFLoader) => IGLTFLoaderExtension): void {
  73. if (GLTFLoader.UnregisterExtension(name)) {
  74. Tools.Warn(`Extension with the name '${name}' already exists`);
  75. }
  76. GLTFLoader._ExtensionFactories[name] = factory;
  77. // Keep the order of registration so that extensions registered first are called first.
  78. GLTFLoader._ExtensionNames.push(name);
  79. }
  80. /**
  81. * Unregisters a loader extension.
  82. * @param name The name of the loader extenion.
  83. * @returns A boolean indicating whether the extension has been unregistered
  84. */
  85. public static UnregisterExtension(name: string): boolean {
  86. if (!GLTFLoader._ExtensionFactories[name]) {
  87. return false;
  88. }
  89. delete GLTFLoader._ExtensionFactories[name];
  90. const index = GLTFLoader._ExtensionNames.indexOf(name);
  91. if (index !== -1) {
  92. GLTFLoader._ExtensionNames.splice(index, 1);
  93. }
  94. return true;
  95. }
  96. /**
  97. * Gets the loader state.
  98. */
  99. public get state(): Nullable<GLTFLoaderState> {
  100. return this._state;
  101. }
  102. /** @hidden */
  103. constructor(parent: GLTFFileLoader) {
  104. this._parent = parent;
  105. }
  106. /** @hidden */
  107. public dispose(): void {
  108. if (this._disposed) {
  109. return;
  110. }
  111. this._disposed = true;
  112. for (const request of this._requests) {
  113. request.abort();
  114. }
  115. this._requests.length = 0;
  116. delete this.gltf;
  117. delete this.babylonScene;
  118. this._completePromises.length = 0;
  119. for (const name in this._extensions) {
  120. const extension = this._extensions[name];
  121. if (extension.dispose) {
  122. this._extensions[name].dispose();
  123. }
  124. }
  125. this._extensions = {};
  126. delete this._rootBabylonMesh;
  127. delete this._progressCallback;
  128. this._parent._clear();
  129. }
  130. /** @hidden */
  131. public importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void, fileName?: string): Promise<{ meshes: AbstractMesh[], particleSystems: IParticleSystem[], skeletons: Skeleton[], animationGroups: AnimationGroup[] }> {
  132. return Promise.resolve().then(() => {
  133. this.babylonScene = scene;
  134. this._rootUrl = rootUrl;
  135. this._fileName = fileName || "scene";
  136. this._progressCallback = onProgress;
  137. this._loadData(data);
  138. let nodes: Nullable<Array<number>> = null;
  139. if (meshesNames) {
  140. const nodeMap: { [name: string]: number } = {};
  141. if (this.gltf.nodes) {
  142. for (const node of this.gltf.nodes) {
  143. if (node.name) {
  144. nodeMap[node.name] = node.index;
  145. }
  146. }
  147. }
  148. const names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  149. nodes = names.map(name => {
  150. const node = nodeMap[name];
  151. if (node === undefined) {
  152. throw new Error(`Failed to find node '${name}'`);
  153. }
  154. return node;
  155. });
  156. }
  157. return this._loadAsync(nodes, () => {
  158. return {
  159. meshes: this._getMeshes(),
  160. particleSystems: [],
  161. skeletons: this._getSkeletons(),
  162. animationGroups: this._getAnimationGroups()
  163. };
  164. });
  165. });
  166. }
  167. /** @hidden */
  168. public loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void, fileName?: string): Promise<void> {
  169. return Promise.resolve().then(() => {
  170. this.babylonScene = scene;
  171. this._rootUrl = rootUrl;
  172. this._fileName = fileName || "scene";
  173. this._progressCallback = onProgress;
  174. this._loadData(data);
  175. return this._loadAsync(null, () => undefined);
  176. });
  177. }
  178. private _loadAsync<T>(nodes: Nullable<Array<number>>, resultFunc: () => T): Promise<T> {
  179. return Promise.resolve().then(() => {
  180. this._uniqueRootUrl = (this._rootUrl.indexOf("file:") === -1 && this._fileName) ? this._rootUrl : `${this._rootUrl}${Date.now()}/`;
  181. this._loadExtensions();
  182. this._checkExtensions();
  183. const loadingToReadyCounterName = `${GLTFLoaderState[GLTFLoaderState.LOADING]} => ${GLTFLoaderState[GLTFLoaderState.READY]}`;
  184. const loadingToCompleteCounterName = `${GLTFLoaderState[GLTFLoaderState.LOADING]} => ${GLTFLoaderState[GLTFLoaderState.COMPLETE]}`;
  185. this._parent._startPerformanceCounter(loadingToReadyCounterName);
  186. this._parent._startPerformanceCounter(loadingToCompleteCounterName);
  187. this._setState(GLTFLoaderState.LOADING);
  188. this._extensionsOnLoading();
  189. const promises = new Array<Promise<any>>();
  190. if (nodes) {
  191. promises.push(this.loadSceneAsync("#/nodes", { nodes: nodes, index: -1 }));
  192. }
  193. else {
  194. const scene = ArrayItem.Get(`#/scene`, this.gltf.scenes, this.gltf.scene || 0);
  195. promises.push(this.loadSceneAsync(`#/scenes/${scene.index}`, scene));
  196. }
  197. if (this._parent.compileMaterials) {
  198. promises.push(this._compileMaterialsAsync());
  199. }
  200. if (this._parent.compileShadowGenerators) {
  201. promises.push(this._compileShadowGeneratorsAsync());
  202. }
  203. const resultPromise = Promise.all(promises).then(() => {
  204. this._setState(GLTFLoaderState.READY);
  205. this._extensionsOnReady();
  206. this._startAnimations();
  207. return resultFunc();
  208. });
  209. resultPromise.then(() => {
  210. this._parent._endPerformanceCounter(loadingToReadyCounterName);
  211. Tools.SetImmediate(() => {
  212. if (!this._disposed) {
  213. Promise.all(this._completePromises).then(() => {
  214. this._parent._endPerformanceCounter(loadingToCompleteCounterName);
  215. this._setState(GLTFLoaderState.COMPLETE);
  216. this._parent.onCompleteObservable.notifyObservers(undefined);
  217. this._parent.onCompleteObservable.clear();
  218. this.dispose();
  219. }, error => {
  220. this._parent.onErrorObservable.notifyObservers(error);
  221. this._parent.onErrorObservable.clear();
  222. this.dispose();
  223. });
  224. }
  225. });
  226. });
  227. return resultPromise;
  228. }, error => {
  229. if (!this._disposed) {
  230. this._parent.onErrorObservable.notifyObservers(error);
  231. this._parent.onErrorObservable.clear();
  232. this.dispose();
  233. }
  234. throw error;
  235. });
  236. }
  237. private _loadData(data: IGLTFLoaderData): void {
  238. this.gltf = data.json as ILoaderGLTF;
  239. this._setupData();
  240. if (data.bin) {
  241. const buffers = this.gltf.buffers;
  242. if (buffers && buffers[0] && !buffers[0].uri) {
  243. const binaryBuffer = buffers[0];
  244. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  245. Tools.Warn(`Binary buffer length (${binaryBuffer.byteLength}) from JSON does not match chunk length (${data.bin.byteLength})`);
  246. }
  247. binaryBuffer._data = Promise.resolve(data.bin);
  248. }
  249. else {
  250. Tools.Warn("Unexpected BIN chunk");
  251. }
  252. }
  253. }
  254. private _setupData(): void {
  255. ArrayItem.Assign(this.gltf.accessors);
  256. ArrayItem.Assign(this.gltf.animations);
  257. ArrayItem.Assign(this.gltf.buffers);
  258. ArrayItem.Assign(this.gltf.bufferViews);
  259. ArrayItem.Assign(this.gltf.cameras);
  260. ArrayItem.Assign(this.gltf.images);
  261. ArrayItem.Assign(this.gltf.materials);
  262. ArrayItem.Assign(this.gltf.meshes);
  263. ArrayItem.Assign(this.gltf.nodes);
  264. ArrayItem.Assign(this.gltf.samplers);
  265. ArrayItem.Assign(this.gltf.scenes);
  266. ArrayItem.Assign(this.gltf.skins);
  267. ArrayItem.Assign(this.gltf.textures);
  268. if (this.gltf.nodes) {
  269. const nodeParents: { [index: number]: number } = {};
  270. for (const node of this.gltf.nodes) {
  271. if (node.children) {
  272. for (const index of node.children) {
  273. nodeParents[index] = node.index;
  274. }
  275. }
  276. }
  277. const rootNode = this._createRootNode();
  278. for (const node of this.gltf.nodes) {
  279. const parentIndex = nodeParents[node.index];
  280. node.parent = parentIndex === undefined ? rootNode : this.gltf.nodes[parentIndex];
  281. }
  282. }
  283. }
  284. private _loadExtensions(): void {
  285. for (const name of GLTFLoader._ExtensionNames) {
  286. const extension = GLTFLoader._ExtensionFactories[name](this);
  287. this._extensions[name] = extension;
  288. this._parent.onExtensionLoadedObservable.notifyObservers(extension);
  289. }
  290. this._parent.onExtensionLoadedObservable.clear();
  291. }
  292. private _checkExtensions(): void {
  293. if (this.gltf.extensionsRequired) {
  294. for (const name of this.gltf.extensionsRequired) {
  295. const extension = this._extensions[name];
  296. if (!extension || !extension.enabled) {
  297. throw new Error(`Require extension ${name} is not available`);
  298. }
  299. }
  300. }
  301. }
  302. private _setState(state: GLTFLoaderState): void {
  303. this._state = state;
  304. this.log(GLTFLoaderState[this._state]);
  305. }
  306. private _createRootNode(): ILoaderNode {
  307. this._rootBabylonMesh = new Mesh("__root__", this.babylonScene);
  308. const rootNode: ILoaderNode = {
  309. _babylonMesh: this._rootBabylonMesh,
  310. index: -1
  311. };
  312. switch (this._parent.coordinateSystemMode) {
  313. case GLTFLoaderCoordinateSystemMode.AUTO: {
  314. if (!this.babylonScene.useRightHandedSystem) {
  315. rootNode.rotation = [0, 1, 0, 0];
  316. rootNode.scale = [1, 1, -1];
  317. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  318. }
  319. break;
  320. }
  321. case GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  322. this.babylonScene.useRightHandedSystem = true;
  323. break;
  324. }
  325. default: {
  326. throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`);
  327. }
  328. }
  329. this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  330. return rootNode;
  331. }
  332. /**
  333. * Loads a glTF scene.
  334. * @param context The context when loading the asset
  335. * @param scene The glTF scene property
  336. * @returns A promise that resolves when the load is complete
  337. */
  338. public loadSceneAsync(context: string, scene: ILoaderScene): Promise<void> {
  339. const extensionPromise = this._extensionsLoadSceneAsync(context, scene);
  340. if (extensionPromise) {
  341. return extensionPromise;
  342. }
  343. const promises = new Array<Promise<any>>();
  344. this.logOpen(`${context} ${scene.name || ""}`);
  345. if (scene.nodes) {
  346. for (let index of scene.nodes) {
  347. const node = ArrayItem.Get(`${context}/nodes/${index}`, this.gltf.nodes, index);
  348. promises.push(this.loadNodeAsync(`#/nodes/${node.index}`, node, babylonMesh => {
  349. babylonMesh.parent = this._rootBabylonMesh;
  350. }));
  351. }
  352. }
  353. promises.push(this._loadAnimationsAsync());
  354. this.logClose();
  355. return Promise.all(promises).then(() => {});
  356. }
  357. private _forEachPrimitive(node: ILoaderNode, callback: (babylonMesh: Mesh) => void): void {
  358. if (node._primitiveBabylonMeshes) {
  359. for (const babylonMesh of node._primitiveBabylonMeshes) {
  360. callback(babylonMesh);
  361. }
  362. }
  363. else {
  364. callback(node._babylonMesh!);
  365. }
  366. }
  367. private _getMeshes(): Mesh[] {
  368. const meshes = new Array<Mesh>();
  369. // Root mesh is always first.
  370. meshes.push(this._rootBabylonMesh);
  371. const nodes = this.gltf.nodes;
  372. if (nodes) {
  373. for (const node of nodes) {
  374. if (node._babylonMesh) {
  375. meshes.push(node._babylonMesh);
  376. }
  377. if (node._primitiveBabylonMeshes) {
  378. for (const babylonMesh of node._primitiveBabylonMeshes) {
  379. meshes.push(babylonMesh);
  380. }
  381. }
  382. }
  383. }
  384. return meshes;
  385. }
  386. private _getSkeletons(): Skeleton[] {
  387. const skeletons = new Array<Skeleton>();
  388. const skins = this.gltf.skins;
  389. if (skins) {
  390. for (const skin of skins) {
  391. if (skin._babylonSkeleton) {
  392. skeletons.push(skin._babylonSkeleton);
  393. }
  394. }
  395. }
  396. return skeletons;
  397. }
  398. private _getAnimationGroups(): AnimationGroup[] {
  399. const animationGroups = new Array<AnimationGroup>();
  400. const animations = this.gltf.animations;
  401. if (animations) {
  402. for (const animation of animations) {
  403. if (animation._babylonAnimationGroup) {
  404. animationGroups.push(animation._babylonAnimationGroup);
  405. }
  406. }
  407. }
  408. return animationGroups;
  409. }
  410. private _startAnimations(): void {
  411. switch (this._parent.animationStartMode) {
  412. case GLTFLoaderAnimationStartMode.NONE: {
  413. // do nothing
  414. break;
  415. }
  416. case GLTFLoaderAnimationStartMode.FIRST: {
  417. const babylonAnimationGroups = this._getAnimationGroups();
  418. if (babylonAnimationGroups.length !== 0) {
  419. babylonAnimationGroups[0].start(true);
  420. }
  421. break;
  422. }
  423. case GLTFLoaderAnimationStartMode.ALL: {
  424. const babylonAnimationGroups = this._getAnimationGroups();
  425. for (const babylonAnimationGroup of babylonAnimationGroups) {
  426. babylonAnimationGroup.start(true);
  427. }
  428. break;
  429. }
  430. default: {
  431. Tools.Error(`Invalid animation start mode (${this._parent.animationStartMode})`);
  432. return;
  433. }
  434. }
  435. }
  436. /**
  437. * Loads a glTF node.
  438. * @param context The context when loading the asset
  439. * @param node The glTF node property
  440. * @param assign A function called synchronously after parsing the glTF properties
  441. * @returns A promise that resolves with the loaded Babylon mesh when the load is complete
  442. */
  443. public loadNodeAsync(context: string, node: ILoaderNode, assign: (babylonMesh: Mesh) => void = () => {}): Promise<Mesh> {
  444. const extensionPromise = this._extensionsLoadNodeAsync(context, node, assign);
  445. if (extensionPromise) {
  446. return extensionPromise;
  447. }
  448. if (node._babylonMesh) {
  449. throw new Error(`${context}: Invalid recursive node hierarchy`);
  450. }
  451. const promises = new Array<Promise<any>>();
  452. this.logOpen(`${context} ${node.name || ""}`);
  453. const babylonMesh = new Mesh(node.name || `node${node.index}`, this.babylonScene);
  454. node._babylonMesh = babylonMesh;
  455. babylonMesh.setEnabled(false);
  456. GLTFLoader._LoadTransform(node, babylonMesh);
  457. if (node.mesh != undefined) {
  458. const mesh = ArrayItem.Get(`${context}/mesh`, this.gltf.meshes, node.mesh);
  459. promises.push(this._loadMeshAsync(`#/meshes/${mesh.index}`, node, mesh, babylonMesh));
  460. }
  461. if (node.camera != undefined) {
  462. const camera = ArrayItem.Get(`${context}/camera`, this.gltf.cameras, node.camera);
  463. promises.push(this.loadCameraAsync(`#/cameras/${camera.index}`, camera, babylonCamera => {
  464. babylonCamera.parent = babylonMesh;
  465. }));
  466. }
  467. if (node.children) {
  468. for (const index of node.children) {
  469. const childNode = ArrayItem.Get(`${context}/children/${index}`, this.gltf.nodes, index);
  470. promises.push(this.loadNodeAsync(`#/nodes/${node.index}`, childNode, childBabylonMesh => {
  471. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  472. if (childNode.skin != undefined) {
  473. childBabylonMesh.parent = this._rootBabylonMesh;
  474. return;
  475. }
  476. childBabylonMesh.parent = babylonMesh;
  477. }));
  478. }
  479. }
  480. assign(babylonMesh);
  481. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  482. this.logClose();
  483. return Promise.all(promises).then(() => {
  484. babylonMesh.setEnabled(true);
  485. return babylonMesh;
  486. });
  487. }
  488. private _loadMeshAsync(context: string, node: ILoaderNode, mesh: ILoaderMesh, babylonMesh: Mesh): Promise<void> {
  489. const promises = new Array<Promise<any>>();
  490. this.logOpen(`${context} ${mesh.name || ""}`);
  491. const primitives = mesh.primitives;
  492. if (!primitives || primitives.length === 0) {
  493. throw new Error(`${context}: Primitives are missing`);
  494. }
  495. ArrayItem.Assign(primitives);
  496. if (primitives.length === 1) {
  497. const primitive = primitives[0];
  498. promises.push(this._loadMeshPrimitiveAsync(`${context}/primitives/${primitive.index}`, node, mesh, primitive, babylonMesh));
  499. }
  500. else {
  501. node._primitiveBabylonMeshes = [];
  502. for (const primitive of primitives) {
  503. const primitiveBabylonMesh = new Mesh(`${mesh.name || babylonMesh.name}_${primitive.index}`, this.babylonScene, babylonMesh);
  504. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  505. promises.push(this._loadMeshPrimitiveAsync(`${context}/primitives/${primitive.index}`, node, mesh, primitive, primitiveBabylonMesh));
  506. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  507. }
  508. }
  509. if (node.skin != undefined) {
  510. const skin = ArrayItem.Get(`${context}/skin`, this.gltf.skins, node.skin);
  511. promises.push(this._loadSkinAsync(`#/skins/${skin.index}`, node, skin));
  512. }
  513. this.logClose();
  514. return Promise.all(promises).then(() => {
  515. this._forEachPrimitive(node, babylonMesh => {
  516. babylonMesh._refreshBoundingInfo(true);
  517. });
  518. });
  519. }
  520. private _loadMeshPrimitiveAsync(context: string, node: ILoaderNode, mesh: ILoaderMesh, primitive: ILoaderMeshPrimitive, babylonMesh: Mesh): Promise<void> {
  521. const promises = new Array<Promise<any>>();
  522. this.logOpen(`${context}`);
  523. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  524. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(babylonGeometry => {
  525. return this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(() => {
  526. babylonGeometry.applyToMesh(babylonMesh);
  527. });
  528. }));
  529. const babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  530. if (primitive.material == undefined) {
  531. let babylonMaterial = this._defaultBabylonMaterialData[babylonDrawMode];
  532. if (!babylonMaterial) {
  533. babylonMaterial = this._createDefaultMaterial("__gltf_default", babylonDrawMode);
  534. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  535. this._defaultBabylonMaterialData[babylonDrawMode] = babylonMaterial;
  536. }
  537. babylonMesh.material = babylonMaterial;
  538. }
  539. else {
  540. const material = ArrayItem.Get(`${context}/material`, this.gltf.materials, primitive.material);
  541. promises.push(this._loadMaterialAsync(`#/materials/${material.index}`, material, babylonMesh, babylonDrawMode, babylonMaterial => {
  542. babylonMesh.material = babylonMaterial;
  543. }));
  544. }
  545. this.logClose();
  546. return Promise.all(promises).then(() => {});
  547. }
  548. private _loadVertexDataAsync(context: string, primitive: ILoaderMeshPrimitive, babylonMesh: Mesh): Promise<Geometry> {
  549. const extensionPromise = this._extensionsLoadVertexDataAsync(context, primitive, babylonMesh);
  550. if (extensionPromise) {
  551. return extensionPromise;
  552. }
  553. const attributes = primitive.attributes;
  554. if (!attributes) {
  555. throw new Error(`${context}: Attributes are missing`);
  556. }
  557. const promises = new Array<Promise<any>>();
  558. const babylonGeometry = new Geometry(babylonMesh.name, this.babylonScene);
  559. if (primitive.indices == undefined) {
  560. babylonMesh.isUnIndexed = true;
  561. }
  562. else {
  563. const accessor = ArrayItem.Get(`${context}/indices`, this.gltf.accessors, primitive.indices);
  564. promises.push(this._loadIndicesAccessorAsync(`#/accessors/${accessor.index}`, accessor).then(data => {
  565. babylonGeometry.setIndices(data);
  566. }));
  567. }
  568. const loadAttribute = (attribute: string, kind: string, callback?: (accessor: ILoaderAccessor) => void) => {
  569. if (attributes[attribute] == undefined) {
  570. return;
  571. }
  572. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  573. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  574. babylonMesh._delayInfo.push(kind);
  575. }
  576. const accessor = ArrayItem.Get(`${context}/attributes/${attribute}`, this.gltf.accessors, attributes[attribute]);
  577. promises.push(this._loadVertexAccessorAsync(`#/accessors/${accessor.index}`, accessor, kind).then(babylonVertexBuffer => {
  578. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  579. }));
  580. if (callback) {
  581. callback(accessor);
  582. }
  583. };
  584. loadAttribute("POSITION", VertexBuffer.PositionKind);
  585. loadAttribute("NORMAL", VertexBuffer.NormalKind);
  586. loadAttribute("TANGENT", VertexBuffer.TangentKind);
  587. loadAttribute("TEXCOORD_0", VertexBuffer.UVKind);
  588. loadAttribute("TEXCOORD_1", VertexBuffer.UV2Kind);
  589. loadAttribute("JOINTS_0", VertexBuffer.MatricesIndicesKind);
  590. loadAttribute("WEIGHTS_0", VertexBuffer.MatricesWeightsKind);
  591. loadAttribute("COLOR_0", VertexBuffer.ColorKind, accessor => {
  592. if (accessor.type === AccessorType.VEC4) {
  593. babylonMesh.hasVertexAlpha = true;
  594. }
  595. });
  596. return Promise.all(promises).then(() => {
  597. return babylonGeometry;
  598. });
  599. }
  600. private _createMorphTargets(context: string, node: ILoaderNode, mesh: ILoaderMesh, primitive: ILoaderMeshPrimitive, babylonMesh: Mesh): void {
  601. if (!primitive.targets) {
  602. return;
  603. }
  604. if (node._numMorphTargets == undefined) {
  605. node._numMorphTargets = primitive.targets.length;
  606. }
  607. else if (primitive.targets.length !== node._numMorphTargets) {
  608. throw new Error(`${context}: Primitives do not have the same number of targets`);
  609. }
  610. babylonMesh.morphTargetManager = new MorphTargetManager();
  611. for (let index = 0; index < primitive.targets.length; index++) {
  612. const weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  613. babylonMesh.morphTargetManager.addTarget(new MorphTarget(`morphTarget${index}`, weight));
  614. // TODO: tell the target whether it has positions, normals, tangents
  615. }
  616. }
  617. private _loadMorphTargetsAsync(context: string, primitive: ILoaderMeshPrimitive, babylonMesh: Mesh, babylonGeometry: Geometry): Promise<void> {
  618. if (!primitive.targets) {
  619. return Promise.resolve();
  620. }
  621. const promises = new Array<Promise<any>>();
  622. const morphTargetManager = babylonMesh.morphTargetManager!;
  623. for (let index = 0; index < morphTargetManager.numTargets; index++) {
  624. const babylonMorphTarget = morphTargetManager.getTarget(index);
  625. promises.push(this._loadMorphTargetVertexDataAsync(`${context}/targets/${index}`, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  626. }
  627. return Promise.all(promises).then(() => {});
  628. }
  629. private _loadMorphTargetVertexDataAsync(context: string, babylonGeometry: Geometry, attributes: { [name: string]: number }, babylonMorphTarget: MorphTarget): Promise<void> {
  630. const promises = new Array<Promise<any>>();
  631. const loadAttribute = (attribute: string, kind: string, setData: (babylonVertexBuffer: VertexBuffer, data: Float32Array) => void) => {
  632. if (attributes[attribute] == undefined) {
  633. return;
  634. }
  635. const babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  636. if (!babylonVertexBuffer) {
  637. return;
  638. }
  639. const accessor = ArrayItem.Get(`${context}/${attribute}`, this.gltf.accessors, attributes[attribute]);
  640. promises.push(this._loadFloatAccessorAsync(`#/accessors/${accessor.index}`, accessor).then(data => {
  641. setData(babylonVertexBuffer, data);
  642. }));
  643. };
  644. loadAttribute("POSITION", VertexBuffer.PositionKind, (babylonVertexBuffer, data) => {
  645. babylonVertexBuffer.forEach(data.length, (value, index) => {
  646. data[index] += value;
  647. });
  648. babylonMorphTarget.setPositions(data);
  649. });
  650. loadAttribute("NORMAL", VertexBuffer.NormalKind, (babylonVertexBuffer, data) => {
  651. babylonVertexBuffer.forEach(data.length, (value, index) => {
  652. data[index] += value;
  653. });
  654. babylonMorphTarget.setNormals(data);
  655. });
  656. loadAttribute("TANGENT", VertexBuffer.TangentKind, (babylonVertexBuffer, data) => {
  657. let dataIndex = 0;
  658. babylonVertexBuffer.forEach(data.length / 3 * 4, (value, index) => {
  659. // Tangent data for morph targets is stored as xyz delta.
  660. // The vertexData.tangent is stored as xyzw.
  661. // So we need to skip every fourth vertexData.tangent.
  662. if (((index + 1) % 4) !== 0) {
  663. data[dataIndex++] += value;
  664. }
  665. });
  666. babylonMorphTarget.setTangents(data);
  667. });
  668. return Promise.all(promises).then(() => {});
  669. }
  670. private static _LoadTransform(node: ILoaderNode, babylonNode: TransformNode): void {
  671. let position = Vector3.Zero();
  672. let rotation = Quaternion.Identity();
  673. let scaling = Vector3.One();
  674. if (node.matrix) {
  675. const matrix = Matrix.FromArray(node.matrix);
  676. matrix.decompose(scaling, rotation, position);
  677. }
  678. else {
  679. if (node.translation) position = Vector3.FromArray(node.translation);
  680. if (node.rotation) rotation = Quaternion.FromArray(node.rotation);
  681. if (node.scale) scaling = Vector3.FromArray(node.scale);
  682. }
  683. babylonNode.position = position;
  684. babylonNode.rotationQuaternion = rotation;
  685. babylonNode.scaling = scaling;
  686. }
  687. private _loadSkinAsync(context: string, node: ILoaderNode, skin: ILoaderSkin): Promise<void> {
  688. const assignSkeleton = (skeleton: Skeleton) => {
  689. this._forEachPrimitive(node, babylonMesh => {
  690. babylonMesh.skeleton = skeleton;
  691. });
  692. // Ignore the TRS of skinned nodes.
  693. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  694. node._babylonMesh!.position = Vector3.Zero();
  695. node._babylonMesh!.rotationQuaternion = Quaternion.Identity();
  696. node._babylonMesh!.scaling = Vector3.One();
  697. };
  698. if (skin._promise) {
  699. return skin._promise.then(() => {
  700. assignSkeleton(skin._babylonSkeleton!);
  701. });
  702. }
  703. const skeletonId = `skeleton${skin.index}`;
  704. const babylonSkeleton = new Skeleton(skin.name || skeletonId, skeletonId, this.babylonScene);
  705. skin._babylonSkeleton = babylonSkeleton;
  706. this._loadBones(context, skin);
  707. assignSkeleton(babylonSkeleton);
  708. return (skin._promise = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(inverseBindMatricesData => {
  709. this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  710. }));
  711. }
  712. private _loadBones(context: string, skin: ILoaderSkin): void {
  713. const babylonBones: { [index: number]: Bone } = {};
  714. for (const index of skin.joints) {
  715. const node = ArrayItem.Get(`${context}/joints/${index}`, this.gltf.nodes, index);
  716. this._loadBone(node, skin, babylonBones);
  717. }
  718. }
  719. private _loadBone(node: ILoaderNode, skin: ILoaderSkin, babylonBones: { [index: number]: Bone }): Bone {
  720. let babylonBone = babylonBones[node.index];
  721. if (babylonBone) {
  722. return babylonBone;
  723. }
  724. let babylonParentBone: Nullable<Bone> = null;
  725. if (node.parent && node.parent._babylonMesh !== this._rootBabylonMesh) {
  726. babylonParentBone = this._loadBone(node.parent, skin, babylonBones);
  727. }
  728. const boneIndex = skin.joints.indexOf(node.index);
  729. babylonBone = new Bone(node.name || `joint${node.index}`, skin._babylonSkeleton!, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  730. babylonBones[node.index] = babylonBone;
  731. node._babylonBones = node._babylonBones || [];
  732. node._babylonBones.push(babylonBone);
  733. return babylonBone;
  734. }
  735. private _loadSkinInverseBindMatricesDataAsync(context: string, skin: ILoaderSkin): Promise<Nullable<Float32Array>> {
  736. if (skin.inverseBindMatrices == undefined) {
  737. return Promise.resolve(null);
  738. }
  739. const accessor = ArrayItem.Get(`${context}/inverseBindMatrices`, this.gltf.accessors, skin.inverseBindMatrices);
  740. return this._loadFloatAccessorAsync(`#/accessors/${accessor.index}`, accessor);
  741. }
  742. private _updateBoneMatrices(babylonSkeleton: Skeleton, inverseBindMatricesData: Nullable<Float32Array>): void {
  743. for (const babylonBone of babylonSkeleton.bones) {
  744. let baseMatrix = Matrix.Identity();
  745. const boneIndex = babylonBone._index!;
  746. if (inverseBindMatricesData && boneIndex !== -1) {
  747. Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  748. baseMatrix.invertToRef(baseMatrix);
  749. }
  750. const babylonParentBone = babylonBone.getParent();
  751. if (babylonParentBone) {
  752. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  753. }
  754. babylonBone.updateMatrix(baseMatrix, false, false);
  755. babylonBone._updateDifferenceMatrix(undefined, false);
  756. }
  757. }
  758. private _getNodeMatrix(node: ILoaderNode): Matrix {
  759. return node.matrix ?
  760. Matrix.FromArray(node.matrix) :
  761. Matrix.Compose(
  762. node.scale ? Vector3.FromArray(node.scale) : Vector3.One(),
  763. node.rotation ? Quaternion.FromArray(node.rotation) : Quaternion.Identity(),
  764. node.translation ? Vector3.FromArray(node.translation) : Vector3.Zero());
  765. }
  766. /**
  767. * Loads a glTF camera.
  768. * @param context The context when loading the asset
  769. * @param camera The glTF camera property
  770. * @param assign A function called synchronously after parsing the glTF properties
  771. * @returns A promise that resolves with the loaded Babylon camera when the load is complete
  772. */
  773. public loadCameraAsync(context: string, camera: ILoaderCamera, assign: (babylonCamera: Camera) => void = () => {}): Promise<Camera> {
  774. const extensionPromise = this._extensionsLoadCameraAsync(context, camera, assign);
  775. if (extensionPromise) {
  776. return extensionPromise;
  777. }
  778. const promises = new Array<Promise<any>>();
  779. this.logOpen(`${context} ${camera.name || ""}`);
  780. const babylonCamera = new FreeCamera(camera.name || `camera${camera.index}`, Vector3.Zero(), this.babylonScene, false);
  781. babylonCamera.rotation = new Vector3(0, Math.PI, 0);
  782. switch (camera.type) {
  783. case CameraType.PERSPECTIVE: {
  784. const perspective = camera.perspective;
  785. if (!perspective) {
  786. throw new Error(`${context}: Camera perspective properties are missing`);
  787. }
  788. babylonCamera.fov = perspective.yfov;
  789. babylonCamera.minZ = perspective.znear;
  790. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  791. break;
  792. }
  793. case CameraType.ORTHOGRAPHIC: {
  794. if (!camera.orthographic) {
  795. throw new Error(`${context}: Camera orthographic properties are missing`);
  796. }
  797. babylonCamera.mode = Camera.ORTHOGRAPHIC_CAMERA;
  798. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  799. babylonCamera.orthoRight = camera.orthographic.xmag;
  800. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  801. babylonCamera.orthoTop = camera.orthographic.ymag;
  802. babylonCamera.minZ = camera.orthographic.znear;
  803. babylonCamera.maxZ = camera.orthographic.zfar;
  804. break;
  805. }
  806. default: {
  807. throw new Error(`${context}: Invalid camera type (${camera.type})`);
  808. }
  809. }
  810. assign(babylonCamera);
  811. this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);
  812. return Promise.all(promises).then(() => {
  813. return babylonCamera;
  814. });
  815. }
  816. private _loadAnimationsAsync(): Promise<void> {
  817. const animations = this.gltf.animations;
  818. if (!animations) {
  819. return Promise.resolve();
  820. }
  821. const promises = new Array<Promise<any>>();
  822. for (let index = 0; index < animations.length; index++) {
  823. const animation = animations[index];
  824. promises.push(this.loadAnimationAsync(`#/animations/${animation.index}`, animation));
  825. }
  826. return Promise.all(promises).then(() => {});
  827. }
  828. /**
  829. * Loads a glTF animation.
  830. * @param context The context when loading the asset
  831. * @param animation The glTF animation property
  832. * @returns A promise that resolves with the loaded Babylon animation group when the load is complete
  833. */
  834. public loadAnimationAsync(context: string, animation: ILoaderAnimation): Promise<AnimationGroup> {
  835. const promise = this._extensionsLoadAnimationAsync(context, animation);
  836. if (promise) {
  837. return promise;
  838. }
  839. const babylonAnimationGroup = new AnimationGroup(animation.name || `animation${animation.index}`, this.babylonScene);
  840. animation._babylonAnimationGroup = babylonAnimationGroup;
  841. const promises = new Array<Promise<any>>();
  842. ArrayItem.Assign(animation.channels);
  843. ArrayItem.Assign(animation.samplers);
  844. for (const channel of animation.channels) {
  845. promises.push(this._loadAnimationChannelAsync(`${context}/channels/${channel.index}`, context, animation, channel, babylonAnimationGroup));
  846. }
  847. return Promise.all(promises).then(() => {
  848. babylonAnimationGroup.normalize(0);
  849. return babylonAnimationGroup;
  850. });
  851. }
  852. private _loadAnimationChannelAsync(context: string, animationContext: string, animation: ILoaderAnimation, channel: ILoaderAnimationChannel, babylonAnimationGroup: AnimationGroup): Promise<void> {
  853. const targetNode = ArrayItem.Get(`${context}/target/node`, this.gltf.nodes, channel.target.node);
  854. // Ignore animations that have no animation targets.
  855. if ((channel.target.path === AnimationChannelTargetPath.WEIGHTS && !targetNode._numMorphTargets) ||
  856. (channel.target.path !== AnimationChannelTargetPath.WEIGHTS && !targetNode._babylonMesh)) {
  857. return Promise.resolve();
  858. }
  859. // Ignore animations targeting TRS of skinned nodes.
  860. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  861. if (targetNode.skin != undefined && channel.target.path !== AnimationChannelTargetPath.WEIGHTS) {
  862. return Promise.resolve();
  863. }
  864. const sampler = ArrayItem.Get(`${context}/sampler`, animation.samplers, channel.sampler);
  865. return this._loadAnimationSamplerAsync(`${animationContext}/samplers/${channel.sampler}`, sampler).then(data => {
  866. let targetPath: string;
  867. let animationType: number;
  868. switch (channel.target.path) {
  869. case AnimationChannelTargetPath.TRANSLATION: {
  870. targetPath = "position";
  871. animationType = Animation.ANIMATIONTYPE_VECTOR3;
  872. break;
  873. }
  874. case AnimationChannelTargetPath.ROTATION: {
  875. targetPath = "rotationQuaternion";
  876. animationType = Animation.ANIMATIONTYPE_QUATERNION;
  877. break;
  878. }
  879. case AnimationChannelTargetPath.SCALE: {
  880. targetPath = "scaling";
  881. animationType = Animation.ANIMATIONTYPE_VECTOR3;
  882. break;
  883. }
  884. case AnimationChannelTargetPath.WEIGHTS: {
  885. targetPath = "influence";
  886. animationType = Animation.ANIMATIONTYPE_FLOAT;
  887. break;
  888. }
  889. default: {
  890. throw new Error(`${context}/target/path: Invalid value (${channel.target.path})`);
  891. }
  892. }
  893. let outputBufferOffset = 0;
  894. let getNextOutputValue: () => Vector3 | Quaternion | Array<number>;
  895. switch (targetPath) {
  896. case "position": {
  897. getNextOutputValue = () => {
  898. const value = Vector3.FromArray(data.output, outputBufferOffset);
  899. outputBufferOffset += 3;
  900. return value;
  901. };
  902. break;
  903. }
  904. case "rotationQuaternion": {
  905. getNextOutputValue = () => {
  906. const value = Quaternion.FromArray(data.output, outputBufferOffset);
  907. outputBufferOffset += 4;
  908. return value;
  909. };
  910. break;
  911. }
  912. case "scaling": {
  913. getNextOutputValue = () => {
  914. const value = Vector3.FromArray(data.output, outputBufferOffset);
  915. outputBufferOffset += 3;
  916. return value;
  917. };
  918. break;
  919. }
  920. case "influence": {
  921. getNextOutputValue = () => {
  922. const value = new Array<number>(targetNode._numMorphTargets!);
  923. for (let i = 0; i < targetNode._numMorphTargets!; i++) {
  924. value[i] = data.output[outputBufferOffset++];
  925. }
  926. return value;
  927. };
  928. break;
  929. }
  930. }
  931. let getNextKey: (frameIndex: number) => IAnimationKey;
  932. switch (data.interpolation) {
  933. case AnimationSamplerInterpolation.STEP: {
  934. getNextKey = frameIndex => ({
  935. frame: data.input[frameIndex],
  936. value: getNextOutputValue(),
  937. interpolation: AnimationKeyInterpolation.STEP
  938. });
  939. break;
  940. }
  941. case AnimationSamplerInterpolation.LINEAR: {
  942. getNextKey = frameIndex => ({
  943. frame: data.input[frameIndex],
  944. value: getNextOutputValue()
  945. });
  946. break;
  947. }
  948. case AnimationSamplerInterpolation.CUBICSPLINE: {
  949. getNextKey = frameIndex => ({
  950. frame: data.input[frameIndex],
  951. inTangent: getNextOutputValue(),
  952. value: getNextOutputValue(),
  953. outTangent: getNextOutputValue()
  954. });
  955. break;
  956. }
  957. }
  958. const keys = new Array(data.input.length);
  959. for (let frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  960. keys[frameIndex] = getNextKey!(frameIndex);
  961. }
  962. if (targetPath === "influence") {
  963. for (let targetIndex = 0; targetIndex < targetNode._numMorphTargets!; targetIndex++) {
  964. const animationName = `${babylonAnimationGroup.name}_channel${babylonAnimationGroup.targetedAnimations.length}`;
  965. const babylonAnimation = new Animation(animationName, targetPath, 1, animationType);
  966. babylonAnimation.setKeys(keys.map(key => ({
  967. frame: key.frame,
  968. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  969. value: key.value[targetIndex],
  970. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  971. })));
  972. this._forEachPrimitive(targetNode, babylonMesh => {
  973. const morphTarget = babylonMesh.morphTargetManager!.getTarget(targetIndex);
  974. const babylonAnimationClone = babylonAnimation.clone();
  975. morphTarget.animations.push(babylonAnimationClone);
  976. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  977. });
  978. }
  979. }
  980. else {
  981. const animationName = `${babylonAnimationGroup.name}_channel${babylonAnimationGroup.targetedAnimations.length}`;
  982. const babylonAnimation = new Animation(animationName, targetPath, 1, animationType);
  983. babylonAnimation.setKeys(keys);
  984. if (targetNode._babylonBones) {
  985. const babylonAnimationTargets = [targetNode._babylonMesh!, ...targetNode._babylonBones];
  986. for (const babylonAnimationTarget of babylonAnimationTargets) {
  987. babylonAnimationTarget.animations.push(babylonAnimation);
  988. }
  989. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  990. }
  991. else {
  992. targetNode._babylonMesh!.animations.push(babylonAnimation);
  993. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  994. }
  995. }
  996. });
  997. }
  998. private _loadAnimationSamplerAsync(context: string, sampler: ILoaderAnimationSampler): Promise<_ILoaderAnimationSamplerData> {
  999. if (sampler._data) {
  1000. return sampler._data;
  1001. }
  1002. const interpolation = sampler.interpolation || AnimationSamplerInterpolation.LINEAR;
  1003. switch (interpolation) {
  1004. case AnimationSamplerInterpolation.STEP:
  1005. case AnimationSamplerInterpolation.LINEAR:
  1006. case AnimationSamplerInterpolation.CUBICSPLINE: {
  1007. break;
  1008. }
  1009. default: {
  1010. throw new Error(`${context}/interpolation: Invalid value (${sampler.interpolation})`);
  1011. }
  1012. }
  1013. const inputAccessor = ArrayItem.Get(`${context}/input`, this.gltf.accessors, sampler.input);
  1014. const outputAccessor = ArrayItem.Get(`${context}/output`, this.gltf.accessors, sampler.output);
  1015. sampler._data = Promise.all([
  1016. this._loadFloatAccessorAsync(`#/accessors/${inputAccessor.index}`, inputAccessor),
  1017. this._loadFloatAccessorAsync(`#/accessors/${outputAccessor.index}`, outputAccessor)
  1018. ]).then(([inputData, outputData]) => {
  1019. return {
  1020. input: inputData,
  1021. interpolation: interpolation,
  1022. output: outputData,
  1023. };
  1024. });
  1025. return sampler._data;
  1026. }
  1027. private _loadBufferAsync(context: string, buffer: ILoaderBuffer): Promise<ArrayBufferView> {
  1028. if (buffer._data) {
  1029. return buffer._data;
  1030. }
  1031. if (!buffer.uri) {
  1032. throw new Error(`${context}/uri: Value is missing`);
  1033. }
  1034. buffer._data = this.loadUriAsync(`${context}/uri`, buffer.uri);
  1035. return buffer._data;
  1036. }
  1037. /**
  1038. * Loads a glTF buffer view.
  1039. * @param context The context when loading the asset
  1040. * @param bufferView The glTF buffer view property
  1041. * @returns A promise that resolves with the loaded data when the load is complete
  1042. */
  1043. public loadBufferViewAsync(context: string, bufferView: ILoaderBufferView): Promise<ArrayBufferView> {
  1044. if (bufferView._data) {
  1045. return bufferView._data;
  1046. }
  1047. const buffer = ArrayItem.Get(`${context}/buffer`, this.gltf.buffers, bufferView.buffer);
  1048. bufferView._data = this._loadBufferAsync(`#/buffers/${buffer.index}`, buffer).then(data => {
  1049. try {
  1050. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  1051. }
  1052. catch (e) {
  1053. throw new Error(`${context}: ${e.message}`);
  1054. }
  1055. });
  1056. return bufferView._data;
  1057. }
  1058. private _loadIndicesAccessorAsync(context: string, accessor: ILoaderAccessor): Promise<IndicesArray> {
  1059. if (accessor.type !== AccessorType.SCALAR) {
  1060. throw new Error(`${context}/type: Invalid value ${accessor.type}`);
  1061. }
  1062. if (accessor.componentType !== AccessorComponentType.UNSIGNED_BYTE &&
  1063. accessor.componentType !== AccessorComponentType.UNSIGNED_SHORT &&
  1064. accessor.componentType !== AccessorComponentType.UNSIGNED_INT) {
  1065. throw new Error(`${context}/componentType: Invalid value ${accessor.componentType}`);
  1066. }
  1067. if (accessor._data) {
  1068. return accessor._data as Promise<IndicesArray>;
  1069. }
  1070. const bufferView = ArrayItem.Get(`${context}/bufferView`, this.gltf.bufferViews, accessor.bufferView);
  1071. accessor._data = this.loadBufferViewAsync(`#/bufferViews/${bufferView.index}`, bufferView).then(data => {
  1072. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  1073. });
  1074. return accessor._data as Promise<IndicesArray>;
  1075. }
  1076. private _loadFloatAccessorAsync(context: string, accessor: ILoaderAccessor): Promise<Float32Array> {
  1077. // TODO: support normalized and stride
  1078. if (accessor.componentType !== AccessorComponentType.FLOAT) {
  1079. throw new Error(`Invalid component type ${accessor.componentType}`);
  1080. }
  1081. if (accessor._data) {
  1082. return accessor._data as Promise<Float32Array>;
  1083. }
  1084. const numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  1085. const length = numComponents * accessor.count;
  1086. if (accessor.bufferView == undefined) {
  1087. accessor._data = Promise.resolve(new Float32Array(length));
  1088. }
  1089. else {
  1090. const bufferView = ArrayItem.Get(`${context}/bufferView`, this.gltf.bufferViews, accessor.bufferView);
  1091. accessor._data = this.loadBufferViewAsync(`#/bufferViews/${bufferView.index}`, bufferView).then(data => {
  1092. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  1093. });
  1094. }
  1095. if (accessor.sparse) {
  1096. const sparse = accessor.sparse;
  1097. accessor._data = accessor._data.then((data: Float32Array) => {
  1098. const indicesBufferView = ArrayItem.Get(`${context}/sparse/indices/bufferView`, this.gltf.bufferViews, sparse.indices.bufferView);
  1099. const valuesBufferView = ArrayItem.Get(`${context}/sparse/values/bufferView`, this.gltf.bufferViews, sparse.values.bufferView);
  1100. return Promise.all([
  1101. this.loadBufferViewAsync(`#/bufferViews/${indicesBufferView.index}`, indicesBufferView),
  1102. this.loadBufferViewAsync(`#/bufferViews/${valuesBufferView.index}`, valuesBufferView)
  1103. ]).then(([indicesData, valuesData]) => {
  1104. const indices = GLTFLoader._GetTypedArray(`${context}/sparse/indices`, sparse.indices.componentType, indicesData, sparse.indices.byteOffset, sparse.count) as IndicesArray;
  1105. const values = GLTFLoader._GetTypedArray(`${context}/sparse/values`, accessor.componentType, valuesData, sparse.values.byteOffset, numComponents * sparse.count) as Float32Array;
  1106. let valuesIndex = 0;
  1107. for (let indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  1108. let dataIndex = indices[indicesIndex] * numComponents;
  1109. for (let componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  1110. data[dataIndex++] = values[valuesIndex++];
  1111. }
  1112. }
  1113. return data;
  1114. });
  1115. });
  1116. }
  1117. return accessor._data as Promise<Float32Array>;
  1118. }
  1119. private _loadVertexBufferViewAsync(bufferView: ILoaderBufferView, kind: string): Promise<Buffer> {
  1120. if (bufferView._babylonBuffer) {
  1121. return bufferView._babylonBuffer;
  1122. }
  1123. bufferView._babylonBuffer = this.loadBufferViewAsync(`#/bufferViews/${bufferView.index}`, bufferView).then(data => {
  1124. return new Buffer(this.babylonScene.getEngine(), data, false);
  1125. });
  1126. return bufferView._babylonBuffer;
  1127. }
  1128. private _loadVertexAccessorAsync(context: string, accessor: ILoaderAccessor, kind: string): Promise<VertexBuffer> {
  1129. if (accessor._babylonVertexBuffer) {
  1130. return accessor._babylonVertexBuffer;
  1131. }
  1132. if (accessor.sparse) {
  1133. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(`#/accessors/${accessor.index}`, accessor).then(data => {
  1134. return new VertexBuffer(this.babylonScene.getEngine(), data, kind, false);
  1135. });
  1136. }
  1137. // HACK: If byte offset is not a multiple of component type byte length then load as a float array instead of using Babylon buffers.
  1138. else if (accessor.byteOffset && accessor.byteOffset % VertexBuffer.GetTypeByteLength(accessor.componentType) !== 0) {
  1139. Tools.Warn("Accessor byte offset is not a multiple of component type byte length");
  1140. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(`#/accessors/${accessor.index}`, accessor).then(data => {
  1141. return new VertexBuffer(this.babylonScene.getEngine(), data, kind, false);
  1142. });
  1143. }
  1144. else {
  1145. const bufferView = ArrayItem.Get(`${context}/bufferView`, this.gltf.bufferViews, accessor.bufferView);
  1146. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync(bufferView, kind).then(babylonBuffer => {
  1147. const size = GLTFLoader._GetNumComponents(context, accessor.type);
  1148. return new VertexBuffer(this.babylonScene.getEngine(), babylonBuffer, kind, false, false, bufferView.byteStride,
  1149. false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  1150. });
  1151. }
  1152. return accessor._babylonVertexBuffer;
  1153. }
  1154. private _loadMaterialMetallicRoughnessPropertiesAsync(context: string, material: ILoaderMaterial, properties: ILoaderMaterialPbrMetallicRoughness, babylonMaterial: Material): Promise<void> {
  1155. if (!(babylonMaterial instanceof PBRMaterial)) {
  1156. throw new Error(`${context}: Material type not supported`);
  1157. }
  1158. const promises = new Array<Promise<any>>();
  1159. if (properties) {
  1160. if (properties.baseColorFactor) {
  1161. babylonMaterial.albedoColor = Color3.FromArray(properties.baseColorFactor);
  1162. babylonMaterial.alpha = properties.baseColorFactor[3];
  1163. }
  1164. else {
  1165. babylonMaterial.albedoColor = Color3.White();
  1166. }
  1167. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  1168. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  1169. if (properties.baseColorTexture) {
  1170. promises.push(this.loadTextureInfoAsync(`${context}/baseColorTexture`, properties.baseColorTexture, texture => {
  1171. babylonMaterial.albedoTexture = texture;
  1172. }));
  1173. }
  1174. if (properties.metallicRoughnessTexture) {
  1175. promises.push(this.loadTextureInfoAsync(`${context}/metallicRoughnessTexture`, properties.metallicRoughnessTexture, texture => {
  1176. babylonMaterial.metallicTexture = texture;
  1177. }));
  1178. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  1179. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  1180. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  1181. }
  1182. }
  1183. return Promise.all(promises).then(() => {});
  1184. }
  1185. /** @hidden */
  1186. public _loadMaterialAsync(context: string, material: ILoaderMaterial, babylonMesh: Mesh, babylonDrawMode: number, assign: (babylonMaterial: Material) => void = () => {}): Promise<Material> {
  1187. const extensionPromise = this._extensionsLoadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign);
  1188. if (extensionPromise) {
  1189. return extensionPromise;
  1190. }
  1191. material._babylonData = material._babylonData || {};
  1192. let babylonData = material._babylonData[babylonDrawMode];
  1193. if (!babylonData) {
  1194. this.logOpen(`${context} ${material.name || ""}`);
  1195. const babylonMaterial = this.createMaterial(context, material, babylonDrawMode);
  1196. babylonData = {
  1197. material: babylonMaterial,
  1198. meshes: [],
  1199. promise: this.loadMaterialPropertiesAsync(context, material, babylonMaterial)
  1200. };
  1201. material._babylonData[babylonDrawMode] = babylonData;
  1202. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  1203. this.logClose();
  1204. }
  1205. babylonData.meshes.push(babylonMesh);
  1206. babylonMesh.onDisposeObservable.addOnce(() => {
  1207. const index = babylonData.meshes.indexOf(babylonMesh);
  1208. if (index !== -1) {
  1209. babylonData.meshes.splice(index, 1);
  1210. }
  1211. });
  1212. assign(babylonData.material);
  1213. return babylonData.promise.then(() => {
  1214. return babylonData.material;
  1215. });
  1216. }
  1217. private _createDefaultMaterial(name: string, babylonDrawMode: number): Material {
  1218. const babylonMaterial = new PBRMaterial(name, this.babylonScene);
  1219. babylonMaterial.sideOrientation = this.babylonScene.useRightHandedSystem ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation;
  1220. babylonMaterial.fillMode = babylonDrawMode;
  1221. babylonMaterial.enableSpecularAntiAliasing = true;
  1222. babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;
  1223. babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;
  1224. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_OPAQUE;
  1225. babylonMaterial.metallic = 1;
  1226. babylonMaterial.roughness = 1;
  1227. return babylonMaterial;
  1228. }
  1229. /**
  1230. * Creates a Babylon material from a glTF material.
  1231. * @param context The context when loading the asset
  1232. * @param material The glTF material property
  1233. * @param babylonDrawMode The draw mode for the Babylon material
  1234. * @returns The Babylon material
  1235. */
  1236. public createMaterial(context: string, material: ILoaderMaterial, babylonDrawMode: number): Material {
  1237. const extensionPromise = this._extensionsCreateMaterial(context, material, babylonDrawMode);
  1238. if (extensionPromise) {
  1239. return extensionPromise;
  1240. }
  1241. const name = material.name || `material${material.index}`;
  1242. return this._createDefaultMaterial(name, babylonDrawMode);
  1243. }
  1244. /**
  1245. * Loads properties from a glTF material into a Babylon material.
  1246. * @param context The context when loading the asset
  1247. * @param material The glTF material property
  1248. * @param babylonMaterial The Babylon material
  1249. * @returns A promise that resolves when the load is complete
  1250. */
  1251. public loadMaterialPropertiesAsync(context: string, material: ILoaderMaterial, babylonMaterial: Material): Promise<void> {
  1252. const extensionPromise = this._extensionsLoadMaterialPropertiesAsync(context, material, babylonMaterial);
  1253. if (extensionPromise) {
  1254. return extensionPromise;
  1255. }
  1256. const promises = new Array<Promise<any>>();
  1257. promises.push(this.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  1258. if (material.pbrMetallicRoughness) {
  1259. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${context}/pbrMetallicRoughness`, material, material.pbrMetallicRoughness, babylonMaterial));
  1260. }
  1261. this.loadMaterialAlphaProperties(context, material, babylonMaterial);
  1262. return Promise.all(promises).then(() => {});
  1263. }
  1264. /**
  1265. * Loads the normal, occlusion, and emissive properties from a glTF material into a Babylon material.
  1266. * @param context The context when loading the asset
  1267. * @param material The glTF material property
  1268. * @param babylonMaterial The Babylon material
  1269. * @returns A promise that resolves when the load is complete
  1270. */
  1271. public loadMaterialBasePropertiesAsync(context: string, material: ILoaderMaterial, babylonMaterial: Material): Promise<void> {
  1272. if (!(babylonMaterial instanceof PBRMaterial)) {
  1273. throw new Error(`${context}: Material type not supported`);
  1274. }
  1275. const promises = new Array<Promise<any>>();
  1276. babylonMaterial.emissiveColor = material.emissiveFactor ? Color3.FromArray(material.emissiveFactor) : new Color3(0, 0, 0);
  1277. if (material.doubleSided) {
  1278. babylonMaterial.backFaceCulling = false;
  1279. babylonMaterial.twoSidedLighting = true;
  1280. }
  1281. if (material.normalTexture) {
  1282. promises.push(this.loadTextureInfoAsync(`${context}/normalTexture`, material.normalTexture, texture => {
  1283. babylonMaterial.bumpTexture = texture;
  1284. }));
  1285. babylonMaterial.invertNormalMapX = !this.babylonScene.useRightHandedSystem;
  1286. babylonMaterial.invertNormalMapY = this.babylonScene.useRightHandedSystem;
  1287. if (material.normalTexture.scale != undefined) {
  1288. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  1289. }
  1290. }
  1291. if (material.occlusionTexture) {
  1292. promises.push(this.loadTextureInfoAsync(`${context}/occlusionTexture`, material.occlusionTexture, texture => {
  1293. babylonMaterial.ambientTexture = texture;
  1294. }));
  1295. babylonMaterial.useAmbientInGrayScale = true;
  1296. if (material.occlusionTexture.strength != undefined) {
  1297. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  1298. }
  1299. }
  1300. if (material.emissiveTexture) {
  1301. promises.push(this.loadTextureInfoAsync(`${context}/emissiveTexture`, material.emissiveTexture, texture => {
  1302. babylonMaterial.emissiveTexture = texture;
  1303. }));
  1304. }
  1305. return Promise.all(promises).then(() => {});
  1306. }
  1307. /**
  1308. * Loads the alpha properties from a glTF material into a Babylon material.
  1309. * Must be called after the setting the albedo texture of the Babylon material when the material has an albedo texture.
  1310. * @param context The context when loading the asset
  1311. * @param material The glTF material property
  1312. * @param babylonMaterial The Babylon material
  1313. */
  1314. public loadMaterialAlphaProperties(context: string, material: ILoaderMaterial, babylonMaterial: Material): void {
  1315. if (!(babylonMaterial instanceof PBRMaterial)) {
  1316. throw new Error(`${context}: Material type not supported`);
  1317. }
  1318. const alphaMode = material.alphaMode || MaterialAlphaMode.OPAQUE;
  1319. switch (alphaMode) {
  1320. case MaterialAlphaMode.OPAQUE: {
  1321. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_OPAQUE;
  1322. break;
  1323. }
  1324. case MaterialAlphaMode.MASK: {
  1325. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHATEST;
  1326. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  1327. if (babylonMaterial.albedoTexture) {
  1328. babylonMaterial.albedoTexture.hasAlpha = true;
  1329. }
  1330. break;
  1331. }
  1332. case MaterialAlphaMode.BLEND: {
  1333. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHABLEND;
  1334. if (babylonMaterial.albedoTexture) {
  1335. babylonMaterial.albedoTexture.hasAlpha = true;
  1336. babylonMaterial.useAlphaFromAlbedoTexture = true;
  1337. }
  1338. break;
  1339. }
  1340. default: {
  1341. throw new Error(`${context}/alphaMode: Invalid value (${material.alphaMode})`);
  1342. }
  1343. }
  1344. }
  1345. /**
  1346. * Loads a glTF texture info.
  1347. * @param context The context when loading the asset
  1348. * @param textureInfo The glTF texture info property
  1349. * @param assign A function called synchronously after parsing the glTF properties
  1350. * @returns A promise that resolves with the loaded Babylon texture when the load is complete
  1351. */
  1352. public loadTextureInfoAsync(context: string, textureInfo: ILoaderTextureInfo, assign: (babylonTexture: BaseTexture) => void = () => {}): Promise<BaseTexture> {
  1353. const extensionPromise = this._extensionsLoadTextureInfoAsync(context, textureInfo, assign);
  1354. if (extensionPromise) {
  1355. return extensionPromise;
  1356. }
  1357. this.logOpen(`${context}`);
  1358. const texture = ArrayItem.Get(`${context}/index`, this.gltf.textures, textureInfo.index);
  1359. const promise = this._loadTextureAsync(`#/textures/${textureInfo.index}`, texture, babylonTexture => {
  1360. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  1361. assign(babylonTexture);
  1362. });
  1363. this.logClose();
  1364. return promise;
  1365. }
  1366. private _loadTextureAsync(context: string, texture: ILoaderTexture, assign: (babylonTexture: BaseTexture) => void = () => {}): Promise<BaseTexture> {
  1367. const promises = new Array<Promise<any>>();
  1368. this.logOpen(`${context} ${texture.name || ""}`);
  1369. const sampler = (texture.sampler == undefined ? GLTFLoader._DefaultSampler : ArrayItem.Get(`${context}/sampler`, this.gltf.samplers, texture.sampler));
  1370. const samplerData = this._loadSampler(`#/samplers/${sampler.index}`, sampler);
  1371. const deferred = new Deferred<void>();
  1372. const babylonTexture = new Texture(null, this.babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, () => {
  1373. if (!this._disposed) {
  1374. deferred.resolve();
  1375. }
  1376. }, (message, exception) => {
  1377. if (!this._disposed) {
  1378. deferred.reject(new Error(`${context}: ${(exception && exception.message) ? exception.message : message || "Failed to load texture"}`));
  1379. }
  1380. });
  1381. promises.push(deferred.promise);
  1382. babylonTexture.name = texture.name || `texture${texture.index}`;
  1383. babylonTexture.wrapU = samplerData.wrapU;
  1384. babylonTexture.wrapV = samplerData.wrapV;
  1385. const image = ArrayItem.Get(`${context}/source`, this.gltf.images, texture.source);
  1386. promises.push(this.loadImageAsync(`#/images/${image.index}`, image).then(data => {
  1387. const name = image.uri || `${this._fileName}#image${image.index}`;
  1388. const dataUrl = `data:${this._uniqueRootUrl}${name}`;
  1389. babylonTexture.updateURL(dataUrl, new Blob([data], { type: image.mimeType }));
  1390. }));
  1391. assign(babylonTexture);
  1392. this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);
  1393. this.logClose();
  1394. return Promise.all(promises).then(() => {
  1395. return babylonTexture;
  1396. });
  1397. }
  1398. private _loadSampler(context: string, sampler: ILoaderSampler): _ILoaderSamplerData {
  1399. if (!sampler._data) {
  1400. sampler._data = {
  1401. noMipMaps: (sampler.minFilter === TextureMinFilter.NEAREST || sampler.minFilter === TextureMinFilter.LINEAR),
  1402. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler),
  1403. wrapU: GLTFLoader._GetTextureWrapMode(`${context}/wrapS`, sampler.wrapS),
  1404. wrapV: GLTFLoader._GetTextureWrapMode(`${context}/wrapT`, sampler.wrapT)
  1405. };
  1406. };
  1407. return sampler._data;
  1408. }
  1409. /**
  1410. * Loads a glTF image.
  1411. * @param context The context when loading the asset
  1412. * @param image The glTF image property
  1413. * @returns A promise that resolves with the loaded data when the load is complete
  1414. */
  1415. public loadImageAsync(context: string, image: ILoaderImage): Promise<ArrayBufferView> {
  1416. if (!image._data) {
  1417. this.logOpen(`${context} ${image.name || ""}`);
  1418. if (image.uri) {
  1419. image._data = this.loadUriAsync(`${context}/uri`, image.uri);
  1420. }
  1421. else {
  1422. const bufferView = ArrayItem.Get(`${context}/bufferView`, this.gltf.bufferViews, image.bufferView);
  1423. image._data = this.loadBufferViewAsync(`#/bufferViews/${bufferView.index}`, bufferView);
  1424. }
  1425. this.logClose();
  1426. }
  1427. return image._data;
  1428. }
  1429. /**
  1430. * Loads a glTF uri.
  1431. * @param context The context when loading the asset
  1432. * @param uri The base64 or relative uri
  1433. * @returns A promise that resolves with the loaded data when the load is complete
  1434. */
  1435. public loadUriAsync(context: string, uri: string): Promise<ArrayBufferView> {
  1436. const extensionPromise = this._extensionsLoadUriAsync(context, uri);
  1437. if (extensionPromise) {
  1438. return extensionPromise;
  1439. }
  1440. if (!GLTFLoader._ValidateUri(uri)) {
  1441. throw new Error(`${context}: '${uri}' is invalid`);
  1442. }
  1443. if (Tools.IsBase64(uri)) {
  1444. const data = new Uint8Array(Tools.DecodeBase64(uri));
  1445. this.log(`Decoded ${uri.substr(0, 64)}... (${data.length} bytes)`);
  1446. return Promise.resolve(data);
  1447. }
  1448. this.log(`Loading ${uri}`);
  1449. return this._parent.preprocessUrlAsync(this._rootUrl + uri).then(url => {
  1450. return new Promise<ArrayBufferView>((resolve, reject) => {
  1451. if (!this._disposed) {
  1452. const request = Tools.LoadFile(url, fileData => {
  1453. if (!this._disposed) {
  1454. const data = new Uint8Array(fileData as ArrayBuffer);
  1455. this.log(`Loaded ${uri} (${data.length} bytes)`);
  1456. resolve(data);
  1457. }
  1458. }, event => {
  1459. if (!this._disposed) {
  1460. if (request) {
  1461. request._lengthComputable = event.lengthComputable;
  1462. request._loaded = event.loaded;
  1463. request._total = event.total;
  1464. }
  1465. if (this._state === GLTFLoaderState.LOADING) {
  1466. try {
  1467. this._onProgress();
  1468. }
  1469. catch (e) {
  1470. reject(e);
  1471. }
  1472. }
  1473. }
  1474. }, this.babylonScene.database, true, (request, exception) => {
  1475. if (!this._disposed) {
  1476. reject(new LoadFileError(`${context}: Failed to load '${uri}'${request ? ": " + request.status + " " + request.statusText : ""}`, request));
  1477. }
  1478. }) as IFileRequestInfo;
  1479. this._requests.push(request);
  1480. }
  1481. });
  1482. });
  1483. }
  1484. private _onProgress(): void {
  1485. if (!this._progressCallback) {
  1486. return;
  1487. }
  1488. let lengthComputable = true;
  1489. let loaded = 0;
  1490. let total = 0;
  1491. for (let request of this._requests) {
  1492. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  1493. return;
  1494. }
  1495. lengthComputable = lengthComputable && request._lengthComputable;
  1496. loaded += request._loaded;
  1497. total += request._total;
  1498. }
  1499. this._progressCallback(new SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  1500. }
  1501. private static _GetTextureWrapMode(context: string, mode: TextureWrapMode | undefined): number {
  1502. // Set defaults if undefined
  1503. mode = mode == undefined ? TextureWrapMode.REPEAT : mode;
  1504. switch (mode) {
  1505. case TextureWrapMode.CLAMP_TO_EDGE: return Texture.CLAMP_ADDRESSMODE;
  1506. case TextureWrapMode.MIRRORED_REPEAT: return Texture.MIRROR_ADDRESSMODE;
  1507. case TextureWrapMode.REPEAT: return Texture.WRAP_ADDRESSMODE;
  1508. default:
  1509. Tools.Warn(`${context}: Invalid value (${mode})`);
  1510. return Texture.WRAP_ADDRESSMODE;
  1511. }
  1512. }
  1513. private static _GetTextureSamplingMode(context: string, sampler: ILoaderSampler): number {
  1514. // Set defaults if undefined
  1515. const magFilter = sampler.magFilter == undefined ? TextureMagFilter.LINEAR : sampler.magFilter;
  1516. const minFilter = sampler.minFilter == undefined ? TextureMinFilter.LINEAR_MIPMAP_LINEAR : sampler.minFilter;
  1517. if (magFilter === TextureMagFilter.LINEAR) {
  1518. switch (minFilter) {
  1519. case TextureMinFilter.NEAREST: return Texture.LINEAR_NEAREST;
  1520. case TextureMinFilter.LINEAR: return Texture.LINEAR_LINEAR;
  1521. case TextureMinFilter.NEAREST_MIPMAP_NEAREST: return Texture.LINEAR_NEAREST_MIPNEAREST;
  1522. case TextureMinFilter.LINEAR_MIPMAP_NEAREST: return Texture.LINEAR_LINEAR_MIPNEAREST;
  1523. case TextureMinFilter.NEAREST_MIPMAP_LINEAR: return Texture.LINEAR_NEAREST_MIPLINEAR;
  1524. case TextureMinFilter.LINEAR_MIPMAP_LINEAR: return Texture.LINEAR_LINEAR_MIPLINEAR;
  1525. default:
  1526. Tools.Warn(`${context}/minFilter: Invalid value (${minFilter})`);
  1527. return Texture.LINEAR_LINEAR_MIPLINEAR;
  1528. }
  1529. }
  1530. else {
  1531. if (magFilter !== TextureMagFilter.NEAREST) {
  1532. Tools.Warn(`${context}/magFilter: Invalid value (${magFilter})`);
  1533. }
  1534. switch (minFilter) {
  1535. case TextureMinFilter.NEAREST: return Texture.NEAREST_NEAREST;
  1536. case TextureMinFilter.LINEAR: return Texture.NEAREST_LINEAR;
  1537. case TextureMinFilter.NEAREST_MIPMAP_NEAREST: return Texture.NEAREST_NEAREST_MIPNEAREST;
  1538. case TextureMinFilter.LINEAR_MIPMAP_NEAREST: return Texture.NEAREST_LINEAR_MIPNEAREST;
  1539. case TextureMinFilter.NEAREST_MIPMAP_LINEAR: return Texture.NEAREST_NEAREST_MIPLINEAR;
  1540. case TextureMinFilter.LINEAR_MIPMAP_LINEAR: return Texture.NEAREST_LINEAR_MIPLINEAR;
  1541. default:
  1542. Tools.Warn(`${context}/minFilter: Invalid value (${minFilter})`);
  1543. return Texture.NEAREST_NEAREST_MIPNEAREST;
  1544. }
  1545. }
  1546. }
  1547. private static _GetTypedArray(context: string, componentType: AccessorComponentType, bufferView: ArrayBufferView, byteOffset: number | undefined, length: number): ArrayBufferView {
  1548. const buffer = bufferView.buffer;
  1549. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  1550. try {
  1551. switch (componentType) {
  1552. case AccessorComponentType.BYTE: return new Int8Array(buffer, byteOffset, length);
  1553. case AccessorComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, length);
  1554. case AccessorComponentType.SHORT: return new Int16Array(buffer, byteOffset, length);
  1555. case AccessorComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, length);
  1556. case AccessorComponentType.UNSIGNED_INT: return new Uint32Array(buffer, byteOffset, length);
  1557. case AccessorComponentType.FLOAT: return new Float32Array(buffer, byteOffset, length);
  1558. default: throw new Error(`Invalid component type ${componentType}`);
  1559. }
  1560. }
  1561. catch (e) {
  1562. throw new Error(`${context}: ${e}`);
  1563. }
  1564. }
  1565. private static _GetNumComponents(context: string, type: string): number {
  1566. switch (type) {
  1567. case "SCALAR": return 1;
  1568. case "VEC2": return 2;
  1569. case "VEC3": return 3;
  1570. case "VEC4": return 4;
  1571. case "MAT2": return 4;
  1572. case "MAT3": return 9;
  1573. case "MAT4": return 16;
  1574. }
  1575. throw new Error(`${context}: Invalid type (${type})`);
  1576. }
  1577. private static _ValidateUri(uri: string): boolean {
  1578. return (Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  1579. }
  1580. private static _GetDrawMode(context: string, mode: number | undefined): number {
  1581. if (mode == undefined) {
  1582. mode = MeshPrimitiveMode.TRIANGLES;
  1583. }
  1584. switch (mode) {
  1585. case MeshPrimitiveMode.POINTS: return Material.PointListDrawMode;
  1586. case MeshPrimitiveMode.LINES: return Material.LineListDrawMode;
  1587. case MeshPrimitiveMode.LINE_LOOP: return Material.LineLoopDrawMode;
  1588. case MeshPrimitiveMode.LINE_STRIP: return Material.LineStripDrawMode;
  1589. case MeshPrimitiveMode.TRIANGLES: return Material.TriangleFillMode;
  1590. case MeshPrimitiveMode.TRIANGLE_STRIP: return Material.TriangleStripDrawMode;
  1591. case MeshPrimitiveMode.TRIANGLE_FAN: return Material.TriangleFanDrawMode;
  1592. }
  1593. throw new Error(`${context}: Invalid mesh primitive mode (${mode})`);
  1594. }
  1595. private _compileMaterialsAsync(): Promise<void> {
  1596. this._parent._startPerformanceCounter("Compile materials");
  1597. const promises = new Array<Promise<any>>();
  1598. if (this.gltf.materials) {
  1599. for (const material of this.gltf.materials) {
  1600. if (material._babylonData) {
  1601. for (const babylonDrawMode in material._babylonData) {
  1602. const babylonData = material._babylonData[babylonDrawMode];
  1603. for (const babylonMesh of babylonData.meshes) {
  1604. // Ensure nonUniformScaling is set if necessary.
  1605. babylonMesh.computeWorldMatrix(true);
  1606. const babylonMaterial = babylonData.material;
  1607. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  1608. if (this._parent.useClipPlane) {
  1609. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  1610. }
  1611. }
  1612. }
  1613. }
  1614. }
  1615. }
  1616. return Promise.all(promises).then(() => {
  1617. this._parent._endPerformanceCounter("Compile materials");
  1618. });
  1619. }
  1620. private _compileShadowGeneratorsAsync(): Promise<void> {
  1621. this._parent._startPerformanceCounter("Compile shadow generators");
  1622. const promises = new Array<Promise<any>>();
  1623. const lights = this.babylonScene.lights;
  1624. for (let light of lights) {
  1625. let generator = light.getShadowGenerator();
  1626. if (generator) {
  1627. promises.push(generator.forceCompilationAsync());
  1628. }
  1629. }
  1630. return Promise.all(promises).then(() => {
  1631. this._parent._endPerformanceCounter("Compile shadow generators");
  1632. });
  1633. }
  1634. private _forEachExtensions(action: (extension: IGLTFLoaderExtension) => void): void {
  1635. for (const name of GLTFLoader._ExtensionNames) {
  1636. const extension = this._extensions[name];
  1637. if (extension.enabled) {
  1638. action(extension);
  1639. }
  1640. }
  1641. }
  1642. private _applyExtensions<T>(property: IProperty, actionAsync: (extension: IGLTFLoaderExtension) => Nullable<T> | undefined): Nullable<T> {
  1643. for (const name of GLTFLoader._ExtensionNames) {
  1644. const extension = this._extensions[name];
  1645. if (extension.enabled) {
  1646. const loaderProperty = property as ILoaderProperty;
  1647. loaderProperty._activeLoaderExtensions = loaderProperty._activeLoaderExtensions || {};
  1648. const activeLoaderExtensions = loaderProperty._activeLoaderExtensions;
  1649. if (!activeLoaderExtensions[name]) {
  1650. activeLoaderExtensions[name] = true;
  1651. try {
  1652. const result = actionAsync(extension);
  1653. if (result) {
  1654. return result;
  1655. }
  1656. }
  1657. finally {
  1658. delete activeLoaderExtensions[name];
  1659. }
  1660. }
  1661. }
  1662. }
  1663. return null;
  1664. }
  1665. private _extensionsOnLoading(): void {
  1666. this._forEachExtensions(extension => extension.onLoading && extension.onLoading());
  1667. }
  1668. private _extensionsOnReady(): void {
  1669. this._forEachExtensions(extension => extension.onReady && extension.onReady());
  1670. }
  1671. private _extensionsLoadSceneAsync(context: string, scene: ILoaderScene): Nullable<Promise<void>> {
  1672. return this._applyExtensions(scene, extension => extension.loadSceneAsync && extension.loadSceneAsync(context, scene));
  1673. }
  1674. private _extensionsLoadNodeAsync(context: string, node: ILoaderNode, assign: (babylonMesh: Mesh) => void): Nullable<Promise<Mesh>> {
  1675. return this._applyExtensions(node, extension => extension.loadNodeAsync && extension.loadNodeAsync(context, node, assign));
  1676. }
  1677. private _extensionsLoadCameraAsync(context: string, camera: ILoaderCamera, assign: (babylonCamera: Camera) => void): Nullable<Promise<Camera>> {
  1678. return this._applyExtensions(camera, extension => extension.loadCameraAsync && extension.loadCameraAsync(context, camera, assign));
  1679. }
  1680. private _extensionsLoadVertexDataAsync(context: string, primitive: ILoaderMeshPrimitive, babylonMesh: Mesh): Nullable<Promise<Geometry>> {
  1681. return this._applyExtensions(primitive, extension => extension._loadVertexDataAsync && extension._loadVertexDataAsync(context, primitive, babylonMesh));
  1682. }
  1683. private _extensionsLoadMaterialAsync(context: string, material: ILoaderMaterial, babylonMesh: Mesh, babylonDrawMode: number, assign: (babylonMaterial: Material) => void): Nullable<Promise<Material>> {
  1684. return this._applyExtensions(material, extension => extension._loadMaterialAsync && extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign));
  1685. }
  1686. private _extensionsCreateMaterial(context: string, material: ILoaderMaterial, babylonDrawMode: number): Nullable<Material> {
  1687. return this._applyExtensions({}, extension => extension.createMaterial && extension.createMaterial(context, material, babylonDrawMode));
  1688. }
  1689. private _extensionsLoadMaterialPropertiesAsync(context: string, material: ILoaderMaterial, babylonMaterial: Material): Nullable<Promise<void>> {
  1690. return this._applyExtensions(material, extension => extension.loadMaterialPropertiesAsync && extension.loadMaterialPropertiesAsync(context, material, babylonMaterial));
  1691. }
  1692. private _extensionsLoadTextureInfoAsync(context: string, textureInfo: ITextureInfo, assign: (babylonTexture: BaseTexture) => void): Nullable<Promise<BaseTexture>> {
  1693. return this._applyExtensions(textureInfo, extension => extension.loadTextureInfoAsync && extension.loadTextureInfoAsync(context, textureInfo, assign));
  1694. }
  1695. private _extensionsLoadAnimationAsync(context: string, animation: ILoaderAnimation): Nullable<Promise<AnimationGroup>> {
  1696. return this._applyExtensions(animation, extension => extension.loadAnimationAsync && extension.loadAnimationAsync(context, animation));
  1697. }
  1698. private _extensionsLoadUriAsync(context: string, uri: string): Nullable<Promise<ArrayBufferView>> {
  1699. return this._applyExtensions({}, extension => extension._loadUriAsync && extension._loadUriAsync(context, uri));
  1700. }
  1701. /**
  1702. * Helper method called by a loader extension to load an glTF extension.
  1703. * @param context The context when loading the asset
  1704. * @param property The glTF property to load the extension from
  1705. * @param extensionName The name of the extension to load
  1706. * @param actionAsync The action to run
  1707. * @returns The promise returned by actionAsync or null if the extension does not exist
  1708. */
  1709. public static LoadExtensionAsync<TExtension = any, TResult = void>(context: string, property: IProperty, extensionName: string, actionAsync: (extensionContext: string, extension: TExtension) => Nullable<Promise<TResult>>): Nullable<Promise<TResult>> {
  1710. if (!property.extensions) {
  1711. return null;
  1712. }
  1713. const extensions = property.extensions;
  1714. const extension = extensions[extensionName] as TExtension;
  1715. if (!extension) {
  1716. return null;
  1717. }
  1718. return actionAsync(`${context}/extensions/${extensionName}`, extension);
  1719. }
  1720. /**
  1721. * Helper method called by a loader extension to load a glTF extra.
  1722. * @param context The context when loading the asset
  1723. * @param property The glTF property to load the extra from
  1724. * @param extensionName The name of the extension to load
  1725. * @param actionAsync The action to run
  1726. * @returns The promise returned by actionAsync or null if the extra does not exist
  1727. */
  1728. public static LoadExtraAsync<TExtra = any, TResult = void>(context: string, property: IProperty, extensionName: string, actionAsync: (extraContext: string, extra: TExtra) => Nullable<Promise<TResult>>): Nullable<Promise<TResult>> {
  1729. if (!property.extras) {
  1730. return null;
  1731. }
  1732. const extras = property.extras;
  1733. const extra = extras[extensionName] as TExtra;
  1734. if (!extra) {
  1735. return null;
  1736. }
  1737. return actionAsync(`${context}/extras/${extensionName}`, extra);
  1738. }
  1739. /**
  1740. * Increments the indentation level and logs a message.
  1741. * @param message The message to log
  1742. */
  1743. public logOpen(message: string): void {
  1744. this._parent._logOpen(message);
  1745. }
  1746. /**
  1747. * Decrements the indentation level.
  1748. */
  1749. public logClose(): void {
  1750. this._parent._logClose();
  1751. }
  1752. /**
  1753. * Logs a message
  1754. * @param message The message to log
  1755. */
  1756. public log(message: string): void {
  1757. this._parent._log(message);
  1758. }
  1759. /**
  1760. * Starts a performance counter.
  1761. * @param counterName The name of the performance counter
  1762. */
  1763. public startPerformanceCounter(counterName: string): void {
  1764. this._parent._startPerformanceCounter(counterName);
  1765. }
  1766. /**
  1767. * Ends a performance counter.
  1768. * @param counterName The name of the performance counter
  1769. */
  1770. public endPerformanceCounter(counterName: string): void {
  1771. this._parent._endPerformanceCounter(counterName);
  1772. }
  1773. }
  1774. GLTFFileLoader._CreateGLTFLoaderV2 = parent => new GLTFLoader(parent);
  1775. }