glTFLoader.ts 96 KB

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