SceneCamera.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. using BansheeEngine;
  2. namespace BansheeEditor
  3. {
  4. /// <summary>
  5. /// Handles camera movement in the scene view.
  6. /// </summary>
  7. [RunInEditor]
  8. internal sealed class SceneCamera : Component
  9. {
  10. public const string MoveForwardBinding = "SceneForward";
  11. public const string MoveLeftBinding = "SceneLeft";
  12. public const string MoveRightBinding = "SceneRight";
  13. public const string MoveBackBinding = "SceneBackward";
  14. public const string FastMoveBinding = "SceneFastMove";
  15. public const string RotateBinding = "SceneRotate";
  16. public const string HorizontalAxisBinding = "SceneHorizontal";
  17. public const string VerticalAxisBinding = "SceneVertical";
  18. private const float StartSpeed = 4.0f;
  19. private const float TopSpeed = 12.0f;
  20. private const float Acceleration = 1.0f;
  21. private const float FastModeMultiplier = 2.0f;
  22. private const float RotationalSpeed = 360.0f; // Degrees/second
  23. private VirtualButton moveForwardBtn;
  24. private VirtualButton moveLeftBtn;
  25. private VirtualButton moveRightBtn;
  26. private VirtualButton moveBackwardBtn;
  27. private VirtualButton fastMoveBtn;
  28. private VirtualButton activeBtn;
  29. private VirtualAxis horizontalAxis;
  30. private VirtualAxis verticalAxis;
  31. private float currentSpeed;
  32. private Degree yaw;
  33. private Degree pitch;
  34. private bool lastButtonState;
  35. private Camera camera;
  36. private bool inputEnabled = true;
  37. // Animating camera transitions
  38. private CameraAnimation animation = new CameraAnimation();
  39. private float currentSize = 50.0f;
  40. private float lerp;
  41. private bool isAnimating;
  42. private void OnReset()
  43. {
  44. camera = SceneObject.GetComponent<Camera>();
  45. moveForwardBtn = new VirtualButton(MoveForwardBinding);
  46. moveLeftBtn = new VirtualButton(MoveLeftBinding);
  47. moveRightBtn = new VirtualButton(MoveRightBinding);
  48. moveBackwardBtn = new VirtualButton(MoveBackBinding);
  49. fastMoveBtn = new VirtualButton(FastMoveBinding);
  50. activeBtn = new VirtualButton(RotateBinding);
  51. horizontalAxis = new VirtualAxis(HorizontalAxisBinding);
  52. verticalAxis = new VirtualAxis(VerticalAxisBinding);
  53. }
  54. private void OnUpdate()
  55. {
  56. bool goingForward = VirtualInput.IsButtonHeld(moveForwardBtn);
  57. bool goingBack = VirtualInput.IsButtonHeld(moveBackwardBtn);
  58. bool goingLeft = VirtualInput.IsButtonHeld(moveLeftBtn);
  59. bool goingRight = VirtualInput.IsButtonHeld(moveRightBtn);
  60. bool fastMove = VirtualInput.IsButtonHeld(fastMoveBtn);
  61. bool camActive = VirtualInput.IsButtonHeld(activeBtn);
  62. if (camActive != lastButtonState)
  63. {
  64. if (camActive)
  65. Cursor.Hide();
  66. else
  67. Cursor.Show();
  68. lastButtonState = camActive;
  69. }
  70. float frameDelta = Time.FrameDelta;
  71. if (camActive)
  72. {
  73. float horzValue = VirtualInput.GetAxisValue(horizontalAxis);
  74. float vertValue = VirtualInput.GetAxisValue(verticalAxis);
  75. yaw += new Degree(horzValue * RotationalSpeed * frameDelta);
  76. pitch += new Degree(vertValue * RotationalSpeed * frameDelta);
  77. yaw = MathEx.WrapAngle(yaw);
  78. pitch = MathEx.WrapAngle(pitch);
  79. Quaternion yRot = Quaternion.FromAxisAngle(Vector3.YAxis, yaw);
  80. Quaternion xRot = Quaternion.FromAxisAngle(Vector3.XAxis, pitch);
  81. Quaternion camRot = yRot * xRot;
  82. camRot.Normalize();
  83. SceneObject.Rotation = camRot;
  84. Vector3 direction = Vector3.Zero;
  85. if (goingForward) direction += SceneObject.Forward;
  86. if (goingBack) direction -= SceneObject.Forward;
  87. if (goingRight) direction += SceneObject.Right;
  88. if (goingLeft) direction -= SceneObject.Right;
  89. if (direction.SqrdLength != 0)
  90. {
  91. direction.Normalize();
  92. float multiplier = 1.0f;
  93. if (fastMove)
  94. multiplier = FastModeMultiplier;
  95. currentSpeed = MathEx.Clamp(currentSpeed + Acceleration * frameDelta, StartSpeed, TopSpeed);
  96. currentSpeed *= multiplier;
  97. }
  98. else
  99. {
  100. currentSpeed = 0.0f;
  101. }
  102. const float tooSmall = 0.0001f;
  103. if (currentSpeed > tooSmall)
  104. {
  105. Vector3 velocity = direction * currentSpeed;
  106. SceneObject.Move(velocity * frameDelta);
  107. }
  108. }
  109. UpdateAnim();
  110. }
  111. /// <summary>
  112. /// Enables or disables camera controls.
  113. /// </summary>
  114. /// <param name="enable">True to enable controls, false to disable.</param>
  115. public void EnableInput(bool enable)
  116. {
  117. if (inputEnabled == enable)
  118. return;
  119. inputEnabled = enable;
  120. if (!inputEnabled)
  121. {
  122. if (VirtualInput.IsButtonHeld(activeBtn))
  123. Cursor.Show();
  124. }
  125. }
  126. /// <summary>
  127. /// Focuses the camera on the currently selected object(s).
  128. /// </summary>
  129. public void FrameSelected()
  130. {
  131. SceneObject[] selectedObjects = Selection.SceneObjects;
  132. if (selectedObjects.Length > 0)
  133. {
  134. AABox box = EditorUtility.CalculateBounds(Selection.SceneObjects);
  135. FrameBounds(box);
  136. }
  137. }
  138. /// <summary>
  139. /// Moves and orients a camera so that the provided bounds end covering the camera's viewport.
  140. /// </summary>
  141. /// <param name="bounds">Bounds to frame in camera's view.</param>
  142. /// <param name="padding">Amount of padding to leave on the borders of the viewport, in percent [0, 1].</param>
  143. private void FrameBounds(AABox bounds, float padding = 0.2f)
  144. {
  145. // TODO - Use AABox bounds directly instead of a sphere to be more accurate
  146. float worldWidth = bounds.Size.Length;
  147. float worldHeight = worldWidth;
  148. if (worldWidth == 0.0f)
  149. worldWidth = 1.0f;
  150. if (worldHeight == 0.0f)
  151. worldHeight = 1.0f;
  152. float boundsAspect = worldWidth / worldHeight;
  153. float paddingScale = MathEx.Clamp01(padding) + 1.0f;
  154. float frustumWidth;
  155. // If camera has wider aspect than bounds then height will be the limiting dimension
  156. if (camera.AspectRatio > boundsAspect)
  157. frustumWidth = worldHeight * 1.0f/camera.AspectRatio * paddingScale;
  158. else // Otherwise width
  159. frustumWidth = worldWidth * paddingScale;
  160. float distance = CalcDistanceForFrustumWidth(frustumWidth);
  161. Vector3 forward = bounds.Center - SceneObject.Position;
  162. forward.Normalize();
  163. CameraState state = new CameraState();
  164. state.Position = bounds.Center - forward * distance;
  165. state.Rotation = Quaternion.LookRotation(forward, Vector3.YAxis);
  166. state.Ortographic = camera.ProjectionType == ProjectionType.Orthographic;
  167. state.Size = distance;
  168. SetState(state);
  169. }
  170. /// <summary>
  171. /// Changes the state of the camera, either instantly or animated over several frames. The state includes
  172. /// camera position, rotation, type and possibly other parameters.
  173. /// </summary>
  174. /// <param name="state">New state of the camera.</param>
  175. /// <param name="animated">Should the state be linearly interpolated over a course of several frames.</param>
  176. private void SetState(CameraState state, bool animated = true)
  177. {
  178. CameraState startState = new CameraState();
  179. startState.Position = SceneObject.Position;
  180. startState.Rotation = SceneObject.Rotation;
  181. startState.Ortographic = camera.ProjectionType == ProjectionType.Orthographic;
  182. startState.Size = currentSize;
  183. animation.Start(startState, state);
  184. if (!animated)
  185. {
  186. ApplyState(1.0f);
  187. isAnimating = false;
  188. }
  189. else
  190. {
  191. isAnimating = true;
  192. lerp = 0.0f;
  193. }
  194. }
  195. /// <summary>
  196. /// Applies the animation target state depending on the interpolation parameter. <see cref="SetState"/>.
  197. /// </summary>
  198. /// <param name="t">Interpolation parameter ranging [0, 1] that interpolated between the start state and the
  199. /// target state.</param>
  200. private void ApplyState(float t)
  201. {
  202. animation.Update(t);
  203. SceneObject.Position = animation.State.Position;
  204. SceneObject.Rotation = animation.State.Rotation;
  205. camera.ProjectionType = animation.State.Ortographic ? ProjectionType.Orthographic : ProjectionType.Perspective;
  206. currentSize = animation.State.Size;
  207. Vector3 eulerAngles = SceneObject.Rotation.ToEuler();
  208. pitch = eulerAngles.x;
  209. yaw = eulerAngles.y;
  210. // Note: Consider having a global setting for near/far planes as changing it here might confuse the user
  211. if (currentSize < 1)
  212. {
  213. camera.NearClipPlane = 0.005f;
  214. camera.FarClipPlane = 1000f;
  215. }
  216. if (currentSize < 100)
  217. {
  218. camera.NearClipPlane = 0.05f;
  219. camera.FarClipPlane = 2500f;
  220. }
  221. else if (currentSize < 1000)
  222. {
  223. camera.NearClipPlane = 0.5f;
  224. camera.FarClipPlane = 10000f;
  225. }
  226. else
  227. {
  228. camera.NearClipPlane = 5.0f;
  229. camera.FarClipPlane = 1000000f;
  230. }
  231. }
  232. /// <summary>
  233. /// Calculates distance at which the camera's frustum width is equal to the provided width.
  234. /// </summary>
  235. /// <param name="frustumWidth">Frustum width to find the distance for, in world units.</param>
  236. /// <returns>Distance at which the camera's frustum is the specified width, in world units.</returns>
  237. private float CalcDistanceForFrustumWidth(float frustumWidth)
  238. {
  239. if (camera.ProjectionType == ProjectionType.Perspective)
  240. return (frustumWidth*0.5f)/MathEx.Tan(camera.FieldOfView*0.5f);
  241. else
  242. return frustumWidth * 2.0f;
  243. }
  244. /// <summary>
  245. /// Updates camera state transition animation. Should be called every frame.
  246. /// </summary>
  247. private void UpdateAnim()
  248. {
  249. if (!isAnimating)
  250. return;
  251. const float ANIM_TIME = 0.5f; // 0.5f seconds
  252. lerp += Time.FrameDelta * (1.0f / ANIM_TIME);
  253. if (lerp >= 1.0f)
  254. {
  255. lerp = 1.0f;
  256. isAnimating = false;
  257. }
  258. ApplyState(lerp);
  259. }
  260. /// <summary>
  261. /// Contains data for a possible camera state. Camera states can be interpolated between each other as needed.
  262. /// </summary>
  263. private struct CameraState
  264. {
  265. internal float _ortographic;
  266. public Vector3 Position { get; set; }
  267. public Quaternion Rotation { get; set; }
  268. public float Size { get; set; }
  269. public bool Ortographic
  270. {
  271. get { return _ortographic > 0.5; }
  272. set { _ortographic = value ? 1.0f : 0.0f; }
  273. }
  274. }
  275. /// <summary>
  276. /// Helper class that performs linear interpolation between two camera states.
  277. /// </summary>
  278. private struct CameraAnimation
  279. {
  280. private CameraState start;
  281. private CameraState target;
  282. private CameraState interpolated;
  283. /// <summary>
  284. /// Returns currently interpolated animation state.
  285. /// </summary>
  286. public CameraState State
  287. {
  288. get { return interpolated; }
  289. }
  290. /// <summary>
  291. /// Initializes the animation with initial and target states.
  292. /// </summary>
  293. /// <param name="start">Initial state to animate from.</param>
  294. /// <param name="target">Target state to animate towards.</param>
  295. public void Start(CameraState start, CameraState target)
  296. {
  297. this.start = start;
  298. this.target = target;
  299. }
  300. /// <summary>
  301. /// Updates the animation by interpolating between the start and target states.
  302. /// </summary>
  303. /// <param name="t">Interpolation parameter in range [0, 1] that determines how much to interpolate between
  304. /// start and target states.</param>
  305. public void Update(float t)
  306. {
  307. interpolated.Position = start.Position * (1.0f - t) + target.Position * t;
  308. interpolated.Rotation = Quaternion.Slerp(start.Rotation, target.Rotation, t);
  309. interpolated._ortographic = start._ortographic * (1.0f - t) + target._ortographic * t;
  310. interpolated.Size = start.Size * (1.0f - t) + target.Size * t;
  311. }
  312. };
  313. }
  314. }