SceneWindow.cs 53 KB

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