babylon.glTFLoader.ts 81 KB

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