EditorApplication.cs 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Runtime.CompilerServices;
  6. using System.IO;
  7. using bs;
  8. namespace bs.Editor
  9. {
  10. /** @addtogroup Editor-General
  11. * @{
  12. */
  13. /// <summary>
  14. /// Available tools in the scene view.
  15. /// </summary>
  16. public enum SceneViewTool
  17. {
  18. View,
  19. Move,
  20. Rotate,
  21. Scale
  22. }
  23. /// <summary>
  24. /// Pivot mode used by the scene view tools.
  25. /// </summary>
  26. public enum HandlePivotMode
  27. {
  28. Center,
  29. Pivot
  30. }
  31. /// <summary>
  32. /// Coordinate mode used by the scene view tools.
  33. /// </summary>
  34. public enum HandleCoordinateMode
  35. {
  36. Local,
  37. World
  38. }
  39. /// <summary>
  40. /// Manages various generic and global settings relating to the editor.
  41. /// </summary>
  42. public class EditorApplication
  43. {
  44. internal const string CutBinding = "Cut";
  45. internal const string CopyBinding = "Copy";
  46. internal const string RenameBinding = "Rename";
  47. internal const string DuplicateBinding = "Duplicate";
  48. internal const string DeleteBinding = "Delete";
  49. internal const string PasteBinding = "Paste";
  50. internal const string EditorSceneDataPrefix = "__EditorSceneData";
  51. /// <summary>
  52. /// Determines the active tool shown in the scene view.
  53. /// </summary>
  54. public static SceneViewTool ActiveSceneTool
  55. {
  56. get { return EditorSettings.ActiveSceneTool; }
  57. set { EditorSettings.ActiveSceneTool = value; }
  58. }
  59. /// <summary>
  60. /// Determines the coordinate mode used by the tools in the scene view.
  61. /// </summary>
  62. public static HandleCoordinateMode ActiveCoordinateMode
  63. {
  64. get { return EditorSettings.ActiveCoordinateMode; }
  65. set { EditorSettings.ActiveCoordinateMode = value; }
  66. }
  67. /// <summary>
  68. /// Determines the pivot mode used by the tools in the scene view.
  69. /// </summary>
  70. public static HandlePivotMode ActivePivotMode
  71. {
  72. get { return EditorSettings.ActivePivotMode; }
  73. set { EditorSettings.ActivePivotMode = value; }
  74. }
  75. /// <summary>
  76. /// Camera used for rendering the scene view.
  77. /// </summary>
  78. public static Camera SceneViewCamera
  79. {
  80. get
  81. {
  82. SceneWindow sceneWindow = EditorWindow.GetWindow<SceneWindow>();
  83. return sceneWindow?.Camera.Camera;
  84. }
  85. }
  86. /// <summary>
  87. /// Absolute path to the folder containing the currently open project.
  88. /// </summary>
  89. public static string ProjectPath { get { return Internal_GetProjectPath(); } }
  90. /// <summary>
  91. /// Name of the currently open project.
  92. /// </summary>
  93. public static string ProjectName { get { return Internal_GetProjectName(); } }
  94. /// <summary>
  95. /// Checks is any project currently loaded.
  96. /// </summary>
  97. public static bool IsProjectLoaded { get { return Internal_GetProjectLoaded(); } }
  98. /// <summary>
  99. /// Checks whether the editor currently has focus.
  100. /// </summary>
  101. public static bool HasFocus
  102. {
  103. get { return Internal_HasFocus(); }
  104. }
  105. /// <summary>
  106. /// Returns true if the editor is waiting on a scene to be asynchronously loaded.
  107. /// </summary>
  108. public static bool IsSceneLoading
  109. {
  110. get
  111. {
  112. if (lastLoadedScene != null)
  113. return !lastLoadedScene.IsLoaded;
  114. return false;
  115. }
  116. }
  117. /// <summary>
  118. /// Returns the load progress of the scene that's being asynchronously loaded
  119. /// </summary>
  120. public static float SceneLoadProgress
  121. {
  122. get
  123. {
  124. if (lastLoadedScene != null)
  125. return Resources.GetLoadProgress(lastLoadedScene);
  126. return 0.0f;
  127. }
  128. }
  129. /// <summary>
  130. /// Triggered right before the project is being saved.
  131. /// </summary>
  132. public static event Action OnProjectSave;
  133. /// <summary>
  134. /// Render target that the main camera in the scene (if any) will render its view to. This generally means the main
  135. /// game window when running standalone, or the Game viewport when running in editor.
  136. /// </summary>
  137. internal static RenderTarget MainRenderTarget
  138. {
  139. set
  140. {
  141. IntPtr rtPtr = IntPtr.Zero;
  142. if (value != null)
  143. rtPtr = value.GetCachedPtr();
  144. Internal_SetMainRenderTarget(rtPtr);
  145. }
  146. }
  147. /// <summary>
  148. /// Returns an object that can be used for storing data that persists throughout the entire editor session.
  149. /// </summary>
  150. internal static EditorPersistentData PersistentData => persistentData;
  151. /// <summary>
  152. /// Editor specific data for the currently loaded scene. Can be null if no scene is loaded.
  153. /// </summary>
  154. internal static EditorSceneData EditorSceneData
  155. {
  156. get => PersistentData.editorSceneData;
  157. private set => PersistentData.editorSceneData = value;
  158. }
  159. /// <summary>
  160. /// Returns the path where the script compiler is located at.
  161. /// </summary>
  162. internal static string CompilerPath { get { return Internal_GetCompilerPath(); } }
  163. /// <summary>
  164. /// Returns the absolute path to the executable capable of executing managed assemblies.
  165. /// </summary>
  166. internal static string MonoExecPath { get { return Internal_GetMonoExecPath(); } }
  167. /// <summary>
  168. /// Returns the path to the folder where the custom script assemblies are located at.
  169. /// </summary>
  170. internal static string ScriptAssemblyPath { get { return Internal_GetScriptAssemblyPath(); } }
  171. /// <summary>
  172. /// Returns the path to the folder where the .NET framework assemblies are located at.
  173. /// </summary>
  174. internal static string FrameworkAssemblyPath { get { return Internal_GetFrameworkAssemblyPath(); } }
  175. /// <summary>
  176. /// Name of the builtin assembly containing engine specific types.
  177. /// </summary>
  178. internal static string EngineAssemblyName { get { return Internal_GetEngineAssemblyName(); } }
  179. /// <summary>
  180. /// Name of the builtin assembly containing editor specific types.
  181. /// </summary>
  182. internal static string EditorAssemblyName { get { return Internal_GetEditorAssemblyName(); } }
  183. /// <summary>
  184. /// Name of the custom assembly compiled from non-editor scripts within the project.
  185. /// </summary>
  186. internal static string ScriptGameAssemblyName { get { return Internal_GetScriptGameAssemblyName(); } }
  187. /// <summary>
  188. /// Name of the custom assembly compiled from editor scripts within the project.
  189. /// </summary>
  190. internal static string ScriptEditorAssemblyName { get { return Internal_GetScriptEditorAssemblyName(); } }
  191. /// <summary>
  192. /// Returns the path to the folder where the builtin release script assemblies are located at.
  193. /// </summary>
  194. internal static string BuiltinReleaseAssemblyPath { get { return Internal_GetBuiltinReleaseAssemblyPath(); } }
  195. /// <summary>
  196. /// Returns the path to the folder where the builtin debug script assemblies are located at.
  197. /// </summary>
  198. internal static string BuiltinDebugAssemblyPath { get { return Internal_GetBuiltinDebugAssemblyPath(); } }
  199. internal static VirtualButton CutKey = new VirtualButton(CutBinding);
  200. internal static VirtualButton CopyKey = new VirtualButton(CopyBinding);
  201. internal static VirtualButton PasteKey = new VirtualButton(PasteBinding);
  202. internal static VirtualButton RenameKey = new VirtualButton(RenameBinding);
  203. internal static VirtualButton DuplicateKey = new VirtualButton(DuplicateBinding);
  204. internal static VirtualButton DeleteKey = new VirtualButton(DeleteBinding);
  205. private static FolderMonitor monitor;
  206. private static ScriptCodeManager codeManager;
  207. private static RRef<Prefab> lastLoadedScene;
  208. private static bool sceneDirty;
  209. private static bool unitTestsExecuted;
  210. private static EditorPersistentData persistentData;
  211. private static bool delayUnloadProject;
  212. private static Action delayUnloadCallback;
  213. #pragma warning disable 0414
  214. private static EditorApplication instance;
  215. #pragma warning restore 0414
  216. /// <summary>
  217. /// Constructs a new editor application. Called at editor start-up by the runtime, and any time assembly refresh
  218. /// occurs.
  219. /// </summary>
  220. internal EditorApplication()
  221. {
  222. instance = this;
  223. const string soName = "EditorPersistentData";
  224. SceneObject so = Scene.Root.FindChild(soName);
  225. if (so == null)
  226. so = new SceneObject(soName, true);
  227. persistentData = so.GetComponent<EditorPersistentData>();
  228. if (persistentData == null)
  229. persistentData = so.AddComponent<EditorPersistentData>();
  230. codeManager = new ScriptCodeManager();
  231. Scene.OnSceneLoad += OnSceneLoad;
  232. Scene.OnSceneUnload += OnSceneUnload;
  233. PlayInEditor.OnPlay += () =>
  234. {
  235. if (EditorSettings.GetBool(LogWindow.CLEAR_ON_PLAY_KEY, true))
  236. {
  237. Debug.Clear();
  238. LogWindow log = EditorWindow.GetWindow<LogWindow>();
  239. if (log != null)
  240. log.Refresh();
  241. }
  242. ToggleToolbarItem("Play", true);
  243. };
  244. PlayInEditor.OnStopped += () => ToggleToolbarItem("Play", false);
  245. PlayInEditor.OnPaused += () => ToggleToolbarItem("Pause", true);
  246. PlayInEditor.OnUnpaused += () => ToggleToolbarItem("Pause", false);
  247. // Register controls
  248. InputConfiguration inputConfig = VirtualInput.KeyConfig;
  249. inputConfig.RegisterButton(SceneCamera.MoveForwardBinding, ButtonCode.W);
  250. inputConfig.RegisterButton(SceneCamera.MoveBackBinding, ButtonCode.S);
  251. inputConfig.RegisterButton(SceneCamera.MoveLeftBinding, ButtonCode.A);
  252. inputConfig.RegisterButton(SceneCamera.MoveRightBinding, ButtonCode.D);
  253. inputConfig.RegisterButton(SceneCamera.MoveUpBinding, ButtonCode.E);
  254. inputConfig.RegisterButton(SceneCamera.MoveDownBinding, ButtonCode.Q);
  255. inputConfig.RegisterButton(SceneCamera.MoveForwardBinding, ButtonCode.Up);
  256. inputConfig.RegisterButton(SceneCamera.MoveBackBinding, ButtonCode.Down);
  257. inputConfig.RegisterButton(SceneCamera.MoveLeftBinding, ButtonCode.Left);
  258. inputConfig.RegisterButton(SceneCamera.MoveRightBinding, ButtonCode.Right);
  259. inputConfig.RegisterButton(SceneCamera.FastMoveBinding, ButtonCode.LeftShift);
  260. inputConfig.RegisterButton(SceneCamera.RotateBinding, ButtonCode.MouseRight);
  261. inputConfig.RegisterButton(SceneCamera.PanBinding, ButtonCode.MouseMiddle);
  262. inputConfig.RegisterAxis(SceneCamera.HorizontalAxisBinding, InputAxis.MouseX);
  263. inputConfig.RegisterAxis(SceneCamera.VerticalAxisBinding, InputAxis.MouseY);
  264. inputConfig.RegisterAxis(SceneCamera.ScrollAxisBinding, InputAxis.MouseZ);
  265. inputConfig.RegisterButton(SceneWindow.ToggleProfilerOverlayBinding, ButtonCode.P, ButtonModifier.CtrlAlt);
  266. inputConfig.RegisterButton(SceneWindow.ViewToolBinding, ButtonCode.Q);
  267. inputConfig.RegisterButton(SceneWindow.FrameBinding, ButtonCode.F);
  268. inputConfig.RegisterButton(SceneWindow.MoveToolBinding, ButtonCode.W);
  269. inputConfig.RegisterButton(SceneWindow.RotateToolBinding, ButtonCode.E);
  270. inputConfig.RegisterButton(SceneWindow.ScaleToolBinding, ButtonCode.R);
  271. inputConfig.RegisterButton(CutBinding, ButtonCode.X, ButtonModifier.Ctrl);
  272. inputConfig.RegisterButton(CopyBinding, ButtonCode.C, ButtonModifier.Ctrl);
  273. inputConfig.RegisterButton(PasteBinding, ButtonCode.V, ButtonModifier.Ctrl);
  274. inputConfig.RegisterButton(DuplicateBinding, ButtonCode.D, ButtonModifier.Ctrl);
  275. inputConfig.RegisterButton(DeleteBinding, ButtonCode.Delete);
  276. inputConfig.RegisterButton(RenameBinding, ButtonCode.F2);
  277. if (IsProjectLoaded)
  278. {
  279. monitor = new FolderMonitor(ProjectLibrary.ResourceFolder);
  280. monitor.OnAdded += OnAssetModified;
  281. monitor.OnRemoved += OnAssetModified;
  282. monitor.OnModified += OnAssetModified;
  283. }
  284. }
  285. /// <summary>
  286. /// Updates <see cref="EditorSceneData"/> with the current state of the active scene.
  287. /// </summary>
  288. internal static void UpdateEditorSceneData()
  289. {
  290. if (EditorSceneData == null)
  291. EditorSceneData = EditorSceneData.FromScene(Scene.Root);
  292. else
  293. EditorSceneData.UpdateFromScene(Scene.Root);
  294. HierarchyWindow hierarcyWindow = EditorWindow.GetWindow<HierarchyWindow>();
  295. hierarcyWindow?.SaveHierarchyState(EditorSceneData);
  296. }
  297. /// <summary>
  298. /// Triggered when the scene has been loaded.
  299. /// </summary>
  300. /// <param name="uuid">UUID of the loaded scene.</param>
  301. private static void OnSceneUnload(UUID uuid)
  302. {
  303. UpdateEditorSceneData();
  304. string key = EditorSceneDataPrefix + uuid;
  305. ProjectSettings.SetObject(key, EditorSceneData);
  306. }
  307. /// <summary>
  308. /// Triggered when a scene is about to be unloaded.
  309. /// </summary>
  310. /// <param name="uuid">UUID of the scene to be unloaded.</param>
  311. private static void OnSceneLoad(UUID uuid)
  312. {
  313. string key = EditorSceneDataPrefix + uuid;
  314. EditorSceneData = ProjectSettings.GetObject<EditorSceneData>(key);
  315. if (EditorSceneData == null)
  316. EditorSceneData = EditorSceneData.FromScene(Scene.Root);
  317. }
  318. /// <summary>
  319. /// Triggered when the folder monitor detects an asset in the monitored folder was modified.
  320. /// </summary>
  321. /// <param name="path">Path to the modified file or folder.</param>
  322. private static void OnAssetModified(string path)
  323. {
  324. ProjectLibrary.Refresh(path);
  325. }
  326. /// <summary>
  327. /// Called every frame by the runtime.
  328. /// </summary>
  329. internal void OnEditorUpdate()
  330. {
  331. // Update managers
  332. ProjectLibrary.Update();
  333. codeManager.Update();
  334. if (delayUnloadProject)
  335. {
  336. delayUnloadProject = false;
  337. UnloadProject();
  338. delayUnloadCallback?.Invoke();
  339. delayUnloadCallback = null;
  340. }
  341. }
  342. /// <summary>
  343. /// Manually triggers a global shortcut.
  344. /// </summary>
  345. /// <param name="btn">Button for the shortcut. If this doesn't correspond to any shortcut, it is ignored.</param>
  346. internal static void TriggerGlobalShortcut(VirtualButton btn)
  347. {
  348. IGlobalShortcuts window = null;
  349. if (btn != PasteKey)
  350. {
  351. // The system ensures elsewhere that only either a resource or a scene object is selected, but not both
  352. if (Selection.ResourcePaths.Length > 0)
  353. {
  354. window = EditorWindow.GetWindow<LibraryWindow>();
  355. }
  356. else if (Selection.SceneObjects.Length > 0)
  357. {
  358. window = EditorWindow.GetWindow<HierarchyWindow>();
  359. if (window == null)
  360. window = EditorWindow.GetWindow<SceneWindow>();
  361. }
  362. if (window != null)
  363. {
  364. if (btn == CopyKey)
  365. window.OnCopyPressed();
  366. else if (btn == CutKey)
  367. window.OnCutPressed();
  368. else if (btn == PasteKey)
  369. window.OnPastePressed();
  370. else if (btn == DuplicateKey)
  371. window.OnDuplicatePressed();
  372. else if (btn == RenameKey)
  373. window.OnRenamePressed();
  374. else if (btn == DeleteKey)
  375. window.OnDeletePressed();
  376. }
  377. }
  378. else
  379. {
  380. HierarchyWindow hierarchy = EditorWindow.GetWindow<HierarchyWindow>();
  381. if (hierarchy != null && hierarchy.HasFocus)
  382. window = hierarchy;
  383. else
  384. {
  385. LibraryWindow library = EditorWindow.GetWindow<LibraryWindow>();
  386. if (library != null && library.HasFocus)
  387. window = library;
  388. }
  389. if (window != null)
  390. window.OnPastePressed();
  391. }
  392. }
  393. /// <summary>
  394. /// Creates a new empty scene.
  395. /// </summary>
  396. [MenuItem("File/New Scene", 10051, true)]
  397. private static void NewScene()
  398. {
  399. LoadScene(null);
  400. }
  401. /// <summary>
  402. /// Opens a dialog that allows the user to select a new prefab to load as the current scene. If current scene
  403. /// is modified the user is offered a chance to save it.
  404. /// </summary>
  405. [MenuItem("File/Open Scene", ButtonModifier.Ctrl, ButtonCode.L, 10050)]
  406. private static void LoadScene()
  407. {
  408. string[] scenePaths;
  409. if (BrowseDialog.OpenFile(ProjectLibrary.ResourceFolder, "", false, out scenePaths))
  410. {
  411. if (scenePaths.Length > 0)
  412. LoadScene(scenePaths[0]);
  413. }
  414. }
  415. /// <summary>
  416. /// Opens a dialog to allows the user to select a location where to save the current scene. If scene was previously
  417. /// saved it is instead automatically saved at the last location.
  418. /// </summary>
  419. public static void SaveScene(Action onSuccess = null, Action onFailure = null)
  420. {
  421. if (!Scene.ActiveSceneUUID.IsEmpty())
  422. {
  423. string scenePath = ProjectLibrary.GetPath(Scene.ActiveSceneUUID);
  424. if (!string.IsNullOrEmpty(scenePath))
  425. {
  426. if (Scene.IsGenericPrefab)
  427. {
  428. SaveGenericPrefab(onSuccess, onFailure);
  429. }
  430. else
  431. {
  432. SaveScene(scenePath);
  433. if (onSuccess != null)
  434. onSuccess();
  435. }
  436. }
  437. else
  438. SaveSceneAs(onSuccess, onFailure);
  439. }
  440. else
  441. SaveSceneAs(onSuccess, onFailure);
  442. }
  443. /// <summary>
  444. /// Opens a dialog to allows the user to select a location where to save the current scene.
  445. /// </summary>
  446. public static void SaveSceneAs(Action onSuccess = null, Action onFailure = null)
  447. {
  448. string scenePath = "";
  449. if (BrowseDialog.SaveFile(ProjectLibrary.ResourceFolder, "*.prefab", out scenePath))
  450. {
  451. if (!PathEx.IsPartOf(scenePath, ProjectLibrary.ResourceFolder))
  452. {
  453. DialogBox.Open("Error", "The location must be inside the Resources folder of the project.",
  454. DialogBox.Type.OK,
  455. x =>
  456. {
  457. if (onFailure != null)
  458. onFailure();
  459. });
  460. }
  461. else
  462. {
  463. // TODO - If path points to an existing non-scene asset or folder I should delete it otherwise
  464. // Internal_SaveScene will silently fail.
  465. scenePath = Path.ChangeExtension(scenePath, ".prefab");
  466. SaveScene(scenePath);
  467. }
  468. }
  469. else
  470. {
  471. // User canceled, so technically a success
  472. if (onSuccess != null)
  473. onSuccess();
  474. }
  475. }
  476. /// <summary>
  477. /// Loads a prefab as the current scene at the specified path. If current scene is modified the user is offered a
  478. /// chance to save it.
  479. /// </summary>
  480. /// <param name="path">Path to a valid prefab relative to the resource folder. If path is empty a brand new
  481. /// scene will be loaded.</param>
  482. public static void LoadScene(string path)
  483. {
  484. Action<string> continueLoad =
  485. (scenePath) =>
  486. {
  487. if (string.IsNullOrEmpty(path))
  488. {
  489. Scene.Clear();
  490. lastLoadedScene = null;
  491. }
  492. else
  493. lastLoadedScene = Scene.LoadAsync(path);
  494. SetSceneDirty(false);
  495. ProjectSettings.LastOpenScene = scenePath;
  496. ProjectSettings.Save();
  497. };
  498. Action<DialogBox.ResultType> dialogCallback =
  499. (result) =>
  500. {
  501. if (result == DialogBox.ResultType.Yes)
  502. {
  503. SaveScene();
  504. continueLoad(path);
  505. }
  506. else if (result == DialogBox.ResultType.No)
  507. continueLoad(path);
  508. };
  509. if (IsSceneModified())
  510. {
  511. DialogBox.Open("Warning", "You current scene has modifications. Do you wish to save them first?",
  512. DialogBox.Type.YesNoCancel, dialogCallback);
  513. }
  514. else
  515. continueLoad(path);
  516. }
  517. /// <summary>
  518. /// Saves the currently loaded scene to the specified path.
  519. /// </summary>
  520. /// <param name="path">Path relative to the resource folder. This can be the path to the existing scene
  521. /// prefab if it just needs updating. </param>
  522. internal static void SaveScene(string path)
  523. {
  524. Prefab scene = Internal_SaveScene(path);
  525. Scene.SetActive(scene);
  526. ProjectLibrary.Refresh(true);
  527. SetSceneDirty(false);
  528. }
  529. /// <summary>
  530. /// Attempts to save the current scene by applying the changes to a prefab, instead of saving it as a brand new
  531. /// scene. This is necessary for generic prefabs that have don't have a scene root included in the prefab. If the
  532. /// object added any other objects to the root, or has moved or deleted the original generic prefab the user
  533. /// will be asked to save the scene normally, creating a brand new prefab.
  534. /// </summary>
  535. private static void SaveGenericPrefab(Action onSuccess = null, Action onFailure = null)
  536. {
  537. // Find prefab root
  538. SceneObject root = null;
  539. int numChildren = Scene.Root.GetNumChildren();
  540. int numNormalChildren = 0;
  541. for (int i = 0; i < numChildren; i++)
  542. {
  543. SceneObject child = Scene.Root.GetChild(i);
  544. if (EditorUtility.IsInternal(child))
  545. continue;
  546. UUID prefabUUID = PrefabUtility.GetPrefabUUID(child);
  547. if (prefabUUID == Scene.ActiveSceneUUID)
  548. root = child;
  549. // If user added any other prefabs other than the initial one, the scene no longer represents a generic
  550. // prefab (as we can now longer save it by applying changes only to that prefab)
  551. numNormalChildren++;
  552. if (numNormalChildren > 1)
  553. {
  554. root = null;
  555. break;
  556. }
  557. }
  558. if (root != null)
  559. {
  560. PrefabUtility.ApplyPrefab(root, false);
  561. ProjectLibrary.Refresh(true);
  562. SetSceneDirty(false);
  563. if (onSuccess != null)
  564. onSuccess();
  565. }
  566. else
  567. {
  568. SaveSceneAs(onSuccess, onFailure);
  569. }
  570. }
  571. /// <summary>
  572. /// Checks does the folder at the provieded path contain a valid project.
  573. /// </summary>
  574. /// <param name="path">Absolute path to the root project folder.</param>
  575. /// <returns>True if the folder contains a valid project.</returns>
  576. public static bool IsValidProject(string path)
  577. {
  578. return Internal_IsValidProject(path);
  579. }
  580. /// <summary>
  581. /// Contains a new project in the provided folder.
  582. /// </summary>
  583. /// <param name="path">Absolute path to the folder to create the project in. Name of this folder will be used as the
  584. /// project's name.</param>
  585. public static void CreateProject(string path)
  586. {
  587. Internal_CreateProject(path);
  588. }
  589. /// <summary>
  590. /// Wrapper for menu items for <see cref="SaveScene(Action, Action)"/> method
  591. /// </summary>
  592. [MenuItem("File/Save Scene", ButtonModifier.Ctrl, ButtonCode.S, 10049)]
  593. [ToolbarItem("Save Scene", ToolbarIcon.SaveScene, "Save scene (Ctrl + S)", 1998)]
  594. private static void SaveSceneMenu()
  595. {
  596. SaveScene();
  597. }
  598. /// <summary>
  599. /// Wrapper for menu items for <see cref="SaveSceneAs(Action, Action)"/> method
  600. /// </summary>
  601. [MenuItem("File/Save Scene As", 10048)]
  602. private static void SaveSceneAsMenu()
  603. {
  604. SaveSceneAs();
  605. }
  606. /// <summary>
  607. /// Opens a Project Window allowing you to browse for or create a project.
  608. /// </summary>
  609. [MenuItem("File/Open Project", 10100)]
  610. [ToolbarItem("Open Project", ToolbarIcon.OpenProject, "Project manager", 2000)]
  611. public static void BrowseForProject()
  612. {
  613. ProjectWindow.Open();
  614. }
  615. /// <summary>
  616. /// Saves all data in the currently open project.
  617. /// </summary>
  618. [MenuItem("File/Save Project", 10099)]
  619. [ToolbarItem("Save Project", ToolbarIcon.SaveProject, "Save project", 1999)]
  620. public static void SaveProject()
  621. {
  622. OnProjectSave?.Invoke();
  623. // Apply changes to any animation clips edited using the animation editor
  624. foreach (var KVP in persistentData.dirtyAnimClips)
  625. KVP.Value.SaveToClip();
  626. // Save all dirty resources to disk
  627. foreach (var KVP in persistentData.dirtyResources)
  628. {
  629. UUID resourceUUID = KVP.Key;
  630. string path = ProjectLibrary.GetPath(resourceUUID);
  631. if (!IsNative(path))
  632. continue; // Imported resources can't be changed
  633. Resource resource = ProjectLibrary.Load<Resource>(path);
  634. if(resource != null)
  635. ProjectLibrary.Save(resource);
  636. }
  637. persistentData.dirtyAnimClips.Clear();
  638. persistentData.dirtyResources.Clear();
  639. SetStatusProject(false);
  640. Internal_SaveProject();
  641. }
  642. /// <summary>
  643. /// Loads the project at the specified path. This method executes asynchronously.
  644. /// </summary>
  645. /// <param name="path">Absolute path to the project's root folder.</param>
  646. public static void LoadProject(string path)
  647. {
  648. if (IsProjectLoaded && path == ProjectPath)
  649. return;
  650. if (!Internal_IsValidProject(path))
  651. {
  652. Debug.LogWarning("Provided path: \"" + path + "\" is not a valid project.");
  653. return;
  654. }
  655. if (IsProjectLoaded)
  656. TryUnloadProject(() => Internal_LoadProject(path));
  657. else
  658. Internal_LoadProject(path); // Triggers Internal_OnProjectLoaded when done
  659. }
  660. /// <summary>
  661. /// Closes the editor.
  662. /// </summary>
  663. public static void Quit()
  664. {
  665. Internal_Quit();
  666. }
  667. /// <summary>
  668. /// Toggles an existing toolbar button into an on or off state which changes the visuals of the button.
  669. /// </summary>
  670. /// <param name="name">Name of the existing button to toggle</param>
  671. /// <param name="on">True to toggle on, false to toggle off (default)</param>
  672. public static void ToggleToolbarItem(string name, bool on)
  673. {
  674. Internal_ToggleToolbarItem(name, on);
  675. }
  676. /// <summary>
  677. /// Opens a folder in the default external application.
  678. /// </summary>
  679. /// <param name="path">Absolute path to the folder to open.</param>
  680. public static void OpenFolder(string path)
  681. {
  682. Internal_OpenFolder(path);
  683. }
  684. /// <summary>
  685. /// Marks a resource as dirty so that it may be saved the next time the project is saved. Optionally you may also
  686. /// call <see cref="ProjectLibrary.Save"/> to save it immediately.
  687. /// </summary>
  688. /// <param name="resource">Resource to mark as dirty</param>
  689. public static void SetDirty(Resource resource)
  690. {
  691. if (resource == null)
  692. return;
  693. SetStatusProject(true);
  694. persistentData.dirtyResources[resource.UUID] = resource;
  695. }
  696. /// <summary>
  697. /// Marks the current project dirty (requires saving in order for changes not to be lost).
  698. /// </summary>
  699. public static void SetProjectDirty()
  700. {
  701. SetStatusProject(true);
  702. }
  703. /// <summary>
  704. /// Marks the current scene as dirty.
  705. /// </summary>
  706. public static void SetSceneDirty()
  707. {
  708. SetSceneDirty(true);
  709. }
  710. /// <summary>
  711. /// Marks the current scene as clean or dirty.
  712. /// </summary>
  713. /// <param name="dirty">Should the scene be marked as clean or dirty.</param>
  714. internal static void SetSceneDirty(bool dirty)
  715. {
  716. sceneDirty = dirty;
  717. SetStatusScene(Scene.ActiveSceneName, dirty);
  718. if (!dirty && !Scene.ActiveSceneUUID.IsEmpty())
  719. persistentData.dirtyResources.Remove(Scene.ActiveSceneUUID);
  720. }
  721. /// <summary>
  722. /// Checks is the specific resource dirty and needs saving.
  723. /// </summary>
  724. /// <param name="resource">Resource to check.</param>
  725. /// <returns>True if the resource requires saving, false otherwise.</returns>
  726. public static bool IsDirty(Resource resource)
  727. {
  728. return persistentData.dirtyResources.ContainsKey(resource.UUID);
  729. }
  730. /// <summary>
  731. /// Checks does the path represent a native resource.
  732. /// </summary>
  733. /// <param name="path">Filename or path to check.</param>
  734. /// <returns>True if the path represents a native resource.</returns>
  735. public static bool IsNative(string path)
  736. {
  737. string extension = Path.GetExtension(path);
  738. return extension == ".asset" || extension == ".prefab";
  739. }
  740. /// <summary>
  741. /// Attempts to unload the currently loaded project. Offers the user a chance to save the current scene if it is
  742. /// modified. Automatically saves all project data before unloading.
  743. /// </summary>
  744. /// <param name="onDone">Callback to trigger when project project unload is done.</param>
  745. private static void TryUnloadProject(Action onDone)
  746. {
  747. if (delayUnloadProject)
  748. return;
  749. AskToSaveSceneAndContinue(
  750. () =>
  751. {
  752. if (ProjectLibrary.ImportInProgress)
  753. {
  754. ConfirmImportInProgressWindow.Show();
  755. delayUnloadCallback = onDone;
  756. delayUnloadProject = true;
  757. }
  758. else
  759. {
  760. UnloadProject();
  761. onDone?.Invoke();
  762. }
  763. });
  764. }
  765. /// <summary>
  766. /// Unloads the currently loaded project, without making any checks or requiring confirmation.
  767. /// </summary>
  768. private static void UnloadProject()
  769. {
  770. Scene.Clear();
  771. if (monitor != null)
  772. {
  773. monitor.Destroy();
  774. monitor = null;
  775. }
  776. LibraryWindow window = EditorWindow.GetWindow<LibraryWindow>();
  777. if (window != null)
  778. window.Reset();
  779. SetSceneDirty(false);
  780. Internal_UnloadProject();
  781. SetStatusProject(false);
  782. }
  783. /// <summary>
  784. /// Checks if the current scene is modified and asks the user to save the scene if it is. Triggers the
  785. /// <see cref="next"/> callback when done, unless user cancels the operation.
  786. /// </summary>
  787. /// <param name="next">Callback to trigger after this method finishes.</param>
  788. internal static void AskToSaveSceneAndContinue(Action next)
  789. {
  790. Action trySaveScene = null;
  791. trySaveScene = () =>
  792. {
  793. SaveScene(next, trySaveScene);
  794. };
  795. Action<DialogBox.ResultType> dialogCallback =
  796. (result) =>
  797. {
  798. if (result == DialogBox.ResultType.Yes)
  799. trySaveScene();
  800. else if (result == DialogBox.ResultType.No)
  801. next?.Invoke();
  802. };
  803. if (IsSceneModified())
  804. {
  805. DialogBox.Open("Warning", "You current scene has modifications. Do you wish to save them first?",
  806. DialogBox.Type.YesNoCancel, dialogCallback);
  807. }
  808. else
  809. next?.Invoke();
  810. }
  811. /// <summary>
  812. /// Reloads all script assemblies in case they were modified. This action is delayed and will be executed
  813. /// at the beginning of the next frame.
  814. /// </summary>
  815. public static void ReloadAssemblies()
  816. {
  817. UpdateEditorSceneData();
  818. Internal_ReloadAssemblies();
  819. }
  820. /// <summary>
  821. /// Changes the scene displayed on the status bar.
  822. /// </summary>
  823. /// <param name="name">Name of the scene.</param>
  824. /// <param name="modified">Whether to display the scene as modified or not.</param>
  825. private static void SetStatusScene(string name, bool modified)
  826. {
  827. Internal_SetStatusScene(name, modified);
  828. }
  829. /// <summary>
  830. /// Changes the project state displayed on the status bar.
  831. /// </summary>
  832. /// <param name="modified">Whether to display the project as modified or not.</param>
  833. private static void SetStatusProject(bool modified)
  834. {
  835. Internal_SetStatusProject(modified);
  836. }
  837. /// <summary>
  838. /// Displays or hides the "compilation in progress" visual on the status bar.
  839. /// </summary>
  840. /// <param name="compiling">True to display the visual, false otherwise.</param>
  841. internal static void SetStatusCompiling(bool compiling)
  842. {
  843. Internal_SetStatusCompiling(compiling);
  844. }
  845. /// <summary>
  846. /// Displays or hides the "import in progress" visuals on the status bar and updates the related progress bar.
  847. /// </summary>
  848. /// <param name="importing">True to display the visual, false otherwise.</param>
  849. /// <param name="percent">Percent in range [0, 1] to display on the progress bar.</param>
  850. internal static void SetStatusImporting(bool importing, float percent)
  851. {
  852. Internal_SetStatusImporting(importing, percent);
  853. }
  854. /// <summary>
  855. /// Checks did we make any modifications to the scene since it was last saved.
  856. /// </summary>
  857. /// <returns>True if the scene was never saved, or was modified after last save.</returns>
  858. public static bool IsSceneModified()
  859. {
  860. return sceneDirty;
  861. }
  862. /// <summary>
  863. /// Executes any editor-specific unit tests. This should be called after a project is loaded if possible.
  864. /// </summary>
  865. private static void RunUnitTests()
  866. {
  867. #if DEBUG
  868. Internal_RunUnitTests();
  869. #endif
  870. }
  871. /// <summary>
  872. /// Triggered by the runtime when <see cref="LoadProject"/> method completes.
  873. /// </summary>
  874. private static void Internal_OnProjectLoaded()
  875. {
  876. SetStatusProject(false);
  877. if (!unitTestsExecuted)
  878. {
  879. RunUnitTests();
  880. unitTestsExecuted = true;
  881. }
  882. if (!IsProjectLoaded)
  883. {
  884. ProjectWindow.Open();
  885. return;
  886. }
  887. string projectPath = ProjectPath;
  888. RecentProject[] recentProjects = EditorSettings.RecentProjects;
  889. bool foundPath = false;
  890. for (int i = 0; i < recentProjects.Length; i++)
  891. {
  892. if (PathEx.Compare(recentProjects[i].path, projectPath))
  893. {
  894. recentProjects[i].accessTimestamp = (ulong)DateTime.Now.Ticks;
  895. EditorSettings.RecentProjects = recentProjects;
  896. foundPath = true;
  897. break;
  898. }
  899. }
  900. if (!foundPath)
  901. {
  902. List<RecentProject> extendedRecentProjects = new List<RecentProject>();
  903. extendedRecentProjects.AddRange(recentProjects);
  904. RecentProject newProject = new RecentProject();
  905. newProject.path = projectPath;
  906. newProject.accessTimestamp = (ulong)DateTime.Now.Ticks;
  907. extendedRecentProjects.Add(newProject);
  908. EditorSettings.RecentProjects = extendedRecentProjects.ToArray();
  909. }
  910. EditorSettings.LastOpenProject = projectPath;
  911. EditorSettings.Save();
  912. ProjectLibrary.Refresh();
  913. if(monitor != null)
  914. {
  915. monitor.Destroy();
  916. monitor = null;
  917. }
  918. monitor = new FolderMonitor(ProjectLibrary.ResourceFolder);
  919. monitor.OnAdded += OnAssetModified;
  920. monitor.OnRemoved += OnAssetModified;
  921. monitor.OnModified += OnAssetModified;
  922. if (!string.IsNullOrWhiteSpace(ProjectSettings.LastOpenScene))
  923. {
  924. lastLoadedScene = Scene.LoadAsync(ProjectSettings.LastOpenScene);
  925. SetSceneDirty(false);
  926. }
  927. }
  928. /// <summary>
  929. /// Triggered by the runtime when the user clicks on the status bar.
  930. /// </summary>
  931. private static void Internal_OnStatusBarClicked()
  932. {
  933. EditorWindow.OpenWindow<LogWindow>();
  934. }
  935. [MethodImpl(MethodImplOptions.InternalCall)]
  936. private static extern void Internal_SetStatusScene(string name, bool modified);
  937. [MethodImpl(MethodImplOptions.InternalCall)]
  938. private static extern void Internal_SetStatusProject(bool modified);
  939. [MethodImpl(MethodImplOptions.InternalCall)]
  940. private static extern void Internal_SetStatusCompiling(bool compiling);
  941. [MethodImpl(MethodImplOptions.InternalCall)]
  942. private static extern void Internal_SetStatusImporting(bool importing, float percent);
  943. [MethodImpl(MethodImplOptions.InternalCall)]
  944. private static extern string Internal_GetProjectPath();
  945. [MethodImpl(MethodImplOptions.InternalCall)]
  946. private static extern string Internal_GetProjectName();
  947. [MethodImpl(MethodImplOptions.InternalCall)]
  948. private static extern bool Internal_GetProjectLoaded();
  949. [MethodImpl(MethodImplOptions.InternalCall)]
  950. private static extern string Internal_GetCompilerPath();
  951. [MethodImpl(MethodImplOptions.InternalCall)]
  952. private static extern string Internal_GetMonoExecPath();
  953. [MethodImpl(MethodImplOptions.InternalCall)]
  954. private static extern string Internal_GetBuiltinReleaseAssemblyPath();
  955. [MethodImpl(MethodImplOptions.InternalCall)]
  956. private static extern string Internal_GetBuiltinDebugAssemblyPath();
  957. [MethodImpl(MethodImplOptions.InternalCall)]
  958. private static extern string Internal_GetScriptAssemblyPath();
  959. [MethodImpl(MethodImplOptions.InternalCall)]
  960. private static extern string Internal_GetFrameworkAssemblyPath();
  961. [MethodImpl(MethodImplOptions.InternalCall)]
  962. private static extern string Internal_GetEngineAssemblyName();
  963. [MethodImpl(MethodImplOptions.InternalCall)]
  964. private static extern string Internal_GetEditorAssemblyName();
  965. [MethodImpl(MethodImplOptions.InternalCall)]
  966. private static extern string Internal_GetScriptGameAssemblyName();
  967. [MethodImpl(MethodImplOptions.InternalCall)]
  968. private static extern string Internal_GetScriptEditorAssemblyName();
  969. [MethodImpl(MethodImplOptions.InternalCall)]
  970. private static extern Prefab Internal_SaveScene(string path);
  971. [MethodImpl(MethodImplOptions.InternalCall)]
  972. private static extern bool Internal_IsValidProject(string path);
  973. [MethodImpl(MethodImplOptions.InternalCall)]
  974. private static extern void Internal_SaveProject();
  975. [MethodImpl(MethodImplOptions.InternalCall)]
  976. private static extern void Internal_LoadProject(string path);
  977. [MethodImpl(MethodImplOptions.InternalCall)]
  978. private static extern void Internal_UnloadProject();
  979. [MethodImpl(MethodImplOptions.InternalCall)]
  980. private static extern void Internal_CreateProject(string path);
  981. [MethodImpl(MethodImplOptions.InternalCall)]
  982. private static extern void Internal_ReloadAssemblies();
  983. [MethodImpl(MethodImplOptions.InternalCall)]
  984. private static extern void Internal_OpenFolder(string path);
  985. [MethodImpl(MethodImplOptions.InternalCall)]
  986. private static extern void Internal_RunUnitTests();
  987. [MethodImpl(MethodImplOptions.InternalCall)]
  988. private static extern void Internal_Quit();
  989. [MethodImpl(MethodImplOptions.InternalCall)]
  990. private static extern void Internal_ToggleToolbarItem(string name, bool on);
  991. [MethodImpl(MethodImplOptions.InternalCall)]
  992. private static extern void Internal_SetMainRenderTarget(IntPtr rendertarget);
  993. [MethodImpl(MethodImplOptions.InternalCall)]
  994. private static extern bool Internal_HasFocus();
  995. }
  996. /** @} */
  997. }