SceneCamera.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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 = 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. yaw += new Degree(horzValue*RotationalSpeed*frameDelta);
  174. pitch += new Degree(vertValue*RotationalSpeed*frameDelta);
  175. yaw = MathEx.WrapAngle(yaw);
  176. pitch = MathEx.WrapAngle(pitch);
  177. Quaternion yRot = Quaternion.FromAxisAngle(Vector3.YAxis, yaw);
  178. Quaternion xRot = Quaternion.FromAxisAngle(Vector3.XAxis, pitch);
  179. Quaternion camRot = yRot*xRot;
  180. camRot.Normalize();
  181. SceneObject.Rotation = camRot;
  182. // Handle movement using movement keys
  183. Vector3 direction = Vector3.Zero;
  184. if (goingForward) direction += SceneObject.Forward;
  185. if (goingBack) direction -= SceneObject.Forward;
  186. if (goingRight) direction += SceneObject.Right;
  187. if (goingLeft) direction -= SceneObject.Right;
  188. if (goingUp) direction += SceneObject.Up;
  189. if (goingDown) direction -= SceneObject.Up;
  190. if (direction.SqrdLength != 0)
  191. {
  192. direction.Normalize();
  193. float multiplier = 1.0f;
  194. if (fastMove)
  195. multiplier = FastModeMultiplier;
  196. currentSpeed = MathEx.Clamp(currentSpeed + Acceleration*frameDelta, StartSpeed, TopSpeed);
  197. currentSpeed *= multiplier;
  198. }
  199. else
  200. {
  201. currentSpeed = 0.0f;
  202. }
  203. const float tooSmall = 0.0001f;
  204. if (currentSpeed > tooSmall)
  205. {
  206. Vector3 velocity = direction*currentSpeed;
  207. SceneObject.Move(velocity*frameDelta);
  208. }
  209. }
  210. // Pan
  211. if (isPanning)
  212. {
  213. float horzValue = VirtualInput.GetAxisValue(horizontalAxis);
  214. float vertValue = VirtualInput.GetAxisValue(verticalAxis);
  215. Vector3 direction = new Vector3(horzValue, -vertValue, 0.0f);
  216. direction = camera.SceneObject.Rotation.Rotate(direction);
  217. SceneObject.Move(direction*PanSpeed*frameDelta);
  218. }
  219. }
  220. else
  221. {
  222. Cursor.Show();
  223. Cursor.ClipDisable();
  224. }
  225. SceneWindow sceneWindow = EditorWindow.GetWindow<SceneWindow>();
  226. if (sceneWindow.Active)
  227. {
  228. Rect2I bounds = sceneWindow.Bounds;
  229. // Move using scroll wheel
  230. if (bounds.Contains(Input.PointerPosition))
  231. {
  232. float scrollAmount = VirtualInput.GetAxisValue(scrollAxis);
  233. if (!isOrtographic)
  234. {
  235. SceneObject.Move(SceneObject.Forward*scrollAmount*ScrollSpeed);
  236. }
  237. else
  238. {
  239. float orthoHeight = MathEx.Max(1.0f, camera.OrthoHeight - scrollAmount);
  240. camera.OrthoHeight = orthoHeight;
  241. }
  242. }
  243. }
  244. UpdateAnim();
  245. }
  246. /// <summary>
  247. /// Moves and orients a camera so that the provided bounds end covering the camera's viewport.
  248. /// </summary>
  249. /// <param name="bounds">Bounds to frame in camera's view.</param>
  250. /// <param name="padding">Amount of padding to leave on the borders of the viewport, in percent [0, 1].</param>
  251. private void FrameBounds(AABox bounds, float padding = 0.0f)
  252. {
  253. // TODO - Use AABox bounds directly instead of a sphere to be more accurate
  254. float worldWidth = bounds.Size.Length;
  255. float worldHeight = worldWidth;
  256. if (worldWidth == 0.0f)
  257. worldWidth = 1.0f;
  258. if (worldHeight == 0.0f)
  259. worldHeight = 1.0f;
  260. float boundsAspect = worldWidth / worldHeight;
  261. float paddingScale = MathEx.Clamp01(padding) + 1.0f;
  262. float frustumWidth;
  263. // If camera has wider aspect than bounds then height will be the limiting dimension
  264. if (camera.AspectRatio > boundsAspect)
  265. frustumWidth = worldHeight * camera.AspectRatio * paddingScale;
  266. else // Otherwise width
  267. frustumWidth = worldWidth * paddingScale;
  268. float distance = CalcDistanceForFrustumWidth(frustumWidth);
  269. Vector3 forward = bounds.Center - SceneObject.Position;
  270. forward.Normalize();
  271. CameraState state = new CameraState();
  272. state.Position = bounds.Center - forward * distance;
  273. state.Rotation = Quaternion.LookRotation(forward, Vector3.YAxis);
  274. state.Ortographic = camera.ProjectionType == ProjectionType.Orthographic;
  275. state.FrustumWidth = frustumWidth;
  276. SetState(state);
  277. }
  278. /// <summary>
  279. /// Changes the state of the camera, either instantly or animated over several frames. The state includes
  280. /// camera position, rotation, type and possibly other parameters.
  281. /// </summary>
  282. /// <param name="state">New state of the camera.</param>
  283. /// <param name="animated">Should the state be linearly interpolated over a course of several frames.</param>
  284. private void SetState(CameraState state, bool animated = true)
  285. {
  286. CameraState startState = new CameraState();
  287. startState.Position = SceneObject.Position;
  288. startState.Rotation = SceneObject.Rotation;
  289. startState.Ortographic = camera.ProjectionType == ProjectionType.Orthographic;
  290. startState.FrustumWidth = frustumWidth;
  291. animation.Start(startState, state);
  292. if (!animated)
  293. {
  294. ApplyState(1.0f);
  295. isAnimating = false;
  296. }
  297. else
  298. {
  299. isAnimating = true;
  300. lerp = 0.0f;
  301. }
  302. }
  303. /// <summary>
  304. /// Applies the animation target state depending on the interpolation parameter. <see cref="SetState"/>.
  305. /// </summary>
  306. /// <param name="t">Interpolation parameter ranging [0, 1] that interpolated between the start state and the
  307. /// target state.</param>
  308. private void ApplyState(float t)
  309. {
  310. animation.Update(t);
  311. SceneObject.Position = animation.State.Position;
  312. SceneObject.Rotation = animation.State.Rotation;
  313. frustumWidth = animation.State.FrustumWidth;
  314. Vector3 eulerAngles = SceneObject.Rotation.ToEuler();
  315. pitch = eulerAngles.x;
  316. yaw = eulerAngles.y;
  317. Degree FOV = (1.0f - animation.State.OrtographicPct)*FieldOfView;
  318. if (FOV < 5.0f)
  319. {
  320. camera.ProjectionType = ProjectionType.Orthographic;
  321. camera.OrthoHeight = frustumWidth * 0.5f / camera.AspectRatio;
  322. }
  323. else
  324. {
  325. camera.ProjectionType = ProjectionType.Perspective;
  326. camera.FieldOfView = FOV;
  327. }
  328. // Note: Consider having a global setting for near/far planes as changing it here might confuse the user
  329. float distance = CalcDistanceForFrustumWidth(frustumWidth);
  330. if (distance < 1)
  331. {
  332. camera.NearClipPlane = 0.005f;
  333. camera.FarClipPlane = 1000f;
  334. }
  335. if (distance < 100)
  336. {
  337. camera.NearClipPlane = 0.05f;
  338. camera.FarClipPlane = 2500f;
  339. }
  340. else if (distance < 1000)
  341. {
  342. camera.NearClipPlane = 0.5f;
  343. camera.FarClipPlane = 10000f;
  344. }
  345. else
  346. {
  347. camera.NearClipPlane = 5.0f;
  348. camera.FarClipPlane = 1000000f;
  349. }
  350. }
  351. /// <summary>
  352. /// Calculates distance at which the camera's frustum width is equal to the provided width.
  353. /// </summary>
  354. /// <param name="frustumWidth">Frustum width to find the distance for, in world units.</param>
  355. /// <returns>Distance at which the camera's frustum is the specified width, in world units.</returns>
  356. private float CalcDistanceForFrustumWidth(float frustumWidth)
  357. {
  358. if (camera.ProjectionType == ProjectionType.Perspective)
  359. return (frustumWidth*0.5f)/MathEx.Tan(camera.FieldOfView*0.5f);
  360. else
  361. return frustumWidth * 2.0f;
  362. }
  363. /// <summary>
  364. /// Updates camera state transition animation. Should be called every frame.
  365. /// </summary>
  366. private void UpdateAnim()
  367. {
  368. if (!isAnimating)
  369. return;
  370. const float ANIM_TIME = 0.5f; // 0.5f seconds
  371. lerp += Time.FrameDelta * (1.0f / ANIM_TIME);
  372. if (lerp >= 1.0f)
  373. {
  374. lerp = 1.0f;
  375. isAnimating = false;
  376. }
  377. ApplyState(lerp);
  378. }
  379. /// <summary>
  380. /// Contains data for a possible camera state. Camera states can be interpolated between each other as needed.
  381. /// </summary>
  382. private struct CameraState
  383. {
  384. private float _ortographic;
  385. public Vector3 Position { get; set; }
  386. public Quaternion Rotation { get; set; }
  387. public float FrustumWidth { get; set; }
  388. public bool Ortographic
  389. {
  390. get { return _ortographic > 0.5; }
  391. set { _ortographic = value ? 1.0f : 0.0f; }
  392. }
  393. public float OrtographicPct
  394. {
  395. get { return _ortographic; }
  396. set { _ortographic = value; }
  397. }
  398. }
  399. /// <summary>
  400. /// Helper class that performs linear interpolation between two camera states.
  401. /// </summary>
  402. private struct CameraAnimation
  403. {
  404. private CameraState start;
  405. private CameraState target;
  406. private CameraState interpolated;
  407. /// <summary>
  408. /// Returns currently interpolated animation state.
  409. /// </summary>
  410. public CameraState State
  411. {
  412. get { return interpolated; }
  413. }
  414. /// <summary>
  415. /// Initializes the animation with initial and target states.
  416. /// </summary>
  417. /// <param name="start">Initial state to animate from.</param>
  418. /// <param name="target">Target state to animate towards.</param>
  419. public void Start(CameraState start, CameraState target)
  420. {
  421. this.start = start;
  422. this.target = target;
  423. }
  424. /// <summary>
  425. /// Updates the animation by interpolating between the start and target states.
  426. /// </summary>
  427. /// <param name="t">Interpolation parameter in range [0, 1] that determines how much to interpolate between
  428. /// start and target states.</param>
  429. public void Update(float t)
  430. {
  431. interpolated.Position = start.Position * (1.0f - t) + target.Position * t;
  432. interpolated.Rotation = Quaternion.Slerp(start.Rotation, target.Rotation, t);
  433. interpolated.OrtographicPct = start.OrtographicPct * (1.0f - t) + target.OrtographicPct * t;
  434. interpolated.FrustumWidth = start.FrustumWidth * (1.0f - t) + target.FrustumWidth * t;
  435. }
  436. };
  437. #endregion
  438. }
  439. }