EditorApplication.cs 46 KB

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