glTFLoader.ts 100 KB

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