SceneCamera.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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. /// <summary>
  7. /// Handles camera movement in the scene view.
  8. /// </summary>
  9. [RunInEditor]
  10. internal sealed class SceneCamera : Component
  11. {
  12. #region Constants
  13. public const string MoveForwardBinding = "SceneForward";
  14. public const string MoveLeftBinding = "SceneLeft";
  15. public const string MoveRightBinding = "SceneRight";
  16. public const string MoveBackBinding = "SceneBackward";
  17. public const string MoveUpBinding = "SceneUp";
  18. public const string MoveDownBinding = "SceneDown";
  19. public const string FastMoveBinding = "SceneFastMove";
  20. public const string PanBinding = "ScenePan";
  21. public const string RotateBinding = "SceneRotate";
  22. public const string HorizontalAxisBinding = "SceneHorizontal";
  23. public const string VerticalAxisBinding = "SceneVertical";
  24. public const string ScrollAxisBinding = "SceneScroll";
  25. private const float StartSpeed = 4.0f;
  26. private const float TopSpeed = 12.0f;
  27. private const float Acceleration = 1.0f;
  28. private const float FastModeMultiplier = 2.0f;
  29. private const float PanSpeed = 3.0f;
  30. private const float ScrollSpeed = 3.0f;
  31. private const float RotationalSpeed = 360.0f; // Degrees/second
  32. private readonly Degree FieldOfView = (Degree)90.0f;
  33. #endregion
  34. #region Fields
  35. private VirtualButton moveForwardBtn;
  36. private VirtualButton moveLeftBtn;
  37. private VirtualButton moveRightBtn;
  38. private VirtualButton moveBackwardBtn;
  39. private VirtualButton moveUpBtn;
  40. private VirtualButton moveDownBtn;
  41. private VirtualButton fastMoveBtn;
  42. private VirtualButton activeBtn;
  43. private VirtualButton panBtn;
  44. private VirtualAxis horizontalAxis;
  45. private VirtualAxis verticalAxis;
  46. private VirtualAxis scrollAxis;
  47. private float currentSpeed;
  48. private Degree yaw;
  49. private Degree pitch;
  50. private bool lastButtonState;
  51. private Camera camera;
  52. private bool inputEnabled = true;
  53. // Animating camera transitions
  54. private CameraAnimation animation = new CameraAnimation();
  55. private float frustumWidth = 50.0f;
  56. private float lerp;
  57. private bool isAnimating;
  58. #endregion
  59. #region Public properties
  60. /// <summary>
  61. /// Type of projection used by camera for rendering the scene.
  62. /// </summary>
  63. public ProjectionType ProjectionType
  64. {
  65. get { return camera.ProjectionType; }
  66. set
  67. {
  68. if (camera.ProjectionType != value)
  69. {
  70. CameraState state = new CameraState();
  71. state.Position = camera.SceneObject.Position;
  72. state.Rotation = camera.SceneObject.Rotation;
  73. state.Ortographic = value == ProjectionType.Orthographic;
  74. state.FrustumWidth = frustumWidth;
  75. SetState(state);
  76. }
  77. }
  78. }
  79. #endregion
  80. #region Public methods
  81. /// <summary>
  82. /// Enables or disables camera controls.
  83. /// </summary>
  84. /// <param name="enable">True to enable controls, false to disable.</param>
  85. public void EnableInput(bool enable)
  86. {
  87. inputEnabled = enable;
  88. }
  89. /// <summary>
  90. /// Focuses the camera on the currently selected object(s).
  91. /// </summary>
  92. public void FrameSelected()
  93. {
  94. SceneObject[] selectedObjects = Selection.SceneObjects;
  95. if (selectedObjects.Length > 0)
  96. {
  97. AABox box = EditorUtility.CalculateBounds(Selection.SceneObjects);
  98. FrameBounds(box);
  99. }
  100. }
  101. /// <summary>
  102. /// Orients the camera so it looks along the provided axis.
  103. /// </summary>
  104. public void LookAlong(Vector3 axis)
  105. {
  106. Vector3 up = Vector3.YAxis;
  107. if (MathEx.Abs(Vector3.Dot(axis, up)) > 0.9f)
  108. up = Vector3.ZAxis;
  109. CameraState state = new CameraState();
  110. state.Position = camera.SceneObject.Position;
  111. state.Rotation = Quaternion.LookRotation(axis, up);
  112. state.Ortographic = camera.ProjectionType == ProjectionType.Orthographic;
  113. state.FrustumWidth = frustumWidth;
  114. SetState(state);
  115. }
  116. #endregion
  117. #region Private methods
  118. private void OnReset()
  119. {
  120. camera = SceneObject.GetComponent<Camera>();
  121. moveForwardBtn = new VirtualButton(MoveForwardBinding);
  122. moveLeftBtn = new VirtualButton(MoveLeftBinding);
  123. moveRightBtn = new VirtualButton(MoveRightBinding);
  124. moveBackwardBtn = new VirtualButton(MoveBackBinding);
  125. moveUpBtn = new VirtualButton(MoveUpBinding);
  126. moveDownBtn = new VirtualButton(MoveDownBinding);
  127. fastMoveBtn = new VirtualButton(FastMoveBinding);
  128. activeBtn = new VirtualButton(RotateBinding);
  129. panBtn = new VirtualButton(PanBinding);
  130. horizontalAxis = new VirtualAxis(HorizontalAxisBinding);
  131. verticalAxis = new VirtualAxis(VerticalAxisBinding);
  132. scrollAxis = new VirtualAxis(ScrollAxisBinding);
  133. }
  134. private void OnUpdate()
  135. {
  136. bool isOrtographic = camera.ProjectionType == ProjectionType.Orthographic;
  137. if (inputEnabled)
  138. {
  139. bool goingForward = VirtualInput.IsButtonHeld(moveForwardBtn);
  140. bool goingBack = VirtualInput.IsButtonHeld(moveBackwardBtn);
  141. bool goingLeft = VirtualInput.IsButtonHeld(moveLeftBtn);
  142. bool goingRight = VirtualInput.IsButtonHeld(moveRightBtn);
  143. bool goingUp = VirtualInput.IsButtonHeld(moveUpBtn);
  144. bool goingDown = VirtualInput.IsButtonHeld(moveDownBtn);
  145. bool fastMove = VirtualInput.IsButtonHeld(fastMoveBtn);
  146. bool camActive = VirtualInput.IsButtonHeld(activeBtn);
  147. bool isPanning = VirtualInput.IsButtonHeld(panBtn);
  148. bool hideCursor = camActive || isPanning;
  149. if (hideCursor != lastButtonState)
  150. {
  151. if (hideCursor)
  152. {
  153. Cursor.Hide();
  154. Rect2I clipRect;
  155. clipRect.x = Input.PointerPosition.x - 2;
  156. clipRect.y = Input.PointerPosition.y - 2;
  157. clipRect.width = 4;
  158. clipRect.height = 4;
  159. Cursor.ClipToRect(clipRect);
  160. }
  161. else
  162. {
  163. Cursor.Show();
  164. Cursor.ClipDisable();
  165. }
  166. lastButtonState = hideCursor;
  167. }
  168. float frameDelta = Time.FrameDelta;
  169. if (camActive)
  170. {
  171. float horzValue = VirtualInput.GetAxisValue(horizontalAxis);
  172. float vertValue = VirtualInput.GetAxisValue(verticalAxis);
  173. float rotationAmount = RotationalSpeed * EditorSettings.MouseSensitivity * frameDelta;
  174. yaw += new Degree(horzValue * rotationAmount);
  175. pitch += new Degree(vertValue * rotationAmount);
  176. yaw = MathEx.WrapAngle(yaw);
  177. pitch = MathEx.WrapAngle(pitch);
  178. Quaternion yRot = Quaternion.FromAxisAngle(Vector3.YAxis, yaw);
  179. Quaternion xRot = Quaternion.FromAxisAngle(Vector3.XAxis, pitch);
  180. Quaternion camRot = yRot*xRot;
  181. camRot.Normalize();
  182. SceneObject.Rotation = camRot;
  183. // Handle movement using movement keys
  184. Vector3 direction = Vector3.Zero;
  185. if (goingForward) direction += SceneObject.Forward;
  186. if (goingBack) direction -= SceneObject.Forward;
  187. if (goingRight) direction += SceneObject.Right;
  188. if (goingLeft) direction -= SceneObject.Right;
  189. if (goingUp) direction += SceneObject.Up;
  190. if (goingDown) direction -= SceneObject.Up;
  191. if (direction.SqrdLength != 0)
  192. {
  193. direction.Normalize();
  194. float multiplier = 1.0f;
  195. if (fastMove)
  196. multiplier = FastModeMultiplier;
  197. currentSpeed = MathEx.Clamp(currentSpeed + Acceleration*frameDelta, StartSpeed, TopSpeed);
  198. currentSpeed *= multiplier;
  199. }
  200. else
  201. {
  202. currentSpeed = 0.0f;
  203. }
  204. const float tooSmall = 0.0001f;
  205. if (currentSpeed > tooSmall)
  206. {
  207. Vector3 velocity = direction*currentSpeed;
  208. SceneObject.Move(velocity*frameDelta);
  209. }
  210. }
  211. // Pan
  212. if (isPanning)
  213. {
  214. float horzValue = VirtualInput.GetAxisValue(horizontalAxis);
  215. float vertValue = VirtualInput.GetAxisValue(verticalAxis);
  216. Vector3 direction = new Vector3(horzValue, -vertValue, 0.0f);
  217. direction = camera.SceneObject.Rotation.Rotate(direction);
  218. SceneObject.Move(direction*PanSpeed*frameDelta);
  219. }
  220. }
  221. else
  222. {
  223. Cursor.Show();
  224. Cursor.ClipDisable();
  225. }
  226. SceneWindow sceneWindow = EditorWindow.GetWindow<SceneWindow>();
  227. if (sceneWindow.Active)
  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*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)*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.Position = start.Position * (1.0f - t) + target.Position * t;
  433. interpolated.Rotation = Quaternion.Slerp(start.Rotation, target.Rotation, t);
  434. interpolated.OrtographicPct = start.OrtographicPct * (1.0f - t) + target.OrtographicPct * t;
  435. interpolated.FrustumWidth = start.FrustumWidth * (1.0f - t) + target.FrustumWidth * t;
  436. }
  437. };
  438. #endregion
  439. }
  440. }