filesInput.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. import { Engine } from "../Engines/engine";
  2. import { Scene } from "../scene";
  3. import { ISceneLoaderProgressEvent, SceneLoader } from "../Loading/sceneLoader";
  4. import { Logger } from "../Misc/logger";
  5. import { FilesInputStore } from "./filesInputStore";
  6. /**
  7. * Class used to help managing file picking and drag'n'drop
  8. */
  9. export class FilesInput {
  10. /**
  11. * List of files ready to be loaded
  12. */
  13. public static get FilesToLoad() {
  14. return FilesInputStore.FilesToLoad;
  15. }
  16. /**
  17. * Callback called when a file is processed
  18. */
  19. public onProcessFileCallback: (file: File, name: string, extension: string) => true = () => { return true; };
  20. private _engine: Engine;
  21. private _currentScene: Scene;
  22. private _sceneLoadedCallback: (sceneFile: File, scene: Scene) => void;
  23. private _progressCallback: (progress: ISceneLoaderProgressEvent) => void;
  24. private _additionalRenderLoopLogicCallback: () => void;
  25. private _textureLoadingCallback: (remaining: number) => void;
  26. private _startingProcessingFilesCallback: (files?: File[]) => void;
  27. private _onReloadCallback: (sceneFile: File) => void;
  28. private _errorCallback: (sceneFile: File, scene: Scene, message: string) => void;
  29. private _elementToMonitor: HTMLElement;
  30. private _sceneFileToLoad: File;
  31. private _filesToLoad: File[];
  32. /**
  33. * Creates a new FilesInput
  34. * @param engine defines the rendering engine
  35. * @param scene defines the hosting scene
  36. * @param sceneLoadedCallback callback called when scene is loaded
  37. * @param progressCallback callback called to track progress
  38. * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop
  39. * @param textureLoadingCallback callback called when a texture is loading
  40. * @param startingProcessingFilesCallback callback called when the system is about to process all files
  41. * @param onReloadCallback callback called when a reload is requested
  42. * @param errorCallback callback call if an error occurs
  43. */
  44. constructor(engine: Engine, scene: Scene, sceneLoadedCallback: (sceneFile: File, scene: Scene) => void, progressCallback: (progress: ISceneLoaderProgressEvent) => void, additionalRenderLoopLogicCallback: () => void,
  45. textureLoadingCallback: (remaining: number) => void, startingProcessingFilesCallback: (files?: File[]) => void, onReloadCallback: (sceneFile: File) => void, errorCallback: (sceneFile: File, scene: Scene, message: string) => void) {
  46. this._engine = engine;
  47. this._currentScene = scene;
  48. this._sceneLoadedCallback = sceneLoadedCallback;
  49. this._progressCallback = progressCallback;
  50. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  51. this._textureLoadingCallback = textureLoadingCallback;
  52. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  53. this._onReloadCallback = onReloadCallback;
  54. this._errorCallback = errorCallback;
  55. }
  56. private _dragEnterHandler: (e: any) => void;
  57. private _dragOverHandler: (e: any) => void;
  58. private _dropHandler: (e: any) => void;
  59. /**
  60. * Calls this function to listen to drag'n'drop events on a specific DOM element
  61. * @param elementToMonitor defines the DOM element to track
  62. */
  63. public monitorElementForDragNDrop(elementToMonitor: HTMLElement): void {
  64. if (elementToMonitor) {
  65. this._elementToMonitor = elementToMonitor;
  66. this._dragEnterHandler = (e) => { this.drag(e); };
  67. this._dragOverHandler = (e) => { this.drag(e); };
  68. this._dropHandler = (e) => { this.drop(e); };
  69. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  70. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  71. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  72. }
  73. }
  74. /**
  75. * Release all associated resources
  76. */
  77. public dispose() {
  78. if (!this._elementToMonitor) {
  79. return;
  80. }
  81. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  82. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  83. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  84. }
  85. private renderFunction(): void {
  86. if (this._additionalRenderLoopLogicCallback) {
  87. this._additionalRenderLoopLogicCallback();
  88. }
  89. if (this._currentScene) {
  90. if (this._textureLoadingCallback) {
  91. var remaining = this._currentScene.getWaitingItemsCount();
  92. if (remaining > 0) {
  93. this._textureLoadingCallback(remaining);
  94. }
  95. }
  96. this._currentScene.render();
  97. }
  98. }
  99. private drag(e: DragEvent): void {
  100. e.stopPropagation();
  101. e.preventDefault();
  102. }
  103. private drop(eventDrop: DragEvent): void {
  104. eventDrop.stopPropagation();
  105. eventDrop.preventDefault();
  106. this.loadFiles(eventDrop);
  107. }
  108. private _traverseFolder(folder: any, files: Array<any>, remaining: { count: number }, callback: () => void) {
  109. var reader = folder.createReader();
  110. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  111. reader.readEntries((entries: any) => {
  112. remaining.count += entries.length;
  113. for (let entry of entries) {
  114. if (entry.isFile) {
  115. entry.file((file: any) => {
  116. file.correctName = relativePath + file.name;
  117. files.push(file);
  118. if (--remaining.count === 0) {
  119. callback();
  120. }
  121. });
  122. }
  123. else if (entry.isDirectory) {
  124. this._traverseFolder(entry, files, remaining, callback);
  125. }
  126. }
  127. if (--remaining.count) {
  128. callback();
  129. }
  130. });
  131. }
  132. private _processFiles(files: Array<any>): void {
  133. for (var i = 0; i < files.length; i++) {
  134. var name = files[i].correctName.toLowerCase();
  135. var extension = name.split('.').pop();
  136. if (!this.onProcessFileCallback(files[i], name, extension)) {
  137. continue;
  138. }
  139. if (SceneLoader.IsPluginForExtensionAvailable("." + extension)) {
  140. this._sceneFileToLoad = files[i];
  141. }
  142. FilesInput.FilesToLoad[name] = files[i];
  143. }
  144. }
  145. /**
  146. * Load files from a drop event
  147. * @param event defines the drop event to use as source
  148. */
  149. public loadFiles(event: any): void {
  150. // Handling data transfer via drag'n'drop
  151. if (event && event.dataTransfer && event.dataTransfer.files) {
  152. this._filesToLoad = event.dataTransfer.files;
  153. }
  154. // Handling files from input files
  155. if (event && event.target && event.target.files) {
  156. this._filesToLoad = event.target.files;
  157. }
  158. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  159. return;
  160. }
  161. if (this._startingProcessingFilesCallback) {
  162. this._startingProcessingFilesCallback(this._filesToLoad);
  163. }
  164. if (this._filesToLoad && this._filesToLoad.length > 0) {
  165. let files = new Array<File>();
  166. let folders = [];
  167. var items = event.dataTransfer ? event.dataTransfer.items : null;
  168. for (var i = 0; i < this._filesToLoad.length; i++) {
  169. let fileToLoad: any = this._filesToLoad[i];
  170. let name = fileToLoad.name.toLowerCase();
  171. let entry;
  172. fileToLoad.correctName = name;
  173. if (items) {
  174. let item = items[i];
  175. if (item.getAsEntry) {
  176. entry = item.getAsEntry();
  177. } else if (item.webkitGetAsEntry) {
  178. entry = item.webkitGetAsEntry();
  179. }
  180. }
  181. if (!entry) {
  182. files.push(fileToLoad);
  183. } else {
  184. if (entry.isDirectory) {
  185. folders.push(entry);
  186. } else {
  187. files.push(fileToLoad);
  188. }
  189. }
  190. }
  191. if (folders.length === 0) {
  192. this._processFiles(files);
  193. this._processReload();
  194. } else {
  195. var remaining = { count: folders.length };
  196. for (var folder of folders) {
  197. this._traverseFolder(folder, files, remaining, () => {
  198. this._processFiles(files);
  199. if (remaining.count === 0) {
  200. this._processReload();
  201. }
  202. });
  203. }
  204. }
  205. }
  206. }
  207. private _processReload() {
  208. if (this._onReloadCallback) {
  209. this._onReloadCallback(this._sceneFileToLoad);
  210. }
  211. else {
  212. this.reload();
  213. }
  214. }
  215. /**
  216. * Reload the current scene from the loaded files
  217. */
  218. public reload() {
  219. // If a scene file has been provided
  220. if (this._sceneFileToLoad) {
  221. if (this._currentScene) {
  222. if (Logger.errorsCount > 0) {
  223. Logger.ClearLogCache();
  224. }
  225. this._engine.stopRenderLoop();
  226. }
  227. SceneLoader.ShowLoadingScreen = false;
  228. this._engine.displayLoadingUI();
  229. SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, (progress) => {
  230. if (this._progressCallback) {
  231. this._progressCallback(progress);
  232. }
  233. }).then((scene) => {
  234. if (this._currentScene) {
  235. this._currentScene.dispose();
  236. }
  237. this._currentScene = scene;
  238. if (this._sceneLoadedCallback) {
  239. this._sceneLoadedCallback(this._sceneFileToLoad, this._currentScene);
  240. }
  241. // Wait for textures and shaders to be ready
  242. this._currentScene.executeWhenReady(() => {
  243. this._engine.hideLoadingUI();
  244. this._engine.runRenderLoop(() => {
  245. this.renderFunction();
  246. });
  247. });
  248. }).catch((error) => {
  249. this._engine.hideLoadingUI();
  250. if (this._errorCallback) {
  251. this._errorCallback(this._sceneFileToLoad, this._currentScene, error.message);
  252. }
  253. });
  254. }
  255. else {
  256. Logger.Error("Please provide a valid .babylon file.");
  257. }
  258. }
  259. }