glTFLoader.ts 105 KB

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