babylon.glTFLoader.ts 98 KB

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