babylon.glTFLoader.ts 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830
  1. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2. module BABYLON.GLTF2 {
  3. class GLTFLoaderTracker {
  4. private _pendingCount = 0;
  5. private _callback: () => void;
  6. constructor(onComplete: () => void) {
  7. this._callback = onComplete;
  8. }
  9. public _addPendingData(data: any): void {
  10. this._pendingCount++;
  11. }
  12. public _removePendingData(data: any): void {
  13. if (--this._pendingCount === 0) {
  14. this._callback();
  15. }
  16. }
  17. }
  18. interface TypedArray extends ArrayBufferView {
  19. [index: number]: number;
  20. }
  21. interface TypedArrayConstructor<T extends TypedArray> {
  22. readonly prototype: T;
  23. new(length: number): T;
  24. new(array: ArrayLike<number>): T;
  25. new(buffer: ArrayBuffer, byteOffset?: number, length?: number): T;
  26. readonly BYTES_PER_ELEMENT: number;
  27. }
  28. interface GLTFLoaderRequest extends XMLHttpRequest {
  29. _loaded: Nullable<number>;
  30. _total: Nullable<number>;
  31. }
  32. interface IProgressEventData {
  33. lengthComputable: boolean;
  34. loaded: number;
  35. total: number;
  36. }
  37. export class GLTFLoader implements IGLTFLoader {
  38. public _gltf: IGLTF;
  39. public _babylonScene: Scene;
  40. private _disposed = false;
  41. private _parent: GLTFFileLoader;
  42. private _rootUrl: string;
  43. private _defaultMaterial: PBRMaterial;
  44. private _rootNode: IGLTFNode;
  45. private _successCallback: () => void;
  46. private _progressCallback: (event: ProgressEvent) => void;
  47. private _errorCallback: (message: string) => void;
  48. private _renderReady = false;
  49. private _requests = new Array<GLTFLoaderRequest>();
  50. private _renderReadyObservable = new Observable<GLTFLoader>();
  51. // Count of pending work that needs to complete before the asset is rendered.
  52. private _renderPendingCount = 0;
  53. // Count of pending work that needs to complete before the loader is disposed.
  54. private _loaderPendingCount = 0;
  55. private _loaderTrackers = new Array<GLTFLoaderTracker>();
  56. public static Extensions: { [name: string]: GLTFLoaderExtension } = {};
  57. public static RegisterExtension(extension: GLTFLoaderExtension): void {
  58. if (GLTFLoader.Extensions[extension.name]) {
  59. Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  60. return;
  61. }
  62. GLTFLoader.Extensions[extension.name] = extension;
  63. // Keep the order of registration so that extensions registered first are called first.
  64. GLTFLoaderExtension._Extensions.push(extension);
  65. }
  66. // IE 11 Compatibility.
  67. private static _progressEventFactory: (name: string, data: IProgressEventData) => ProgressEvent;
  68. private static _createProgressEventByConstructor(name: string, data: IProgressEventData): ProgressEvent {
  69. return new ProgressEvent(name, data);
  70. }
  71. private static _createProgressEventByDocument(name: string, data: IProgressEventData): ProgressEvent {
  72. const event = document.createEvent("ProgressEvent");
  73. event.initProgressEvent(name, false, false, data.lengthComputable, data.loaded, data.total);
  74. return event;
  75. }
  76. public constructor(parent: GLTFFileLoader) {
  77. this._parent = parent;
  78. if (!GLTFLoader._progressEventFactory) {
  79. if (typeof (<any>window)["ProgressEvent"] === "function") {
  80. GLTFLoader._progressEventFactory = GLTFLoader._createProgressEventByConstructor;
  81. }
  82. else {
  83. GLTFLoader._progressEventFactory = GLTFLoader._createProgressEventByDocument;
  84. }
  85. }
  86. }
  87. public dispose(): void {
  88. if (this._disposed) {
  89. return;
  90. }
  91. this._disposed = true;
  92. // Abort requests that are not complete
  93. for (const request of this._requests) {
  94. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  95. request.abort();
  96. }
  97. }
  98. // Revoke object urls created during load
  99. if (this._gltf.textures) {
  100. for (const texture of this._gltf.textures) {
  101. if (texture.url) {
  102. URL.revokeObjectURL(texture.url);
  103. }
  104. }
  105. }
  106. }
  107. public importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, onProgress: (event: ProgressEvent) => void, onError: (message: string) => void): void {
  108. this._loadAsync(meshesNames, scene, data, rootUrl, () => {
  109. onSuccess(this._getMeshes(), [], this._getSkeletons());
  110. }, onProgress, onError);
  111. }
  112. public loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess: () => void, onProgress: (event: ProgressEvent) => void, onError: (message: string) => void): void {
  113. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  114. }
  115. private _loadAsync(nodeNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess: () => void, onProgress: (event: ProgressEvent) => void, onError: (message: string) => void): void {
  116. this._tryCatchOnError(() => {
  117. this._loadData(data);
  118. this._babylonScene = scene;
  119. this._rootUrl = rootUrl;
  120. this._successCallback = onSuccess;
  121. this._progressCallback = onProgress;
  122. this._errorCallback = onError;
  123. this._addPendingData(this);
  124. this._loadDefaultScene(nodeNames);
  125. this._loadAnimations();
  126. this._removePendingData(this);
  127. });
  128. }
  129. private _onProgress(): void {
  130. if (!this._progressCallback) {
  131. return;
  132. }
  133. let loaded = 0;
  134. let total = 0;
  135. for (let request of this._requests) {
  136. if (!request._loaded || !request._total) {
  137. return;
  138. }
  139. loaded += request._loaded;
  140. total += request._total;
  141. }
  142. this._progressCallback(GLTFLoader._progressEventFactory("GLTFLoaderProgress", {
  143. lengthComputable: true,
  144. loaded: loaded,
  145. total: total
  146. }));
  147. }
  148. public _executeWhenRenderReady(func: () => void): void {
  149. if (this._renderReady) {
  150. func();
  151. }
  152. else {
  153. this._renderReadyObservable.add(func);
  154. }
  155. }
  156. private _onRenderReady(): void {
  157. this._rootNode.babylonMesh.setEnabled(true);
  158. this._startAnimations();
  159. this._successCallback();
  160. this._renderReadyObservable.notifyObservers(this);
  161. }
  162. private _onComplete(): void {
  163. if (this._parent.onComplete) {
  164. this._parent.onComplete();
  165. }
  166. this.dispose();
  167. }
  168. private _loadData(data: IGLTFLoaderData): void {
  169. this._gltf = <IGLTF>data.json;
  170. // Assign the index of each object for convinience.
  171. GLTFLoader._AssignIndices(this._gltf.accessors);
  172. GLTFLoader._AssignIndices(this._gltf.animations);
  173. GLTFLoader._AssignIndices(this._gltf.buffers);
  174. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  175. GLTFLoader._AssignIndices(this._gltf.images);
  176. GLTFLoader._AssignIndices(this._gltf.materials);
  177. GLTFLoader._AssignIndices(this._gltf.meshes);
  178. GLTFLoader._AssignIndices(this._gltf.nodes);
  179. GLTFLoader._AssignIndices(this._gltf.scenes);
  180. GLTFLoader._AssignIndices(this._gltf.skins);
  181. GLTFLoader._AssignIndices(this._gltf.textures);
  182. if (data.bin) {
  183. const buffers = this._gltf.buffers;
  184. if (buffers && buffers[0] && !buffers[0].uri) {
  185. const binaryBuffer = buffers[0];
  186. if (binaryBuffer.byteLength != data.bin.byteLength) {
  187. Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  188. }
  189. binaryBuffer.loadedData = data.bin;
  190. }
  191. else {
  192. Tools.Warn("Unexpected BIN chunk");
  193. }
  194. }
  195. }
  196. private _getMeshes(): AbstractMesh[] {
  197. const meshes = new Array<AbstractMesh>();
  198. // Root mesh is always first.
  199. meshes.push(this._rootNode.babylonMesh);
  200. const nodes = this._gltf.nodes;
  201. if (nodes) {
  202. for (const node of nodes) {
  203. if (node.babylonMesh) {
  204. meshes.push(node.babylonMesh);
  205. }
  206. }
  207. }
  208. return meshes;
  209. }
  210. private _getSkeletons(): Skeleton[] {
  211. const skeletons = new Array<Skeleton>();
  212. const skins = this._gltf.skins;
  213. if (skins) {
  214. for (const skin of skins) {
  215. if (skin.babylonSkeleton) {
  216. skeletons.push(skin.babylonSkeleton);
  217. }
  218. }
  219. }
  220. return skeletons;
  221. }
  222. private _getAnimationTargets(): any[] {
  223. const targets = new Array();
  224. const animations = this._gltf.animations;
  225. if (animations) {
  226. for (const animation of animations) {
  227. targets.push(...animation.targets);
  228. }
  229. }
  230. return targets;
  231. }
  232. private _startAnimations(): void {
  233. for (const target of this._getAnimationTargets()) {
  234. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  235. }
  236. }
  237. private _loadDefaultScene(nodeNames: any): void {
  238. const scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  239. if (!scene) {
  240. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  241. }
  242. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  243. }
  244. private _loadScene(context: string, scene: IGLTFScene, nodeNames: any): void {
  245. this._rootNode = { babylonMesh: new Mesh("__root__", this._babylonScene) } as IGLTFNode;
  246. switch (this._parent.coordinateSystemMode) {
  247. case GLTFLoaderCoordinateSystemMode.AUTO: {
  248. if (!this._babylonScene.useRightHandedSystem) {
  249. this._rootNode.rotation = [ 0, 1, 0, 0 ];
  250. this._rootNode.scale = [ 1, 1, -1 ];
  251. this._loadTransform(this._rootNode);
  252. }
  253. break;
  254. }
  255. case GLTFLoaderCoordinateSystemMode.PASS_THROUGH: {
  256. // do nothing
  257. break;
  258. }
  259. case GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  260. this._babylonScene.useRightHandedSystem = true;
  261. break;
  262. }
  263. default: {
  264. Tools.Error("Invalid coordinate system mode " + this._parent.coordinateSystemMode);
  265. return;
  266. }
  267. }
  268. if (this._parent.onMeshLoaded) {
  269. this._parent.onMeshLoaded(this._rootNode.babylonMesh);
  270. }
  271. let nodeIndices = scene.nodes;
  272. this._traverseNodes(context, nodeIndices, (node, parentNode) => {
  273. node.parent = parentNode;
  274. return true;
  275. }, this._rootNode);
  276. if (nodeNames) {
  277. if (!(nodeNames instanceof Array)) {
  278. nodeNames = [nodeNames];
  279. }
  280. const filteredNodeIndices = new Array<number>();
  281. this._traverseNodes(context, nodeIndices, node => {
  282. if (nodeNames.indexOf(node.name) !== -1) {
  283. filteredNodeIndices.push(node.index);
  284. return false;
  285. }
  286. return true;
  287. }, this._rootNode);
  288. nodeIndices = filteredNodeIndices;
  289. }
  290. for (const index of nodeIndices) {
  291. const node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  292. if (!node) {
  293. throw new Error(context + ": Failed to find node " + index);
  294. }
  295. this._loadNode("#/nodes/" + index, node);
  296. }
  297. // Disable the root mesh until the asset is ready to render.
  298. this._rootNode.babylonMesh.setEnabled(false);
  299. }
  300. public _loadNode(context: string, node: IGLTFNode): void {
  301. if (GLTFLoaderExtension.LoadNode(this, context, node)) {
  302. return;
  303. }
  304. node.babylonMesh = new Mesh(node.name || "mesh" + node.index, this._babylonScene);
  305. node.babylonMesh.hasVertexAlpha = true;
  306. this._loadTransform(node);
  307. if (node.mesh != null) {
  308. const mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  309. if (!mesh) {
  310. throw new Error(context + ": Failed to find mesh " + node.mesh);
  311. }
  312. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  313. }
  314. node.babylonMesh.parent = node.parent.babylonMesh;
  315. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  316. node.babylonAnimationTargets.push(node.babylonMesh);
  317. if (node.skin != null) {
  318. const skin = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  319. if (!skin) {
  320. throw new Error(context + ": Failed to find skin " + node.skin);
  321. }
  322. this._loadSkinAsync("#/skins/" + node.skin, skin, () => {
  323. node.babylonMesh.skeleton = skin.babylonSkeleton;
  324. node.babylonMesh._refreshBoundingInfo(true);
  325. });
  326. node.babylonMesh.parent = this._rootNode.babylonMesh;
  327. node.babylonMesh.position = Vector3.Zero();
  328. node.babylonMesh.rotationQuaternion = Quaternion.Identity();
  329. node.babylonMesh.scaling = Vector3.One();
  330. }
  331. if (node.camera != null) {
  332. // TODO: handle cameras
  333. }
  334. if (node.children) {
  335. for (const index of node.children) {
  336. const childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  337. if (!childNode) {
  338. throw new Error(context + ": Failed to find child node " + index);
  339. }
  340. this._loadNode("#/nodes/" + index, childNode);
  341. }
  342. }
  343. if (this._parent.onMeshLoaded) {
  344. this._parent.onMeshLoaded(node.babylonMesh);
  345. }
  346. }
  347. private _loadMesh(context: string, node: IGLTFNode, mesh: IGLTFMesh): void {
  348. const primitives = mesh.primitives;
  349. if (!primitives || primitives.length === 0) {
  350. throw new Error(context + ": Primitives are missing");
  351. }
  352. this._createMorphTargets(context, node, mesh);
  353. this._loadAllVertexDataAsync(context, mesh, () => {
  354. this._loadMorphTargets(context, node, mesh);
  355. const vertexData = new VertexData();
  356. for (const primitive of primitives) {
  357. vertexData.merge(primitive.vertexData);
  358. }
  359. new Geometry(node.babylonMesh.name, this._babylonScene, vertexData, false, node.babylonMesh);
  360. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  361. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  362. node.babylonMesh.subMeshes = [];
  363. let verticesStart = 0;
  364. let indicesStart = 0;
  365. for (let index = 0; index < primitives.length; index++) {
  366. const vertexData = primitives[index].vertexData;
  367. const verticesCount = vertexData.positions!.length;
  368. const indicesCount = vertexData.indices!.length;
  369. SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  370. verticesStart += verticesCount;
  371. indicesStart += indicesCount;
  372. };
  373. });
  374. if (primitives.length === 1) {
  375. const primitive = primitives[0];
  376. if (primitive.material == null) {
  377. node.babylonMesh.material = this._getDefaultMaterial();
  378. }
  379. else {
  380. const material = GLTFLoader._GetProperty(this._gltf.materials, primitive.material);
  381. if (!material) {
  382. throw new Error(context + ": Failed to find material " + primitive.material);
  383. }
  384. this._loadMaterial("#/materials/" + material.index, material, (babylonMaterial, isNew) => {
  385. if (isNew && this._parent.onMaterialLoaded) {
  386. this._parent.onMaterialLoaded(babylonMaterial);
  387. }
  388. node.babylonMesh.material = babylonMaterial;
  389. });
  390. }
  391. }
  392. else {
  393. const multiMaterial = new MultiMaterial(node.babylonMesh.name, this._babylonScene);
  394. node.babylonMesh.material = multiMaterial;
  395. const subMaterials = multiMaterial.subMaterials;
  396. for (let index = 0; index < primitives.length; index++) {
  397. const primitive = primitives[index];
  398. if (primitive.material == null) {
  399. subMaterials[index] = this._getDefaultMaterial();
  400. }
  401. else {
  402. const material = GLTFLoader._GetProperty(this._gltf.materials, primitive.material);
  403. if (!material) {
  404. throw new Error(context + ": Failed to find material " + primitive.material);
  405. }
  406. this._loadMaterial("#/materials/" + material.index, material, (babylonMaterial, isNew) => {
  407. if (isNew && this._parent.onMaterialLoaded) {
  408. this._parent.onMaterialLoaded(babylonMaterial);
  409. }
  410. subMaterials[index] = babylonMaterial;
  411. });
  412. }
  413. };
  414. }
  415. }
  416. private _loadAllVertexDataAsync(context: string, mesh: IGLTFMesh, onSuccess: () => void): void {
  417. const primitives = mesh.primitives;
  418. let numRemainingPrimitives = primitives.length;
  419. for (let index = 0; index < primitives.length; index++) {
  420. let primitive = primitives[index];
  421. this._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, vertexData => {
  422. primitive.vertexData = vertexData;
  423. if (--numRemainingPrimitives === 0) {
  424. onSuccess();
  425. }
  426. });
  427. }
  428. }
  429. /**
  430. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  431. * @param {ArrayBufferView} data
  432. * @param {IGLTFAccessor} accessor
  433. */
  434. private _convertToFloat4TextureCoordArray(context: string, data: ArrayBufferView, accessor: IGLTFAccessor): Float32Array {
  435. if (accessor.componentType == EComponentType.FLOAT) {
  436. return data as Float32Array;
  437. }
  438. const buffer = data as TypedArray;
  439. let factor = 1;
  440. switch (accessor.componentType) {
  441. case EComponentType.UNSIGNED_BYTE: {
  442. factor = 1 / 255;
  443. break;
  444. }
  445. case EComponentType.UNSIGNED_SHORT: {
  446. factor = 1 / 65535;
  447. break;
  448. }
  449. default: {
  450. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  451. }
  452. }
  453. const result = new Float32Array(accessor.count * 2);
  454. for (let i = 0; i < result.length; ++i) {
  455. result[i] = buffer[i] * factor;
  456. }
  457. return result;
  458. }
  459. /**
  460. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  461. * @param {ArrayBufferView} data
  462. * @param {IGLTFAccessor} accessor
  463. */
  464. private _convertToFloat4ColorArray(context: string, data: ArrayBufferView, accessor: IGLTFAccessor): Float32Array {
  465. const colorComponentCount = GLTFLoader._GetNumComponents(accessor.type);
  466. if (colorComponentCount === 4 && accessor.componentType === EComponentType.FLOAT) {
  467. return data as Float32Array;
  468. }
  469. const buffer = data as TypedArray;
  470. let factor = 1;
  471. switch (accessor.componentType) {
  472. case EComponentType.FLOAT: {
  473. factor = 1;
  474. break;
  475. }
  476. case EComponentType.UNSIGNED_BYTE: {
  477. factor = 1 / 255;
  478. break;
  479. }
  480. case EComponentType.UNSIGNED_SHORT: {
  481. factor = 1 / 65535;
  482. break;
  483. }
  484. default: {
  485. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  486. }
  487. }
  488. const result = new Float32Array(accessor.count * 4);
  489. if (colorComponentCount === 4) {
  490. for (let i = 0; i < result.length; ++i) {
  491. result[i] = buffer[i] * factor;
  492. }
  493. }
  494. else {
  495. let offset = 0;
  496. for (let i = 0; i < result.length; ++i) {
  497. if ((i + 1) % 4 === 0) {
  498. result[i] = 1;
  499. }
  500. else {
  501. result[i] = buffer[offset++] * factor;
  502. }
  503. }
  504. }
  505. return result;
  506. }
  507. private _loadVertexDataAsync(context: string, mesh: IGLTFMesh, primitive: IGLTFMeshPrimitive, onSuccess: (vertexData: VertexData) => void): void {
  508. const attributes = primitive.attributes;
  509. if (!attributes) {
  510. throw new Error(context + ": Attributes are missing");
  511. }
  512. if (primitive.mode && primitive.mode !== EMeshPrimitiveMode.TRIANGLES) {
  513. // TODO: handle other primitive modes
  514. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  515. }
  516. const vertexData = new VertexData();
  517. let numRemainingAttributes = Object.keys(attributes).length;
  518. for (const attribute in attributes) {
  519. const accessor = GLTFLoader._GetProperty(this._gltf.accessors, attributes[attribute]);
  520. if (!accessor) {
  521. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  522. }
  523. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, data => {
  524. switch (attribute) {
  525. case "POSITION": {
  526. vertexData.positions = <Float32Array>data;
  527. break;
  528. }
  529. case "NORMAL": {
  530. vertexData.normals = <Float32Array>data;
  531. break;
  532. }
  533. case "TANGENT": {
  534. vertexData.tangents = <Float32Array>data;
  535. break;
  536. }
  537. case "TEXCOORD_0": {
  538. vertexData.uvs = this._convertToFloat4TextureCoordArray(context, data, accessor);
  539. break;
  540. }
  541. case "TEXCOORD_1": {
  542. vertexData.uvs2 = this._convertToFloat4TextureCoordArray(context, data, accessor);
  543. break;
  544. }
  545. case "JOINTS_0": {
  546. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  547. break;
  548. }
  549. case "WEIGHTS_0": {
  550. //TODO: need to add support for normalized weights.
  551. vertexData.matricesWeights = <Float32Array>data;
  552. break;
  553. }
  554. case "COLOR_0": {
  555. vertexData.colors = this._convertToFloat4ColorArray(context, data, accessor);
  556. break;
  557. }
  558. default: {
  559. Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  560. break;
  561. }
  562. }
  563. if (--numRemainingAttributes === 0) {
  564. if (primitive.indices == null) {
  565. vertexData.indices = new Uint32Array(vertexData.positions!.length / 3);
  566. for (let i = 0; i < vertexData.indices.length; i++) {
  567. vertexData.indices[i] = i;
  568. }
  569. onSuccess(vertexData);
  570. }
  571. else {
  572. const indicesAccessor = GLTFLoader._GetProperty(this._gltf.accessors, primitive.indices);
  573. if (!indicesAccessor) {
  574. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  575. }
  576. this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, data => {
  577. vertexData.indices = <IndicesArray>data;
  578. onSuccess(vertexData);
  579. });
  580. }
  581. }
  582. });
  583. }
  584. }
  585. private _createMorphTargets(context: string, node: IGLTFNode, mesh: IGLTFMesh): void {
  586. const primitives = mesh.primitives;
  587. const targets = primitives[0].targets;
  588. if (!targets) {
  589. return;
  590. }
  591. for (const primitive of primitives) {
  592. if (!primitive.targets || primitive.targets.length != targets.length) {
  593. throw new Error(context + ": All primitives are required to list the same number of targets");
  594. }
  595. }
  596. const morphTargetManager = new MorphTargetManager();
  597. node.babylonMesh.morphTargetManager = morphTargetManager;
  598. for (let index = 0; index < targets.length; index++) {
  599. const weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  600. morphTargetManager.addTarget(new MorphTarget("morphTarget" + index, weight));
  601. }
  602. }
  603. private _loadMorphTargets(context: string, node: IGLTFNode, mesh: IGLTFMesh): void {
  604. const morphTargetManager = node.babylonMesh.morphTargetManager;
  605. if (!morphTargetManager) {
  606. return;
  607. }
  608. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, () => {
  609. const numTargets = morphTargetManager.numTargets;
  610. for (let index = 0; index < numTargets; index++) {
  611. const vertexData = new VertexData();
  612. for (const primitive of mesh.primitives) {
  613. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  614. }
  615. if (!vertexData.positions) {
  616. throw new Error(context + ": Positions are missing");
  617. }
  618. const target = morphTargetManager.getTarget(index);
  619. target.setPositions(vertexData.positions);
  620. target.setNormals(vertexData.normals);
  621. target.setTangents(vertexData.tangents);
  622. }
  623. });
  624. }
  625. private _loadAllMorphTargetVertexDataAsync(context: string, node: IGLTFNode, mesh: IGLTFMesh, onSuccess: () => void): void {
  626. let numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager!.numTargets;
  627. for (const primitive of mesh.primitives) {
  628. const targets = primitive.targets!;
  629. primitive.targetsVertexData = new Array<VertexData>(targets.length);
  630. for (let index = 0; index < targets.length; index++) {
  631. this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], vertexData => {
  632. primitive.targetsVertexData[index] = vertexData;
  633. if (--numRemainingTargets === 0) {
  634. onSuccess();
  635. }
  636. });
  637. }
  638. }
  639. }
  640. private _loadMorphTargetVertexDataAsync(context: string, vertexData: VertexData, attributes: { [name: string]: number }, onSuccess: (vertexData: VertexData) => void): void {
  641. const targetVertexData = new VertexData();
  642. let numRemainingAttributes = Object.keys(attributes).length;
  643. for (let attribute in attributes) {
  644. const accessor = GLTFLoader._GetProperty(this._gltf.accessors, attributes[attribute]);
  645. if (!accessor) {
  646. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  647. }
  648. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, data => {
  649. // glTF stores morph target information as deltas while babylon.js expects the final data.
  650. // As a result we have to add the original data to the delta to calculate the final data.
  651. const values = <Float32Array>data;
  652. switch (attribute) {
  653. case "POSITION": {
  654. for (let i = 0; i < values.length; i++) {
  655. values[i] += vertexData.positions![i];
  656. }
  657. targetVertexData.positions = values;
  658. break;
  659. }
  660. case "NORMAL": {
  661. for (let i = 0; i < values.length; i++) {
  662. values[i] += vertexData.normals![i];
  663. }
  664. targetVertexData.normals = values;
  665. break;
  666. }
  667. case "TANGENT": {
  668. // Tangent data for morph targets is stored as xyz delta.
  669. // The vertexData.tangent is stored as xyzw.
  670. // So we need to skip every fourth vertexData.tangent.
  671. for (let i = 0, j = 0; i < values.length; i++, j++) {
  672. values[i] += vertexData.tangents![j];
  673. if ((i + 1) % 3 == 0) {
  674. j++;
  675. }
  676. }
  677. targetVertexData.tangents = values;
  678. break;
  679. }
  680. default: {
  681. Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  682. break;
  683. }
  684. }
  685. if (--numRemainingAttributes === 0) {
  686. onSuccess(targetVertexData);
  687. }
  688. });
  689. }
  690. }
  691. private _loadTransform(node: IGLTFNode): void {
  692. let position: Vector3 = Vector3.Zero();
  693. let rotation: Quaternion = Quaternion.Identity();
  694. let scaling: Vector3 = Vector3.One();
  695. if (node.matrix) {
  696. const matrix = Matrix.FromArray(node.matrix);
  697. matrix.decompose(scaling, rotation, position);
  698. }
  699. else {
  700. if (node.translation) position = Vector3.FromArray(node.translation);
  701. if (node.rotation) rotation = Quaternion.FromArray(node.rotation);
  702. if (node.scale) scaling = Vector3.FromArray(node.scale);
  703. }
  704. node.babylonMesh.position = position;
  705. node.babylonMesh.rotationQuaternion = rotation;
  706. node.babylonMesh.scaling = scaling;
  707. }
  708. private _loadSkinAsync(context: string, skin: IGLTFSkin, onSuccess: () => void): void {
  709. if (skin.babylonSkeleton) {
  710. onSuccess();
  711. return;
  712. }
  713. const skeletonId = "skeleton" + skin.index;
  714. skin.babylonSkeleton = new Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  715. if (skin.inverseBindMatrices == null) {
  716. this._loadBones(context, skin, null);
  717. onSuccess();
  718. }
  719. else {
  720. const accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  721. if (!accessor) {
  722. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  723. }
  724. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, data => {
  725. this._loadBones(context, skin, <Float32Array>data);
  726. onSuccess();
  727. });
  728. }
  729. }
  730. private _createBone(node: IGLTFNode, skin: IGLTFSkin, parent: Nullable<Bone>, localMatrix: Matrix, baseMatrix: Matrix, index: number): Bone {
  731. const babylonBone = new Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  732. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  733. node.babylonAnimationTargets.push(babylonBone);
  734. return babylonBone;
  735. }
  736. private _loadBones(context: string, skin: IGLTFSkin, inverseBindMatrixData: Nullable<Float32Array>): void {
  737. const babylonBones: { [index: number]: Bone } = {};
  738. for (const index of skin.joints) {
  739. const node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  740. if (!node) {
  741. throw new Error(context + ": Failed to find joint " + index);
  742. }
  743. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  744. }
  745. }
  746. private _loadBone(node: IGLTFNode, skin: IGLTFSkin, inverseBindMatrixData: Nullable<Float32Array>, babylonBones: { [index: number]: Bone }): Bone {
  747. let babylonBone = babylonBones[node.index];
  748. if (babylonBone) {
  749. return babylonBone;
  750. }
  751. const boneIndex = skin.joints.indexOf(node.index);
  752. let baseMatrix = Matrix.Identity();
  753. if (inverseBindMatrixData && boneIndex !== -1) {
  754. baseMatrix = Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  755. baseMatrix.invertToRef(baseMatrix);
  756. }
  757. let babylonParentBone: Nullable<Bone> = null;
  758. if (node.parent !== this._rootNode) {
  759. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  760. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  761. }
  762. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  763. babylonBones[node.index] = babylonBone;
  764. return babylonBone;
  765. }
  766. private _getNodeMatrix(node: IGLTFNode): Matrix {
  767. return node.matrix ?
  768. Matrix.FromArray(node.matrix) :
  769. Matrix.Compose(
  770. node.scale ? Vector3.FromArray(node.scale) : Vector3.One(),
  771. node.rotation ? Quaternion.FromArray(node.rotation) : Quaternion.Identity(),
  772. node.translation ? Vector3.FromArray(node.translation) : Vector3.Zero());
  773. }
  774. private _traverseNodes(context: string, indices: number[], action: (node: IGLTFNode, parentNode: IGLTFNode) => boolean, parentNode: IGLTFNode): void {
  775. for (const index of indices) {
  776. const node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  777. if (!node) {
  778. throw new Error(context + ": Failed to find node " + index);
  779. }
  780. this._traverseNode(context, node, action, parentNode);
  781. }
  782. }
  783. public _traverseNode(context: string, node: IGLTFNode, action: (node: IGLTFNode, parentNode: IGLTFNode) => boolean, parentNode: IGLTFNode): void {
  784. if (GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  785. return;
  786. }
  787. if (!action(node, parentNode)) {
  788. return;
  789. }
  790. if (node.children) {
  791. this._traverseNodes(context, node.children, action, node);
  792. }
  793. }
  794. private _loadAnimations(): void {
  795. const animations = this._gltf.animations;
  796. if (!animations) {
  797. return;
  798. }
  799. for (let index = 0; index < animations.length; index++) {
  800. const animation = animations[index];
  801. this._loadAnimation("#/animations/" + index, animation);
  802. }
  803. }
  804. private _loadAnimation(context: string, animation: IGLTFAnimation): void {
  805. animation.targets = [];
  806. for (let index = 0; index < animation.channels.length; index++) {
  807. const channel = GLTFLoader._GetProperty(animation.channels, index);
  808. if (!channel) {
  809. throw new Error(context + ": Failed to find channel " + index);
  810. }
  811. const sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  812. if (!sampler) {
  813. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  814. }
  815. this._loadAnimationChannel(animation,
  816. context + "/channels/" + index, channel,
  817. context + "/samplers/" + channel.sampler, sampler);
  818. }
  819. }
  820. private _loadAnimationChannel(animation: IGLTFAnimation, channelContext: string, channel: IGLTFAnimationChannel, samplerContext: string, sampler: IGLTFAnimationSampler): void {
  821. const targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  822. if (!targetNode) {
  823. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  824. }
  825. let targetPath: string;
  826. let animationType: number;
  827. switch (channel.target.path) {
  828. case "translation": {
  829. targetPath = "position";
  830. animationType = Animation.ANIMATIONTYPE_VECTOR3;
  831. break;
  832. }
  833. case "rotation": {
  834. targetPath = "rotationQuaternion";
  835. animationType = Animation.ANIMATIONTYPE_QUATERNION;
  836. break;
  837. }
  838. case "scale": {
  839. targetPath = "scaling";
  840. animationType = Animation.ANIMATIONTYPE_VECTOR3;
  841. break;
  842. }
  843. case "weights": {
  844. targetPath = "influence";
  845. animationType = Animation.ANIMATIONTYPE_FLOAT;
  846. break;
  847. }
  848. default: {
  849. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  850. }
  851. }
  852. let inputData: Float32Array;
  853. let outputData: Float32Array;
  854. const checkSuccess = () => {
  855. if (!inputData || !outputData) {
  856. return;
  857. }
  858. let outputBufferOffset = 0;
  859. let getNextOutputValue: () => any;
  860. switch (targetPath) {
  861. case "position": {
  862. getNextOutputValue = () => {
  863. const value = Vector3.FromArray(outputData, outputBufferOffset);
  864. outputBufferOffset += 3;
  865. return value;
  866. };
  867. break;
  868. }
  869. case "rotationQuaternion": {
  870. getNextOutputValue = () => {
  871. const value = Quaternion.FromArray(outputData, outputBufferOffset);
  872. outputBufferOffset += 4;
  873. return value;
  874. };
  875. break;
  876. }
  877. case "scaling": {
  878. getNextOutputValue = () => {
  879. const value = Vector3.FromArray(outputData, outputBufferOffset);
  880. outputBufferOffset += 3;
  881. return value;
  882. };
  883. break;
  884. }
  885. case "influence": {
  886. getNextOutputValue = () => {
  887. const numTargets = targetNode.babylonMesh.morphTargetManager!.numTargets;
  888. const value = new Array<number>(numTargets);
  889. for (let i = 0; i < numTargets; i++) {
  890. value[i] = outputData[outputBufferOffset++];
  891. }
  892. return value;
  893. };
  894. break;
  895. }
  896. }
  897. let getNextKey: (frameIndex: number) => any;
  898. switch (sampler.interpolation) {
  899. case "LINEAR": {
  900. getNextKey = frameIndex => ({
  901. frame: inputData[frameIndex],
  902. value: getNextOutputValue()
  903. });
  904. break;
  905. }
  906. case "CUBICSPLINE": {
  907. getNextKey = frameIndex => ({
  908. frame: inputData[frameIndex],
  909. inTangent: getNextOutputValue(),
  910. value: getNextOutputValue(),
  911. outTangent: getNextOutputValue()
  912. });
  913. break;
  914. }
  915. default: {
  916. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  917. }
  918. };
  919. let keys: Array<any>;
  920. if (inputData.length === 1) {
  921. let key = getNextKey(0);
  922. keys = [
  923. { frame: key.frame, value: key.value },
  924. { frame: key.frame + 1, value: key.value }
  925. ];
  926. }
  927. else {
  928. keys = new Array(inputData.length);
  929. for (let frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  930. keys[frameIndex] = getNextKey(frameIndex);
  931. }
  932. }
  933. if (targetPath === "influence") {
  934. const morphTargetManager = targetNode.babylonMesh.morphTargetManager!;
  935. for (let targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  936. const morphTarget = morphTargetManager.getTarget(targetIndex);
  937. const animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  938. const babylonAnimation = new Animation(animationName, targetPath, 1, animationType);
  939. babylonAnimation.setKeys(keys.map(key => ({
  940. frame: key.frame,
  941. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  942. value: key.value[targetIndex],
  943. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  944. })));
  945. morphTarget.animations.push(babylonAnimation);
  946. animation.targets.push(morphTarget);
  947. }
  948. }
  949. else {
  950. const animationName = animation.name || "anim" + animation.index;
  951. const babylonAnimation = new Animation(animationName, targetPath, 1, animationType);
  952. babylonAnimation.setKeys(keys);
  953. if (targetNode.babylonAnimationTargets) {
  954. for (const target of targetNode.babylonAnimationTargets) {
  955. target.animations.push(babylonAnimation.clone());
  956. animation.targets.push(target);
  957. }
  958. }
  959. }
  960. };
  961. const inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  962. if (!inputAccessor) {
  963. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  964. }
  965. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, data => {
  966. inputData = <Float32Array>data;
  967. checkSuccess();
  968. });
  969. const outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  970. if (!outputAccessor) {
  971. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  972. }
  973. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, data => {
  974. outputData = <Float32Array>data;
  975. checkSuccess();
  976. });
  977. }
  978. private _loadBufferAsync(context: string, buffer: IGLTFBuffer, onSuccess: (data: ArrayBufferView) => void): void {
  979. this._addPendingData(buffer);
  980. if (buffer.loadedData) {
  981. onSuccess(buffer.loadedData);
  982. this._removePendingData(buffer);
  983. }
  984. else if (buffer.loadedObservable) {
  985. buffer.loadedObservable.add(buffer => {
  986. onSuccess(buffer.loadedData!);
  987. this._removePendingData(buffer);
  988. });
  989. }
  990. else {
  991. if (!buffer.uri) {
  992. throw new Error(context + ": Uri is missing");
  993. }
  994. buffer.loadedObservable = new Observable<IGLTFBuffer>();
  995. buffer.loadedObservable.add(buffer => {
  996. onSuccess(buffer.loadedData!);
  997. this._removePendingData(buffer);
  998. });
  999. this._loadUriAsync(context, buffer.uri, data => {
  1000. buffer.loadedData = data;
  1001. buffer.loadedObservable!.notifyObservers(buffer);
  1002. buffer.loadedObservable = undefined;
  1003. });
  1004. }
  1005. }
  1006. private _loadBufferViewAsync(context: string, bufferView: IGLTFBufferView, onSuccess: (data: ArrayBufferView) => void): void {
  1007. const buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  1008. if (!buffer) {
  1009. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  1010. }
  1011. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, bufferData => {
  1012. let data: ArrayBufferView;
  1013. try {
  1014. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  1015. }
  1016. catch (e) {
  1017. throw new Error(context + ": " + e.message);
  1018. }
  1019. onSuccess(data);
  1020. });
  1021. }
  1022. private _loadAccessorAsync(context: string, accessor: IGLTFAccessor, onSuccess: (data: ArrayBufferView) => void): void {
  1023. if (accessor.sparse) {
  1024. throw new Error(context + ": Sparse accessors are not currently supported");
  1025. }
  1026. const bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  1027. if (!bufferView) {
  1028. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  1029. }
  1030. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, bufferViewData => {
  1031. const numComponents = GLTFLoader._GetNumComponents(accessor.type);
  1032. if (numComponents === 0) {
  1033. throw new Error(context + ": Invalid type " + accessor.type);
  1034. }
  1035. let data: ArrayBufferView;
  1036. let byteOffset = accessor.byteOffset || 0;
  1037. let byteStride = bufferView.byteStride;
  1038. try {
  1039. switch (accessor.componentType) {
  1040. case EComponentType.BYTE: {
  1041. data = this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1042. break;
  1043. }
  1044. case EComponentType.UNSIGNED_BYTE: {
  1045. data = this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1046. break;
  1047. }
  1048. case EComponentType.SHORT: {
  1049. data = this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1050. break;
  1051. }
  1052. case EComponentType.UNSIGNED_SHORT: {
  1053. data = this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1054. break;
  1055. }
  1056. case EComponentType.UNSIGNED_INT: {
  1057. data = this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1058. break;
  1059. }
  1060. case EComponentType.FLOAT: {
  1061. data = this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1062. break;
  1063. }
  1064. default: {
  1065. throw new Error(context + ": Invalid component type " + accessor.componentType);
  1066. }
  1067. }
  1068. }
  1069. catch (e) {
  1070. throw new Error(context + ": " + e);
  1071. }
  1072. onSuccess(data);
  1073. });
  1074. }
  1075. private _buildArrayBuffer<T extends TypedArray>(typedArray: TypedArrayConstructor<T>, data: ArrayBufferView, byteOffset: number, count: number, numComponents: number, byteStride?: number): T {
  1076. byteOffset += data.byteOffset;
  1077. const targetLength = count * numComponents;
  1078. if (byteStride == null || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  1079. return new typedArray(data.buffer, byteOffset, targetLength);
  1080. }
  1081. const elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  1082. const sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  1083. const targetBuffer = new typedArray(targetLength);
  1084. let sourceIndex = 0;
  1085. let targetIndex = 0;
  1086. while (targetIndex < targetLength) {
  1087. for (let componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  1088. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  1089. targetIndex++;
  1090. }
  1091. sourceIndex += elementStride;
  1092. }
  1093. return targetBuffer;
  1094. }
  1095. public _addPendingData(data: any): void {
  1096. if (!this._renderReady) {
  1097. this._renderPendingCount++;
  1098. }
  1099. this._addLoaderPendingData(data);
  1100. }
  1101. public _removePendingData(data: any): void {
  1102. if (!this._renderReady) {
  1103. if (--this._renderPendingCount === 0) {
  1104. this._addLoaderPendingData(this);
  1105. this._compileMaterialsAsync(() => {
  1106. this._compileShadowGeneratorsAsync(() => {
  1107. this._removeLoaderPendingData(this);
  1108. this._renderReady = true;
  1109. this._onRenderReady();
  1110. });
  1111. });
  1112. }
  1113. }
  1114. this._removeLoaderPendingData(data);
  1115. }
  1116. public _addLoaderPendingData(data: any): void {
  1117. this._loaderPendingCount++;
  1118. for (const tracker of this._loaderTrackers) {
  1119. tracker._addPendingData(data);
  1120. }
  1121. }
  1122. public _removeLoaderPendingData(data: any): void {
  1123. for (const tracker of this._loaderTrackers) {
  1124. tracker._removePendingData(data);
  1125. }
  1126. if (--this._loaderPendingCount === 0) {
  1127. this._onComplete();
  1128. }
  1129. }
  1130. public _whenAction(action: () => void, onComplete: () => void): void {
  1131. const tracker = new GLTFLoaderTracker(() => {
  1132. this._loaderTrackers.splice(this._loaderTrackers.indexOf(tracker), 1);
  1133. onComplete();
  1134. });
  1135. this._loaderTrackers.push(tracker);
  1136. this._addLoaderPendingData(tracker);
  1137. action();
  1138. this._removeLoaderPendingData(tracker);
  1139. }
  1140. private _getDefaultMaterial(): Material {
  1141. if (!this._defaultMaterial) {
  1142. const id = "__gltf_default";
  1143. let material = <PBRMaterial>this._babylonScene.getMaterialByName(id);
  1144. if (!material) {
  1145. material = new PBRMaterial(id, this._babylonScene);
  1146. material.sideOrientation = Material.CounterClockWiseSideOrientation;
  1147. material.metallic = 1;
  1148. material.roughness = 1;
  1149. }
  1150. this._defaultMaterial = material;
  1151. }
  1152. return this._defaultMaterial;
  1153. }
  1154. private _loadMaterialMetallicRoughnessProperties(context: string, material: IGLTFMaterial): void {
  1155. const babylonMaterial = material.babylonMaterial as PBRMaterial;
  1156. // Ensure metallic workflow
  1157. babylonMaterial.metallic = 1;
  1158. babylonMaterial.roughness = 1;
  1159. const properties = material.pbrMetallicRoughness;
  1160. if (!properties) {
  1161. return;
  1162. }
  1163. babylonMaterial.albedoColor = properties.baseColorFactor ? Color3.FromArray(properties.baseColorFactor) : new Color3(1, 1, 1);
  1164. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  1165. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  1166. if (properties.baseColorTexture) {
  1167. const texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  1168. if (!texture) {
  1169. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  1170. }
  1171. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  1172. }
  1173. if (properties.metallicRoughnessTexture) {
  1174. const texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  1175. if (!texture) {
  1176. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  1177. }
  1178. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  1179. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  1180. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  1181. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  1182. }
  1183. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  1184. }
  1185. public _loadMaterial(context: string, material: IGLTFMaterial, assign: (babylonMaterial: Material, isNew: boolean) => void): void {
  1186. if (material.babylonMaterial) {
  1187. assign(material.babylonMaterial, false);
  1188. return;
  1189. }
  1190. if (GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  1191. return;
  1192. }
  1193. this._createPbrMaterial(material);
  1194. this._loadMaterialBaseProperties(context, material);
  1195. this._loadMaterialMetallicRoughnessProperties(context, material);
  1196. assign(material.babylonMaterial, true);
  1197. }
  1198. public _createPbrMaterial(material: IGLTFMaterial): void {
  1199. const babylonMaterial = new PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  1200. babylonMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;
  1201. material.babylonMaterial = babylonMaterial;
  1202. }
  1203. public _loadMaterialBaseProperties(context: string, material: IGLTFMaterial): void {
  1204. const babylonMaterial = material.babylonMaterial as PBRMaterial;
  1205. babylonMaterial.emissiveColor = material.emissiveFactor ? Color3.FromArray(material.emissiveFactor) : new Color3(0, 0, 0);
  1206. if (material.doubleSided) {
  1207. babylonMaterial.backFaceCulling = false;
  1208. babylonMaterial.twoSidedLighting = true;
  1209. }
  1210. if (material.normalTexture) {
  1211. const texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  1212. if (!texture) {
  1213. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  1214. }
  1215. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  1216. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  1217. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  1218. if (material.normalTexture.scale != null) {
  1219. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  1220. }
  1221. }
  1222. if (material.occlusionTexture) {
  1223. const texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  1224. if (!texture) {
  1225. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  1226. }
  1227. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  1228. babylonMaterial.useAmbientInGrayScale = true;
  1229. if (material.occlusionTexture.strength != null) {
  1230. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  1231. }
  1232. }
  1233. if (material.emissiveTexture) {
  1234. const texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  1235. if (!texture) {
  1236. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  1237. }
  1238. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  1239. }
  1240. }
  1241. public _loadMaterialAlphaProperties(context: string, material: IGLTFMaterial, colorFactor: number[]): void {
  1242. const babylonMaterial = material.babylonMaterial as PBRMaterial;
  1243. const alphaMode = material.alphaMode || "OPAQUE";
  1244. switch (alphaMode) {
  1245. case "OPAQUE": {
  1246. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_OPAQUE;
  1247. break;
  1248. }
  1249. case "MASK": {
  1250. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHATEST;
  1251. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  1252. if (colorFactor) {
  1253. if (colorFactor[3] == 0) {
  1254. babylonMaterial.alphaCutOff = 1;
  1255. }
  1256. else {
  1257. babylonMaterial.alphaCutOff /= colorFactor[3];
  1258. }
  1259. }
  1260. if (babylonMaterial.albedoTexture) {
  1261. babylonMaterial.albedoTexture.hasAlpha = true;
  1262. }
  1263. break;
  1264. }
  1265. case "BLEND": {
  1266. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHABLEND;
  1267. if (colorFactor) {
  1268. babylonMaterial.alpha = colorFactor[3];
  1269. }
  1270. if (babylonMaterial.albedoTexture) {
  1271. babylonMaterial.albedoTexture.hasAlpha = true;
  1272. babylonMaterial.useAlphaFromAlbedoTexture = true;
  1273. }
  1274. break;
  1275. }
  1276. default: {
  1277. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  1278. }
  1279. }
  1280. }
  1281. public _loadTexture(context: string, texture: IGLTFTexture, coordinatesIndex?: number): Texture {
  1282. const sampler = (texture.sampler == null ? <IGLTFSampler>{} : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  1283. if (!sampler) {
  1284. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  1285. }
  1286. const noMipMaps = (sampler.minFilter === ETextureMinFilter.NEAREST || sampler.minFilter === ETextureMinFilter.LINEAR);
  1287. const samplingMode = GLTFLoader._GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  1288. this._addPendingData(texture);
  1289. const babylonTexture = new Texture(null, this._babylonScene, noMipMaps, false, samplingMode, () => {
  1290. this._tryCatchOnError(() => {
  1291. this._removePendingData(texture);
  1292. });
  1293. }, message => {
  1294. this._tryCatchOnError(() => {
  1295. throw new Error(context + ": " + message);
  1296. });
  1297. });
  1298. if (texture.url) {
  1299. babylonTexture.updateURL(texture.url);
  1300. }
  1301. else if (texture.dataReadyObservable) {
  1302. texture.dataReadyObservable.add(texture => {
  1303. babylonTexture.updateURL(texture.url!);
  1304. });
  1305. }
  1306. else {
  1307. texture.dataReadyObservable = new Observable<IGLTFTexture>();
  1308. texture.dataReadyObservable.add(texture => {
  1309. babylonTexture.updateURL(texture.url!);
  1310. });
  1311. const image = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  1312. if (!image) {
  1313. throw new Error(context + ": Failed to find source " + texture.source);
  1314. }
  1315. this._loadImageAsync("#/images/" + image.index, image, data => {
  1316. texture.url = URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  1317. texture.dataReadyObservable!.notifyObservers(texture);
  1318. texture.dataReadyObservable = undefined;
  1319. });
  1320. }
  1321. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  1322. babylonTexture.wrapU = GLTFLoader._GetTextureWrapMode(sampler.wrapS);
  1323. babylonTexture.wrapV = GLTFLoader._GetTextureWrapMode(sampler.wrapT);
  1324. babylonTexture.name = texture.name || "texture" + texture.index;
  1325. if (this._parent.onTextureLoaded) {
  1326. this._parent.onTextureLoaded(babylonTexture);
  1327. }
  1328. return babylonTexture;
  1329. }
  1330. private _loadImageAsync(context: string, image: IGLTFImage, onSuccess: (data: ArrayBufferView) => void): void {
  1331. if (image.uri) {
  1332. this._loadUriAsync(context, image.uri, onSuccess);
  1333. }
  1334. else {
  1335. const bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  1336. if (!bufferView) {
  1337. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  1338. }
  1339. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  1340. }
  1341. }
  1342. public _loadUriAsync(context: string, uri: string, onSuccess: (data: ArrayBufferView) => void): void {
  1343. if (GLTFUtils.IsBase64(uri)) {
  1344. onSuccess(new Uint8Array(GLTFUtils.DecodeBase64(uri)));
  1345. return;
  1346. }
  1347. if (!GLTFUtils.ValidateUri(uri)) {
  1348. throw new Error(context + ": Uri '" + uri + "' is invalid");
  1349. }
  1350. let request = Tools.LoadFile(this._rootUrl + uri, data => {
  1351. this._tryCatchOnError(() => {
  1352. onSuccess(new Uint8Array(data as ArrayBuffer));
  1353. });
  1354. }, event => {
  1355. this._tryCatchOnError(() => {
  1356. if (request && !this._renderReady) {
  1357. request._loaded = event.loaded;
  1358. request._total = event.total;
  1359. this._onProgress();
  1360. }
  1361. });
  1362. }, this._babylonScene.database, true, request => {
  1363. this._tryCatchOnError(() => {
  1364. throw new Error(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  1365. });
  1366. }) as GLTFLoaderRequest;
  1367. if (request) {
  1368. request._loaded = null;
  1369. request._total = null;
  1370. this._requests.push(request);
  1371. }
  1372. }
  1373. public _tryCatchOnError(handler: () => void): void {
  1374. if (this._disposed) {
  1375. return;
  1376. }
  1377. try {
  1378. handler();
  1379. }
  1380. catch (e) {
  1381. Tools.Error("glTF Loader: " + e.message);
  1382. if (this._errorCallback) {
  1383. this._errorCallback(e.message);
  1384. }
  1385. this.dispose();
  1386. }
  1387. }
  1388. private static _AssignIndices(array?: Array<{index: number}>): void {
  1389. if (array) {
  1390. for (let index = 0; index < array.length; index++) {
  1391. array[index].index = index;
  1392. }
  1393. }
  1394. }
  1395. public static _GetProperty<T extends IGLTFProperty>(array?: ArrayLike<T>, index?: number): Nullable<T> {
  1396. if (!array || index == undefined || !array[index]) {
  1397. return null;
  1398. }
  1399. return array[index];
  1400. }
  1401. private static _GetTextureWrapMode(mode?: ETextureWrapMode): number {
  1402. // Set defaults if undefined
  1403. mode = mode == undefined ? ETextureWrapMode.REPEAT : mode;
  1404. switch (mode) {
  1405. case ETextureWrapMode.CLAMP_TO_EDGE: return Texture.CLAMP_ADDRESSMODE;
  1406. case ETextureWrapMode.MIRRORED_REPEAT: return Texture.MIRROR_ADDRESSMODE;
  1407. case ETextureWrapMode.REPEAT: return Texture.WRAP_ADDRESSMODE;
  1408. default:
  1409. Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  1410. return Texture.WRAP_ADDRESSMODE;
  1411. }
  1412. }
  1413. private static _GetTextureSamplingMode(magFilter?: ETextureMagFilter, minFilter?: ETextureMinFilter): number {
  1414. // Set defaults if undefined
  1415. magFilter = magFilter == undefined ? ETextureMagFilter.LINEAR : magFilter;
  1416. minFilter = minFilter == undefined ? ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  1417. if (magFilter === ETextureMagFilter.LINEAR) {
  1418. switch (minFilter) {
  1419. case ETextureMinFilter.NEAREST: return Texture.LINEAR_NEAREST;
  1420. case ETextureMinFilter.LINEAR: return Texture.LINEAR_LINEAR;
  1421. case ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return Texture.LINEAR_NEAREST_MIPNEAREST;
  1422. case ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return Texture.LINEAR_LINEAR_MIPNEAREST;
  1423. case ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return Texture.LINEAR_NEAREST_MIPLINEAR;
  1424. case ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return Texture.LINEAR_LINEAR_MIPLINEAR;
  1425. default:
  1426. Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  1427. return Texture.LINEAR_LINEAR_MIPLINEAR;
  1428. }
  1429. }
  1430. else {
  1431. if (magFilter !== ETextureMagFilter.NEAREST) {
  1432. Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  1433. }
  1434. switch (minFilter) {
  1435. case ETextureMinFilter.NEAREST: return Texture.NEAREST_NEAREST;
  1436. case ETextureMinFilter.LINEAR: return Texture.NEAREST_LINEAR;
  1437. case ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return Texture.NEAREST_NEAREST_MIPNEAREST;
  1438. case ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return Texture.NEAREST_LINEAR_MIPNEAREST;
  1439. case ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return Texture.NEAREST_NEAREST_MIPLINEAR;
  1440. case ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return Texture.NEAREST_LINEAR_MIPLINEAR;
  1441. default:
  1442. Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  1443. return Texture.NEAREST_NEAREST_MIPNEAREST;
  1444. }
  1445. }
  1446. }
  1447. private static _GetNumComponents(type: string): number {
  1448. switch (type) {
  1449. case "SCALAR": return 1;
  1450. case "VEC2": return 2;
  1451. case "VEC3": return 3;
  1452. case "VEC4": return 4;
  1453. case "MAT2": return 4;
  1454. case "MAT3": return 9;
  1455. case "MAT4": return 16;
  1456. }
  1457. return 0;
  1458. }
  1459. private _compileMaterialAsync(babylonMaterial: Material, babylonMesh: AbstractMesh, onSuccess: () => void): void {
  1460. if (!this._parent.compileMaterials) {
  1461. onSuccess();
  1462. return;
  1463. }
  1464. if (this._parent.useClipPlane) {
  1465. babylonMaterial.forceCompilation(babylonMesh, () => {
  1466. babylonMaterial.forceCompilation(babylonMesh, () => {
  1467. this._tryCatchOnError(onSuccess);
  1468. }, { clipPlane: true });
  1469. });
  1470. }
  1471. else {
  1472. babylonMaterial.forceCompilation(babylonMesh, () => {
  1473. this._tryCatchOnError(onSuccess);
  1474. });
  1475. }
  1476. }
  1477. private _compileMaterialsAsync(onSuccess: () => void): void {
  1478. if (!this._parent.compileMaterials || !this._gltf.materials) {
  1479. onSuccess();
  1480. return;
  1481. }
  1482. let meshes = this._getMeshes();
  1483. let remaining = 0;
  1484. for (let mesh of meshes) {
  1485. if (mesh.material instanceof MultiMaterial) {
  1486. for (let subMaterial of mesh.material.subMaterials) {
  1487. if (subMaterial) {
  1488. remaining++;
  1489. }
  1490. }
  1491. }
  1492. else {
  1493. remaining++;
  1494. }
  1495. }
  1496. if (remaining === 0) {
  1497. onSuccess();
  1498. return;
  1499. }
  1500. for (let mesh of meshes) {
  1501. if (mesh.material instanceof MultiMaterial) {
  1502. for (let subMaterial of mesh.material.subMaterials) {
  1503. if (subMaterial) {
  1504. this._compileMaterialAsync(subMaterial, mesh, () => {
  1505. if (--remaining === 0) {
  1506. onSuccess();
  1507. }
  1508. });
  1509. }
  1510. }
  1511. }
  1512. else if (mesh.material !== null) {
  1513. this._compileMaterialAsync(mesh.material, mesh, () => {
  1514. if (--remaining === 0) {
  1515. onSuccess();
  1516. }
  1517. })
  1518. }
  1519. }
  1520. }
  1521. private _compileShadowGeneratorsAsync(onSuccess: () => void): void {
  1522. if (!this._parent.compileShadowGenerators) {
  1523. onSuccess();
  1524. return;
  1525. }
  1526. let lights = this._babylonScene.lights;
  1527. let remaining = 0;
  1528. for (let light of lights) {
  1529. let generator = light.getShadowGenerator();
  1530. if (generator) {
  1531. remaining++;
  1532. }
  1533. }
  1534. if (remaining === 0) {
  1535. onSuccess();
  1536. return;
  1537. }
  1538. for (let light of lights) {
  1539. let generator = light.getShadowGenerator();
  1540. if (generator) {
  1541. generator.forceCompilation(() => {
  1542. if (--remaining === 0) {
  1543. this._tryCatchOnError(onSuccess);
  1544. }
  1545. });
  1546. }
  1547. }
  1548. }
  1549. }
  1550. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = parent => new GLTFLoader(parent);
  1551. }