SceneWindow.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  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.IO;
  6. using BansheeEngine;
  7. namespace BansheeEditor
  8. {
  9. /// <summary>
  10. /// Displays the scene view camera and various scene controls.
  11. /// </summary>
  12. internal sealed class SceneWindow : EditorWindow, IGlobalShortcuts
  13. {
  14. internal const string ToggleProfilerOverlayBinding = "ToggleProfilerOverlay";
  15. internal const string ViewToolBinding = "ViewTool";
  16. internal const string MoveToolBinding = "MoveTool";
  17. internal const string RotateToolBinding = "RotateTool";
  18. internal const string ScaleToolBinding = "ScaleTool";
  19. internal const string FrameBinding = "SceneFrame";
  20. private const int HeaderHeight = 20;
  21. private const float DefaultPlacementDepth = 5.0f;
  22. private static readonly Color ClearColor = new Color(83.0f/255.0f, 83.0f/255.0f, 83.0f/255.0f);
  23. private const string ProfilerOverlayActiveKey = "_Internal_ProfilerOverlayActive";
  24. private const int HandleAxesGUISize = 50;
  25. private const int HandleAxesGUIPaddingX = 10;
  26. private const int HandleAxesGUIPaddingY = 5;
  27. private Camera camera;
  28. private SceneCamera cameraController;
  29. private RenderTexture2D renderTexture;
  30. private GUILayoutY mainLayout;
  31. private GUIPanel rtPanel;
  32. private GUIButton focusCatcher;
  33. private GUIRenderTexture renderTextureGUI;
  34. private SceneGrid sceneGrid;
  35. private SceneSelection sceneSelection;
  36. private SceneGizmos sceneGizmos;
  37. private SceneHandles sceneHandles;
  38. private GUIToggle viewButton;
  39. private GUIToggle moveButton;
  40. private GUIToggle rotateButton;
  41. private GUIToggle scaleButton;
  42. private GUIToggle localCoordButton;
  43. private GUIToggle worldCoordButton;
  44. private GUIToggle pivotButton;
  45. private GUIToggle centerButton;
  46. private GUIToggle moveSnapButton;
  47. private GUIFloatField moveSnapInput;
  48. private GUIToggle rotateSnapButton;
  49. private GUIFloatField rotateSnapInput;
  50. private SceneAxesGUI sceneAxesGUI;
  51. private bool hasContentFocus = false;
  52. private bool HasContentFocus { get { return HasFocus && hasContentFocus; } }
  53. private int editorSettingsHash = int.MaxValue;
  54. private VirtualButton frameKey;
  55. // Tool shortcuts
  56. private VirtualButton viewToolKey;
  57. private VirtualButton moveToolKey;
  58. private VirtualButton rotateToolKey;
  59. private VirtualButton scaleToolKey;
  60. // Profiler overlay
  61. private ProfilerOverlay activeProfilerOverlay;
  62. private Camera profilerCamera;
  63. private VirtualButton toggleProfilerOverlayKey;
  64. // Drag & drop
  65. private bool dragActive;
  66. private SceneObject draggedSO;
  67. /// <summary>
  68. /// Returns the scene camera.
  69. /// </summary>
  70. public Camera Camera
  71. {
  72. get { return camera; }
  73. }
  74. /// <summary>
  75. /// Determines scene camera's projection type.
  76. /// </summary>
  77. internal ProjectionType ProjectionType
  78. {
  79. get { return cameraController.ProjectionType; }
  80. set { cameraController.ProjectionType = value; sceneAxesGUI.ProjectionType = value; }
  81. }
  82. /// <summary>
  83. /// Constructs a new scene window.
  84. /// </summary>
  85. internal SceneWindow()
  86. { }
  87. /// <summary>
  88. /// Opens a scene window if its not open already.
  89. /// </summary>
  90. [MenuItem("Windows/Scene", ButtonModifier.CtrlAlt, ButtonCode.S, 6000)]
  91. private static void OpenSceneWindow()
  92. {
  93. OpenWindow<SceneWindow>();
  94. }
  95. /// <summary>
  96. /// Focuses on the currently selected object.
  97. /// </summary>
  98. [MenuItem("Tools/Frame Selected", ButtonModifier.None, ButtonCode.F, 9275, true)]
  99. private static void OpenSettingsWindow()
  100. {
  101. SceneWindow window = GetWindow<SceneWindow>();
  102. if (window != null)
  103. window.cameraController.FrameSelected();
  104. }
  105. /// <summary>
  106. /// Switches the active tool to the view tool.
  107. /// </summary>
  108. [MenuItem("Tools/View", ButtonModifier.Ctrl, ButtonCode.Q, 9274, true)]
  109. private static void SetViewTool()
  110. {
  111. SceneWindow window = GetWindow<SceneWindow>();
  112. if (window != null)
  113. window.OnSceneToolButtonClicked(SceneViewTool.View);
  114. }
  115. /// <summary>
  116. /// Switches the active tool to the move tool.
  117. /// </summary>
  118. [MenuItem("Tools/Move", ButtonModifier.Ctrl, ButtonCode.W, 9273)]
  119. private static void SetMoveTool()
  120. {
  121. SceneWindow window = GetWindow<SceneWindow>();
  122. if (window != null)
  123. window.OnSceneToolButtonClicked(SceneViewTool.Move);
  124. }
  125. /// <summary>
  126. /// Switches the active tool to the rotate tool.
  127. /// </summary>
  128. [MenuItem("Tools/Rotate", ButtonModifier.Ctrl, ButtonCode.E, 9272)]
  129. private static void SetRotateTool()
  130. {
  131. SceneWindow window = GetWindow<SceneWindow>();
  132. if (window != null)
  133. window.OnSceneToolButtonClicked(SceneViewTool.Rotate);
  134. }
  135. /// <summary>
  136. /// Switches the active tool to the scale tool.
  137. /// </summary>
  138. [MenuItem("Tools/Scale", ButtonModifier.Ctrl, ButtonCode.R, 9271)]
  139. private static void SetScaleTool()
  140. {
  141. SceneWindow window = GetWindow<SceneWindow>();
  142. if (window != null)
  143. window.OnSceneToolButtonClicked(SceneViewTool.Scale);
  144. }
  145. /// <inheritdoc/>
  146. protected override LocString GetDisplayName()
  147. {
  148. return new LocEdString("Scene");
  149. }
  150. private void OnInitialize()
  151. {
  152. mainLayout = GUI.AddLayoutY();
  153. GUIContent viewIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.View),
  154. new LocEdString("View"));
  155. GUIContent moveIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.Move),
  156. new LocEdString("Move"));
  157. GUIContent rotateIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.Rotate),
  158. new LocEdString("Rotate"));
  159. GUIContent scaleIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.Scale),
  160. new LocEdString("Scale"));
  161. GUIContent localIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.Local),
  162. new LocEdString("Local"));
  163. GUIContent worldIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.World),
  164. new LocEdString("World"));
  165. GUIContent pivotIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.Pivot),
  166. new LocEdString("Pivot"));
  167. GUIContent centerIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.Center),
  168. new LocEdString("Center"));
  169. GUIContent moveSnapIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.MoveSnap),
  170. new LocEdString("Move snap"));
  171. GUIContent rotateSnapIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.RotateSnap),
  172. new LocEdString("Rotate snap"));
  173. GUIToggleGroup handlesTG = new GUIToggleGroup();
  174. viewButton = new GUIToggle(viewIcon, handlesTG, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  175. moveButton = new GUIToggle(moveIcon, handlesTG, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  176. rotateButton = new GUIToggle(rotateIcon, handlesTG, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  177. scaleButton = new GUIToggle(scaleIcon, handlesTG, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  178. GUIToggleGroup coordModeTG = new GUIToggleGroup();
  179. localCoordButton = new GUIToggle(localIcon, coordModeTG, EditorStyles.Button, GUIOption.FlexibleWidth(75));
  180. worldCoordButton = new GUIToggle(worldIcon, coordModeTG, EditorStyles.Button, GUIOption.FlexibleWidth(75));
  181. GUIToggleGroup pivotModeTG = new GUIToggleGroup();
  182. pivotButton = new GUIToggle(pivotIcon, pivotModeTG, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  183. centerButton = new GUIToggle(centerIcon, pivotModeTG, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  184. moveSnapButton = new GUIToggle(moveSnapIcon, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  185. moveSnapInput = new GUIFloatField("", GUIOption.FlexibleWidth(35));
  186. rotateSnapButton = new GUIToggle(rotateSnapIcon, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  187. rotateSnapInput = new GUIFloatField("", GUIOption.FlexibleWidth(35));
  188. viewButton.OnClick += () => OnSceneToolButtonClicked(SceneViewTool.View);
  189. moveButton.OnClick += () => OnSceneToolButtonClicked(SceneViewTool.Move);
  190. rotateButton.OnClick += () => OnSceneToolButtonClicked(SceneViewTool.Rotate);
  191. scaleButton.OnClick += () => OnSceneToolButtonClicked(SceneViewTool.Scale);
  192. localCoordButton.OnClick += () => OnCoordinateModeButtonClicked(HandleCoordinateMode.Local);
  193. worldCoordButton.OnClick += () => OnCoordinateModeButtonClicked(HandleCoordinateMode.World);
  194. pivotButton.OnClick += () => OnPivotModeButtonClicked(HandlePivotMode.Pivot);
  195. centerButton.OnClick += () => OnPivotModeButtonClicked(HandlePivotMode.Center);
  196. moveSnapButton.OnToggled += (bool active) => OnMoveSnapToggled(active);
  197. moveSnapInput.OnChanged += (float value) => OnMoveSnapValueChanged(value);
  198. rotateSnapButton.OnToggled += (bool active) => OnRotateSnapToggled(active);
  199. rotateSnapInput.OnChanged += (float value) => OnRotateSnapValueChanged(value);
  200. GUILayout handlesLayout = mainLayout.AddLayoutX();
  201. handlesLayout.AddElement(viewButton);
  202. handlesLayout.AddElement(moveButton);
  203. handlesLayout.AddElement(rotateButton);
  204. handlesLayout.AddElement(scaleButton);
  205. handlesLayout.AddSpace(10);
  206. handlesLayout.AddElement(localCoordButton);
  207. handlesLayout.AddElement(worldCoordButton);
  208. handlesLayout.AddSpace(10);
  209. handlesLayout.AddElement(pivotButton);
  210. handlesLayout.AddElement(centerButton);
  211. handlesLayout.AddFlexibleSpace();
  212. handlesLayout.AddElement(moveSnapButton);
  213. handlesLayout.AddElement(moveSnapInput);
  214. handlesLayout.AddSpace(10);
  215. handlesLayout.AddElement(rotateSnapButton);
  216. handlesLayout.AddElement(rotateSnapInput);
  217. GUIPanel mainPanel = mainLayout.AddPanel();
  218. rtPanel = mainPanel.AddPanel();
  219. GUIPanel sceneAxesPanel = mainPanel.AddPanel(-1);
  220. sceneAxesGUI = new SceneAxesGUI(this, sceneAxesPanel, HandleAxesGUISize, HandleAxesGUISize, ProjectionType.Perspective);
  221. focusCatcher = new GUIButton("", EditorStyles.Blank);
  222. focusCatcher.OnFocusGained += () => hasContentFocus = true;
  223. focusCatcher.OnFocusLost += () => hasContentFocus = false;
  224. GUIPanel focusPanel = GUI.AddPanel(-2);
  225. focusPanel.AddElement(focusCatcher);
  226. toggleProfilerOverlayKey = new VirtualButton(ToggleProfilerOverlayBinding);
  227. viewToolKey = new VirtualButton(ViewToolBinding);
  228. moveToolKey = new VirtualButton(MoveToolBinding);
  229. rotateToolKey = new VirtualButton(RotateToolBinding);
  230. scaleToolKey = new VirtualButton(ScaleToolBinding);
  231. frameKey = new VirtualButton(FrameBinding);
  232. UpdateRenderTexture(Width, Height - HeaderHeight);
  233. UpdateProfilerOverlay();
  234. }
  235. private void OnDestroy()
  236. {
  237. if (camera != null)
  238. {
  239. camera.SceneObject.Destroy();
  240. camera = null;
  241. }
  242. sceneAxesGUI.Destroy();
  243. sceneAxesGUI = null;
  244. }
  245. /// <summary>
  246. /// Deletes all currently selected objects.
  247. /// </summary>
  248. private void DeleteSelection()
  249. {
  250. SceneObject[] selectedObjects = Selection.SceneObjects;
  251. CleanDuplicates(ref selectedObjects);
  252. if (selectedObjects.Length > 0)
  253. {
  254. foreach (var so in selectedObjects)
  255. {
  256. string message = "Deleted " + so.Name;
  257. UndoRedo.DeleteSO(so, message);
  258. }
  259. EditorApplication.SetSceneDirty();
  260. }
  261. }
  262. /// <summary>
  263. /// Duplicates all currently selected objects.
  264. /// </summary>
  265. private void DuplicateSelection()
  266. {
  267. SceneObject[] selectedObjects = Selection.SceneObjects;
  268. CleanDuplicates(ref selectedObjects);
  269. if (selectedObjects.Length > 0)
  270. {
  271. string message;
  272. if (selectedObjects.Length == 1)
  273. message = "Duplicated " + selectedObjects[0].Name;
  274. else
  275. message = "Duplicated " + selectedObjects.Length + " elements";
  276. UndoRedo.CloneSO(selectedObjects, message);
  277. EditorApplication.SetSceneDirty();
  278. }
  279. }
  280. /// <inheritdoc/>
  281. void IGlobalShortcuts.OnRenamePressed()
  282. {
  283. // Do nothing
  284. }
  285. /// <inheritdoc/>
  286. void IGlobalShortcuts.OnDuplicatePressed()
  287. {
  288. DuplicateSelection();
  289. }
  290. /// <inheritdoc/>
  291. void IGlobalShortcuts.OnDeletePressed()
  292. {
  293. DeleteSelection();
  294. }
  295. /// <inheritdoc/>
  296. void IGlobalShortcuts.OnCopyPressed()
  297. {
  298. // Do nothing
  299. }
  300. /// <inheritdoc/>
  301. void IGlobalShortcuts.OnCutPressed()
  302. {
  303. // Do nothing
  304. }
  305. /// <inheritdoc/>
  306. void IGlobalShortcuts.OnPastePressed()
  307. {
  308. // Do nothing
  309. }
  310. /// <summary>
  311. /// Orients the camera so it looks along the provided axis.
  312. /// </summary>
  313. /// <param name="axis">Axis to look along.</param>
  314. internal void LookAlong(Vector3 axis)
  315. {
  316. axis.Normalize();
  317. cameraController.LookAlong(axis);
  318. UpdateGridMode();
  319. }
  320. private void UpdateGridMode()
  321. {
  322. Vector3 forward = camera.SceneObject.Forward;
  323. if (camera.ProjectionType == ProjectionType.Perspective)
  324. sceneGrid.SetMode(GridMode.Perspective);
  325. else
  326. {
  327. float dotX = Vector3.Dot(forward, Vector3.XAxis);
  328. if (dotX >= 0.95f)
  329. sceneGrid.SetMode(GridMode.OrthoX);
  330. else if (dotX <= -0.95f)
  331. sceneGrid.SetMode(GridMode.OrthoNegX);
  332. else
  333. {
  334. float dotY = Vector3.Dot(forward, Vector3.YAxis);
  335. if (dotY >= 0.95f)
  336. sceneGrid.SetMode(GridMode.OrthoY);
  337. else if (dotY <= -0.95f)
  338. sceneGrid.SetMode(GridMode.OrthoNegY);
  339. else
  340. {
  341. float dotZ = Vector3.Dot(forward, Vector3.ZAxis);
  342. if (dotZ >= 0.95f)
  343. sceneGrid.SetMode(GridMode.OrthoZ);
  344. else if (dotZ <= -0.95f)
  345. sceneGrid.SetMode(GridMode.OrthoNegZ);
  346. else
  347. sceneGrid.SetMode(GridMode.Perspective);
  348. }
  349. }
  350. }
  351. }
  352. /// <summary>
  353. /// Converts screen coordinates into coordinates relative to the scene view render texture.
  354. /// </summary>
  355. /// <param name="screenPos">Coordinates relative to the screen.</param>
  356. /// <param name="scenePos">Output coordinates relative to the scene view texture.</param>
  357. /// <returns>True if the coordinates are within the scene view texture, false otherwise.</returns>
  358. private bool ScreenToScenePos(Vector2I screenPos, out Vector2I scenePos)
  359. {
  360. scenePos = screenPos;
  361. Vector2I windowPos = ScreenToWindowPos(screenPos);
  362. Rect2I bounds = GUILayoutUtility.CalculateBounds(renderTextureGUI, GUI);
  363. if (bounds.Contains(windowPos))
  364. {
  365. scenePos.x = windowPos.x - bounds.x;
  366. scenePos.y = windowPos.y - bounds.y;
  367. return true;
  368. }
  369. return false;
  370. }
  371. private void OnEditorUpdate()
  372. {
  373. if (HasFocus)
  374. {
  375. if (!Input.IsPointerButtonHeld(PointerButton.Right))
  376. {
  377. if (VirtualInput.IsButtonDown(EditorApplication.DuplicateKey))
  378. DuplicateSelection();
  379. else if (VirtualInput.IsButtonDown(EditorApplication.DeleteKey))
  380. DeleteSelection();
  381. else if (VirtualInput.IsButtonDown(toggleProfilerOverlayKey))
  382. EditorSettings.SetBool(ProfilerOverlayActiveKey, !EditorSettings.GetBool(ProfilerOverlayActiveKey));
  383. else if(VirtualInput.IsButtonDown(viewToolKey))
  384. EditorApplication.ActiveSceneTool = SceneViewTool.View;
  385. else if(VirtualInput.IsButtonDown(moveToolKey))
  386. EditorApplication.ActiveSceneTool = SceneViewTool.Move;
  387. else if(VirtualInput.IsButtonDown(rotateToolKey))
  388. EditorApplication.ActiveSceneTool = SceneViewTool.Rotate;
  389. else if(VirtualInput.IsButtonDown(scaleToolKey))
  390. EditorApplication.ActiveSceneTool = SceneViewTool.Scale;
  391. }
  392. }
  393. // Refresh GUI buttons if needed (in case someones changes the values from script)
  394. if (editorSettingsHash != EditorSettings.Hash)
  395. {
  396. UpdateButtonStates();
  397. UpdateProfilerOverlay();
  398. editorSettingsHash = EditorSettings.Hash;
  399. }
  400. // Update scene view handles and selection
  401. sceneGizmos.Draw();
  402. sceneGrid.Draw();
  403. bool handleActive = false;
  404. if (Input.IsPointerButtonUp(PointerButton.Left))
  405. {
  406. if (sceneHandles.IsActive())
  407. {
  408. sceneHandles.ClearSelection();
  409. handleActive = true;
  410. }
  411. if (sceneAxesGUI.IsActive())
  412. {
  413. sceneAxesGUI.ClearSelection();
  414. handleActive = true;
  415. }
  416. }
  417. Vector2I scenePos;
  418. bool inBounds = ScreenToScenePos(Input.PointerPosition, out scenePos);
  419. bool draggedOver = DragDrop.DragInProgress || DragDrop.DropInProgress;
  420. draggedOver &= IsPointerHovering && inBounds && DragDrop.Type == DragDropType.Resource;
  421. if (draggedOver)
  422. {
  423. if (DragDrop.DropInProgress)
  424. {
  425. dragActive = false;
  426. if (draggedSO != null)
  427. {
  428. Selection.SceneObject = draggedSO;
  429. EditorApplication.SetSceneDirty();
  430. }
  431. draggedSO = null;
  432. }
  433. else
  434. {
  435. if (!dragActive)
  436. {
  437. dragActive = true;
  438. ResourceDragDropData dragData = (ResourceDragDropData)DragDrop.Data;
  439. string[] draggedPaths = dragData.Paths;
  440. for (int i = 0; i < draggedPaths.Length; i++)
  441. {
  442. ResourceMeta meta = ProjectLibrary.GetMeta(draggedPaths[i]);
  443. if (meta != null)
  444. {
  445. if (meta.ResType == ResourceType.Mesh)
  446. {
  447. if (!string.IsNullOrEmpty(draggedPaths[i]))
  448. {
  449. string meshName = Path.GetFileNameWithoutExtension(draggedPaths[i]);
  450. draggedSO = UndoRedo.CreateSO(meshName, "Created a new Renderable \"" + meshName + "\"");
  451. Mesh mesh = ProjectLibrary.Load<Mesh>(draggedPaths[i]);
  452. Renderable renderable = draggedSO.AddComponent<Renderable>();
  453. renderable.Mesh = mesh;
  454. }
  455. break;
  456. }
  457. else if (meta.ResType == ResourceType.Prefab)
  458. {
  459. if (!string.IsNullOrEmpty(draggedPaths[i]))
  460. {
  461. Prefab prefab = ProjectLibrary.Load<Prefab>(draggedPaths[i]);
  462. draggedSO = UndoRedo.Instantiate(prefab, "Instantiating " + prefab.Name);
  463. }
  464. break;
  465. }
  466. }
  467. }
  468. }
  469. if (draggedSO != null)
  470. {
  471. Ray worldRay = camera.ViewportToWorldRay(scenePos);
  472. draggedSO.Position = worldRay*DefaultPlacementDepth;
  473. }
  474. }
  475. return;
  476. }
  477. else
  478. {
  479. if (dragActive)
  480. {
  481. dragActive = false;
  482. if (draggedSO != null)
  483. {
  484. draggedSO.Destroy();
  485. draggedSO = null;
  486. }
  487. }
  488. }
  489. if (HasContentFocus)
  490. {
  491. cameraController.EnableInput(true);
  492. if (inBounds)
  493. {
  494. if (Input.IsPointerButtonDown(PointerButton.Left))
  495. {
  496. Rect2I sceneAxesGUIBounds = new Rect2I(Width - HandleAxesGUISize - HandleAxesGUIPaddingX,
  497. HandleAxesGUIPaddingY, HandleAxesGUISize, HandleAxesGUISize);
  498. if (sceneAxesGUIBounds.Contains(scenePos))
  499. sceneAxesGUI.TrySelect(scenePos);
  500. else
  501. sceneHandles.TrySelect(scenePos);
  502. }
  503. else if (Input.IsPointerButtonUp(PointerButton.Left))
  504. {
  505. if (!handleActive)
  506. {
  507. bool ctrlHeld = Input.IsButtonHeld(ButtonCode.LeftControl) ||
  508. Input.IsButtonHeld(ButtonCode.RightControl);
  509. sceneSelection.PickObject(scenePos, ctrlHeld);
  510. }
  511. }
  512. }
  513. }
  514. else
  515. cameraController.EnableInput(false);
  516. SceneHandles.BeginInput();
  517. sceneHandles.UpdateInput(scenePos, Input.PointerDelta);
  518. sceneHandles.Draw();
  519. sceneAxesGUI.UpdateInput(scenePos);
  520. sceneAxesGUI.Draw();
  521. SceneHandles.EndInput();
  522. sceneSelection.Draw();
  523. UpdateGridMode();
  524. if (VirtualInput.IsButtonDown(frameKey))
  525. cameraController.FrameSelected();
  526. }
  527. /// <inheritdoc/>
  528. protected override void WindowResized(int width, int height)
  529. {
  530. UpdateRenderTexture(width, height - HeaderHeight);
  531. base.WindowResized(width, height);
  532. }
  533. /// <inheritdoc/>
  534. protected override void FocusChanged(bool inFocus)
  535. {
  536. if (!inFocus)
  537. {
  538. sceneHandles.ClearSelection();
  539. }
  540. }
  541. /// <summary>
  542. /// Triggered when one of the scene tool buttons is clicked, changing the active scene handle.
  543. /// </summary>
  544. /// <param name="tool">Clicked scene tool to activate.</param>
  545. private void OnSceneToolButtonClicked(SceneViewTool tool)
  546. {
  547. EditorApplication.ActiveSceneTool = tool;
  548. editorSettingsHash = EditorSettings.Hash;
  549. }
  550. /// <summary>
  551. /// Triggered when one of the coordinate mode buttons is clicked, changing the active coordinate mode.
  552. /// </summary>
  553. /// <param name="mode">Clicked coordinate mode to activate.</param>
  554. private void OnCoordinateModeButtonClicked(HandleCoordinateMode mode)
  555. {
  556. EditorApplication.ActiveCoordinateMode = mode;
  557. editorSettingsHash = EditorSettings.Hash;
  558. }
  559. /// <summary>
  560. /// Triggered when one of the pivot buttons is clicked, changing the active pivot mode.
  561. /// </summary>
  562. /// <param name="mode">Clicked pivot mode to activate.</param>
  563. private void OnPivotModeButtonClicked(HandlePivotMode mode)
  564. {
  565. EditorApplication.ActivePivotMode = mode;
  566. editorSettingsHash = EditorSettings.Hash;
  567. }
  568. /// <summary>
  569. /// Triggered when the move snap button is toggled.
  570. /// </summary>
  571. /// <param name="active">Determins should be move snap be activated or deactivated.</param>
  572. private void OnMoveSnapToggled(bool active)
  573. {
  574. Handles.MoveHandleSnapActive = active;
  575. editorSettingsHash = EditorSettings.Hash;
  576. }
  577. /// <summary>
  578. /// Triggered when the move snap increment value changes.
  579. /// </summary>
  580. /// <param name="value">Value that determines in what increments to perform move snapping.</param>
  581. private void OnMoveSnapValueChanged(float value)
  582. {
  583. Handles.MoveSnapAmount = MathEx.Clamp(value, 0.01f, 1000.0f);
  584. editorSettingsHash = EditorSettings.Hash;
  585. }
  586. /// <summary>
  587. /// Triggered when the rotate snap button is toggled.
  588. /// </summary>
  589. /// <param name="active">Determins should be rotate snap be activated or deactivated.</param>
  590. private void OnRotateSnapToggled(bool active)
  591. {
  592. Handles.RotateHandleSnapActive = active;
  593. editorSettingsHash = EditorSettings.Hash;
  594. }
  595. /// <summary>
  596. /// Triggered when the rotate snap increment value changes.
  597. /// </summary>
  598. /// <param name="value">Value that determines in what increments to perform rotate snapping.</param>
  599. private void OnRotateSnapValueChanged(float value)
  600. {
  601. Handles.RotateSnapAmount = (Degree)MathEx.Clamp(value, 0.01f, 360.0f);
  602. editorSettingsHash = EditorSettings.Hash;
  603. }
  604. /// <summary>
  605. /// Updates toggle button states according to current editor options. This is useful if tools, coordinate mode,
  606. /// pivot or other scene view options have been modified externally.
  607. /// </summary>
  608. private void UpdateButtonStates()
  609. {
  610. switch (EditorApplication.ActiveSceneTool)
  611. {
  612. case SceneViewTool.View:
  613. viewButton.Value = true;
  614. break;
  615. case SceneViewTool.Move:
  616. moveButton.Value = true;
  617. break;
  618. case SceneViewTool.Rotate:
  619. rotateButton.Value = true;
  620. break;
  621. case SceneViewTool.Scale:
  622. scaleButton.Value = true;
  623. break;
  624. }
  625. switch (EditorApplication.ActiveCoordinateMode)
  626. {
  627. case HandleCoordinateMode.Local:
  628. localCoordButton.Value = true;
  629. break;
  630. case HandleCoordinateMode.World:
  631. worldCoordButton.Value = true;
  632. break;
  633. }
  634. switch (EditorApplication.ActivePivotMode)
  635. {
  636. case HandlePivotMode.Center:
  637. centerButton.Value = true;
  638. break;
  639. case HandlePivotMode.Pivot:
  640. pivotButton.Value = true;
  641. break;
  642. }
  643. if (Handles.MoveHandleSnapActive)
  644. moveSnapButton.Value = true;
  645. else
  646. moveSnapButton.Value = false;
  647. moveSnapInput.Value = Handles.MoveSnapAmount;
  648. if (Handles.RotateHandleSnapActive)
  649. rotateSnapButton.Value = true;
  650. else
  651. rotateSnapButton.Value = false;
  652. moveSnapInput.Value = Handles.RotateSnapAmount.Degrees;
  653. }
  654. /// <summary>
  655. /// Activates or deactivates the profiler overlay according to current editor settings.
  656. /// </summary>
  657. private void UpdateProfilerOverlay()
  658. {
  659. if (EditorSettings.GetBool(ProfilerOverlayActiveKey))
  660. {
  661. if (activeProfilerOverlay == null)
  662. {
  663. SceneObject profilerSO = new SceneObject("EditorProfilerOverlay");
  664. profilerCamera = profilerSO.AddComponent<Camera>();
  665. profilerCamera.Target = renderTexture;
  666. profilerCamera.ClearFlags = ClearFlags.None;
  667. profilerCamera.Priority = 1;
  668. profilerCamera.Layers = 0;
  669. activeProfilerOverlay = profilerSO.AddComponent<ProfilerOverlay>();
  670. }
  671. }
  672. else
  673. {
  674. if (activeProfilerOverlay != null)
  675. {
  676. activeProfilerOverlay.SceneObject.Destroy();
  677. activeProfilerOverlay = null;
  678. profilerCamera = null;
  679. }
  680. }
  681. }
  682. /// <summary>
  683. /// Creates the scene camera and updates the render texture. Should be called at least once before using the
  684. /// scene view. Should be called whenever the window is resized.
  685. /// </summary>
  686. /// <param name="width">Width of the scene render target, in pixels.</param>
  687. /// <param name="height">Height of the scene render target, in pixels.</param>
  688. private void UpdateRenderTexture(int width, int height)
  689. {
  690. width = MathEx.Max(20, width);
  691. height = MathEx.Max(20, height);
  692. renderTexture = new RenderTexture2D(PixelFormat.R8G8B8A8, width, height);
  693. renderTexture.Priority = 1;
  694. if (camera == null)
  695. {
  696. SceneObject sceneCameraSO = new SceneObject("SceneCamera", true);
  697. camera = sceneCameraSO.AddComponent<Camera>();
  698. camera.Target = renderTexture;
  699. camera.ViewportRect = new Rect2(0.0f, 0.0f, 1.0f, 1.0f);
  700. sceneCameraSO.Position = new Vector3(0, 0.5f, 1);
  701. sceneCameraSO.LookAt(new Vector3(0, 0.5f, 0));
  702. camera.Priority = 2;
  703. camera.NearClipPlane = 0.05f;
  704. camera.FarClipPlane = 2500.0f;
  705. camera.ClearColor = ClearColor;
  706. camera.Layers = UInt64.MaxValue & ~SceneAxesHandle.LAYER; // Don't draw scene axes in this camera
  707. cameraController = sceneCameraSO.AddComponent<SceneCamera>();
  708. renderTextureGUI = new GUIRenderTexture(renderTexture);
  709. rtPanel.AddElement(renderTextureGUI);
  710. sceneGrid = new SceneGrid(camera);
  711. sceneSelection = new SceneSelection(camera);
  712. sceneGizmos = new SceneGizmos(camera);
  713. sceneHandles = new SceneHandles(this, camera);
  714. }
  715. else
  716. {
  717. camera.Target = renderTexture;
  718. renderTextureGUI.RenderTexture = renderTexture;
  719. }
  720. Rect2I rtBounds = new Rect2I(0, 0, width, height);
  721. renderTextureGUI.Bounds = rtBounds;
  722. focusCatcher.Bounds = GUILayoutUtility.CalculateBounds(rtPanel, GUI);
  723. sceneAxesGUI.SetPosition(width - HandleAxesGUISize - HandleAxesGUIPaddingX, HandleAxesGUIPaddingY);
  724. // TODO - Consider only doing the resize once user stops resizing the widget in order to reduce constant
  725. // render target destroy/create cycle for every single pixel.
  726. camera.AspectRatio = width / (float)height;
  727. if (profilerCamera != null)
  728. profilerCamera.Target = renderTexture;
  729. }
  730. /// <summary>
  731. /// Parses an array of scene objects and removes elements that are children of elements that are also in the array.
  732. /// </summary>
  733. /// <param name="objects">Array containing duplicate objects as input, and array without duplicate objects as
  734. /// output.</param>
  735. private void CleanDuplicates(ref SceneObject[] objects)
  736. {
  737. List<SceneObject> cleanList = new List<SceneObject>();
  738. for (int i = 0; i < objects.Length; i++)
  739. {
  740. bool foundParent = false;
  741. for (int j = 0; j < objects.Length; j++)
  742. {
  743. SceneObject elem = objects[i];
  744. while (elem != null && elem != objects[j])
  745. elem = elem.Parent;
  746. bool isChildOf = elem == objects[j];
  747. if (i != j && isChildOf)
  748. {
  749. foundParent = true;
  750. break;
  751. }
  752. }
  753. if (!foundParent)
  754. cleanList.Add(objects[i]);
  755. }
  756. objects = cleanList.ToArray();
  757. }
  758. }
  759. }