sceneLoader.ts 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  1. import { Observable, Tools, IFileRequest, FilesInput } from "Tools";
  2. import { Nullable } from "types";
  3. import { Scene } from "scene";
  4. import { Engine } from "Engine";
  5. import { AbstractMesh } from "Mesh";
  6. import { AnimationGroup } from "Animations";
  7. import { _TimeToken } from "Instrumentation";
  8. import { IOfflineProvider } from "Offline";
  9. import { _DepthCullingState, _StencilState, _AlphaState } from "States";
  10. import { AssetContainer } from "assetContainer";
  11. import { IParticleSystem } from "Particles";
  12. import { Skeleton } from "Bones";
  13. /**
  14. * Class used to represent data loading progression
  15. */
  16. export class SceneLoaderProgressEvent {
  17. /**
  18. * Create a new progress event
  19. * @param lengthComputable defines if data length to load can be evaluated
  20. * @param loaded defines the loaded data length
  21. * @param total defines the data length to load
  22. */
  23. constructor(
  24. /** defines if data length to load can be evaluated */
  25. public readonly lengthComputable: boolean,
  26. /** defines the loaded data length */
  27. public readonly loaded: number,
  28. /** defines the data length to load */
  29. public readonly total: number) {
  30. }
  31. /**
  32. * Creates a new SceneLoaderProgressEvent from a ProgressEvent
  33. * @param event defines the source event
  34. * @returns a new SceneLoaderProgressEvent
  35. */
  36. public static FromProgressEvent(event: ProgressEvent): SceneLoaderProgressEvent {
  37. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  38. }
  39. }
  40. /**
  41. * Interface used by SceneLoader plugins to define supported file extensions
  42. */
  43. export interface ISceneLoaderPluginExtensions {
  44. /**
  45. * Defines the list of supported extensions
  46. */
  47. [extension: string]: {
  48. isBinary: boolean;
  49. };
  50. }
  51. /**
  52. * Interface used by SceneLoader plugin factory
  53. */
  54. export interface ISceneLoaderPluginFactory {
  55. /**
  56. * Defines the name of the factory
  57. */
  58. name: string;
  59. /**
  60. * Function called to create a new plugin
  61. * @return the new plugin
  62. */
  63. createPlugin(): ISceneLoaderPlugin | ISceneLoaderPluginAsync;
  64. /**
  65. * Boolean indicating if the plugin can direct load specific data
  66. */
  67. canDirectLoad?: (data: string) => boolean;
  68. }
  69. /**
  70. * Interface used to define a SceneLoader plugin
  71. */
  72. export interface ISceneLoaderPlugin {
  73. /**
  74. * The friendly name of this plugin.
  75. */
  76. name: string;
  77. /**
  78. * The file extensions supported by this plugin.
  79. */
  80. extensions: string | ISceneLoaderPluginExtensions;
  81. /**
  82. * Import meshes into a scene.
  83. * @param meshesNames An array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  84. * @param scene The scene to import into
  85. * @param data The data to import
  86. * @param rootUrl The root url for scene and resources
  87. * @param meshes The meshes array to import into
  88. * @param particleSystems The particle systems array to import into
  89. * @param skeletons The skeletons array to import into
  90. * @param onError The callback when import fails
  91. * @returns True if successful or false otherwise
  92. */
  93. importMesh(meshesNames: any, scene: Scene, data: any, rootUrl: string, meshes: AbstractMesh[], particleSystems: IParticleSystem[], skeletons: Skeleton[], onError?: (message: string, exception?: any) => void): boolean;
  94. /**
  95. * Load into a scene.
  96. * @param scene The scene to load into
  97. * @param data The data to import
  98. * @param rootUrl The root url for scene and resources
  99. * @param onError The callback when import fails
  100. * @returns true if successful or false otherwise
  101. */
  102. load(scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): boolean;
  103. /**
  104. * The callback that returns true if the data can be directly loaded.
  105. */
  106. canDirectLoad?: (data: string) => boolean;
  107. /**
  108. * The callback that allows custom handling of the root url based on the response url.
  109. */
  110. rewriteRootURL?: (rootUrl: string, responseURL?: string) => string;
  111. /**
  112. * Load into an asset container.
  113. * @param scene The scene to load into
  114. * @param data The data to import
  115. * @param rootUrl The root url for scene and resources
  116. * @param onError The callback when import fails
  117. * @returns The loaded asset container
  118. */
  119. loadAssetContainer(scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): AssetContainer;
  120. }
  121. /**
  122. * Interface used to define an async SceneLoader plugin
  123. */
  124. export interface ISceneLoaderPluginAsync {
  125. /**
  126. * The friendly name of this plugin.
  127. */
  128. name: string;
  129. /**
  130. * The file extensions supported by this plugin.
  131. */
  132. extensions: string | ISceneLoaderPluginExtensions;
  133. /**
  134. * Import meshes into a scene.
  135. * @param meshesNames An array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  136. * @param scene The scene to import into
  137. * @param data The data to import
  138. * @param rootUrl The root url for scene and resources
  139. * @param onProgress The callback when the load progresses
  140. * @param fileName Defines the name of the file to load
  141. * @returns The loaded meshes, particle systems, skeletons, and animation groups
  142. */
  143. importMeshAsync(meshesNames: any, scene: Scene, data: any, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void, fileName?: string): Promise<{ meshes: AbstractMesh[], particleSystems: IParticleSystem[], skeletons: Skeleton[], animationGroups: AnimationGroup[] }>;
  144. /**
  145. * Load into a scene.
  146. * @param scene The scene to load into
  147. * @param data The data to import
  148. * @param rootUrl The root url for scene and resources
  149. * @param onProgress The callback when the load progresses
  150. * @param fileName Defines the name of the file to load
  151. * @returns Nothing
  152. */
  153. loadAsync(scene: Scene, data: string, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void, fileName?: string): Promise<void>;
  154. /**
  155. * The callback that returns true if the data can be directly loaded.
  156. */
  157. canDirectLoad?: (data: string) => boolean;
  158. /**
  159. * The callback that allows custom handling of the root url based on the response url.
  160. */
  161. rewriteRootURL?: (rootUrl: string, responseURL?: string) => string;
  162. /**
  163. * Load into an asset container.
  164. * @param scene The scene to load into
  165. * @param data The data to import
  166. * @param rootUrl The root url for scene and resources
  167. * @param onProgress The callback when the load progresses
  168. * @param fileName Defines the name of the file to load
  169. * @returns The loaded asset container
  170. */
  171. loadAssetContainerAsync(scene: Scene, data: string, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void, fileName?: string): Promise<AssetContainer>;
  172. }
  173. /**
  174. * Defines a plugin registered by the SceneLoader
  175. */
  176. interface IRegisteredPlugin {
  177. /**
  178. * Defines the plugin to use
  179. */
  180. plugin: ISceneLoaderPlugin | ISceneLoaderPluginAsync | ISceneLoaderPluginFactory;
  181. /**
  182. * Defines if the plugin supports binary data
  183. */
  184. isBinary: boolean;
  185. }
  186. /**
  187. * Defines file information
  188. */
  189. interface IFileInfo {
  190. /**
  191. * Gets the file url
  192. */
  193. url: string;
  194. /**
  195. * Gets the root url
  196. */
  197. rootUrl: string;
  198. /**
  199. * Gets filename
  200. */
  201. name: string;
  202. }
  203. /**
  204. * Class used to load scene from various file formats using registered plugins
  205. * @see http://doc.babylonjs.com/how_to/load_from_any_file_type
  206. */
  207. export class SceneLoader {
  208. // Flags
  209. private static _ForceFullSceneLoadingForIncremental = false;
  210. private static _ShowLoadingScreen = true;
  211. private static _CleanBoneMatrixWeights = false;
  212. /**
  213. * No logging while loading
  214. */
  215. public static readonly NO_LOGGING = 0;
  216. /**
  217. * Minimal logging while loading
  218. */
  219. public static readonly MINIMAL_LOGGING = 1;
  220. /**
  221. * Summary logging while loading
  222. */
  223. public static readonly SUMMARY_LOGGING = 2;
  224. /**
  225. * Detailled logging while loading
  226. */
  227. public static readonly DETAILED_LOGGING = 3;
  228. private static _loggingLevel = SceneLoader.NO_LOGGING;
  229. /**
  230. * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data
  231. */
  232. public static get ForceFullSceneLoadingForIncremental() {
  233. return SceneLoader._ForceFullSceneLoadingForIncremental;
  234. }
  235. public static set ForceFullSceneLoadingForIncremental(value: boolean) {
  236. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  237. }
  238. /**
  239. * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene
  240. */
  241. public static get ShowLoadingScreen(): boolean {
  242. return SceneLoader._ShowLoadingScreen;
  243. }
  244. public static set ShowLoadingScreen(value: boolean) {
  245. SceneLoader._ShowLoadingScreen = value;
  246. }
  247. /**
  248. * Defines the current logging level (while loading the scene)
  249. * @ignorenaming
  250. */
  251. public static get loggingLevel(): number {
  252. return SceneLoader._loggingLevel;
  253. }
  254. public static set loggingLevel(value: number) {
  255. SceneLoader._loggingLevel = value;
  256. }
  257. /**
  258. * Gets or set a boolean indicating if matrix weights must be cleaned upon loading
  259. */
  260. public static get CleanBoneMatrixWeights(): boolean {
  261. return SceneLoader._CleanBoneMatrixWeights;
  262. }
  263. public static set CleanBoneMatrixWeights(value: boolean) {
  264. SceneLoader._CleanBoneMatrixWeights = value;
  265. }
  266. // Members
  267. /**
  268. * Event raised when a plugin is used to load a scene
  269. */
  270. public static OnPluginActivatedObservable = new Observable<ISceneLoaderPlugin | ISceneLoaderPluginAsync>();
  271. private static _registeredPlugins: { [extension: string]: IRegisteredPlugin } = {};
  272. private static _getDefaultPlugin(): IRegisteredPlugin {
  273. return SceneLoader._registeredPlugins[".babylon"];
  274. }
  275. private static _getPluginForExtension(extension: string): IRegisteredPlugin {
  276. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  277. if (registeredPlugin) {
  278. return registeredPlugin;
  279. }
  280. Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
  281. return SceneLoader._getDefaultPlugin();
  282. }
  283. private static _getPluginForDirectLoad(data: string): IRegisteredPlugin {
  284. for (var extension in SceneLoader._registeredPlugins) {
  285. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  286. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  287. return SceneLoader._registeredPlugins[extension];
  288. }
  289. }
  290. return SceneLoader._getDefaultPlugin();
  291. }
  292. private static _getPluginForFilename(sceneFilename: string): IRegisteredPlugin {
  293. var queryStringPosition = sceneFilename.indexOf("?");
  294. if (queryStringPosition !== -1) {
  295. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  296. }
  297. var dotPosition = sceneFilename.lastIndexOf(".");
  298. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  299. return SceneLoader._getPluginForExtension(extension);
  300. }
  301. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  302. private static _getDirectLoad(sceneFilename: string): Nullable<string> {
  303. if (sceneFilename.substr(0, 5) === "data:") {
  304. return sceneFilename.substr(5);
  305. }
  306. return null;
  307. }
  308. private static _loadData(fileInfo: IFileInfo, scene: Scene, onSuccess: (plugin: ISceneLoaderPlugin | ISceneLoaderPluginAsync, data: any, responseURL?: string) => void, onProgress: ((event: SceneLoaderProgressEvent) => void) | undefined, onError: (message: string, exception?: any) => void, onDispose: () => void, pluginExtension: Nullable<string>): ISceneLoaderPlugin | ISceneLoaderPluginAsync {
  309. let directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  310. let registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  311. let plugin: ISceneLoaderPlugin | ISceneLoaderPluginAsync;
  312. if ((registeredPlugin.plugin as ISceneLoaderPluginFactory).createPlugin) {
  313. plugin = (registeredPlugin.plugin as ISceneLoaderPluginFactory).createPlugin();
  314. }
  315. else {
  316. plugin = <any>registeredPlugin.plugin;
  317. }
  318. let useArrayBuffer = registeredPlugin.isBinary;
  319. let offlineProvider: IOfflineProvider;
  320. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  321. let dataCallback = (data: any, responseURL?: string) => {
  322. if (scene.isDisposed) {
  323. onError("Scene has been disposed");
  324. return;
  325. }
  326. scene.offlineProvider = offlineProvider;
  327. onSuccess(plugin, data, responseURL);
  328. };
  329. let request: Nullable<IFileRequest> = null;
  330. let pluginDisposed = false;
  331. let onDisposeObservable = (plugin as any).onDisposeObservable as Observable<ISceneLoaderPlugin | ISceneLoaderPluginAsync>;
  332. if (onDisposeObservable) {
  333. onDisposeObservable.add(() => {
  334. pluginDisposed = true;
  335. if (request) {
  336. request.abort();
  337. request = null;
  338. }
  339. onDispose();
  340. });
  341. }
  342. let manifestChecked = () => {
  343. if (pluginDisposed) {
  344. return;
  345. }
  346. request = Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? (event) => {
  347. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  348. } : undefined, offlineProvider, useArrayBuffer, (request, exception) => {
  349. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  350. });
  351. };
  352. if (directLoad) {
  353. dataCallback(directLoad);
  354. return plugin;
  355. }
  356. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  357. let engine = scene.getEngine();
  358. let canUseOfflineSupport = engine.enableOfflineSupport;
  359. if (canUseOfflineSupport) {
  360. // Also check for exceptions
  361. let exceptionFound = false;
  362. for (var regex of scene.disableOfflineSupportExceptionRules) {
  363. if (regex.test(fileInfo.url)) {
  364. exceptionFound = true;
  365. break;
  366. }
  367. }
  368. canUseOfflineSupport = !exceptionFound;
  369. }
  370. if (canUseOfflineSupport && Engine.OfflineProviderFactory) {
  371. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  372. offlineProvider = Engine.OfflineProviderFactory(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  373. }
  374. else {
  375. manifestChecked();
  376. }
  377. }
  378. // Loading file from disk via input file or drag'n'drop
  379. else {
  380. const file = FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  381. if (file) {
  382. request = Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  383. } else {
  384. onError("Unable to find file named " + fileInfo.name);
  385. }
  386. }
  387. return plugin;
  388. }
  389. private static _getFileInfo(rootUrl: string, sceneFilename: string): Nullable<IFileInfo> {
  390. let url: string;
  391. let name: string;
  392. if (!sceneFilename) {
  393. url = rootUrl;
  394. name = Tools.GetFilename(rootUrl);
  395. rootUrl = Tools.GetFolderPath(rootUrl);
  396. }
  397. else {
  398. if (sceneFilename.substr(0, 1) === "/") {
  399. Tools.Error("Wrong sceneFilename parameter");
  400. return null;
  401. }
  402. url = rootUrl + sceneFilename;
  403. name = sceneFilename;
  404. }
  405. return {
  406. url: url,
  407. rootUrl: rootUrl,
  408. name: name
  409. };
  410. }
  411. // Public functions
  412. /**
  413. * Gets a plugin that can load the given extension
  414. * @param extension defines the extension to load
  415. * @returns a plugin or null if none works
  416. */
  417. public static GetPluginForExtension(extension: string): ISceneLoaderPlugin | ISceneLoaderPluginAsync | ISceneLoaderPluginFactory {
  418. return SceneLoader._getPluginForExtension(extension).plugin;
  419. }
  420. /**
  421. * Gets a boolean indicating that the given extension can be loaded
  422. * @param extension defines the extension to load
  423. * @returns true if the extension is supported
  424. */
  425. public static IsPluginForExtensionAvailable(extension: string): boolean {
  426. return !!SceneLoader._registeredPlugins[extension];
  427. }
  428. /**
  429. * Adds a new plugin to the list of registered plugins
  430. * @param plugin defines the plugin to add
  431. */
  432. public static RegisterPlugin(plugin: ISceneLoaderPlugin | ISceneLoaderPluginAsync): void {
  433. if (typeof plugin.extensions === "string") {
  434. var extension = <string>plugin.extensions;
  435. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  436. plugin: plugin,
  437. isBinary: false
  438. };
  439. }
  440. else {
  441. var extensions = <ISceneLoaderPluginExtensions>plugin.extensions;
  442. Object.keys(extensions).forEach((extension) => {
  443. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  444. plugin: plugin,
  445. isBinary: extensions[extension].isBinary
  446. };
  447. });
  448. }
  449. }
  450. /**
  451. * Import meshes into a scene
  452. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  453. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  454. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  455. * @param scene the instance of Scene to append to
  456. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  457. * @param onProgress a callback with a progress event for each file being loaded
  458. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  459. * @param pluginExtension the extension used to determine the plugin
  460. * @returns The loaded plugin
  461. */
  462. public static ImportMesh(meshNames: any, rootUrl: string, sceneFilename: string = "", scene: Nullable<Scene> = Engine.LastCreatedScene, onSuccess: Nullable<(meshes: AbstractMesh[], particleSystems: IParticleSystem[], skeletons: Skeleton[], animationGroups: AnimationGroup[]) => void> = null, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, onError: Nullable<(scene: Scene, message: string, exception?: any) => void> = null, pluginExtension: Nullable<string> = null): Nullable<ISceneLoaderPlugin | ISceneLoaderPluginAsync> {
  463. if (!scene) {
  464. Tools.Error("No scene available to import mesh to");
  465. return null;
  466. }
  467. const fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  468. if (!fileInfo) {
  469. return null;
  470. }
  471. var loadingToken = {};
  472. scene._addPendingData(loadingToken);
  473. var disposeHandler = () => {
  474. scene._removePendingData(loadingToken);
  475. };
  476. var errorHandler = (message: string, exception?: any) => {
  477. let errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  478. if (onError) {
  479. onError(scene, errorMessage, exception);
  480. } else {
  481. Tools.Error(errorMessage);
  482. // should the exception be thrown?
  483. }
  484. disposeHandler();
  485. };
  486. var progressHandler = onProgress ? (event: SceneLoaderProgressEvent) => {
  487. try {
  488. onProgress(event);
  489. }
  490. catch (e) {
  491. errorHandler("Error in onProgress callback", e);
  492. }
  493. } : undefined;
  494. var successHandler = (meshes: AbstractMesh[], particleSystems: IParticleSystem[], skeletons: Skeleton[], animationGroups: AnimationGroup[]) => {
  495. scene.importedMeshesFiles.push(fileInfo.url);
  496. if (onSuccess) {
  497. try {
  498. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  499. }
  500. catch (e) {
  501. errorHandler("Error in onSuccess callback", e);
  502. }
  503. }
  504. scene._removePendingData(loadingToken);
  505. };
  506. return SceneLoader._loadData(fileInfo, scene, (plugin, data, responseURL) => {
  507. if (plugin.rewriteRootURL) {
  508. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  509. }
  510. if ((<any>plugin).importMesh) {
  511. var syncedPlugin = <ISceneLoaderPlugin>plugin;
  512. var meshes = new Array<AbstractMesh>();
  513. var particleSystems = new Array<IParticleSystem>();
  514. var skeletons = new Array<Skeleton>();
  515. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  516. return;
  517. }
  518. scene.loadingPluginName = plugin.name;
  519. successHandler(meshes, particleSystems, skeletons, []);
  520. }
  521. else {
  522. var asyncedPlugin = <ISceneLoaderPluginAsync>plugin;
  523. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then((result) => {
  524. scene.loadingPluginName = plugin.name;
  525. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  526. }).catch((error) => {
  527. errorHandler(error.message, error);
  528. });
  529. }
  530. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  531. }
  532. /**
  533. * Import meshes into a scene
  534. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  535. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  536. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  537. * @param scene the instance of Scene to append to
  538. * @param onProgress a callback with a progress event for each file being loaded
  539. * @param pluginExtension the extension used to determine the plugin
  540. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  541. */
  542. public static ImportMeshAsync(meshNames: any, rootUrl: string, sceneFilename: string = "", scene: Nullable<Scene> = Engine.LastCreatedScene, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, pluginExtension: Nullable<string> = null): Promise<{ meshes: AbstractMesh[], particleSystems: IParticleSystem[], skeletons: Skeleton[], animationGroups: AnimationGroup[] }> {
  543. return new Promise((resolve, reject) => {
  544. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, (meshes, particleSystems, skeletons, animationGroups) => {
  545. resolve({
  546. meshes: meshes,
  547. particleSystems: particleSystems,
  548. skeletons: skeletons,
  549. animationGroups: animationGroups
  550. });
  551. }, onProgress, (scene, message, exception) => {
  552. reject(exception || new Error(message));
  553. },
  554. pluginExtension);
  555. });
  556. }
  557. /**
  558. * Load a scene
  559. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  560. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  561. * @param engine is the instance of Engine to use to create the scene
  562. * @param onSuccess a callback with the scene when import succeeds
  563. * @param onProgress a callback with a progress event for each file being loaded
  564. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  565. * @param pluginExtension the extension used to determine the plugin
  566. * @returns The loaded plugin
  567. */
  568. public static Load(rootUrl: string, sceneFilename: string, engine: Engine, onSuccess: Nullable<(scene: Scene) => void> = null, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, onError: Nullable<(scene: Scene, message: string, exception?: any) => void> = null, pluginExtension: Nullable<string> = null): Nullable<ISceneLoaderPlugin | ISceneLoaderPluginAsync> {
  569. return SceneLoader.Append(rootUrl, sceneFilename, new Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  570. }
  571. /**
  572. * Load a scene
  573. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  574. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  575. * @param engine is the instance of Engine to use to create the scene
  576. * @param onProgress a callback with a progress event for each file being loaded
  577. * @param pluginExtension the extension used to determine the plugin
  578. * @returns The loaded scene
  579. */
  580. public static LoadAsync(rootUrl: string, sceneFilename: string, engine: Engine, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, pluginExtension: Nullable<string> = null): Promise<Scene> {
  581. return new Promise((resolve, reject) => {
  582. SceneLoader.Load(rootUrl, sceneFilename, engine, (scene) => {
  583. resolve(scene);
  584. }, onProgress, (scene, message, exception) => {
  585. reject(exception || new Error(message));
  586. }, pluginExtension);
  587. });
  588. }
  589. /**
  590. * Append a scene
  591. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  592. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  593. * @param scene is the instance of Scene to append to
  594. * @param onSuccess a callback with the scene when import succeeds
  595. * @param onProgress a callback with a progress event for each file being loaded
  596. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  597. * @param pluginExtension the extension used to determine the plugin
  598. * @returns The loaded plugin
  599. */
  600. public static Append(rootUrl: string, sceneFilename: string = "", scene: Nullable<Scene> = Engine.LastCreatedScene, onSuccess: Nullable<(scene: Scene) => void> = null, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, onError: Nullable<(scene: Scene, message: string, exception?: any) => void> = null, pluginExtension: Nullable<string> = null): Nullable<ISceneLoaderPlugin | ISceneLoaderPluginAsync> {
  601. if (!scene) {
  602. Tools.Error("No scene available to append to");
  603. return null;
  604. }
  605. const fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  606. if (!fileInfo) {
  607. return null;
  608. }
  609. if (SceneLoader.ShowLoadingScreen) {
  610. scene.getEngine().displayLoadingUI();
  611. }
  612. var loadingToken = {};
  613. scene._addPendingData(loadingToken);
  614. var disposeHandler = () => {
  615. scene._removePendingData(loadingToken);
  616. scene.getEngine().hideLoadingUI();
  617. };
  618. var errorHandler = (message: Nullable<string>, exception?: any) => {
  619. let errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  620. if (onError) {
  621. onError(scene, errorMessage, exception);
  622. } else {
  623. Tools.Error(errorMessage);
  624. // should the exception be thrown?
  625. }
  626. disposeHandler();
  627. };
  628. var progressHandler = onProgress ? (event: SceneLoaderProgressEvent) => {
  629. try {
  630. onProgress(event);
  631. }
  632. catch (e) {
  633. errorHandler("Error in onProgress callback", e);
  634. }
  635. } : undefined;
  636. var successHandler = () => {
  637. if (onSuccess) {
  638. try {
  639. onSuccess(scene);
  640. }
  641. catch (e) {
  642. errorHandler("Error in onSuccess callback", e);
  643. }
  644. }
  645. scene._removePendingData(loadingToken);
  646. };
  647. return SceneLoader._loadData(fileInfo, scene, (plugin, data) => {
  648. if ((<any>plugin).load) {
  649. var syncedPlugin = <ISceneLoaderPlugin>plugin;
  650. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  651. return;
  652. }
  653. scene.loadingPluginName = plugin.name;
  654. successHandler();
  655. } else {
  656. var asyncedPlugin = <ISceneLoaderPluginAsync>plugin;
  657. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(() => {
  658. scene.loadingPluginName = plugin.name;
  659. successHandler();
  660. }).catch((error) => {
  661. errorHandler(error.message, error);
  662. });
  663. }
  664. if (SceneLoader.ShowLoadingScreen) {
  665. scene.executeWhenReady(() => {
  666. scene.getEngine().hideLoadingUI();
  667. });
  668. }
  669. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  670. }
  671. /**
  672. * Append a scene
  673. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  674. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  675. * @param scene is the instance of Scene to append to
  676. * @param onProgress a callback with a progress event for each file being loaded
  677. * @param pluginExtension the extension used to determine the plugin
  678. * @returns The given scene
  679. */
  680. public static AppendAsync(rootUrl: string, sceneFilename: string = "", scene: Nullable<Scene> = Engine.LastCreatedScene, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, pluginExtension: Nullable<string> = null): Promise<Scene> {
  681. return new Promise((resolve, reject) => {
  682. SceneLoader.Append(rootUrl, sceneFilename, scene, (scene) => {
  683. resolve(scene);
  684. }, onProgress, (scene, message, exception) => {
  685. reject(exception || new Error(message));
  686. }, pluginExtension);
  687. });
  688. }
  689. /**
  690. * Load a scene into an asset container
  691. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  692. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  693. * @param scene is the instance of Scene to append to (default: last created scene)
  694. * @param onSuccess a callback with the scene when import succeeds
  695. * @param onProgress a callback with a progress event for each file being loaded
  696. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  697. * @param pluginExtension the extension used to determine the plugin
  698. * @returns The loaded plugin
  699. */
  700. public static LoadAssetContainer(
  701. rootUrl: string,
  702. sceneFilename: string = "",
  703. scene: Nullable<Scene> = Engine.LastCreatedScene,
  704. onSuccess: Nullable<(assets: AssetContainer) => void> = null,
  705. onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null,
  706. onError: Nullable<(scene: Scene, message: string, exception?: any) => void> = null,
  707. pluginExtension: Nullable<string> = null
  708. ): Nullable<ISceneLoaderPlugin | ISceneLoaderPluginAsync> {
  709. if (!scene) {
  710. Tools.Error("No scene available to load asset container to");
  711. return null;
  712. }
  713. const fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  714. if (!fileInfo) {
  715. return null;
  716. }
  717. var loadingToken = {};
  718. scene._addPendingData(loadingToken);
  719. var disposeHandler = () => {
  720. scene._removePendingData(loadingToken);
  721. };
  722. var errorHandler = (message: Nullable<string>, exception?: any) => {
  723. let errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  724. if (onError) {
  725. onError(scene, errorMessage, exception);
  726. } else {
  727. Tools.Error(errorMessage);
  728. // should the exception be thrown?
  729. }
  730. disposeHandler();
  731. };
  732. var progressHandler = onProgress ? (event: SceneLoaderProgressEvent) => {
  733. try {
  734. onProgress(event);
  735. }
  736. catch (e) {
  737. errorHandler("Error in onProgress callback", e);
  738. }
  739. } : undefined;
  740. var successHandler = (assets: AssetContainer) => {
  741. if (onSuccess) {
  742. try {
  743. onSuccess(assets);
  744. }
  745. catch (e) {
  746. errorHandler("Error in onSuccess callback", e);
  747. }
  748. }
  749. scene._removePendingData(loadingToken);
  750. };
  751. return SceneLoader._loadData(fileInfo, scene, (plugin, data) => {
  752. if ((<any>plugin).loadAssetContainer) {
  753. var syncedPlugin = <ISceneLoaderPlugin>plugin;
  754. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  755. if (!assetContainer) {
  756. return;
  757. }
  758. scene.loadingPluginName = plugin.name;
  759. successHandler(assetContainer);
  760. } else if ((<any>plugin).loadAssetContainerAsync) {
  761. var asyncedPlugin = <ISceneLoaderPluginAsync>plugin;
  762. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then((assetContainer) => {
  763. scene.loadingPluginName = plugin.name;
  764. successHandler(assetContainer);
  765. }).catch((error) => {
  766. errorHandler(error.message, error);
  767. });
  768. } else {
  769. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  770. }
  771. if (SceneLoader.ShowLoadingScreen) {
  772. scene.executeWhenReady(() => {
  773. scene.getEngine().hideLoadingUI();
  774. });
  775. }
  776. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  777. }
  778. /**
  779. * Load a scene into an asset container
  780. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  781. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  782. * @param scene is the instance of Scene to append to
  783. * @param onProgress a callback with a progress event for each file being loaded
  784. * @param pluginExtension the extension used to determine the plugin
  785. * @returns The loaded asset container
  786. */
  787. public static LoadAssetContainerAsync(rootUrl: string, sceneFilename: string = "", scene: Nullable<Scene> = Engine.LastCreatedScene, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, pluginExtension: Nullable<string> = null): Promise<AssetContainer> {
  788. return new Promise((resolve, reject) => {
  789. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, (assetContainer) => {
  790. resolve(assetContainer);
  791. }, onProgress, (scene, message, exception) => {
  792. reject(exception || new Error(message));
  793. }, pluginExtension);
  794. });
  795. }
  796. }