SceneCamera.cs 20 KB

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