glTFLoader.ts 105 KB

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