babylon.sceneLoader.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. module BABYLON {
  2. export class SceneLoaderProgressEvent {
  3. constructor(public readonly lengthComputable: boolean, public readonly loaded: number, public readonly total: number) {
  4. }
  5. public static FromProgressEvent(event: ProgressEvent): SceneLoaderProgressEvent {
  6. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  7. }
  8. }
  9. export interface ISceneLoaderPluginExtensions {
  10. [extension: string]: {
  11. isBinary: boolean;
  12. };
  13. }
  14. export interface ISceneLoaderPluginFactory {
  15. name: string;
  16. createPlugin(): ISceneLoaderPlugin | ISceneLoaderPluginAsync;
  17. canDirectLoad?: (data: string) => boolean;
  18. }
  19. export interface ISceneLoaderPlugin {
  20. /**
  21. * The friendly name of this plugin.
  22. */
  23. name: string;
  24. /**
  25. * The file extensions supported by this plugin.
  26. */
  27. extensions: string | ISceneLoaderPluginExtensions;
  28. /**
  29. * Import meshes into a scene.
  30. * @param meshesNames An array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  31. * @param scene The scene to import into
  32. * @param data The data to import
  33. * @param rootUrl The root url for scene and resources
  34. * @param meshes The meshes array to import into
  35. * @param particleSystems The particle systems array to import into
  36. * @param skeletons The skeletons array to import into
  37. * @param onError The callback when import fails
  38. * @returns True if successful or false otherwise
  39. */
  40. importMesh(meshesNames: any, scene: Scene, data: any, rootUrl: string, meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[], onError?: (message: string, exception?: any) => void): boolean;
  41. /**
  42. * Load into a scene.
  43. * @param scene The scene to load into
  44. * @param data The data to import
  45. * @param rootUrl The root url for scene and resources
  46. * @param onError The callback when import fails
  47. * @returns true if successful or false otherwise
  48. */
  49. load(scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): boolean;
  50. /**
  51. * The callback that returns true if the data can be directly loaded.
  52. */
  53. canDirectLoad?: (data: string) => boolean;
  54. /**
  55. * The callback that allows custom handling of the root url based on the response url.
  56. */
  57. rewriteRootURL?: (rootUrl: string, responseURL?: string) => string;
  58. /**
  59. * Load into an asset container.
  60. * @param scene The scene to load into
  61. * @param data The data to import
  62. * @param rootUrl The root url for scene and resources
  63. * @param onError The callback when import fails
  64. * @returns The loaded asset container
  65. */
  66. loadAssetContainer(scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): AssetContainer;
  67. }
  68. export interface ISceneLoaderPluginAsync {
  69. /**
  70. * The friendly name of this plugin.
  71. */
  72. name: string;
  73. /**
  74. * The file extensions supported by this plugin.
  75. */
  76. extensions: string | ISceneLoaderPluginExtensions;
  77. /**
  78. * Import meshes into a scene.
  79. * @param meshesNames An array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  80. * @param scene The scene to import into
  81. * @param data The data to import
  82. * @param rootUrl The root url for scene and resources
  83. * @param onProgress The callback when the load progresses
  84. * @returns The loaded meshes, particle systems, and skeletons
  85. */
  86. importMeshAsync(meshesNames: any, scene: Scene, data: any, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<{ meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[] }>;
  87. /**
  88. * Load into a scene.
  89. * @param scene The scene to load into
  90. * @param data The data to import
  91. * @param rootUrl The root url for scene and resources
  92. * @param onProgress The callback when the load progresses
  93. * @returns Nothing
  94. */
  95. loadAsync(scene: Scene, data: string, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<void>;
  96. /**
  97. * The callback that returns true if the data can be directly loaded.
  98. */
  99. canDirectLoad?: (data: string) => boolean;
  100. /**
  101. * The callback that allows custom handling of the root url based on the response url.
  102. */
  103. rewriteRootURL?: (rootUrl: string, responseURL?: string) => string;
  104. /**
  105. * Load into an asset container.
  106. * @param scene The scene to load into
  107. * @param data The data to import
  108. * @param rootUrl The root url for scene and resources
  109. * @param onProgress The callback when the load progresses
  110. * @returns The loaded asset container
  111. */
  112. loadAssetContainerAsync(scene: Scene, data: string, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<AssetContainer>;
  113. }
  114. interface IRegisteredPlugin {
  115. plugin: ISceneLoaderPlugin | ISceneLoaderPluginAsync | ISceneLoaderPluginFactory;
  116. isBinary: boolean;
  117. }
  118. export class SceneLoader {
  119. // Flags
  120. private static _ForceFullSceneLoadingForIncremental = false;
  121. private static _ShowLoadingScreen = true;
  122. private static _CleanBoneMatrixWeights = false;
  123. public static get NO_LOGGING(): number {
  124. return 0;
  125. }
  126. public static get MINIMAL_LOGGING(): number {
  127. return 1;
  128. }
  129. public static get SUMMARY_LOGGING(): number {
  130. return 2;
  131. }
  132. public static get DETAILED_LOGGING(): number {
  133. return 3;
  134. }
  135. private static _loggingLevel = SceneLoader.NO_LOGGING;
  136. public static get ForceFullSceneLoadingForIncremental() {
  137. return SceneLoader._ForceFullSceneLoadingForIncremental;
  138. }
  139. public static set ForceFullSceneLoadingForIncremental(value: boolean) {
  140. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  141. }
  142. public static get ShowLoadingScreen(): boolean {
  143. return SceneLoader._ShowLoadingScreen;
  144. }
  145. public static set ShowLoadingScreen(value: boolean) {
  146. SceneLoader._ShowLoadingScreen = value;
  147. }
  148. public static get loggingLevel(): number {
  149. return SceneLoader._loggingLevel;
  150. }
  151. public static set loggingLevel(value: number) {
  152. SceneLoader._loggingLevel = value;
  153. }
  154. public static get CleanBoneMatrixWeights(): boolean {
  155. return SceneLoader._CleanBoneMatrixWeights;
  156. }
  157. public static set CleanBoneMatrixWeights(value: boolean) {
  158. SceneLoader._CleanBoneMatrixWeights = value;
  159. }
  160. // Members
  161. public static OnPluginActivatedObservable = new Observable<ISceneLoaderPlugin | ISceneLoaderPluginAsync>();
  162. private static _registeredPlugins: { [extension: string]: IRegisteredPlugin } = {};
  163. private static _getDefaultPlugin(): IRegisteredPlugin {
  164. return SceneLoader._registeredPlugins[".babylon"];
  165. }
  166. private static _getPluginForExtension(extension: string): IRegisteredPlugin {
  167. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  168. if (registeredPlugin) {
  169. return registeredPlugin;
  170. }
  171. Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  172. return SceneLoader._getDefaultPlugin();
  173. }
  174. private static _getPluginForDirectLoad(data: string): IRegisteredPlugin {
  175. for (var extension in SceneLoader._registeredPlugins) {
  176. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  177. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  178. return SceneLoader._registeredPlugins[extension];
  179. }
  180. }
  181. return SceneLoader._getDefaultPlugin();
  182. }
  183. private static _getPluginForFilename(sceneFilename: any): IRegisteredPlugin {
  184. if (sceneFilename.name) {
  185. sceneFilename = sceneFilename.name;
  186. }
  187. var queryStringPosition = sceneFilename.indexOf("?");
  188. if (queryStringPosition !== -1) {
  189. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  190. }
  191. var dotPosition = sceneFilename.lastIndexOf(".");
  192. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  193. return SceneLoader._getPluginForExtension(extension);
  194. }
  195. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  196. private static _getDirectLoad(sceneFilename: string): Nullable<string> {
  197. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  198. return sceneFilename.substr(5);
  199. }
  200. return null;
  201. }
  202. private static _loadData(rootUrl: string, sceneFilename: string, 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 {
  203. let directLoad = SceneLoader._getDirectLoad(sceneFilename);
  204. let registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  205. let plugin: ISceneLoaderPlugin | ISceneLoaderPluginAsync;
  206. if ((registeredPlugin.plugin as ISceneLoaderPluginFactory).createPlugin) {
  207. plugin = (registeredPlugin.plugin as ISceneLoaderPluginFactory).createPlugin();
  208. }
  209. else {
  210. plugin = <any>registeredPlugin.plugin;
  211. }
  212. let useArrayBuffer = registeredPlugin.isBinary;
  213. let database: Database;
  214. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  215. let dataCallback = (data: any, responseURL?: string) => {
  216. if (scene.isDisposed) {
  217. onError("Scene has been disposed");
  218. return;
  219. }
  220. scene.database = database;
  221. onSuccess(plugin, data, responseURL);
  222. };
  223. let request: Nullable<IFileRequest> = null;
  224. let pluginDisposed = false;
  225. let onDisposeObservable = (plugin as any).onDisposeObservable as Observable<ISceneLoaderPlugin | ISceneLoaderPluginAsync>;
  226. if (onDisposeObservable) {
  227. onDisposeObservable.add(() => {
  228. pluginDisposed = true;
  229. if (request) {
  230. request.abort();
  231. request = null;
  232. }
  233. onDispose();
  234. });
  235. }
  236. let manifestChecked = () => {
  237. if (pluginDisposed) {
  238. return;
  239. }
  240. let url = rootUrl + sceneFilename;
  241. request = Tools.LoadFile(url, dataCallback, onProgress ? event => {
  242. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  243. } : undefined, database, useArrayBuffer, (request, exception) => {
  244. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  245. });
  246. };
  247. if (directLoad) {
  248. dataCallback(directLoad);
  249. return plugin;
  250. }
  251. if (rootUrl.indexOf("file:") === -1) {
  252. if (scene.getEngine().enableOfflineSupport) {
  253. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  254. database = new Database(rootUrl + sceneFilename, manifestChecked);
  255. }
  256. else {
  257. manifestChecked();
  258. }
  259. }
  260. // Loading file from disk via input file or drag'n'drop
  261. else {
  262. let fileOrString = <any>sceneFilename;
  263. if (fileOrString.name) { // File
  264. request = Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  265. } else if (FilesInput.FilesToLoad[sceneFilename]) {
  266. request = Tools.ReadFile(FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  267. } else {
  268. onError("Unable to find file named " + sceneFilename);
  269. }
  270. }
  271. return plugin;
  272. }
  273. // Public functions
  274. public static GetPluginForExtension(extension: string): ISceneLoaderPlugin | ISceneLoaderPluginAsync | ISceneLoaderPluginFactory {
  275. return SceneLoader._getPluginForExtension(extension).plugin;
  276. }
  277. public static IsPluginForExtensionAvailable(extension: string): boolean {
  278. return !!SceneLoader._registeredPlugins[extension];
  279. }
  280. public static RegisterPlugin(plugin: ISceneLoaderPlugin | ISceneLoaderPluginAsync): void {
  281. if (typeof plugin.extensions === "string") {
  282. var extension = <string>plugin.extensions;
  283. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  284. plugin: plugin,
  285. isBinary: false
  286. };
  287. }
  288. else {
  289. var extensions = <ISceneLoaderPluginExtensions>plugin.extensions;
  290. Object.keys(extensions).forEach(extension => {
  291. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  292. plugin: plugin,
  293. isBinary: extensions[extension].isBinary
  294. };
  295. });
  296. }
  297. }
  298. /**
  299. * Import meshes into a scene
  300. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  301. * @param rootUrl a string that defines the root url for scene and resources
  302. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  303. * @param scene the instance of BABYLON.Scene to append to
  304. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  305. * @param onProgress a callback with a progress event for each file being loaded
  306. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  307. * @param pluginExtension the extension used to determine the plugin
  308. * @returns The loaded plugin
  309. */
  310. public static ImportMesh(meshNames: any, rootUrl: string, sceneFilename: string, scene: Scene, onSuccess: Nullable<(meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => 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> {
  311. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  312. Tools.Error("Wrong sceneFilename parameter");
  313. return null;
  314. }
  315. var loadingToken = {};
  316. scene._addPendingData(loadingToken);
  317. var disposeHandler = () => {
  318. scene._removePendingData(loadingToken);
  319. };
  320. var errorHandler = (message: string, exception?: any) => {
  321. let errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  322. if (onError) {
  323. onError(scene, errorMessage, exception);
  324. } else {
  325. Tools.Error(errorMessage);
  326. // should the exception be thrown?
  327. }
  328. disposeHandler();
  329. };
  330. var progressHandler = onProgress ? (event: SceneLoaderProgressEvent) => {
  331. try {
  332. onProgress(event);
  333. }
  334. catch (e) {
  335. errorHandler("Error in onProgress callback", e);
  336. }
  337. } : undefined;
  338. var successHandler = (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => {
  339. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  340. if (onSuccess) {
  341. try {
  342. onSuccess(meshes, particleSystems, skeletons);
  343. }
  344. catch (e) {
  345. errorHandler("Error in onSuccess callback", e);
  346. }
  347. }
  348. scene._removePendingData(loadingToken);
  349. };
  350. return SceneLoader._loadData(rootUrl, sceneFilename, scene, (plugin, data, responseURL) => {
  351. if (plugin.rewriteRootURL) {
  352. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  353. }
  354. if (sceneFilename === "") {
  355. if (sceneFilename === "") {
  356. rootUrl = Tools.GetFolderPath(rootUrl, true);
  357. }
  358. }
  359. if ((<any>plugin).importMesh) {
  360. var syncedPlugin = <ISceneLoaderPlugin>plugin;
  361. var meshes = new Array<AbstractMesh>();
  362. var particleSystems = new Array<ParticleSystem>();
  363. var skeletons = new Array<Skeleton>();
  364. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  365. return;
  366. }
  367. scene.loadingPluginName = plugin.name;
  368. successHandler(meshes, particleSystems, skeletons);
  369. }
  370. else {
  371. var asyncedPlugin = <ISceneLoaderPluginAsync>plugin;
  372. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(result => {
  373. scene.loadingPluginName = plugin.name;
  374. successHandler(result.meshes, result.particleSystems, result.skeletons);
  375. }).catch(error => {
  376. errorHandler(error.message, error);
  377. });
  378. }
  379. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  380. }
  381. /**
  382. * Import meshes into a scene
  383. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  384. * @param rootUrl a string that defines the root url for scene and resources
  385. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  386. * @param scene the instance of BABYLON.Scene to append to
  387. * @param onProgress a callback with a progress event for each file being loaded
  388. * @param pluginExtension the extension used to determine the plugin
  389. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  390. */
  391. public static ImportMeshAsync(meshNames: any, rootUrl: string, sceneFilename: string, scene: Scene, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, pluginExtension: Nullable<string> = null): Promise<{ meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[] }> {
  392. return new Promise((resolve, reject) => {
  393. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, (meshes, particleSystems, skeletons) => {
  394. resolve({
  395. meshes: meshes,
  396. particleSystems: particleSystems,
  397. skeletons: skeletons
  398. });
  399. }, onProgress, (scene, message, exception) => {
  400. reject(exception || new Error(message));
  401. });
  402. });
  403. }
  404. /**
  405. * Load a scene
  406. * @param rootUrl a string that defines the root url for scene and resources
  407. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  408. * @param engine is the instance of BABYLON.Engine to use to create the scene
  409. * @param onSuccess a callback with the scene when import succeeds
  410. * @param onProgress a callback with a progress event for each file being loaded
  411. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  412. * @param pluginExtension the extension used to determine the plugin
  413. * @returns The loaded plugin
  414. */
  415. public static Load(rootUrl: string, sceneFilename: any, 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> {
  416. return SceneLoader.Append(rootUrl, sceneFilename, new Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  417. }
  418. /**
  419. * Load a scene
  420. * @param rootUrl a string that defines the root url for scene and resources
  421. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  422. * @param engine is the instance of BABYLON.Engine to use to create the scene
  423. * @param onProgress a callback with a progress event for each file being loaded
  424. * @param pluginExtension the extension used to determine the plugin
  425. * @returns The loaded scene
  426. */
  427. public static LoadAsync(rootUrl: string, sceneFilename: any, engine: Engine, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, pluginExtension: Nullable<string> = null): Promise<Scene> {
  428. return new Promise((resolve, reject) => {
  429. SceneLoader.Load(rootUrl, sceneFilename, engine, scene => {
  430. resolve(scene);
  431. }, onProgress, (scene, message, exception) => {
  432. reject(exception || new Error(message));
  433. }, pluginExtension);
  434. });
  435. }
  436. /**
  437. * Append a scene
  438. * @param rootUrl a string that defines the root url for scene and resources
  439. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  440. * @param scene is the instance of BABYLON.Scene to append to
  441. * @param onSuccess a callback with the scene when import succeeds
  442. * @param onProgress a callback with a progress event for each file being loaded
  443. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  444. * @param pluginExtension the extension used to determine the plugin
  445. * @returns The loaded plugin
  446. */
  447. public static Append(rootUrl: string, sceneFilename: any, scene: Scene, 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> {
  448. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  449. Tools.Error("Wrong sceneFilename parameter");
  450. return null;
  451. }
  452. if (SceneLoader.ShowLoadingScreen) {
  453. scene.getEngine().displayLoadingUI();
  454. }
  455. var loadingToken = {};
  456. scene._addPendingData(loadingToken);
  457. var disposeHandler = () => {
  458. scene._removePendingData(loadingToken);
  459. scene.getEngine().hideLoadingUI();
  460. };
  461. var errorHandler = (message: Nullable<string>, exception?: any) => {
  462. let errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  463. if (onError) {
  464. onError(scene, errorMessage, exception);
  465. } else {
  466. Tools.Error(errorMessage);
  467. // should the exception be thrown?
  468. }
  469. disposeHandler();
  470. };
  471. var progressHandler = onProgress ? (event: SceneLoaderProgressEvent) => {
  472. try {
  473. onProgress(event);
  474. }
  475. catch (e) {
  476. errorHandler("Error in onProgress callback", e);
  477. }
  478. } : undefined;
  479. var successHandler = () => {
  480. if (onSuccess) {
  481. try {
  482. onSuccess(scene);
  483. }
  484. catch (e) {
  485. errorHandler("Error in onSuccess callback", e);
  486. }
  487. }
  488. scene._removePendingData(loadingToken);
  489. };
  490. return SceneLoader._loadData(rootUrl, sceneFilename, scene, (plugin, data, responseURL) => {
  491. if (sceneFilename === "") {
  492. rootUrl = Tools.GetFolderPath(rootUrl, true);
  493. }
  494. if ((<any>plugin).load) {
  495. var syncedPlugin = <ISceneLoaderPlugin>plugin;
  496. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  497. return;
  498. }
  499. scene.loadingPluginName = plugin.name;
  500. successHandler();
  501. } else {
  502. var asyncedPlugin = <ISceneLoaderPluginAsync>plugin;
  503. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(() => {
  504. scene.loadingPluginName = plugin.name;
  505. successHandler();
  506. }).catch(error => {
  507. errorHandler(error.message, error);
  508. });
  509. }
  510. if (SceneLoader.ShowLoadingScreen) {
  511. scene.executeWhenReady(() => {
  512. scene.getEngine().hideLoadingUI();
  513. });
  514. }
  515. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  516. }
  517. /**
  518. * Append a scene
  519. * @param rootUrl a string that defines the root url for scene and resources
  520. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  521. * @param scene is the instance of BABYLON.Scene to append to
  522. * @param onProgress a callback with a progress event for each file being loaded
  523. * @param pluginExtension the extension used to determine the plugin
  524. * @returns The given scene
  525. */
  526. public static AppendAsync(rootUrl: string, sceneFilename: any, scene: Scene, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, pluginExtension: Nullable<string> = null): Promise<Scene> {
  527. return new Promise((resolve, reject) => {
  528. SceneLoader.Append(rootUrl, sceneFilename, scene, scene => {
  529. resolve(scene);
  530. }, onProgress, (scene, message, exception) => {
  531. reject(exception || new Error(message));
  532. }, pluginExtension);
  533. });
  534. }
  535. /**
  536. * Load a scene into an asset container
  537. * @param rootUrl a string that defines the root url for scene and resources
  538. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  539. * @param scene is the instance of BABYLON.Scene to append to
  540. * @param onSuccess a callback with the scene when import succeeds
  541. * @param onProgress a callback with a progress event for each file being loaded
  542. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  543. * @param pluginExtension the extension used to determine the plugin
  544. * @returns The loaded plugin
  545. */
  546. public static LoadAssetContainer(
  547. rootUrl: string,
  548. sceneFilename: any,
  549. scene: Scene,
  550. onSuccess: Nullable<(assets: AssetContainer) => void> = null,
  551. onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null,
  552. onError: Nullable<(scene: Scene, message: string, exception?: any) => void> = null,
  553. pluginExtension: Nullable<string> = null
  554. ): Nullable<ISceneLoaderPlugin | ISceneLoaderPluginAsync> {
  555. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  556. Tools.Error("Wrong sceneFilename parameter");
  557. return null;
  558. }
  559. var loadingToken = {};
  560. scene._addPendingData(loadingToken);
  561. var disposeHandler = () => {
  562. scene._removePendingData(loadingToken);
  563. };
  564. var errorHandler = (message: Nullable<string>, exception?: any) => {
  565. let errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  566. if (onError) {
  567. onError(scene, errorMessage, exception);
  568. } else {
  569. Tools.Error(errorMessage);
  570. // should the exception be thrown?
  571. }
  572. disposeHandler();
  573. };
  574. var progressHandler = onProgress ? (event: SceneLoaderProgressEvent) => {
  575. try {
  576. onProgress(event);
  577. }
  578. catch (e) {
  579. errorHandler("Error in onProgress callback", e);
  580. }
  581. } : undefined;
  582. var successHandler = (assets: AssetContainer) => {
  583. if (onSuccess) {
  584. try {
  585. onSuccess(assets);
  586. }
  587. catch (e) {
  588. errorHandler("Error in onSuccess callback", e);
  589. }
  590. }
  591. scene._removePendingData(loadingToken);
  592. };
  593. return SceneLoader._loadData(rootUrl, sceneFilename, scene, (plugin, data, responseURL) => {
  594. if ((<any>plugin).loadAssetContainer) {
  595. var syncedPlugin = <ISceneLoaderPlugin>plugin;
  596. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  597. if (!assetContainer) {
  598. return;
  599. }
  600. scene.loadingPluginName = plugin.name;
  601. successHandler(assetContainer);
  602. } else if ((<any>plugin).loadAssetContainerAsync) {
  603. var asyncedPlugin = <ISceneLoaderPluginAsync>plugin;
  604. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(assetContainer => {
  605. scene.loadingPluginName = plugin.name;
  606. successHandler(assetContainer);
  607. }).catch(error => {
  608. errorHandler(error.message, error);
  609. });
  610. } else {
  611. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")
  612. }
  613. if (SceneLoader.ShowLoadingScreen) {
  614. scene.executeWhenReady(() => {
  615. scene.getEngine().hideLoadingUI();
  616. });
  617. }
  618. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  619. }
  620. /**
  621. * Load a scene into an asset container
  622. * @param rootUrl a string that defines the root url for scene and resources
  623. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  624. * @param scene is the instance of BABYLON.Scene to append to
  625. * @param onProgress a callback with a progress event for each file being loaded
  626. * @param pluginExtension the extension used to determine the plugin
  627. * @returns The loaded asset container
  628. */
  629. public static LoadAssetContainerAsync(rootUrl: string, sceneFilename: any, scene: Scene, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, pluginExtension: Nullable<string> = null): Promise<AssetContainer> {
  630. return new Promise((resolve, reject) => {
  631. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, assetContainer => {
  632. resolve(assetContainer);
  633. }, onProgress, (scene, message, exception) => {
  634. reject(exception || new Error(message));
  635. }, pluginExtension);
  636. });
  637. }
  638. };
  639. }