SceneCamera.cs 19 KB

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