SampleCamera.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. #region File Description
  2. //-----------------------------------------------------------------------------
  3. // SampleCamera.cs
  4. //
  5. // Microsoft XNA Community Game Platform
  6. // Copyright (C) Microsoft Corporation. All rights reserved.
  7. //-----------------------------------------------------------------------------
  8. #endregion
  9. #region Using Statements
  10. using System;
  11. using System.Collections.Generic;
  12. using Microsoft.Xna.Framework;
  13. using Microsoft.Xna.Framework.Audio;
  14. using Microsoft.Xna.Framework.Graphics;
  15. using Microsoft.Xna.Framework.Input;
  16. using Microsoft.Xna.Framework.Content;
  17. using Microsoft.Xna.Framework.Storage;
  18. #endregion
  19. namespace PerPixelLightingSample
  20. {
  21. public enum SampleArcBallCameraMode
  22. {
  23. /// <summary>
  24. /// A totally free-look arcball that orbits relative
  25. /// to its orientation
  26. /// </summary>
  27. Free = 0,
  28. /// <summary>
  29. /// A camera constrained by roll so that orbits only
  30. /// occur on latitude and longitude
  31. /// </summary>
  32. RollConstrained = 1
  33. }
  34. /// <summary>
  35. /// An example arc ball camera
  36. /// </summary>
  37. public class SampleArcBallCamera
  38. {
  39. #region Helper Functions
  40. /// <summary>
  41. /// Uses a pair of keys to simulate a positive or negative axis input.
  42. /// </summary>
  43. public static float ReadKeyboardAxis(KeyboardState keyState, Keys downKey,
  44. Keys upKey)
  45. {
  46. float value = 0;
  47. if (keyState.IsKeyDown(downKey))
  48. value -= 1.0f;
  49. if (keyState.IsKeyDown(upKey))
  50. value += 1.0f;
  51. return value;
  52. }
  53. #endregion
  54. #region Fields
  55. /// <summary>
  56. /// The location of the look-at target
  57. /// </summary>
  58. private Vector3 targetValue;
  59. /// <summary>
  60. /// The distance between the camera and the target
  61. /// </summary>
  62. private float distanceValue;
  63. /// <summary>
  64. /// The orientation of the camera relative to the target
  65. /// </summary>
  66. private Quaternion orientation;
  67. private float inputDistanceRateValue;
  68. private const float InputTurnRate = 3.0f;
  69. private SampleArcBallCameraMode mode;
  70. private float yaw, pitch;
  71. #endregion
  72. #region Constructors
  73. /// <summary>
  74. /// Create an arcball camera that allows free orbit around a target point.
  75. /// </summary>
  76. public SampleArcBallCamera(SampleArcBallCameraMode controlMode)
  77. {
  78. //orientation quaternion assumes a Pi rotation so you're facing the "front"
  79. //of the model (looking down the +Z axis)
  80. orientation = Quaternion.CreateFromAxisAngle(Vector3.Up, MathHelper.Pi);
  81. mode = controlMode;
  82. inputDistanceRateValue = 4.0f;
  83. yaw = MathHelper.Pi;
  84. pitch = 0;
  85. }
  86. #endregion
  87. #region Calculated Camera Properties
  88. /// <summary>
  89. /// Get the forward direction vector of the camera.
  90. /// </summary>
  91. public Vector3 Direction
  92. {
  93. get
  94. {
  95. //R v R' where v = (0,0,-1,0)
  96. //The equation can be reduced because we know the following things:
  97. // 1. We're using unit quaternions
  98. // 2. The initial aspect does not change
  99. //The reduced form of the same equation follows
  100. Vector3 dir = Vector3.Zero;
  101. dir.X = -2.0f *
  102. ((orientation.X * orientation.Z) + (orientation.W * orientation.Y));
  103. dir.Y = 2.0f *
  104. ((orientation.W * orientation.X) - (orientation.Y * orientation.Z));
  105. dir.Z =
  106. ((orientation.X * orientation.X) + (orientation.Y * orientation.Y)) -
  107. ((orientation.Z * orientation.Z) + (orientation.W * orientation.W));
  108. Vector3.Normalize(ref dir, out dir);
  109. return dir;
  110. }
  111. }
  112. /// <summary>
  113. /// Get the right direction vector of the camera.
  114. /// </summary>
  115. public Vector3 Right
  116. {
  117. get
  118. {
  119. //R v R' where v = (1,0,0,0)
  120. //The equation can be reduced because we know the following things:
  121. // 1. We're using unit quaternions
  122. // 2. The initial aspect does not change
  123. //The reduced form of the same equation follows
  124. Vector3 right = Vector3.Zero;
  125. right.X =
  126. ((orientation.X * orientation.X) + (orientation.W * orientation.W)) -
  127. ((orientation.Z * orientation.Z) + (orientation.Y * orientation.Y));
  128. right.Y = 2.0f *
  129. ((orientation.X * orientation.Y) + (orientation.Z * orientation.W));
  130. right.Z = 2.0f *
  131. ((orientation.X * orientation.Z) - (orientation.Y * orientation.W));
  132. return right;
  133. }
  134. }
  135. /// <summary>
  136. /// Get the up direction vector of the camera.
  137. /// </summary>
  138. public Vector3 Up
  139. {
  140. get
  141. {
  142. //R v R' where v = (0,1,0,0)
  143. //The equation can be reduced because we know the following things:
  144. // 1. We're using unit quaternions
  145. // 2. The initial aspect does not change
  146. //The reduced form of the same equation follows
  147. Vector3 up = Vector3.Zero;
  148. up.X = 2.0f *
  149. ((orientation.X * orientation.Y) - (orientation.Z * orientation.W));
  150. up.Y =
  151. ((orientation.Y * orientation.Y) + (orientation.W * orientation.W)) -
  152. ((orientation.Z * orientation.Z) + (orientation.X * orientation.X));
  153. up.Z = 2.0f *
  154. ((orientation.Y * orientation.Z) + (orientation.X * orientation.W));
  155. return up;
  156. }
  157. }
  158. /// <summary>
  159. /// Get the View (look at) Matrix defined by the camera
  160. /// </summary>
  161. public Matrix ViewMatrix
  162. {
  163. get
  164. {
  165. return Matrix.CreateLookAt(targetValue -
  166. (Direction * distanceValue), targetValue, Up);
  167. }
  168. }
  169. public SampleArcBallCameraMode ControlMode
  170. {
  171. get { return mode; }
  172. set
  173. {
  174. if (value != mode)
  175. {
  176. mode = value;
  177. SetCamera(targetValue - (Direction* distanceValue),
  178. targetValue, Vector3.Up);
  179. }
  180. }
  181. }
  182. #endregion
  183. #region Position Controls
  184. /// <summary>
  185. /// Get or Set the current target of the camera
  186. /// </summary>
  187. public Vector3 Target
  188. {
  189. get
  190. { return targetValue; }
  191. set
  192. { targetValue = value; }
  193. }
  194. /// <summary>
  195. /// Get or Set the camera's distance to the target.
  196. /// </summary>
  197. public float Distance
  198. {
  199. get
  200. { return distanceValue; }
  201. set
  202. { distanceValue = value; }
  203. }
  204. /// <summary>
  205. /// Sets the rate of distance change
  206. /// when automatically handling input
  207. /// </summary>
  208. public float InputDistanceRate
  209. {
  210. get
  211. { return inputDistanceRateValue; }
  212. set
  213. { inputDistanceRateValue = value; }
  214. }
  215. /// <summary>
  216. /// Get/Set the camera's current postion.
  217. /// </summary>
  218. public Vector3 Position
  219. {
  220. get
  221. {
  222. return targetValue - (Direction * Distance);
  223. }
  224. set
  225. {
  226. SetCamera(value, targetValue, Vector3.Up);
  227. }
  228. }
  229. #endregion
  230. #region Orbit Controls
  231. /// <summary>
  232. /// Orbit directly upwards in Free camera or on
  233. /// the longitude line when roll constrained
  234. /// </summary>
  235. public void OrbitUp(float angle)
  236. {
  237. switch (mode)
  238. {
  239. case SampleArcBallCameraMode.Free:
  240. //rotate the aspect by the angle
  241. orientation = orientation *
  242. Quaternion.CreateFromAxisAngle(Vector3.Right, -angle);
  243. //normalize to reduce errors
  244. Quaternion.Normalize(ref orientation, out orientation);
  245. break;
  246. case SampleArcBallCameraMode.RollConstrained:
  247. //update the yaw
  248. pitch -= angle;
  249. //constrain pitch to vertical to avoid confusion
  250. pitch = MathHelper.Clamp(pitch, -(MathHelper.PiOver2) + .0001f,
  251. (MathHelper.PiOver2) - .0001f);
  252. //create a new aspect based on pitch and yaw
  253. orientation = Quaternion.CreateFromAxisAngle(Vector3.Up, -yaw) *
  254. Quaternion.CreateFromAxisAngle(Vector3.Right, pitch);
  255. break;
  256. }
  257. }
  258. /// <summary>
  259. /// Orbit towards the Right vector in Free camera
  260. /// or on the latitude line when roll constrained
  261. /// </summary>
  262. public void OrbitRight(float angle)
  263. {
  264. switch (mode)
  265. {
  266. case SampleArcBallCameraMode.Free:
  267. //rotate the aspect by the angle
  268. orientation = orientation *
  269. Quaternion.CreateFromAxisAngle(Vector3.Up, angle);
  270. //normalize to reduce errors
  271. Quaternion.Normalize(ref orientation, out orientation);
  272. break;
  273. case SampleArcBallCameraMode.RollConstrained:
  274. //update the yaw
  275. yaw -= angle;
  276. //float mod yaw to avoid eventual precision errors
  277. //as we move away from 0
  278. yaw = yaw % MathHelper.TwoPi;
  279. //create a new aspect based on pitch and yaw
  280. orientation = Quaternion.CreateFromAxisAngle(Vector3.Up, -yaw) *
  281. Quaternion.CreateFromAxisAngle(Vector3.Right, pitch);
  282. //normalize to reduce errors
  283. Quaternion.Normalize(ref orientation, out orientation);
  284. break;
  285. }
  286. }
  287. /// <summary>
  288. /// Rotate around the Forward vector
  289. /// in free-look camera only
  290. /// </summary>
  291. public void RotateClockwise(float angle)
  292. {
  293. switch (mode)
  294. {
  295. case SampleArcBallCameraMode.Free:
  296. //rotate the orientation around the direction vector
  297. orientation = orientation *
  298. Quaternion.CreateFromAxisAngle(Vector3.Forward, angle);
  299. Quaternion.Normalize(ref orientation, out orientation);
  300. break;
  301. case SampleArcBallCameraMode.RollConstrained:
  302. //Do nothing, we don't want to roll at all to stay consistent
  303. break;
  304. }
  305. }
  306. /// <summary>
  307. /// Sets up a quaternion & position from vector camera components
  308. /// and oriented the camera up
  309. /// </summary>
  310. /// <param name="eye">The camera position</param>
  311. /// <param name="lookAt">The camera's look-at point</param>
  312. /// <param name="up"></param>
  313. public void SetCamera(Vector3 position, Vector3 target, Vector3 up)
  314. {
  315. //Create a look at matrix, to simplify matters a bit
  316. Matrix temp = Matrix.CreateLookAt(position, target, up);
  317. //invert the matrix, since we're determining the
  318. //orientation from the rotation matrix in RH coords
  319. temp = Matrix.Invert(temp);
  320. //set the postion
  321. targetValue = target;
  322. //create the new aspect from the look-at matrix
  323. orientation = Quaternion.CreateFromRotationMatrix(temp);
  324. //When setting a new eye-view direction
  325. //in one of the gimble-locked modes, the yaw and
  326. //pitch gimble must be calculated.
  327. if (mode != SampleArcBallCameraMode.Free)
  328. {
  329. //first, get the direction projected on the x/z plne
  330. Vector3 dir = Direction;
  331. dir.Y = 0;
  332. if (dir.Length() == 0f)
  333. {
  334. dir = Vector3.Forward;
  335. }
  336. dir.Normalize();
  337. //find the yaw of the direction on the x/z plane
  338. //and use the sign of the x-component since we have 360 degrees
  339. //of freedom
  340. yaw = (float)(Math.Acos(-dir.Z) * Math.Sign(dir.X));
  341. //Get the pitch from the angle formed by the Up vector and the
  342. //the forward direction, then subtracting Pi / 2, since
  343. //we pitch is zero at Forward, not Up.
  344. pitch = (float)-(Math.Acos(Vector3.Dot(Vector3.Up, Direction))
  345. - MathHelper.PiOver2);
  346. }
  347. }
  348. #endregion
  349. #region Input Handlers
  350. /// <summary>
  351. /// Handle default keyboard input for a camera
  352. /// </summary>
  353. public void HandleDefaultKeyboardControls(KeyboardState kbState,
  354. GameTime gameTime)
  355. {
  356. if (gameTime == null)
  357. {
  358. throw new ArgumentNullException("gameTime",
  359. "GameTime parameter cannot be null.");
  360. }
  361. float elapsedTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
  362. float dX = elapsedTime * ReadKeyboardAxis(
  363. kbState, Keys.A, Keys.D) * InputTurnRate;
  364. float dY = elapsedTime * ReadKeyboardAxis(
  365. kbState, Keys.S, Keys.W) * InputTurnRate;
  366. if (dY != 0) OrbitUp(dY);
  367. if (dX != 0) OrbitRight(dX);
  368. distanceValue += ReadKeyboardAxis(kbState, Keys.Z, Keys.X)
  369. * inputDistanceRateValue * elapsedTime;
  370. if (distanceValue < .001f) distanceValue = .001f;
  371. if (mode != SampleArcBallCameraMode.Free)
  372. {
  373. float dR = elapsedTime * ReadKeyboardAxis(
  374. kbState, Keys.Q, Keys.E) * InputTurnRate;
  375. if (dR != 0) RotateClockwise(dR);
  376. }
  377. }
  378. /// <summary>
  379. /// Handle default gamepad input for a camera
  380. /// </summary>
  381. public void HandleDefaultGamepadControls(GamePadState gpState, GameTime gameTime)
  382. {
  383. if (gameTime == null)
  384. {
  385. throw new ArgumentNullException("gameTime",
  386. "GameTime parameter cannot be null.");
  387. }
  388. if (gpState.IsConnected)
  389. {
  390. float elapsedTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
  391. float dX = gpState.ThumbSticks.Right.X * elapsedTime * InputTurnRate;
  392. float dY = gpState.ThumbSticks.Right.Y * elapsedTime * InputTurnRate;
  393. float dR = gpState.Triggers.Right * elapsedTime * InputTurnRate;
  394. dR-= gpState.Triggers.Left * elapsedTime * InputTurnRate;
  395. //change orientation if necessary
  396. if(dY != 0) OrbitUp(dY);
  397. if(dX != 0) OrbitRight(dX);
  398. if (dR != 0) RotateClockwise(dR);
  399. //decrease distance to target (move forward)
  400. if (gpState.Buttons.A == ButtonState.Pressed)
  401. {
  402. distanceValue -= elapsedTime * inputDistanceRateValue;
  403. }
  404. //increase distance to target (move back)
  405. if (gpState.Buttons.B == ButtonState.Pressed)
  406. {
  407. distanceValue += elapsedTime * inputDistanceRateValue;
  408. }
  409. if (distanceValue < .001f) distanceValue = .001f;
  410. }
  411. }
  412. #endregion
  413. #region Misc Camera Controls
  414. /// <summary>
  415. /// Reset the camera to the defaults set in the constructor
  416. /// </summary>
  417. public void Reset()
  418. {
  419. //orientation quaternion assumes a Pi rotation so you're facing the "front"
  420. //of the model (looking down the +Z axis)
  421. orientation = Quaternion.CreateFromAxisAngle(Vector3.Up, MathHelper.Pi);
  422. distanceValue = 3f;
  423. targetValue = Vector3.Zero;
  424. yaw = MathHelper.Pi;
  425. pitch = 0;
  426. }
  427. #endregion
  428. }
  429. }