glTFLoader.ts 95 KB

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