SceneWindow.cs 51 KB

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