babylon.sceneLoader.ts 41 KB

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