SceneCamera.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. using BansheeEngine;
  4. namespace BansheeEditor
  5. {
  6. /** @addtogroup Scene-Editor
  7. * @{
  8. */
  9. /// <summary>
  10. /// Handles camera movement in the scene view.
  11. /// </summary>
  12. [RunInEditor]
  13. internal sealed class SceneCamera : ManagedComponent
  14. {
  15. #region Constants
  16. public const string MoveForwardBinding = "SceneForward";
  17. public const string MoveLeftBinding = "SceneLeft";
  18. public const string MoveRightBinding = "SceneRight";
  19. public const string MoveBackBinding = "SceneBackward";
  20. public const string MoveUpBinding = "SceneUp";
  21. public const string MoveDownBinding = "SceneDown";
  22. public const string FastMoveBinding = "SceneFastMove";
  23. public const string PanBinding = "ScenePan";
  24. public const string RotateBinding = "SceneRotate";
  25. public const string HorizontalAxisBinding = "SceneHorizontal";
  26. public const string VerticalAxisBinding = "SceneVertical";
  27. public const string ScrollAxisBinding = "SceneScroll";
  28. #endregion
  29. #region Fields
  30. private VirtualButton moveForwardBtn;
  31. private VirtualButton moveLeftBtn;
  32. private VirtualButton moveRightBtn;
  33. private VirtualButton moveBackwardBtn;
  34. private VirtualButton moveUpBtn;
  35. private VirtualButton moveDownBtn;
  36. private VirtualButton fastMoveBtn;
  37. private VirtualButton activeBtn;
  38. private VirtualButton panBtn;
  39. private VirtualAxis horizontalAxis;
  40. private VirtualAxis verticalAxis;
  41. private VirtualAxis scrollAxis;
  42. private float currentSpeed;
  43. private Degree yaw;
  44. private Degree pitch;
  45. private bool lastHideCursorState;
  46. private Camera camera;
  47. private bool inputEnabled = true;
  48. // Animating camera transitions
  49. private CameraAnimation animation = new CameraAnimation();
  50. private float frustumWidth = 50.0f;
  51. private float lerp;
  52. private bool isAnimating;
  53. #endregion
  54. #region Public properties
  55. /// <summary>
  56. /// Type of projection used by camera for rendering the scene.
  57. /// </summary>
  58. public ProjectionType ProjectionType
  59. {
  60. get { return camera.ProjectionType; }
  61. set
  62. {
  63. if (camera.ProjectionType != value)
  64. {
  65. CameraState state = new CameraState();
  66. state.Position = camera.SceneObject.Position;
  67. state.Rotation = camera.SceneObject.Rotation;
  68. state.Ortographic = value == ProjectionType.Orthographic;
  69. state.FrustumWidth = frustumWidth;
  70. SetState(state);
  71. }
  72. }
  73. }
  74. public SceneCameraOptions SceneCameraOptions { get; private set; } = new SceneCameraOptions();
  75. #endregion
  76. #region Public methods
  77. /// <summary>
  78. /// Enables or disables camera controls.
  79. /// </summary>
  80. /// <param name="enable">True to enable controls, false to disable.</param>
  81. public void EnableInput(bool enable)
  82. {
  83. inputEnabled = enable;
  84. }
  85. /// <summary>
  86. /// Focuses the camera on the currently selected object(s).
  87. /// </summary>
  88. public void FrameSelected()
  89. {
  90. SceneObject[] selectedObjects = Selection.SceneObjects;
  91. if (selectedObjects.Length > 0)
  92. {
  93. AABox box = EditorUtility.CalculateBounds(Selection.SceneObjects);
  94. FrameBounds(box);
  95. }
  96. }
  97. /// <summary>
  98. /// Orients the camera so it looks along the provided axis.
  99. /// </summary>
  100. public void LookAlong(Vector3 axis)
  101. {
  102. Vector3 up = Vector3.YAxis;
  103. if (MathEx.Abs(Vector3.Dot(axis, up)) > 0.9f)
  104. up = Vector3.ZAxis;
  105. CameraState state = new CameraState();
  106. state.Position = camera.SceneObject.Position;
  107. state.Rotation = Quaternion.LookRotation(axis, up);
  108. state.Ortographic = camera.ProjectionType == ProjectionType.Orthographic;
  109. state.FrustumWidth = frustumWidth;
  110. SetState(state);
  111. }
  112. #endregion
  113. #region Private methods
  114. private void OnReset()
  115. {
  116. camera = SceneObject.GetComponent<Camera>();
  117. moveForwardBtn = new VirtualButton(MoveForwardBinding);
  118. moveLeftBtn = new VirtualButton(MoveLeftBinding);
  119. moveRightBtn = new VirtualButton(MoveRightBinding);
  120. moveBackwardBtn = new VirtualButton(MoveBackBinding);
  121. moveUpBtn = new VirtualButton(MoveUpBinding);
  122. moveDownBtn = new VirtualButton(MoveDownBinding);
  123. fastMoveBtn = new VirtualButton(FastMoveBinding);
  124. activeBtn = new VirtualButton(RotateBinding);
  125. panBtn = new VirtualButton(PanBinding);
  126. horizontalAxis = new VirtualAxis(HorizontalAxisBinding);
  127. verticalAxis = new VirtualAxis(VerticalAxisBinding);
  128. scrollAxis = new VirtualAxis(ScrollAxisBinding);
  129. }
  130. private void OnUpdate()
  131. {
  132. bool isOrtographic = camera.ProjectionType == ProjectionType.Orthographic;
  133. if (inputEnabled)
  134. {
  135. bool goingForward = VirtualInput.IsButtonHeld(moveForwardBtn);
  136. bool goingBack = VirtualInput.IsButtonHeld(moveBackwardBtn);
  137. bool goingLeft = VirtualInput.IsButtonHeld(moveLeftBtn);
  138. bool goingRight = VirtualInput.IsButtonHeld(moveRightBtn);
  139. bool goingUp = VirtualInput.IsButtonHeld(moveUpBtn);
  140. bool goingDown = VirtualInput.IsButtonHeld(moveDownBtn);
  141. bool fastMove = VirtualInput.IsButtonHeld(fastMoveBtn);
  142. bool camActive = VirtualInput.IsButtonHeld(activeBtn);
  143. bool isPanning = VirtualInput.IsButtonHeld(panBtn);
  144. bool hideCursor = camActive || isPanning;
  145. if (hideCursor != lastHideCursorState)
  146. {
  147. if (hideCursor)
  148. {
  149. Cursor.Hide();
  150. Rect2I clipRect;
  151. clipRect.x = Input.PointerPosition.x - 2;
  152. clipRect.y = Input.PointerPosition.y - 2;
  153. clipRect.width = 4;
  154. clipRect.height = 4;
  155. Cursor.ClipToRect(clipRect);
  156. }
  157. else
  158. {
  159. Cursor.Show();
  160. Cursor.ClipDisable();
  161. }
  162. lastHideCursorState = hideCursor;
  163. }
  164. float frameDelta = Time.FrameDelta;
  165. if (camActive)
  166. {
  167. float horzValue = VirtualInput.GetAxisValue(horizontalAxis);
  168. float vertValue = VirtualInput.GetAxisValue(verticalAxis);
  169. float rotationAmount = SceneCameraOptions.RotationalSpeed * EditorSettings.MouseSensitivity;
  170. yaw += new Degree(horzValue * rotationAmount);
  171. pitch += new Degree(vertValue * rotationAmount);
  172. yaw = MathEx.WrapAngle(yaw);
  173. pitch = MathEx.WrapAngle(pitch);
  174. Quaternion yRot = Quaternion.FromAxisAngle(Vector3.YAxis, yaw);
  175. Quaternion xRot = Quaternion.FromAxisAngle(Vector3.XAxis, pitch);
  176. Quaternion camRot = yRot * xRot;
  177. camRot.Normalize();
  178. SceneObject.Rotation = camRot;
  179. // Handle movement using movement keys
  180. Vector3 direction = Vector3.Zero;
  181. if (goingForward) direction += SceneObject.Forward;
  182. if (goingBack) direction -= SceneObject.Forward;
  183. if (goingRight) direction += SceneObject.Right;
  184. if (goingLeft) direction -= SceneObject.Right;
  185. if (goingUp) direction += SceneObject.Up;
  186. if (goingDown) direction -= SceneObject.Up;
  187. if (direction.SqrdLength != 0)
  188. {
  189. direction.Normalize();
  190. float multiplier = 1.0f;
  191. if (fastMove)
  192. multiplier = SceneCameraOptions.FastModeMultiplier;
  193. currentSpeed = MathEx.Clamp(currentSpeed + SceneCameraOptions.Acceleration * frameDelta, SceneCameraOptions.StartSpeed, SceneCameraOptions.TopSpeed);
  194. currentSpeed *= multiplier;
  195. }
  196. else
  197. {
  198. currentSpeed = 0.0f;
  199. }
  200. const float tooSmall = 0.0001f;
  201. if (currentSpeed > tooSmall)
  202. {
  203. Vector3 velocity = direction * currentSpeed;
  204. SceneObject.Move(velocity * frameDelta);
  205. }
  206. }
  207. // Pan
  208. if (isPanning)
  209. {
  210. float horzValue = VirtualInput.GetAxisValue(horizontalAxis);
  211. float vertValue = VirtualInput.GetAxisValue(verticalAxis);
  212. Vector3 direction = new Vector3(horzValue, -vertValue, 0.0f);
  213. direction = camera.SceneObject.Rotation.Rotate(direction);
  214. SceneObject.Move(direction * SceneCameraOptions.PanSpeed * frameDelta);
  215. }
  216. }
  217. else
  218. {
  219. if (lastHideCursorState)
  220. {
  221. Cursor.Show();
  222. Cursor.ClipDisable();
  223. lastHideCursorState = false;
  224. }
  225. }
  226. SceneWindow sceneWindow = EditorWindow.GetWindow<SceneWindow>();
  227. if ((sceneWindow.Active && sceneWindow.HasFocus) || sceneWindow.IsPointerHovering)
  228. {
  229. Rect2I bounds = sceneWindow.Bounds;
  230. // Move using scroll wheel
  231. if (bounds.Contains(Input.PointerPosition))
  232. {
  233. float scrollAmount = VirtualInput.GetAxisValue(scrollAxis);
  234. if (!isOrtographic)
  235. {
  236. SceneObject.Move(SceneObject.Forward * scrollAmount * SceneCameraOptions.ScrollSpeed);
  237. }
  238. else
  239. {
  240. float orthoHeight = MathEx.Max(1.0f, camera.OrthoHeight - scrollAmount);
  241. camera.OrthoHeight = orthoHeight;
  242. }
  243. }
  244. }
  245. UpdateAnim();
  246. }
  247. /// <summary>
  248. /// Moves and orients a camera so that the provided bounds end covering the camera's viewport.
  249. /// </summary>
  250. /// <param name="bounds">Bounds to frame in camera's view.</param>
  251. /// <param name="padding">Amount of padding to leave on the borders of the viewport, in percent [0, 1].</param>
  252. private void FrameBounds(AABox bounds, float padding = 0.0f)
  253. {
  254. // TODO - Use AABox bounds directly instead of a sphere to be more accurate
  255. float worldWidth = bounds.Size.Length;
  256. float worldHeight = worldWidth;
  257. if (worldWidth == 0.0f)
  258. worldWidth = 1.0f;
  259. if (worldHeight == 0.0f)
  260. worldHeight = 1.0f;
  261. float boundsAspect = worldWidth / worldHeight;
  262. float paddingScale = MathEx.Clamp01(padding) + 1.0f;
  263. float frustumWidth;
  264. // If camera has wider aspect than bounds then height will be the limiting dimension
  265. if (camera.AspectRatio > boundsAspect)
  266. frustumWidth = worldHeight * camera.AspectRatio * paddingScale;
  267. else // Otherwise width
  268. frustumWidth = worldWidth * paddingScale;
  269. float distance = CalcDistanceForFrustumWidth(frustumWidth);
  270. Vector3 forward = bounds.Center - SceneObject.Position;
  271. forward.Normalize();
  272. CameraState state = new CameraState();
  273. state.Position = bounds.Center - forward * distance;
  274. state.Rotation = Quaternion.LookRotation(forward, Vector3.YAxis);
  275. state.Ortographic = camera.ProjectionType == ProjectionType.Orthographic;
  276. state.FrustumWidth = frustumWidth;
  277. SetState(state);
  278. }
  279. /// <summary>
  280. /// Changes the state of the camera, either instantly or animated over several frames. The state includes
  281. /// camera position, rotation, type and possibly other parameters.
  282. /// </summary>
  283. /// <param name="state">New state of the camera.</param>
  284. /// <param name="animated">Should the state be linearly interpolated over a course of several frames.</param>
  285. private void SetState(CameraState state, bool animated = true)
  286. {
  287. CameraState startState = new CameraState();
  288. startState.Position = SceneObject.Position;
  289. startState.Rotation = SceneObject.Rotation;
  290. startState.Ortographic = camera.ProjectionType == ProjectionType.Orthographic;
  291. startState.FrustumWidth = frustumWidth;
  292. animation.Start(startState, state);
  293. if (!animated)
  294. {
  295. ApplyState(1.0f);
  296. isAnimating = false;
  297. }
  298. else
  299. {
  300. isAnimating = true;
  301. lerp = 0.0f;
  302. }
  303. }
  304. /// <summary>
  305. /// Applies the animation target state depending on the interpolation parameter. <see cref="SetState"/>.
  306. /// </summary>
  307. /// <param name="t">Interpolation parameter ranging [0, 1] that interpolated between the start state and the
  308. /// target state.</param>
  309. private void ApplyState(float t)
  310. {
  311. animation.Update(t);
  312. SceneObject.Position = animation.State.Position;
  313. SceneObject.Rotation = animation.State.Rotation;
  314. frustumWidth = animation.State.FrustumWidth;
  315. Vector3 eulerAngles = SceneObject.Rotation.ToEuler();
  316. pitch = (Degree)eulerAngles.x;
  317. yaw = (Degree)eulerAngles.y;
  318. Degree FOV = (Degree)(1.0f - animation.State.OrtographicPct) * SceneCameraOptions.FieldOfView;
  319. if (FOV < (Degree)5.0f)
  320. {
  321. camera.ProjectionType = ProjectionType.Orthographic;
  322. camera.OrthoHeight = frustumWidth * 0.5f / camera.AspectRatio;
  323. }
  324. else
  325. {
  326. camera.ProjectionType = ProjectionType.Perspective;
  327. camera.FieldOfView = FOV;
  328. }
  329. // Note: Consider having a global setting for near/far planes as changing it here might confuse the user
  330. float distance = CalcDistanceForFrustumWidth(frustumWidth);
  331. if (distance < 1)
  332. {
  333. camera.NearClipPlane = 0.005f;
  334. camera.FarClipPlane = 1000f;
  335. }
  336. if (distance < 100)
  337. {
  338. camera.NearClipPlane = 0.05f;
  339. camera.FarClipPlane = 2500f;
  340. }
  341. else if (distance < 1000)
  342. {
  343. camera.NearClipPlane = 0.5f;
  344. camera.FarClipPlane = 10000f;
  345. }
  346. else
  347. {
  348. camera.NearClipPlane = 5.0f;
  349. camera.FarClipPlane = 1000000f;
  350. }
  351. }
  352. /// <summary>
  353. /// Calculates distance at which the camera's frustum width is equal to the provided width.
  354. /// </summary>
  355. /// <param name="frustumWidth">Frustum width to find the distance for, in world units.</param>
  356. /// <returns>Distance at which the camera's frustum is the specified width, in world units.</returns>
  357. private float CalcDistanceForFrustumWidth(float frustumWidth)
  358. {
  359. if (camera.ProjectionType == ProjectionType.Perspective)
  360. return (frustumWidth * 0.5f) / MathEx.Tan(camera.FieldOfView * 0.5f);
  361. else
  362. return frustumWidth * 2.0f;
  363. }
  364. /// <summary>
  365. /// Updates camera state transition animation. Should be called every frame.
  366. /// </summary>
  367. private void UpdateAnim()
  368. {
  369. if (!isAnimating)
  370. return;
  371. const float ANIM_TIME = 0.5f; // 0.5f seconds
  372. lerp += Time.FrameDelta * (1.0f / ANIM_TIME);
  373. if (lerp >= 1.0f)
  374. {
  375. lerp = 1.0f;
  376. isAnimating = false;
  377. }
  378. ApplyState(lerp);
  379. }
  380. /// <summary>
  381. /// Contains data for a possible camera state. Camera states can be interpolated between each other as needed.
  382. /// </summary>
  383. private struct CameraState
  384. {
  385. private float _ortographic;
  386. public Vector3 Position { get; set; }
  387. public Quaternion Rotation { get; set; }
  388. public float FrustumWidth { get; set; }
  389. public bool Ortographic
  390. {
  391. get { return _ortographic > 0.5; }
  392. set { _ortographic = value ? 1.0f : 0.0f; }
  393. }
  394. public float OrtographicPct
  395. {
  396. get { return _ortographic; }
  397. set { _ortographic = value; }
  398. }
  399. }
  400. /// <summary>
  401. /// Helper class that performs linear interpolation between two camera states.
  402. /// </summary>
  403. private struct CameraAnimation
  404. {
  405. private CameraState start;
  406. private CameraState target;
  407. private CameraState interpolated;
  408. /// <summary>
  409. /// Returns currently interpolated animation state.
  410. /// </summary>
  411. public CameraState State
  412. {
  413. get { return interpolated; }
  414. }
  415. /// <summary>
  416. /// Initializes the animation with initial and target states.
  417. /// </summary>
  418. /// <param name="start">Initial state to animate from.</param>
  419. /// <param name="target">Target state to animate towards.</param>
  420. public void Start(CameraState start, CameraState target)
  421. {
  422. this.start = start;
  423. this.target = target;
  424. }
  425. /// <summary>
  426. /// Updates the animation by interpolating between the start and target states.
  427. /// </summary>
  428. /// <param name="t">Interpolation parameter in range [0, 1] that determines how much to interpolate between
  429. /// start and target states.</param>
  430. public void Update(float t)
  431. {
  432. interpolated = new CameraState();
  433. interpolated.Position = start.Position * (1.0f - t) + target.Position * t;
  434. interpolated.Rotation = Quaternion.Slerp(start.Rotation, target.Rotation, t);
  435. interpolated.OrtographicPct = start.OrtographicPct * (1.0f - t) + target.OrtographicPct * t;
  436. interpolated.FrustumWidth = start.FrustumWidth * (1.0f - t) + target.FrustumWidth * t;
  437. }
  438. };
  439. #endregion
  440. }
  441. /** @} */
  442. }