SceneWindow.cs 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. using bs;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. namespace bs.Editor
  8. {
  9. /** @addtogroup Scene-Editor
  10. * @{
  11. */
  12. /// <summary>
  13. /// Displays the scene view camera and various scene controls.
  14. /// </summary>
  15. internal sealed class SceneWindow : EditorWindow, IGlobalShortcuts
  16. {
  17. internal const string ToggleProfilerOverlayBinding = "ToggleProfilerOverlay";
  18. internal const string ViewToolBinding = "ViewTool";
  19. internal const string MoveToolBinding = "MoveTool";
  20. internal const string RotateToolBinding = "RotateTool";
  21. internal const string ScaleToolBinding = "ScaleTool";
  22. internal const string FrameBinding = "SceneFrame";
  23. private const string CameraPositionKey = "SceneCamera0_Position";
  24. private const string CameraRotationKey = "SceneCamera0_Rotation";
  25. private const int HeaderHeight = 20;
  26. private const float DefaultPlacementDepth = 5.0f;
  27. private static readonly Color ClearColor = new Color(0.0f, 0.3685f, 0.7969f);
  28. private const int HandleAxesGUISize = 50;
  29. private const int HandleAxesGUIPaddingX = 10;
  30. private const int HandleAxesGUIPaddingY = 5;
  31. private Camera camera;
  32. private SceneCamera sceneCamera;
  33. private RenderTexture renderTexture;
  34. private GUILayoutY mainLayout;
  35. private GUIPanel rtPanel;
  36. private GUIPanel sceneAxesPanel;
  37. private GUIButton focusCatcher;
  38. private GUIRenderTexture renderTextureGUI;
  39. private SceneGrid sceneGrid;
  40. private SceneSelection sceneSelection;
  41. private SceneGizmos sceneGizmos;
  42. private SceneHandles sceneHandles;
  43. private GUIToggle viewButton;
  44. private GUIToggle moveButton;
  45. private GUIToggle rotateButton;
  46. private GUIToggle scaleButton;
  47. private GUIToggle localCoordButton;
  48. private GUIToggle worldCoordButton;
  49. private GUIToggle pivotButton;
  50. private GUIToggle centerButton;
  51. private GUIToggle moveSnapButton;
  52. private GUIFloatField moveSnapInput;
  53. private GUIToggle rotateSnapButton;
  54. private GUIFloatField rotateSnapInput;
  55. private GUIButton cameraOptionsButton;
  56. private GUILayout progressLayout;
  57. private GUIProgressBar loadProgressBar;
  58. private GUILabel loadLabel;
  59. private SceneAxesGUI sceneAxesGUI;
  60. private ProjectionType sceneAxesLastProjectionType;
  61. private bool hasContentFocus = false;
  62. private bool HasContentFocus { get { return HasFocus && hasContentFocus; } }
  63. private bool loadingProgressShown = false;
  64. private bool AllowViewportInput { get { return !loadingProgressShown; } }
  65. private int editorSettingsHash = int.MaxValue;
  66. private VirtualButton frameKey;
  67. // Tool shortcuts
  68. private VirtualButton viewToolKey;
  69. private VirtualButton moveToolKey;
  70. private VirtualButton rotateToolKey;
  71. private VirtualButton scaleToolKey;
  72. // Drag & drop
  73. private bool dragActive;
  74. private SceneObject draggedSO;
  75. private Vector3 draggedSOOffset;
  76. private GUITexture dragSelection;
  77. private bool isDraggingSelection;
  78. private Vector2I dragSelectionStart;
  79. private Vector2I dragSelectionEnd;
  80. private Vector2I mouseDownPosition;
  81. private GUIPanel selectionPanel;
  82. /// <summary>
  83. /// Returns the scene camera.
  84. /// </summary>
  85. public SceneCamera Camera => sceneCamera;
  86. /// <summary>
  87. /// Constructs a new scene window.
  88. /// </summary>
  89. internal SceneWindow()
  90. { }
  91. /// <summary>
  92. /// Opens a scene window if its not open already.
  93. /// </summary>
  94. [MenuItem("Windows/Scene", ButtonModifier.CtrlAlt, ButtonCode.S, 6000)]
  95. private static void OpenSceneWindow()
  96. {
  97. OpenWindow<SceneWindow>();
  98. }
  99. /// <summary>
  100. /// Focuses on the currently selected object.
  101. /// </summary>
  102. [MenuItem("Tools/Frame Selected", ButtonModifier.None, ButtonCode.F, 9275, true)]
  103. private static void OpenSettingsWindow()
  104. {
  105. SceneWindow window = GetWindow<SceneWindow>();
  106. if (window != null)
  107. window.sceneCamera.FrameSelected();
  108. }
  109. /// <summary>
  110. /// Switches the active tool to the view tool.
  111. /// </summary>
  112. [MenuItem("Tools/View", ButtonModifier.Ctrl, ButtonCode.Q, 9274, true)]
  113. private static void SetViewTool()
  114. {
  115. SceneWindow window = GetWindow<SceneWindow>();
  116. if (window != null)
  117. window.OnSceneToolButtonClicked(SceneViewTool.View);
  118. }
  119. /// <summary>
  120. /// Switches the active tool to the move tool.
  121. /// </summary>
  122. [MenuItem("Tools/Move", ButtonModifier.Ctrl, ButtonCode.W, 9273)]
  123. private static void SetMoveTool()
  124. {
  125. SceneWindow window = GetWindow<SceneWindow>();
  126. if (window != null)
  127. window.OnSceneToolButtonClicked(SceneViewTool.Move);
  128. }
  129. /// <summary>
  130. /// Switches the active tool to the rotate tool.
  131. /// </summary>
  132. [MenuItem("Tools/Rotate", ButtonModifier.Ctrl, ButtonCode.E, 9272)]
  133. private static void SetRotateTool()
  134. {
  135. SceneWindow window = GetWindow<SceneWindow>();
  136. if (window != null)
  137. window.OnSceneToolButtonClicked(SceneViewTool.Rotate);
  138. }
  139. /// <summary>
  140. /// Switches the active tool to the scale tool.
  141. /// </summary>
  142. [MenuItem("Tools/Scale", ButtonModifier.Ctrl, ButtonCode.R, 9271)]
  143. private static void SetScaleTool()
  144. {
  145. SceneWindow window = GetWindow<SceneWindow>();
  146. if (window != null)
  147. window.OnSceneToolButtonClicked(SceneViewTool.Scale);
  148. }
  149. /// <inheritdoc/>
  150. protected override LocString GetDisplayName()
  151. {
  152. return new LocEdString("Scene");
  153. }
  154. private void OnInitialize()
  155. {
  156. mainLayout = GUI.AddLayoutY();
  157. GUIContent viewIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.View),
  158. new LocEdString("View"));
  159. GUIContent moveIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.Move),
  160. new LocEdString("Move"));
  161. GUIContent rotateIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.Rotate),
  162. new LocEdString("Rotate"));
  163. GUIContent scaleIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.Scale),
  164. new LocEdString("Scale"));
  165. GUIContent localIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.Local),
  166. new LocEdString("Local"));
  167. GUIContent worldIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.World),
  168. new LocEdString("World"));
  169. GUIContent pivotIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.Pivot),
  170. new LocEdString("Pivot"));
  171. GUIContent centerIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.Center),
  172. new LocEdString("Center"));
  173. GUIContent moveSnapIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.MoveSnap),
  174. new LocEdString("Move snap"));
  175. GUIContent rotateSnapIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.RotateSnap),
  176. new LocEdString("Rotate snap"));
  177. GUIToggleGroup handlesTG = new GUIToggleGroup();
  178. viewButton = new GUIToggle(viewIcon, handlesTG, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  179. moveButton = new GUIToggle(moveIcon, handlesTG, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  180. rotateButton = new GUIToggle(rotateIcon, handlesTG, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  181. scaleButton = new GUIToggle(scaleIcon, handlesTG, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  182. GUIToggleGroup coordModeTG = new GUIToggleGroup();
  183. localCoordButton = new GUIToggle(localIcon, coordModeTG, EditorStyles.Button, GUIOption.FlexibleWidth(75));
  184. worldCoordButton = new GUIToggle(worldIcon, coordModeTG, EditorStyles.Button, GUIOption.FlexibleWidth(75));
  185. GUIToggleGroup pivotModeTG = new GUIToggleGroup();
  186. pivotButton = new GUIToggle(pivotIcon, pivotModeTG, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  187. centerButton = new GUIToggle(centerIcon, pivotModeTG, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  188. moveSnapButton = new GUIToggle(moveSnapIcon, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  189. moveSnapInput = new GUIFloatField("", GUIOption.FlexibleWidth(35));
  190. rotateSnapButton = new GUIToggle(rotateSnapIcon, EditorStyles.Button, GUIOption.FlexibleWidth(35));
  191. rotateSnapInput = new GUIFloatField("", GUIOption.FlexibleWidth(35));
  192. GUIContent cameraOptionsIcon = new GUIContent(EditorBuiltin.GetSceneWindowIcon(SceneWindowIcon.SceneCameraOptions), new LocEdString("Camera options"));
  193. cameraOptionsButton = new GUIButton(cameraOptionsIcon);
  194. viewButton.OnClick += () => OnSceneToolButtonClicked(SceneViewTool.View);
  195. moveButton.OnClick += () => OnSceneToolButtonClicked(SceneViewTool.Move);
  196. rotateButton.OnClick += () => OnSceneToolButtonClicked(SceneViewTool.Rotate);
  197. scaleButton.OnClick += () => OnSceneToolButtonClicked(SceneViewTool.Scale);
  198. localCoordButton.OnClick += () => OnCoordinateModeButtonClicked(HandleCoordinateMode.Local);
  199. worldCoordButton.OnClick += () => OnCoordinateModeButtonClicked(HandleCoordinateMode.World);
  200. pivotButton.OnClick += () => OnPivotModeButtonClicked(HandlePivotMode.Pivot);
  201. centerButton.OnClick += () => OnPivotModeButtonClicked(HandlePivotMode.Center);
  202. moveSnapButton.OnToggled += (bool active) => OnMoveSnapToggled(active);
  203. moveSnapInput.OnChanged += (float value) => OnMoveSnapValueChanged(value);
  204. rotateSnapButton.OnToggled += (bool active) => OnRotateSnapToggled(active);
  205. rotateSnapInput.OnChanged += (float value) => OnRotateSnapValueChanged(value);
  206. cameraOptionsButton.OnClick += () => OnCameraOptionsClicked();
  207. GUILayout handlesLayout = mainLayout.AddLayoutX();
  208. handlesLayout.AddElement(viewButton);
  209. handlesLayout.AddElement(moveButton);
  210. handlesLayout.AddElement(rotateButton);
  211. handlesLayout.AddElement(scaleButton);
  212. handlesLayout.AddSpace(10);
  213. handlesLayout.AddElement(localCoordButton);
  214. handlesLayout.AddElement(worldCoordButton);
  215. handlesLayout.AddSpace(10);
  216. handlesLayout.AddElement(pivotButton);
  217. handlesLayout.AddElement(centerButton);
  218. handlesLayout.AddFlexibleSpace();
  219. handlesLayout.AddElement(moveSnapButton);
  220. handlesLayout.AddElement(moveSnapInput);
  221. handlesLayout.AddSpace(10);
  222. handlesLayout.AddElement(rotateSnapButton);
  223. handlesLayout.AddElement(rotateSnapInput);
  224. handlesLayout.AddSpace(10);
  225. handlesLayout.AddElement(cameraOptionsButton);
  226. handlesLayout.SetHeight(viewButton.Bounds.height);
  227. GUIPanel mainPanel = mainLayout.AddPanel();
  228. rtPanel = mainPanel.AddPanel();
  229. // Loading progress
  230. loadLabel = new GUILabel(new LocEdString("Loading scene..."));
  231. loadProgressBar = new GUIProgressBar("", GUIOption.FixedWidth(200));
  232. progressLayout = mainPanel.AddLayoutY();
  233. progressLayout.AddFlexibleSpace();
  234. GUILayout loadLabelLayout = progressLayout.AddLayoutX();
  235. loadLabelLayout.AddFlexibleSpace();
  236. loadLabelLayout.AddElement(loadLabel);
  237. loadLabelLayout.AddFlexibleSpace();
  238. GUILayout progressBarLayout = progressLayout.AddLayoutX();
  239. progressBarLayout.AddFlexibleSpace();
  240. progressBarLayout.AddElement(loadProgressBar);
  241. progressBarLayout.AddFlexibleSpace();
  242. progressLayout.AddFlexibleSpace();
  243. progressLayout.Active = false;
  244. selectionPanel = mainPanel.AddPanel(-1);
  245. sceneAxesPanel = mainPanel.AddPanel(-1);
  246. sceneAxesGUI = new SceneAxesGUI(this, sceneAxesPanel, HandleAxesGUISize, HandleAxesGUISize, ProjectionType.Perspective);
  247. sceneAxesLastProjectionType = ProjectionType.Perspective;
  248. focusCatcher = new GUIButton("", EditorStyles.Blank);
  249. focusCatcher.OnFocusGained += () => hasContentFocus = true;
  250. focusCatcher.OnFocusLost += () => hasContentFocus = false;
  251. GUIPanel focusPanel = GUI.AddPanel(-2);
  252. focusPanel.AddElement(focusCatcher);
  253. viewToolKey = new VirtualButton(ViewToolBinding);
  254. moveToolKey = new VirtualButton(MoveToolBinding);
  255. rotateToolKey = new VirtualButton(RotateToolBinding);
  256. scaleToolKey = new VirtualButton(ScaleToolBinding);
  257. frameKey = new VirtualButton(FrameBinding);
  258. UpdateRenderTexture(Width, Height - HeaderHeight);
  259. UpdateLoadingProgress();
  260. }
  261. private void OnCameraOptionsClicked()
  262. {
  263. SceneCameraSettingsWindow.Open();
  264. }
  265. private void OnDestroy()
  266. {
  267. if (camera != null)
  268. {
  269. Vector3 pos = camera.SceneObject.Position;
  270. Quaternion rot = camera.SceneObject.Rotation;
  271. ProjectSettings.SetObject(CameraPositionKey, pos);
  272. ProjectSettings.SetObject(CameraRotationKey, rot);
  273. camera.SceneObject.Destroy(true);
  274. camera = null;
  275. }
  276. sceneAxesGUI.Destroy();
  277. sceneAxesGUI = null;
  278. }
  279. /// <summary>
  280. /// Deletes all currently selected objects.
  281. /// </summary>
  282. private void DeleteSelection()
  283. {
  284. SceneObject[] selectedObjects = Selection.SceneObjects;
  285. CleanDuplicates(ref selectedObjects);
  286. if (selectedObjects.Length > 0)
  287. {
  288. foreach (var so in selectedObjects)
  289. {
  290. string message = "Deleted " + so.Name;
  291. UndoRedo.DeleteSO(so, message);
  292. }
  293. EditorApplication.SetSceneDirty();
  294. }
  295. }
  296. /// <summary>
  297. /// Duplicates all currently selected objects.
  298. /// </summary>
  299. private void DuplicateSelection()
  300. {
  301. SceneObject[] selectedObjects = Selection.SceneObjects;
  302. CleanDuplicates(ref selectedObjects);
  303. if (selectedObjects.Length > 0)
  304. {
  305. string message;
  306. if (selectedObjects.Length == 1)
  307. message = "Duplicated " + selectedObjects[0].Name;
  308. else
  309. message = "Duplicated " + selectedObjects.Length + " elements";
  310. Transform[] savedTransforms = new Transform[selectedObjects.Length];
  311. for (int i = 0; i < savedTransforms.Length; i++)
  312. savedTransforms[i] = new Transform(selectedObjects[i]);
  313. SceneObject[] clonedObjects = UndoRedo.CloneSO(selectedObjects, message);
  314. // Restore world positions
  315. for (int i = 0; i < savedTransforms.Length; i++)
  316. savedTransforms[i].Apply(clonedObjects[i]);
  317. EditorApplication.SetSceneDirty();
  318. }
  319. }
  320. /// <inheritdoc/>
  321. void IGlobalShortcuts.OnRenamePressed()
  322. {
  323. // Do nothing
  324. }
  325. /// <inheritdoc/>
  326. void IGlobalShortcuts.OnDuplicatePressed()
  327. {
  328. DuplicateSelection();
  329. }
  330. /// <inheritdoc/>
  331. void IGlobalShortcuts.OnDeletePressed()
  332. {
  333. DeleteSelection();
  334. }
  335. /// <inheritdoc/>
  336. void IGlobalShortcuts.OnCopyPressed()
  337. {
  338. // Do nothing
  339. }
  340. /// <inheritdoc/>
  341. void IGlobalShortcuts.OnCutPressed()
  342. {
  343. // Do nothing
  344. }
  345. /// <inheritdoc/>
  346. void IGlobalShortcuts.OnPastePressed()
  347. {
  348. // Do nothing
  349. }
  350. /// <summary>
  351. /// Orients the camera so it looks along the provided axis.
  352. /// </summary>
  353. /// <param name="axis">Axis to look along.</param>
  354. internal void LookAlong(Vector3 axis)
  355. {
  356. axis.Normalize();
  357. sceneCamera.LookAlong(axis);
  358. UpdateGridMode();
  359. }
  360. private void UpdateGridMode()
  361. {
  362. Vector3 forward = camera.SceneObject.Forward;
  363. if (camera.ProjectionType == ProjectionType.Perspective)
  364. sceneGrid.SetMode(GridMode.Perspective);
  365. else
  366. {
  367. float dotX = Vector3.Dot(forward, Vector3.XAxis);
  368. if (dotX >= 0.95f)
  369. sceneGrid.SetMode(GridMode.OrthoX);
  370. else if (dotX <= -0.95f)
  371. sceneGrid.SetMode(GridMode.OrthoNegX);
  372. else
  373. {
  374. float dotY = Vector3.Dot(forward, Vector3.YAxis);
  375. if (dotY >= 0.95f)
  376. sceneGrid.SetMode(GridMode.OrthoY);
  377. else if (dotY <= -0.95f)
  378. sceneGrid.SetMode(GridMode.OrthoNegY);
  379. else
  380. {
  381. float dotZ = Vector3.Dot(forward, Vector3.ZAxis);
  382. if (dotZ >= 0.95f)
  383. sceneGrid.SetMode(GridMode.OrthoZ);
  384. else if (dotZ <= -0.95f)
  385. sceneGrid.SetMode(GridMode.OrthoNegZ);
  386. else
  387. sceneGrid.SetMode(GridMode.Perspective);
  388. }
  389. }
  390. }
  391. }
  392. /// <summary>
  393. /// Converts screen coordinates into coordinates relative to the scene view render texture.
  394. /// </summary>
  395. /// <param name="screenPos">Coordinates relative to the screen.</param>
  396. /// <param name="scenePos">Output coordinates relative to the scene view texture.</param>
  397. /// <returns>True if the coordinates are within the scene view texture, false otherwise.</returns>
  398. private bool ScreenToScenePos(Vector2I screenPos, out Vector2I scenePos)
  399. {
  400. scenePos = screenPos;
  401. Vector2I windowPos = ScreenToWindowPos(screenPos);
  402. Rect2I bounds = GUIUtility.CalculateBounds(renderTextureGUI, GUI);
  403. if (bounds.Contains(windowPos))
  404. {
  405. scenePos.x = windowPos.x - bounds.x;
  406. scenePos.y = windowPos.y - bounds.y;
  407. return true;
  408. }
  409. return false;
  410. }
  411. private void OnEditorUpdate()
  412. {
  413. UpdateLoadingProgress();
  414. if (HasFocus)
  415. {
  416. if (!Input.IsPointerButtonHeld(PointerButton.Right))
  417. {
  418. if (VirtualInput.IsButtonDown(EditorApplication.DuplicateKey))
  419. DuplicateSelection();
  420. else if (VirtualInput.IsButtonDown(EditorApplication.DeleteKey))
  421. DeleteSelection();
  422. else if (VirtualInput.IsButtonDown(viewToolKey))
  423. EditorApplication.ActiveSceneTool = SceneViewTool.View;
  424. else if (VirtualInput.IsButtonDown(moveToolKey))
  425. EditorApplication.ActiveSceneTool = SceneViewTool.Move;
  426. else if (VirtualInput.IsButtonDown(rotateToolKey))
  427. EditorApplication.ActiveSceneTool = SceneViewTool.Rotate;
  428. else if (VirtualInput.IsButtonDown(scaleToolKey))
  429. EditorApplication.ActiveSceneTool = SceneViewTool.Scale;
  430. }
  431. }
  432. // Refresh GUI buttons if needed (in case someones changes the values from script)
  433. if (editorSettingsHash != EditorSettings.Hash)
  434. {
  435. UpdateButtonStates();
  436. editorSettingsHash = EditorSettings.Hash;
  437. }
  438. // Update scene view handles and selection
  439. sceneGrid.Draw();
  440. ProjectionType currentProjType = camera.ProjectionType;
  441. if (sceneAxesLastProjectionType != currentProjType)
  442. {
  443. sceneAxesGUI.ProjectionType = currentProjType;
  444. sceneAxesLastProjectionType = currentProjType;
  445. }
  446. bool handleActive = sceneHandles.IsActive() || sceneAxesGUI.IsActive();
  447. Vector2I scenePos;
  448. bool inBounds = ScreenToScenePos(Input.PointerPosition, out scenePos);
  449. bool clearSelection = false;
  450. if (AllowViewportInput)
  451. {
  452. if (Input.IsPointerButtonUp(PointerButton.Left))
  453. clearSelection = true;
  454. else if (Input.IsPointerButtonDown(PointerButton.Left))
  455. mouseDownPosition = scenePos;
  456. }
  457. else
  458. {
  459. clearSelection = true;
  460. inBounds = false;
  461. }
  462. bool dragResult = false;
  463. if (clearSelection)
  464. {
  465. dragResult = EndDragSelection();
  466. if (sceneHandles.IsActive())
  467. sceneHandles.ClearSelection();
  468. if (sceneAxesGUI.IsActive())
  469. sceneAxesGUI.ClearSelection();
  470. }
  471. bool draggedOver = DragDrop.DragInProgress || DragDrop.DropInProgress;
  472. draggedOver &= IsPointerHovering && inBounds && DragDrop.Type == DragDropType.Resource;
  473. if (draggedOver)
  474. {
  475. if (DragDrop.DropInProgress)
  476. {
  477. dragActive = false;
  478. if (draggedSO != null)
  479. {
  480. Selection.SceneObject = draggedSO;
  481. EditorApplication.SetSceneDirty();
  482. }
  483. draggedSO = null;
  484. }
  485. else
  486. {
  487. if (!dragActive)
  488. {
  489. dragActive = true;
  490. ResourceDragDropData dragData = (ResourceDragDropData)DragDrop.Data;
  491. string[] draggedPaths = dragData.Paths;
  492. for (int i = 0; i < draggedPaths.Length; i++)
  493. {
  494. ResourceMeta meta = ProjectLibrary.GetMeta(draggedPaths[i]);
  495. if (meta != null)
  496. {
  497. if (meta.ResType == ResourceType.Mesh)
  498. {
  499. if (!string.IsNullOrEmpty(draggedPaths[i]))
  500. {
  501. string meshName = Path.GetFileNameWithoutExtension(draggedPaths[i]);
  502. draggedSO = UndoRedo.CreateSO(meshName, "Created a new Renderable \"" + meshName + "\"");
  503. Mesh mesh = ProjectLibrary.Load<Mesh>(draggedPaths[i]);
  504. Renderable renderable = draggedSO.AddComponent<Renderable>();
  505. renderable.Mesh = mesh;
  506. if (mesh != null)
  507. draggedSOOffset = mesh.Bounds.Box.Center;
  508. else
  509. draggedSOOffset = Vector3.Zero;
  510. }
  511. break;
  512. }
  513. else if (meta.ResType == ResourceType.Prefab)
  514. {
  515. if (!string.IsNullOrEmpty(draggedPaths[i]))
  516. {
  517. Prefab prefab = ProjectLibrary.Load<Prefab>(draggedPaths[i]);
  518. draggedSO = UndoRedo.Instantiate(prefab, "Instantiating " + prefab.Name);
  519. if (draggedSO != null)
  520. {
  521. AABox draggedObjBounds = EditorUtility.CalculateBounds(draggedSO);
  522. draggedSOOffset = draggedObjBounds.Center;
  523. }
  524. else
  525. draggedSOOffset = Vector3.Zero;
  526. }
  527. break;
  528. }
  529. }
  530. }
  531. }
  532. if (draggedSO != null)
  533. {
  534. if (Input.IsButtonHeld(ButtonCode.Space))
  535. {
  536. SnapData snapData;
  537. sceneSelection.Snap(scenePos, out snapData, new SceneObject[] { draggedSO });
  538. Quaternion q = Quaternion.FromToRotation(Vector3.YAxis, snapData.normal);
  539. draggedSO.Position = snapData.position;
  540. draggedSO.Rotation = q;
  541. }
  542. else
  543. {
  544. Ray worldRay = camera.ScreenPointToRay(scenePos);
  545. draggedSO.Position = worldRay * DefaultPlacementDepth - draggedSOOffset;
  546. }
  547. }
  548. }
  549. return;
  550. }
  551. else
  552. {
  553. if (dragActive)
  554. {
  555. dragActive = false;
  556. if (draggedSO != null)
  557. {
  558. draggedSO.Destroy();
  559. draggedSO = null;
  560. }
  561. }
  562. }
  563. if ((HasContentFocus || IsPointerHovering) && AllowViewportInput)
  564. {
  565. sceneCamera.EnableInput(true);
  566. if (inBounds && HasContentFocus)
  567. {
  568. if (Input.IsPointerButtonDown(PointerButton.Left))
  569. {
  570. Rect2I sceneAxesGUIBounds = new Rect2I(Width - HandleAxesGUISize - HandleAxesGUIPaddingX,
  571. HandleAxesGUIPaddingY, HandleAxesGUISize, HandleAxesGUISize);
  572. if (sceneAxesGUIBounds.Contains(scenePos))
  573. sceneAxesGUI.TrySelect(scenePos);
  574. else
  575. sceneHandles.TrySelect(scenePos);
  576. }
  577. else if (Input.IsPointerButtonHeld(PointerButton.Left) && !handleActive && !dragActive &&
  578. draggedSO == null && scenePos != mouseDownPosition)
  579. {
  580. if (isDraggingSelection)
  581. UpdateDragSelection(scenePos);
  582. else
  583. StartDragSelection(scenePos);
  584. }
  585. else if (Input.IsPointerButtonUp(PointerButton.Left))
  586. {
  587. if (!handleActive && !dragActive && !dragResult)
  588. {
  589. bool ctrlHeld = Input.IsButtonHeld(ButtonCode.LeftControl) ||
  590. Input.IsButtonHeld(ButtonCode.RightControl);
  591. sceneSelection.PickObject(scenePos, ctrlHeld, new SceneObject[] { draggedSO });
  592. }
  593. }
  594. }
  595. }
  596. else
  597. sceneCamera.EnableInput(false);
  598. if (AllowViewportInput)
  599. {
  600. SceneHandles.BeginInput();
  601. sceneHandles.UpdateInput(scenePos, Input.PointerDelta);
  602. sceneAxesGUI.UpdateInput(scenePos);
  603. SceneHandles.EndInput();
  604. }
  605. sceneHandles.Draw();
  606. sceneAxesGUI.Draw();
  607. // Must be done after handle input is processed, in order to reflect most recent transform
  608. sceneGizmos.Draw();
  609. sceneSelection.Draw();
  610. UpdateGridMode();
  611. if (VirtualInput.IsButtonDown(frameKey))
  612. sceneCamera.FrameSelected();
  613. }
  614. /// <inheritdoc/>
  615. protected override void WindowResized(int width, int height)
  616. {
  617. UpdateRenderTexture(width, height - HeaderHeight);
  618. base.WindowResized(width, height);
  619. }
  620. /// <inheritdoc/>
  621. protected override void FocusChanged(bool inFocus)
  622. {
  623. if (!inFocus)
  624. {
  625. sceneHandles.ClearSelection();
  626. }
  627. }
  628. /// <summary>
  629. /// Triggered when one of the scene tool buttons is clicked, changing the active scene handle.
  630. /// </summary>
  631. /// <param name="tool">Clicked scene tool to activate.</param>
  632. private void OnSceneToolButtonClicked(SceneViewTool tool)
  633. {
  634. EditorApplication.ActiveSceneTool = tool;
  635. editorSettingsHash = EditorSettings.Hash;
  636. }
  637. /// <summary>
  638. /// Triggered when one of the coordinate mode buttons is clicked, changing the active coordinate mode.
  639. /// </summary>
  640. /// <param name="mode">Clicked coordinate mode to activate.</param>
  641. private void OnCoordinateModeButtonClicked(HandleCoordinateMode mode)
  642. {
  643. EditorApplication.ActiveCoordinateMode = mode;
  644. editorSettingsHash = EditorSettings.Hash;
  645. }
  646. /// <summary>
  647. /// Triggered when one of the pivot buttons is clicked, changing the active pivot mode.
  648. /// </summary>
  649. /// <param name="mode">Clicked pivot mode to activate.</param>
  650. private void OnPivotModeButtonClicked(HandlePivotMode mode)
  651. {
  652. EditorApplication.ActivePivotMode = mode;
  653. editorSettingsHash = EditorSettings.Hash;
  654. }
  655. /// <summary>
  656. /// Triggered when the move snap button is toggled.
  657. /// </summary>
  658. /// <param name="active">Determins should be move snap be activated or deactivated.</param>
  659. private void OnMoveSnapToggled(bool active)
  660. {
  661. Handles.MoveHandleSnapActive = active;
  662. editorSettingsHash = EditorSettings.Hash;
  663. }
  664. /// <summary>
  665. /// Triggered when the move snap increment value changes.
  666. /// </summary>
  667. /// <param name="value">Value that determines in what increments to perform move snapping.</param>
  668. private void OnMoveSnapValueChanged(float value)
  669. {
  670. Handles.MoveSnapAmount = MathEx.Clamp(value, 0.01f, 1000.0f);
  671. editorSettingsHash = EditorSettings.Hash;
  672. }
  673. /// <summary>
  674. /// Triggered when the rotate snap button is toggled.
  675. /// </summary>
  676. /// <param name="active">Determins should be rotate snap be activated or deactivated.</param>
  677. private void OnRotateSnapToggled(bool active)
  678. {
  679. Handles.RotateHandleSnapActive = active;
  680. editorSettingsHash = EditorSettings.Hash;
  681. }
  682. /// <summary>
  683. /// Triggered when the rotate snap increment value changes.
  684. /// </summary>
  685. /// <param name="value">Value that determines in what increments to perform rotate snapping.</param>
  686. private void OnRotateSnapValueChanged(float value)
  687. {
  688. Handles.RotateSnapAmount = (Degree)MathEx.Clamp(value, 0.01f, 360.0f);
  689. editorSettingsHash = EditorSettings.Hash;
  690. }
  691. /// <summary>
  692. /// Updates toggle button states according to current editor options. This is useful if tools, coordinate mode,
  693. /// pivot or other scene view options have been modified externally.
  694. /// </summary>
  695. private void UpdateButtonStates()
  696. {
  697. switch (EditorApplication.ActiveSceneTool)
  698. {
  699. case SceneViewTool.View:
  700. viewButton.Value = true;
  701. break;
  702. case SceneViewTool.Move:
  703. moveButton.Value = true;
  704. break;
  705. case SceneViewTool.Rotate:
  706. rotateButton.Value = true;
  707. break;
  708. case SceneViewTool.Scale:
  709. scaleButton.Value = true;
  710. break;
  711. }
  712. switch (EditorApplication.ActiveCoordinateMode)
  713. {
  714. case HandleCoordinateMode.Local:
  715. localCoordButton.Value = true;
  716. break;
  717. case HandleCoordinateMode.World:
  718. worldCoordButton.Value = true;
  719. break;
  720. }
  721. switch (EditorApplication.ActivePivotMode)
  722. {
  723. case HandlePivotMode.Center:
  724. centerButton.Value = true;
  725. break;
  726. case HandlePivotMode.Pivot:
  727. pivotButton.Value = true;
  728. break;
  729. }
  730. if (Handles.MoveHandleSnapActive)
  731. moveSnapButton.Value = true;
  732. else
  733. moveSnapButton.Value = false;
  734. moveSnapInput.Value = Handles.MoveSnapAmount;
  735. if (Handles.RotateHandleSnapActive)
  736. rotateSnapButton.Value = true;
  737. else
  738. rotateSnapButton.Value = false;
  739. moveSnapInput.Value = Handles.RotateSnapAmount.Degrees;
  740. }
  741. /// <summary>
  742. /// Creates the scene camera and updates the render texture. Should be called at least once before using the
  743. /// scene view. Should be called whenever the window is resized.
  744. /// </summary>
  745. /// <param name="width">Width of the scene render target, in pixels.</param>
  746. /// <param name="height">Height of the scene render target, in pixels.</param>
  747. private void UpdateRenderTexture(int width, int height)
  748. {
  749. width = MathEx.Max(20, width);
  750. height = MathEx.Max(20, height);
  751. // Note: Depth buffer and readable flags are required because ScenePicking uses it
  752. Texture colorTex = Texture.Create2D(width, height, PixelFormat.RGBA8, TextureUsage.Render | TextureUsage.CPUReadable);
  753. Texture depthTex = Texture.Create2D(width, height, PixelFormat.D32_S8X24, TextureUsage.DepthStencil | TextureUsage.CPUReadable);
  754. renderTexture = new RenderTexture(colorTex, depthTex);
  755. renderTexture.Priority = 1;
  756. if (camera == null)
  757. {
  758. SceneObject sceneCameraSO = new SceneObject("SceneCamera", true);
  759. camera = sceneCameraSO.AddComponent<Camera>();
  760. camera.Viewport.Target = renderTexture;
  761. camera.Viewport.Area = new Rect2(0.0f, 0.0f, 1.0f, 1.0f);
  762. Vector3 camPosition = new Vector3(0.0f, 1.7f, 5.0f);
  763. object camPosObj = ProjectSettings.GetObject<object>(CameraPositionKey);
  764. if (camPosObj is Vector3)
  765. camPosition = (Vector3)camPosObj;
  766. Quaternion camRotation = Quaternion.Identity;
  767. object camRotObj = ProjectSettings.GetObject<object>(CameraRotationKey);
  768. if (camRotObj is Quaternion)
  769. camRotation = (Quaternion)camRotObj;
  770. sceneCameraSO.Position = camPosition;
  771. sceneCameraSO.Rotation = camRotation;
  772. camera.Priority = 2;
  773. camera.Viewport.ClearColor = ClearColor;
  774. camera.Layers = UInt64.MaxValue & ~SceneAxesHandle.LAYER; // Don't draw scene axes in this camera
  775. sceneCamera = sceneCameraSO.AddComponent<SceneCamera>();
  776. renderTextureGUI = new GUIRenderTexture(renderTexture);
  777. rtPanel.AddElement(renderTextureGUI);
  778. sceneGrid = new SceneGrid(camera);
  779. sceneSelection = new SceneSelection(camera);
  780. sceneGizmos = new SceneGizmos(camera);
  781. sceneHandles = new SceneHandles(this, camera);
  782. }
  783. else
  784. {
  785. camera.Viewport.Target = renderTexture;
  786. renderTextureGUI.RenderTexture = renderTexture;
  787. }
  788. Rect2I rtBounds = new Rect2I(0, 0, width, height);
  789. renderTextureGUI.Bounds = rtBounds;
  790. focusCatcher.Bounds = GUIUtility.CalculateBounds(rtPanel, GUI);
  791. sceneAxesGUI.SetPosition(width - HandleAxesGUISize - HandleAxesGUIPaddingX, HandleAxesGUIPaddingY);
  792. // TODO - Consider only doing the resize once user stops resizing the widget in order to reduce constant
  793. // render target destroy/create cycle for every single pixel.
  794. camera.AspectRatio = width / (float)height;
  795. }
  796. /// <summary>
  797. /// Parses an array of scene objects and removes elements that are children of elements that are also in the array.
  798. /// </summary>
  799. /// <param name="objects">Array containing duplicate objects as input, and array without duplicate objects as
  800. /// output.</param>
  801. private void CleanDuplicates(ref SceneObject[] objects)
  802. {
  803. List<SceneObject> cleanList = new List<SceneObject>();
  804. for (int i = 0; i < objects.Length; i++)
  805. {
  806. bool foundParent = false;
  807. for (int j = 0; j < objects.Length; j++)
  808. {
  809. SceneObject elem = objects[i];
  810. while (elem != null && elem != objects[j])
  811. elem = elem.Parent;
  812. bool isChildOf = elem == objects[j];
  813. if (i != j && isChildOf)
  814. {
  815. foundParent = true;
  816. break;
  817. }
  818. }
  819. if (!foundParent)
  820. cleanList.Add(objects[i]);
  821. }
  822. objects = cleanList.ToArray();
  823. }
  824. /// <summary>
  825. /// Checks if the load progress bar needs to be shown, shows/hides it and updates the progress accordingly.
  826. /// </summary>
  827. private void UpdateLoadingProgress()
  828. {
  829. bool needsProgress = EditorApplication.IsSceneLoading;
  830. if (needsProgress && !loadingProgressShown)
  831. {
  832. progressLayout.Active = true;
  833. rtPanel.Active = false;
  834. sceneAxesPanel.Active = false;
  835. loadingProgressShown = true;
  836. }
  837. else if(!needsProgress && loadingProgressShown)
  838. {
  839. progressLayout.Active = false;
  840. rtPanel.Active = true;
  841. sceneAxesPanel.Active = true;
  842. loadingProgressShown = false;
  843. }
  844. if (needsProgress)
  845. loadProgressBar.Percent = EditorApplication.SceneLoadProgress;
  846. }
  847. /// <summary>
  848. /// Starts a drag operation that displays a selection outline allowing the user to select multiple entries at once.
  849. /// </summary>
  850. /// <param name="scenePos">Coordinates relative to the scene where the drag originated.</param>
  851. private void StartDragSelection(Vector2I scenePos)
  852. {
  853. isDraggingSelection = true;
  854. dragSelectionStart = scenePos;
  855. dragSelectionEnd = dragSelectionStart;
  856. }
  857. /// <summary>
  858. /// Updates a selection outline drag operation by expanding the outline to the new location. Elements in the outline
  859. /// are selected.
  860. /// </summary>
  861. /// <param name="scenePos">Coordinates of the pointer relative to the scene.</param>
  862. /// <returns>True if the selection outline drag is valid and was updated, false otherwise.</returns>
  863. private bool UpdateDragSelection(Vector2I scenePos)
  864. {
  865. if (!isDraggingSelection)
  866. return false;
  867. if (dragSelection == null)
  868. {
  869. dragSelection = new GUITexture(null, true, EditorStylesInternal.SelectionArea);
  870. selectionPanel.AddElement(dragSelection);
  871. }
  872. dragSelectionEnd = scenePos;
  873. Rect2I selectionArea = new Rect2I();
  874. Vector2I min = new Vector2I(Math.Min(dragSelectionStart.x, dragSelectionEnd.x), Math.Min(dragSelectionStart.y, dragSelectionEnd.y));
  875. Vector2I max = new Vector2I(Math.Max(dragSelectionStart.x, dragSelectionEnd.x), Math.Max(dragSelectionStart.y, dragSelectionEnd.y));
  876. selectionArea.x = min.x;
  877. selectionArea.y = min.y;
  878. selectionArea.width = Math.Max(max.x - min.x, 1);
  879. selectionArea.height = Math.Max(max.y - min.y, 1);
  880. dragSelection.Bounds = selectionArea;
  881. return true;
  882. }
  883. /// <summary>
  884. /// Ends the selection outline drag operation. Elements in the outline are selected.
  885. /// </summary>
  886. /// <returns>True if the selection outline drag is valid and was ended, false otherwise.</returns>
  887. private bool EndDragSelection()
  888. {
  889. if (!isDraggingSelection)
  890. return false;
  891. if (dragSelection != null)
  892. {
  893. dragSelection.Destroy();
  894. dragSelection = null;
  895. }
  896. if ((dragSelectionEnd - dragSelectionStart).Length < 1)
  897. {
  898. isDraggingSelection = false;
  899. return false;
  900. }
  901. Vector2I min = new Vector2I(Math.Min(dragSelectionStart.x, dragSelectionEnd.x),
  902. Math.Min(dragSelectionStart.y, dragSelectionEnd.y));
  903. Vector2I max = new Vector2I(Math.Max(dragSelectionStart.x, dragSelectionEnd.x),
  904. Math.Max(dragSelectionStart.y, dragSelectionEnd.y));
  905. sceneSelection.PickObjects(min, max - min,
  906. Input.IsButtonHeld(ButtonCode.LeftControl) || Input.IsButtonHeld(ButtonCode.RightControl));
  907. isDraggingSelection = false;
  908. return true;
  909. }
  910. /// <summary>
  911. /// Contains information about world transform of a single scene object.
  912. /// </summary>
  913. struct Transform
  914. {
  915. public Transform(SceneObject so)
  916. {
  917. position = so.Position;
  918. rotation = so.Rotation;
  919. scale = so.Scale;
  920. }
  921. /// <summary>
  922. /// Applies the saved transform to the specified scene object. The transform is assumed to be in world space.
  923. /// </summary>
  924. /// <param name="so">Scene object to apply the transform to.</param>
  925. public void Apply(SceneObject so)
  926. {
  927. so.Position = position;
  928. so.Rotation = rotation;
  929. so.LocalScale = scale;
  930. }
  931. public Vector3 position;
  932. public Quaternion rotation;
  933. public Vector3 scale;
  934. }
  935. }
  936. /** @} */
  937. }