camera.cpp 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "T3D/camera.h"
  24. #include "math/mMath.h"
  25. #include "core/stream/bitStream.h"
  26. #include "T3D/fx/cameraFXMgr.h"
  27. #include "T3D/gameBase/gameConnection.h"
  28. #include "math/mathIO.h"
  29. #include "gui/worldEditor/editor.h"
  30. #include "console/engineAPI.h"
  31. #include "console/consoleTypes.h"
  32. #include "console/engineAPI.h"
  33. #include "math/mathUtils.h"
  34. #include "math/mTransform.h"
  35. #ifdef TORQUE_EXTENDED_MOVE
  36. #include "T3D/gameBase/extended/extendedMove.h"
  37. #endif
  38. S32 Camera::smExtendedMovePosRotIndex = 0; // The ExtendedMove position/rotation index used for camera movements
  39. #define MaxPitch 1.5706f
  40. #define CameraRadius 0.05f;
  41. ImplementEnumType( CameraMotionMode,
  42. "Movement behavior type for Camera.\n\n"
  43. "@ingroup BaseCamera" )
  44. { Camera::StationaryMode, "Stationary", "Camera does not rotate or move." },
  45. { Camera::FreeRotateMode, "FreeRotate", "Camera may rotate but does not move." },
  46. { Camera::FlyMode, "Fly", "Camera may rotate and move freely." },
  47. { Camera::OrbitObjectMode, "OrbitObject", "Camera orbits about a given object. Damage flash and white out is determined by the object being orbited. See Camera::setOrbitMode() to set the orbit object and other parameters." },
  48. { Camera::OrbitPointMode, "OrbitPoint", "Camera orbits about a given point. See Camera::setOrbitMode() to set the orbit point and other parameters." },
  49. { Camera::TrackObjectMode, "TrackObject", "Camera always faces a given object. See Camera::setTrackObject() to set the object to track and a distance to remain from the object." },
  50. { Camera::OverheadMode, "Overhead", "Camera moves in the XY plane." },
  51. { Camera::EditOrbitMode, "EditOrbit", "Used by the World Editor to orbit about a point. When first activated, the camera is rotated to face the orbit point rather than move to it." }
  52. EndImplementEnumType;
  53. //=============================================================================
  54. // CameraData.
  55. //=============================================================================
  56. // MARK: ---- CameraData ----
  57. IMPLEMENT_CO_DATABLOCK_V1( CameraData );
  58. ConsoleDocClass( CameraData,
  59. "@brief A datablock that describes a camera.\n\n"
  60. "@tsexample\n"
  61. "datablock CameraData(Observer)\n"
  62. "{\n"
  63. " mode = \"Observer\";\n"
  64. "};\n"
  65. "@endtsexample\n"
  66. "@see Camera\n\n"
  67. "@ref Datablock_Networking\n"
  68. "@ingroup BaseCamera\n"
  69. "@ingroup Datablocks\n"
  70. );
  71. //-----------------------------------------------------------------------------
  72. void CameraData::initPersistFields()
  73. {
  74. Parent::initPersistFields();
  75. }
  76. //-----------------------------------------------------------------------------
  77. void CameraData::packData(BitStream* stream)
  78. {
  79. Parent::packData(stream);
  80. }
  81. //-----------------------------------------------------------------------------
  82. void CameraData::unpackData(BitStream* stream)
  83. {
  84. Parent::unpackData(stream);
  85. }
  86. //=============================================================================
  87. // Camera.
  88. //=============================================================================
  89. // MARK: ---- Camera ----
  90. IMPLEMENT_CO_NETOBJECT_V1( Camera );
  91. ConsoleDocClass( Camera,
  92. "@brief Represents a position, direction and field of view to render a scene from.\n\n"
  93. "A camera is typically manipulated by a GameConnection. When set as the connection's "
  94. "control object, the camera handles all movement actions ($mvForwardAction, $mvPitch, etc.) "
  95. "just like a Player.\n"
  96. "@tsexample\n"
  97. "// Set an already created camera as the GameConnection's control object\n"
  98. "%connection.setControlObject(%camera);\n"
  99. "@endtsexample\n\n"
  100. "<h3>Methods of Operation</h3>\n\n"
  101. "The camera has two general methods of operation. The first is the standard mode where "
  102. "the camera starts and stops its motion and rotation instantly. This is the default operation "
  103. "of the camera and is used by most games. It may be specifically set with Camera::setFlyMode() "
  104. "for 6 DoF motion. It is also typically the method used with Camera::setOrbitMode() or one of "
  105. "its helper methods to orbit about a specific object (such as the Player's dead body) or a "
  106. "specific point.\n\n"
  107. "The second method goes under the name of Newton as it follows Newton's 2nd law of "
  108. "motion: F=ma. This provides the camera with an ease-in and ease-out feel for both movement "
  109. "and rotation. To activate this method for movement, either use Camera::setNewtonFlyMode() or set "
  110. "the Camera::newtonMode field to true. To activate this method for rotation, set the Camera::newtonRotation "
  111. "to true. This method of operation is not typically used in games, and was developed to allow "
  112. "for a smooth fly through of a game level while recording a demo video. But with the right force "
  113. "and drag settings, it may give a more organic feel to the camera to games that use an overhead view, "
  114. "such as a RTS.\n\n"
  115. "There is a third, minor method of operation but it is not generally used for games. This is when the "
  116. "camera is used with Torque's World Editor in Edit Orbit Mode. When set, this allows the camera "
  117. "to rotate about a specific point in the world, and move towards and away from this point. See "
  118. "Camera::setEditOrbitMode() and Camera::setEditOrbitPoint(). While in this mode, Camera::autoFitRadius() "
  119. "may also be used.\n\n"
  120. "@tsexample\n"
  121. "// Create a camera in the level and set its position to a given spawn point.\n"
  122. "// Note: The camera starts in the standard fly mode.\n"
  123. "%cam = new Camera() {\n"
  124. " datablock = \"Observer\";\n"
  125. "};\n"
  126. "MissionCleanup.add( %cam );\n"
  127. "%cam.setTransform( %spawnPoint.getTransform() );\n"
  128. "@endtsexample\n\n"
  129. "@tsexample\n"
  130. "// Create a camera at the given spawn point for the specified\n"
  131. "// GameConnection i.e. the client. Uses the standard\n"
  132. "// Sim::spawnObject() function to create the camera using the\n"
  133. "// defined default settings.\n"
  134. "// Note: The camera starts in the standard fly mode.\n"
  135. "function GameConnection::spawnCamera(%this, %spawnPoint)\n"
  136. "{\n"
  137. " // Set the control object to the default camera\n"
  138. " if (!isObject(%this.camera))\n"
  139. " {\n"
  140. " if (isDefined(\"$Game::DefaultCameraClass\"))\n"
  141. " %this.camera = spawnObject($Game::DefaultCameraClass, $Game::DefaultCameraDataBlock);\n"
  142. " }\n"
  143. "\n"
  144. " // If we have a camera then set up some properties\n"
  145. " if (isObject(%this.camera))\n"
  146. " {\n"
  147. " // Make sure we're cleaned up when the mission ends\n"
  148. " MissionCleanup.add( %this.camera );\n"
  149. "\n"
  150. " // Make sure the camera is always in scope for the connection\n"
  151. " %this.camera.scopeToClient(%this);\n"
  152. "\n"
  153. " // Send all user input from the connection to the camera\n"
  154. " %this.setControlObject(%this.camera);\n"
  155. "\n"
  156. " if (isDefined(\"%spawnPoint\"))\n"
  157. " {\n"
  158. " // Attempt to treat %spawnPoint as an object, such as a\n"
  159. " // SpawnSphere class.\n"
  160. " if (getWordCount(%spawnPoint) == 1 && isObject(%spawnPoint))\n"
  161. " {\n"
  162. " %this.camera.setTransform(%spawnPoint.getTransform());\n"
  163. " }\n"
  164. " else\n"
  165. " {\n"
  166. " // Treat %spawnPoint as an AngleAxis transform\n"
  167. " %this.camera.setTransform(%spawnPoint);\n"
  168. " }\n"
  169. " }\n"
  170. " }\n"
  171. "}\n"
  172. "@endtsexample\n\n"
  173. "<h3>Motion Modes</h3>\n\n"
  174. "Beyond the different operation methods, the Camera may be set to one of a number "
  175. "of motion modes. These motion modes determine how the camera will respond to input "
  176. "and may be used to constrain how the Camera moves. The CameraMotionMode enumeration "
  177. "defines the possible set of modes and the Camera's current may be obtained by using "
  178. "getMode().\n\n"
  179. "Some of the motion modes may be set using specific script methods. These often provide "
  180. "additional parameters to set up the mode in one go. Otherwise, it is always possible to "
  181. "set a Camera's motion mode using the controlMode property. Just pass in the name of the "
  182. "mode enum. The following table lists the motion modes, how to set them up, and what they offer:\n\n"
  183. "<table border='1' cellpadding='1'>"
  184. "<tr><th>Mode</th><th>Set From Script</th><th>Input Move</th><th>Input Rotate</th><th>Can Use Newton Mode?</th></tr>"
  185. "<tr><td>Stationary</td><td>controlMode property</td><td>No</td><td>No</td><td>No</td></tr>"
  186. "<tr><td>FreeRotate</td><td>controlMode property</td><td>No</td><td>Yes</td><td>Rotate Only</td></tr>"
  187. "<tr><td>Fly</td><td>setFlyMode()</td><td>Yes</td><td>Yes</td><td>Yes</td></tr>"
  188. "<tr><td>OrbitObject</td><td>setOrbitMode()</td><td>Orbits object</td><td>Points to object</td><td>Move only</td></tr>"
  189. "<tr><td>OrbitPoint</td><td>setOrbitPoint()</td><td>Orbits point</td><td>Points to location</td><td>Move only</td></tr>"
  190. "<tr><td>TrackObject</td><td>setTrackObject()</td><td>No</td><td>Points to object</td><td>Yes</td></tr>"
  191. "<tr><td>Overhead</td><td>controlMode property</td><td>Yes</td><td>No</td><td>Yes</td></tr>"
  192. "<tr><td>EditOrbit (object selected)</td><td>setEditOrbitMode()</td><td>Orbits object</td><td>Points to object</td><td>Move only</td></tr>"
  193. "<tr><td>EditOrbit (no object)</td><td>setEditOrbitMode()</td><td>Yes</td><td>Yes</td><td>Yes</td></tr>"
  194. "</table>\n\n"
  195. "<h3>%Trigger Input</h3>\n\n"
  196. "Passing a move trigger ($mvTriggerCount0, $mvTriggerCount1, etc.) on to a Camera performs "
  197. "different actions depending on which mode the camera is in. While in Fly, Overhead or "
  198. "EditOrbit mode, either trigger0 or trigger1 will cause a camera to move twice its normal "
  199. "movement speed. You can see this in action within the World Editor, where holding down the "
  200. "left mouse button while in mouse look mode (right mouse button is also down) causes the Camera "
  201. "to move faster.\n\n"
  202. "Passing along trigger2 will put the camera into strafe mode. While in this mode a Fly, "
  203. "FreeRotate or Overhead Camera will not rotate from the move input. Instead the yaw motion "
  204. "will be applied to the Camera's x motion, and the pitch motion will be applied to the Camera's "
  205. "z motion. You can see this in action within the World Editor where holding down the middle mouse "
  206. "button allows the user to move the camera up, down and side-to-side.\n\n"
  207. "While the camera is operating in Newton Mode, trigger0 and trigger1 behave slightly differently. "
  208. "Here trigger0 activates a multiplier to the applied acceleration force as defined by speedMultiplier. "
  209. "This has the affect of making the camera move up to speed faster. trigger1 has the opposite affect "
  210. "by acting as a brake. When trigger1 is active a multiplier is added to the Camera's drag as "
  211. "defined by brakeMultiplier.\n\n"
  212. "@see CameraData\n"
  213. "@see CameraMotionMode\n"
  214. "@see Camera::movementSpeed\n\n"
  215. "@ingroup BaseCamera\n"
  216. );
  217. F32 Camera::smMovementSpeed = 40.0f;
  218. //----------------------------------------------------------------------------
  219. Camera::Camera()
  220. {
  221. mNetFlags.clear(Ghostable);
  222. mTypeMask |= CameraObjectType;
  223. mDataBlock = 0;
  224. mDelta.pos = Point3F(0.0f, 0.0f, 100.0f);
  225. mDelta.rot = Point3F(0.0f, 0.0f, 0.0f);
  226. mDelta.posVec = mDelta.rotVec = VectorF(0.0f, 0.0f, 0.0f);
  227. mObjToWorld.setColumn(3, mDelta.pos);
  228. mRot = mDelta.rot;
  229. mOffset.set(0.0f, 0.0f, 0.0f);
  230. mMinOrbitDist = 0.0f;
  231. mMaxOrbitDist = 0.0f;
  232. mCurOrbitDist = 0.0f;
  233. mOrbitObject = NULL;
  234. mPosition.set(0.0f, 0.0f, 0.0f);
  235. mObservingClientObject = false;
  236. mMode = FlyMode;
  237. mLastAbsoluteYaw = 0.0f;
  238. mLastAbsolutePitch = 0.0f;
  239. mLastAbsoluteRoll = 0.0f;
  240. // For NewtonFlyMode
  241. mNewtonRotation = false;
  242. mAngularVelocity.set(0.0f, 0.0f, 0.0f);
  243. mAngularForce = 100.0f;
  244. mAngularDrag = 2.0f;
  245. mVelocity.set(0.0f, 0.0f, 0.0f);
  246. mNewtonMode = false;
  247. mMass = 10.0f;
  248. mDrag = 2.0;
  249. mFlyForce = 500.0f;
  250. mSpeedMultiplier = 2.0f;
  251. mBrakeMultiplier = 2.0f;
  252. // For EditOrbitMode
  253. mValidEditOrbitPoint = false;
  254. mEditOrbitPoint.set(0.0f, 0.0f, 0.0f);
  255. mCurrentEditOrbitDist = 2.0;
  256. mLocked = false;
  257. }
  258. //----------------------------------------------------------------------------
  259. Camera::~Camera()
  260. {
  261. }
  262. //----------------------------------------------------------------------------
  263. bool Camera::onAdd()
  264. {
  265. if(!Parent::onAdd() || !mDataBlock)
  266. return false;
  267. mObjBox.maxExtents = mObjScale;
  268. mObjBox.minExtents = mObjScale;
  269. mObjBox.minExtents.neg();
  270. resetWorldBox();
  271. addToScene();
  272. scriptOnAdd();
  273. return true;
  274. }
  275. //----------------------------------------------------------------------------
  276. void Camera::onRemove()
  277. {
  278. scriptOnRemove();
  279. removeFromScene();
  280. Parent::onRemove();
  281. }
  282. //----------------------------------------------------------------------------
  283. bool Camera::onNewDataBlock( GameBaseData *dptr, bool reload )
  284. {
  285. mDataBlock = dynamic_cast<CameraData*>(dptr);
  286. if ( !mDataBlock || !Parent::onNewDataBlock( dptr, reload ) )
  287. return false;
  288. scriptOnNewDataBlock();
  289. return true;
  290. }
  291. //----------------------------------------------------------------------------
  292. void Camera::onEditorEnable()
  293. {
  294. mNetFlags.set(Ghostable);
  295. }
  296. //----------------------------------------------------------------------------
  297. void Camera::onEditorDisable()
  298. {
  299. mNetFlags.clear(Ghostable);
  300. }
  301. //----------------------------------------------------------------------------
  302. // check if the object needs to be observed through its own camera...
  303. void Camera::getCameraTransform(F32* pos, MatrixF* mat)
  304. {
  305. // The camera doesn't support a third person mode,
  306. // so we want to override the default ShapeBase behavior.
  307. ShapeBase * obj = dynamic_cast<ShapeBase*>(static_cast<SimObject*>(mOrbitObject));
  308. if(obj && static_cast<ShapeBaseData*>(obj->getDataBlock())->observeThroughObject)
  309. obj->getCameraTransform(pos, mat);
  310. else
  311. getRenderEyeTransform(mat);
  312. // Apply Camera FX.
  313. mat->mul( gCamFXMgr.getTrans() );
  314. }
  315. void Camera::getEyeCameraTransform(IDisplayDevice *displayDevice, U32 eyeId, MatrixF *outMat)
  316. {
  317. // The camera doesn't support a third person mode,
  318. // so we want to override the default ShapeBase behavior.
  319. ShapeBase * obj = dynamic_cast<ShapeBase*>(static_cast<SimObject*>(mOrbitObject));
  320. if(obj && static_cast<ShapeBaseData*>(obj->getDataBlock())->observeThroughObject)
  321. obj->getEyeCameraTransform(displayDevice, eyeId, outMat);
  322. else
  323. {
  324. Parent::getEyeCameraTransform(displayDevice, eyeId, outMat);
  325. }
  326. }
  327. DisplayPose Camera::calcCameraDeltaPose(GameConnection *con, const DisplayPose& inPose)
  328. {
  329. // NOTE: this is intended to be similar to updateMove
  330. DisplayPose outPose;
  331. outPose.orientation = EulerF(0,0,0);
  332. outPose.position = inPose.position;
  333. // Pitch
  334. outPose.orientation.x = (inPose.orientation.x - mLastAbsolutePitch);
  335. // Constrain the range of mRot.x
  336. while (outPose.orientation.x < -M_PI_F)
  337. outPose.orientation.x += M_2PI_F;
  338. while (outPose.orientation.x > M_PI_F)
  339. outPose.orientation.x -= M_2PI_F;
  340. // Yaw
  341. outPose.orientation.z = (inPose.orientation.z - mLastAbsoluteYaw);
  342. // Constrain the range of mRot.z
  343. while (outPose.orientation.z < -M_PI_F)
  344. outPose.orientation.z += M_2PI_F;
  345. while (outPose.orientation.z > M_PI_F)
  346. outPose.orientation.z -= M_2PI_F;
  347. // Bank
  348. if (mDataBlock->cameraCanBank)
  349. {
  350. outPose.orientation.y = (inPose.orientation.y - mLastAbsoluteRoll);
  351. }
  352. // Constrain the range of mRot.y
  353. while (outPose.orientation.y > M_PI_F)
  354. outPose.orientation.y -= M_2PI_F;
  355. return outPose;
  356. }
  357. //----------------------------------------------------------------------------
  358. F32 Camera::getCameraFov()
  359. {
  360. ShapeBase * obj = dynamic_cast<ShapeBase*>(static_cast<SimObject*>(mOrbitObject));
  361. if(obj && static_cast<ShapeBaseData*>(obj->getDataBlock())->observeThroughObject)
  362. return(obj->getCameraFov());
  363. else
  364. return(Parent::getCameraFov());
  365. }
  366. //----------------------------------------------------------------------------
  367. F32 Camera::getDefaultCameraFov()
  368. {
  369. ShapeBase * obj = dynamic_cast<ShapeBase*>(static_cast<SimObject*>(mOrbitObject));
  370. if(obj && static_cast<ShapeBaseData*>(obj->getDataBlock())->observeThroughObject)
  371. return(obj->getDefaultCameraFov());
  372. else
  373. return(Parent::getDefaultCameraFov());
  374. }
  375. //----------------------------------------------------------------------------
  376. bool Camera::isValidCameraFov(F32 fov)
  377. {
  378. ShapeBase * obj = dynamic_cast<ShapeBase*>(static_cast<SimObject*>(mOrbitObject));
  379. if(obj && static_cast<ShapeBaseData*>(obj->getDataBlock())->observeThroughObject)
  380. return(obj->isValidCameraFov(fov));
  381. else
  382. return(Parent::isValidCameraFov(fov));
  383. }
  384. //----------------------------------------------------------------------------
  385. void Camera::setCameraFov(F32 fov)
  386. {
  387. ShapeBase * obj = dynamic_cast<ShapeBase*>(static_cast<SimObject*>(mOrbitObject));
  388. if(obj && static_cast<ShapeBaseData*>(obj->getDataBlock())->observeThroughObject)
  389. obj->setCameraFov(fov);
  390. else
  391. Parent::setCameraFov(fov);
  392. }
  393. //----------------------------------------------------------------------------
  394. void clampPitchAngle(F32 &pitch)
  395. {
  396. // Clamp pitch to +/-MaxPitch, but allow pitch=PI as it is used by some editor
  397. // views (bottom, front, right)
  398. if ((pitch > MaxPitch) && !mIsEqual(pitch, M_PI_F, 0.001f))
  399. pitch = MaxPitch;
  400. else if (pitch < -MaxPitch)
  401. pitch = -MaxPitch;
  402. }
  403. //----------------------------------------------------------------------------
  404. void Camera::processTick(const Move* move)
  405. {
  406. Parent::processTick(move);
  407. if ( isMounted() )
  408. {
  409. // Fetch Mount Transform.
  410. MatrixF mat;
  411. mMount.object->getMountTransform( mMount.node, mMount.xfm, &mat );
  412. // Apply.
  413. setTransform( mat );
  414. // Update SceneContainer.
  415. updateContainer();
  416. return;
  417. }
  418. Point3F vec,pos;
  419. if (move)
  420. {
  421. bool strafeMode = move->trigger[2];
  422. // If using editor then force camera into fly mode, unless using EditOrbitMode
  423. if(gEditingMission && mMode != FlyMode && mMode != EditOrbitMode)
  424. setFlyMode();
  425. // Massage the mode if we're in EditOrbitMode
  426. CameraMotionMode virtualMode = mMode;
  427. if(mMode == EditOrbitMode)
  428. {
  429. if(!mValidEditOrbitPoint)
  430. {
  431. virtualMode = FlyMode;
  432. }
  433. else
  434. {
  435. // Reset any Newton camera velocities for when we switch
  436. // out of EditOrbitMode.
  437. mNewtonRotation = false;
  438. mVelocity.set(0.0f, 0.0f, 0.0f);
  439. mAngularVelocity.set(0.0f, 0.0f, 0.0f);
  440. }
  441. }
  442. // Update orientation
  443. mDelta.rotVec = mRot;
  444. VectorF rotVec(0, 0, 0);
  445. bool doStandardMove = true;
  446. #ifdef TORQUE_EXTENDED_MOVE
  447. GameConnection* con = getControllingClient();
  448. // Work with an absolute rotation from the ExtendedMove class?
  449. if(con && con->getControlSchemeAbsoluteRotation())
  450. {
  451. doStandardMove = false;
  452. const ExtendedMove* emove = dynamic_cast<const ExtendedMove*>(move);
  453. U32 emoveIndex = smExtendedMovePosRotIndex;
  454. if(emoveIndex >= ExtendedMove::MaxPositionsRotations)
  455. emoveIndex = 0;
  456. if(emove->EulerBasedRotation[emoveIndex])
  457. {
  458. if(virtualMode != StationaryMode &&
  459. virtualMode != TrackObjectMode &&
  460. (!mLocked || virtualMode != OrbitObjectMode && virtualMode != OrbitPointMode))
  461. {
  462. // Pitch
  463. mRot.x += (emove->rotX[emoveIndex] - mLastAbsolutePitch);
  464. // Do we also include the relative pitch value?
  465. if(con->getControlSchemeAddPitchToAbsRot() && !strafeMode)
  466. {
  467. F32 x = move->pitch;
  468. if (x > M_PI_F)
  469. x -= M_2PI_F;
  470. mRot.x += x;
  471. }
  472. // Constrain the range of mRot.x
  473. while (mRot.x < -M_PI_F)
  474. mRot.x += M_2PI_F;
  475. while (mRot.x > M_PI_F)
  476. mRot.x -= M_2PI_F;
  477. // Yaw
  478. mRot.z += (emove->rotZ[emoveIndex] - mLastAbsoluteYaw);
  479. // Do we also include the relative yaw value?
  480. if(con->getControlSchemeAddYawToAbsRot() && !strafeMode)
  481. {
  482. F32 z = move->yaw;
  483. if (z > M_PI_F)
  484. z -= M_2PI_F;
  485. mRot.z += z;
  486. }
  487. // Constrain the range of mRot.z
  488. while (mRot.z < -M_PI_F)
  489. mRot.z += M_2PI_F;
  490. while (mRot.z > M_PI_F)
  491. mRot.z -= M_2PI_F;
  492. mLastAbsoluteYaw = emove->rotZ[emoveIndex];
  493. mLastAbsolutePitch = emove->rotX[emoveIndex];
  494. mLastAbsoluteRoll = emove->rotY[emoveIndex];
  495. // Bank
  496. mRot.y = emove->rotY[emoveIndex];
  497. // Constrain the range of mRot.y
  498. while (mRot.y > M_PI_F)
  499. mRot.y -= M_2PI_F;
  500. }
  501. }
  502. }
  503. #endif
  504. if(doStandardMove)
  505. {
  506. // process input/determine rotation vector
  507. if(virtualMode != StationaryMode &&
  508. virtualMode != TrackObjectMode &&
  509. (!mLocked || virtualMode != OrbitObjectMode && virtualMode != OrbitPointMode))
  510. {
  511. if(!strafeMode)
  512. {
  513. rotVec.x = move->pitch;
  514. rotVec.z = move->yaw;
  515. }
  516. }
  517. else if(virtualMode == TrackObjectMode && bool(mOrbitObject))
  518. {
  519. // orient the camera to face the object
  520. Point3F objPos;
  521. // If this is a shapebase, use its render eye transform
  522. // to avoid jittering.
  523. ShapeBase *shape = dynamic_cast<ShapeBase*>((GameBase*)mOrbitObject);
  524. if( shape != NULL )
  525. {
  526. MatrixF ret;
  527. shape->getRenderEyeTransform( &ret );
  528. objPos = ret.getPosition();
  529. }
  530. else
  531. {
  532. mOrbitObject->getWorldBox().getCenter(&objPos);
  533. }
  534. mObjToWorld.getColumn(3,&pos);
  535. vec = objPos - pos;
  536. vec.normalizeSafe();
  537. F32 pitch, yaw;
  538. MathUtils::getAnglesFromVector(vec, yaw, pitch);
  539. rotVec.x = -pitch - mRot.x;
  540. rotVec.z = yaw - mRot.z;
  541. if(rotVec.z > M_PI_F)
  542. rotVec.z -= M_2PI_F;
  543. else if(rotVec.z < -M_PI_F)
  544. rotVec.z += M_2PI_F;
  545. }
  546. // apply rotation vector according to physics rules
  547. if(mNewtonRotation)
  548. {
  549. const F32 force = mAngularForce;
  550. const F32 drag = mAngularDrag;
  551. VectorF acc(0.0f, 0.0f, 0.0f);
  552. rotVec.x *= 2.0f; // Assume that our -2PI to 2PI range was clamped to -PI to PI in script
  553. rotVec.z *= 2.0f; // Assume that our -2PI to 2PI range was clamped to -PI to PI in script
  554. F32 rotVecL = rotVec.len();
  555. if(rotVecL > 0)
  556. {
  557. acc = (rotVec * force / mMass) * TickSec;
  558. }
  559. // Accelerate
  560. mAngularVelocity += acc;
  561. // Drag
  562. mAngularVelocity -= mAngularVelocity * drag * TickSec;
  563. // Rotate
  564. mRot += mAngularVelocity * TickSec;
  565. clampPitchAngle(mRot.x);
  566. }
  567. else
  568. {
  569. mRot.x += rotVec.x;
  570. mRot.z += rotVec.z;
  571. clampPitchAngle(mRot.x);
  572. }
  573. }
  574. // Update position
  575. VectorF posVec(0, 0, 0);
  576. bool mustValidateEyePoint = false;
  577. bool serverInterpolate = false;
  578. // process input/determine translation vector
  579. if(virtualMode == OrbitObjectMode || virtualMode == OrbitPointMode)
  580. {
  581. pos = mDelta.pos;
  582. if(virtualMode == OrbitObjectMode && bool(mOrbitObject))
  583. {
  584. // If this is a shapebase, use its render eye transform
  585. // to avoid jittering.
  586. GameBase *castObj = mOrbitObject;
  587. ShapeBase* shape = dynamic_cast<ShapeBase*>(castObj);
  588. if( shape != NULL )
  589. {
  590. MatrixF ret;
  591. shape->getRenderEyeTransform( &ret );
  592. mPosition = ret.getPosition();
  593. }
  594. else
  595. {
  596. // Hopefully this is a static object that doesn't move,
  597. // because the worldbox doesn't get updated between ticks.
  598. mOrbitObject->getWorldBox().getCenter(&mPosition);
  599. }
  600. }
  601. posVec = (mPosition + mOffset) - pos;
  602. mustValidateEyePoint = true;
  603. serverInterpolate = mNewtonMode;
  604. }
  605. else if(virtualMode == EditOrbitMode && mValidEditOrbitPoint)
  606. {
  607. bool faster = move->trigger[0] || move->trigger[1];
  608. F32 scale = smMovementSpeed * (faster + 1);
  609. mCurrentEditOrbitDist -= move->y * TickSec * scale;
  610. mCurrentEditOrbitDist -= move->roll * TickSec * scale; // roll will be -Pi to Pi and we'll attempt to scale it here to be in line with the move->y calculation above
  611. if(mCurrentEditOrbitDist < 0.0f)
  612. mCurrentEditOrbitDist = 0.0f;
  613. mPosition = mEditOrbitPoint;
  614. _setPosition(mPosition, mRot);
  615. _calcEditOrbitPoint(&mObjToWorld, mRot);
  616. pos = mPosition;
  617. }
  618. else if(virtualMode == FlyMode)
  619. {
  620. bool faster = move->trigger[0] || move->trigger[1];
  621. F32 scale = smMovementSpeed * (faster + 1);
  622. mObjToWorld.getColumn(3,&pos);
  623. mObjToWorld.getColumn(0,&vec);
  624. posVec = vec * move->x * TickSec * scale + vec * (strafeMode ? move->yaw * 2.0f * TickSec * scale : 0.0f);
  625. mObjToWorld.getColumn(1,&vec);
  626. posVec += vec * move->y * TickSec * scale + vec * move->roll * TickSec * scale;
  627. mObjToWorld.getColumn(2,&vec);
  628. posVec += vec * move->z * TickSec * scale - vec * (strafeMode ? move->pitch * 2.0f * TickSec * scale : 0.0f);
  629. }
  630. else if(virtualMode == OverheadMode)
  631. {
  632. bool faster = move->trigger[0] || move->trigger[1];
  633. F32 scale = smMovementSpeed * (faster + 1);
  634. mObjToWorld.getColumn(3,&pos);
  635. mObjToWorld.getColumn(0,&vec);
  636. vec.z = 0;
  637. vec.normalizeSafe();
  638. vec = vec * move->x * TickSec * scale + (strafeMode ? vec * move->yaw * 2.0f * TickSec * scale : Point3F(0, 0, 0));
  639. posVec = vec;
  640. mObjToWorld.getColumn(1,&vec);
  641. vec.z = 0;
  642. if (vec.isZero())
  643. {
  644. mObjToWorld.getColumn(2,&vec);
  645. vec.z = 0;
  646. }
  647. vec.normalizeSafe();
  648. vec = vec * move->y * TickSec * scale - (strafeMode ? vec * move->pitch * 2.0f * TickSec * scale : Point3F(0, 0, 0));
  649. posVec += vec;
  650. posVec.z += move->z * TickSec * scale + move->roll * TickSec * scale;
  651. }
  652. else // ignore input
  653. {
  654. mObjToWorld.getColumn(3,&pos);
  655. }
  656. // apply translation vector according to physics rules
  657. mDelta.posVec = pos;
  658. if(mNewtonMode)
  659. {
  660. bool faster = move->trigger[0];
  661. bool brake = move->trigger[1];
  662. const F32 movementSpeedMultiplier = smMovementSpeed / 40.0f; // Using the starting value as the base
  663. const F32 force = faster ? mFlyForce * movementSpeedMultiplier * mSpeedMultiplier : mFlyForce * movementSpeedMultiplier;
  664. const F32 drag = brake ? mDrag * mBrakeMultiplier : mDrag;
  665. VectorF acc(0.0f, 0.0f, 0.0f);
  666. F32 posVecL = posVec.len();
  667. if(posVecL > 0)
  668. {
  669. acc = (posVec * force / mMass) * TickSec;
  670. }
  671. // Accelerate
  672. mVelocity += acc;
  673. // Drag
  674. mVelocity -= mVelocity * drag * TickSec;
  675. // Move
  676. pos += mVelocity * TickSec;
  677. }
  678. else
  679. {
  680. pos += posVec;
  681. }
  682. _setPosition(pos,mRot);
  683. // If on the client, calc delta for backstepping
  684. if (serverInterpolate || isClientObject())
  685. {
  686. mDelta.pos = pos;
  687. mDelta.rot = mRot;
  688. mDelta.posVec = mDelta.posVec - mDelta.pos;
  689. mDelta.rotVec = mDelta.rotVec - mDelta.rot;
  690. for(U32 i=0; i<3; ++i)
  691. {
  692. if (mDelta.rotVec[i] > M_PI_F)
  693. mDelta.rotVec[i] -= M_2PI_F;
  694. else if (mDelta.rotVec[i] < -M_PI_F)
  695. mDelta.rotVec[i] += M_2PI_F;
  696. }
  697. }
  698. if(mustValidateEyePoint)
  699. _validateEyePoint(1.0f, &mObjToWorld);
  700. setMaskBits(MoveMask);
  701. }
  702. // Need to calculate the orbit position for the editor so the camera position
  703. // doesn't change when switching between orbit and other camera modes
  704. if (isServerObject() && (mMode == EditOrbitMode && mValidEditOrbitPoint))
  705. _calcEditOrbitPoint(&mObjToWorld, mRot);
  706. if(getControllingClient() && mContainer)
  707. updateContainer();
  708. }
  709. //----------------------------------------------------------------------------
  710. void Camera::onDeleteNotify( SimObject* obj )
  711. {
  712. if( obj == mOrbitObject )
  713. {
  714. mOrbitObject = NULL;
  715. if( mMode == OrbitObjectMode )
  716. mMode = OrbitPointMode;
  717. }
  718. Parent::onDeleteNotify( obj );
  719. }
  720. //----------------------------------------------------------------------------
  721. void Camera::interpolateTick(F32 dt)
  722. {
  723. Parent::interpolateTick(dt);
  724. if ( isMounted() )
  725. {
  726. // Fetch Mount Transform.
  727. MatrixF mat;
  728. mMount.object->getRenderMountTransform( dt, mMount.node, mMount.xfm, &mat );
  729. // Apply.
  730. setRenderTransform( mat );
  731. return;
  732. }
  733. Point3F rot = mDelta.rot + mDelta.rotVec * dt;
  734. if((mMode == OrbitObjectMode || mMode == OrbitPointMode) && !mNewtonMode)
  735. {
  736. if(mMode == OrbitObjectMode && bool(mOrbitObject))
  737. {
  738. // If this is a shapebase, use its render eye transform
  739. // to avoid jittering.
  740. GameBase *castObj = mOrbitObject;
  741. ShapeBase* shape = dynamic_cast<ShapeBase*>(castObj);
  742. if( shape != NULL )
  743. {
  744. MatrixF ret;
  745. shape->getRenderEyeTransform( &ret );
  746. mPosition = ret.getPosition();
  747. }
  748. else
  749. {
  750. // Hopefully this is a static object that doesn't move,
  751. // because the worldbox doesn't get updated between ticks.
  752. mOrbitObject->getWorldBox().getCenter(&mPosition);
  753. }
  754. }
  755. _setRenderPosition( mPosition + mOffset, rot );
  756. _validateEyePoint( 1.0f, &mRenderObjToWorld );
  757. }
  758. else if(mMode == EditOrbitMode && mValidEditOrbitPoint)
  759. {
  760. mPosition = mEditOrbitPoint;
  761. _setRenderPosition(mPosition, rot);
  762. _calcEditOrbitPoint(&mRenderObjToWorld, rot);
  763. }
  764. else if(mMode == TrackObjectMode && bool(mOrbitObject) && !mNewtonRotation)
  765. {
  766. // orient the camera to face the object
  767. Point3F objPos;
  768. // If this is a shapebase, use its render eye transform
  769. // to avoid jittering.
  770. ShapeBase *shape = dynamic_cast<ShapeBase*>((GameBase*)mOrbitObject);
  771. if( shape != NULL )
  772. {
  773. MatrixF ret;
  774. shape->getRenderEyeTransform( &ret );
  775. objPos = ret.getPosition();
  776. }
  777. else
  778. {
  779. mOrbitObject->getWorldBox().getCenter(&objPos);
  780. }
  781. Point3F pos = mDelta.pos + mDelta.posVec * dt;
  782. Point3F vec = objPos - pos;
  783. vec.normalizeSafe();
  784. F32 pitch, yaw;
  785. MathUtils::getAnglesFromVector(vec, yaw, pitch);
  786. rot.x = -pitch;
  787. rot.z = yaw;
  788. _setRenderPosition(pos, rot);
  789. }
  790. else
  791. {
  792. Point3F pos = mDelta.pos + mDelta.posVec * dt;
  793. _setRenderPosition(pos,rot);
  794. if(mMode == OrbitObjectMode || mMode == OrbitPointMode)
  795. _validateEyePoint(1.0f, &mRenderObjToWorld);
  796. }
  797. }
  798. //----------------------------------------------------------------------------
  799. void Camera::_setPosition(const Point3F& pos, const Point3F& rot)
  800. {
  801. MatrixF xRot, zRot;
  802. xRot.set(EulerF(rot.x, 0.0f, 0.0f));
  803. zRot.set(EulerF(0.0f, 0.0f, rot.z));
  804. MatrixF temp;
  805. if(mDataBlock && mDataBlock->cameraCanBank)
  806. {
  807. // Take rot.y into account to bank the camera
  808. MatrixF imat;
  809. imat.mul(zRot, xRot);
  810. MatrixF ymat;
  811. ymat.set(EulerF(0.0f, rot.y, 0.0f));
  812. temp.mul(imat, ymat);
  813. }
  814. else
  815. {
  816. temp.mul(zRot, xRot);
  817. }
  818. temp.setColumn(3, pos);
  819. Parent::setTransform(temp);
  820. mRot = rot;
  821. }
  822. //----------------------------------------------------------------------------
  823. void Camera::setRotation(const Point3F& rot)
  824. {
  825. MatrixF xRot, zRot;
  826. xRot.set(EulerF(rot.x, 0.0f, 0.0f));
  827. zRot.set(EulerF(0.0f, 0.0f, rot.z));
  828. MatrixF temp;
  829. if(mDataBlock && mDataBlock->cameraCanBank)
  830. {
  831. // Take rot.y into account to bank the camera
  832. MatrixF imat;
  833. imat.mul(zRot, xRot);
  834. MatrixF ymat;
  835. ymat.set(EulerF(0.0f, rot.y, 0.0f));
  836. temp.mul(imat, ymat);
  837. }
  838. else
  839. {
  840. temp.mul(zRot, xRot);
  841. }
  842. temp.setColumn(3, getPosition());
  843. Parent::setTransform(temp);
  844. mRot = rot;
  845. }
  846. //----------------------------------------------------------------------------
  847. void Camera::_setRenderPosition(const Point3F& pos,const Point3F& rot)
  848. {
  849. MatrixF xRot, zRot;
  850. xRot.set(EulerF(rot.x, 0, 0));
  851. zRot.set(EulerF(0, 0, rot.z));
  852. MatrixF temp;
  853. // mDataBlock may not be defined yet as this method is called during
  854. // SceneObject::onAdd().
  855. if(mDataBlock && mDataBlock->cameraCanBank)
  856. {
  857. // Take rot.y into account to bank the camera
  858. MatrixF imat;
  859. imat.mul(zRot, xRot);
  860. MatrixF ymat;
  861. ymat.set(EulerF(0.0f, rot.y, 0.0f));
  862. temp.mul(imat, ymat);
  863. }
  864. else
  865. {
  866. temp.mul(zRot, xRot);
  867. }
  868. temp.setColumn(3, pos);
  869. Parent::setRenderTransform(temp);
  870. }
  871. //----------------------------------------------------------------------------
  872. void Camera::writePacketData(GameConnection *connection, BitStream *bstream)
  873. {
  874. // Update client regardless of status flags.
  875. Parent::writePacketData(connection, bstream);
  876. Point3F pos;
  877. mObjToWorld.getColumn(3,&pos);
  878. bstream->setCompressionPoint(pos);
  879. mathWrite(*bstream, pos);
  880. bstream->write(mRot.x);
  881. if(mDataBlock && bstream->writeFlag(mDataBlock->cameraCanBank))
  882. {
  883. // Include mRot.y to allow for camera banking
  884. bstream->write(mRot.y);
  885. }
  886. bstream->write(mRot.z);
  887. U32 writeMode = mMode;
  888. Point3F writePos = mPosition;
  889. S32 gIndex = -1;
  890. if(mMode == OrbitObjectMode)
  891. {
  892. gIndex = bool(mOrbitObject) ? connection->getGhostIndex(mOrbitObject): -1;
  893. if(gIndex == -1)
  894. {
  895. writeMode = OrbitPointMode;
  896. if(bool(mOrbitObject))
  897. mOrbitObject->getWorldBox().getCenter(&writePos);
  898. }
  899. }
  900. else if(mMode == TrackObjectMode)
  901. {
  902. gIndex = bool(mOrbitObject) ? connection->getGhostIndex(mOrbitObject): -1;
  903. if(gIndex == -1)
  904. writeMode = StationaryMode;
  905. }
  906. bstream->writeRangedU32(writeMode, CameraFirstMode, CameraLastMode);
  907. if (writeMode == OrbitObjectMode || writeMode == OrbitPointMode)
  908. {
  909. bstream->write(mMinOrbitDist);
  910. bstream->write(mMaxOrbitDist);
  911. bstream->write(mCurOrbitDist);
  912. if(writeMode == OrbitObjectMode)
  913. {
  914. bstream->writeFlag(mObservingClientObject);
  915. bstream->writeInt(gIndex, NetConnection::GhostIdBitSize);
  916. }
  917. if (writeMode == OrbitPointMode)
  918. bstream->writeCompressedPoint(writePos);
  919. }
  920. else if(writeMode == TrackObjectMode)
  921. {
  922. bstream->writeInt(gIndex, NetConnection::GhostIdBitSize);
  923. }
  924. if(bstream->writeFlag(mNewtonMode))
  925. {
  926. bstream->write(mVelocity.x);
  927. bstream->write(mVelocity.y);
  928. bstream->write(mVelocity.z);
  929. }
  930. if(bstream->writeFlag(mNewtonRotation))
  931. {
  932. bstream->write(mAngularVelocity.x);
  933. bstream->write(mAngularVelocity.y);
  934. bstream->write(mAngularVelocity.z);
  935. }
  936. bstream->writeFlag(mValidEditOrbitPoint);
  937. if(writeMode == EditOrbitMode)
  938. {
  939. bstream->write(mEditOrbitPoint.x);
  940. bstream->write(mEditOrbitPoint.y);
  941. bstream->write(mEditOrbitPoint.z);
  942. bstream->write(mCurrentEditOrbitDist);
  943. }
  944. }
  945. //----------------------------------------------------------------------------
  946. void Camera::readPacketData(GameConnection *connection, BitStream *bstream)
  947. {
  948. Parent::readPacketData(connection, bstream);
  949. Point3F pos,rot;
  950. mathRead(*bstream, &pos);
  951. bstream->setCompressionPoint(pos);
  952. bstream->read(&rot.x);
  953. if(bstream->readFlag())
  954. {
  955. // Include rot.y to allow for camera banking
  956. bstream->read(&rot.y);
  957. }
  958. bstream->read(&rot.z);
  959. GameBase* obj = 0;
  960. mMode = (CameraMotionMode)bstream->readRangedU32(CameraFirstMode, CameraLastMode);
  961. mObservingClientObject = false;
  962. if (mMode == OrbitObjectMode || mMode == OrbitPointMode)
  963. {
  964. bstream->read(&mMinOrbitDist);
  965. bstream->read(&mMaxOrbitDist);
  966. bstream->read(&mCurOrbitDist);
  967. if(mMode == OrbitObjectMode)
  968. {
  969. mObservingClientObject = bstream->readFlag();
  970. S32 gIndex = bstream->readInt(NetConnection::GhostIdBitSize);
  971. obj = static_cast<GameBase*>(connection->resolveGhost(gIndex));
  972. }
  973. if (mMode == OrbitPointMode)
  974. bstream->readCompressedPoint(&mPosition);
  975. }
  976. else if (mMode == TrackObjectMode)
  977. {
  978. S32 gIndex = bstream->readInt(NetConnection::GhostIdBitSize);
  979. obj = static_cast<GameBase*>(connection->resolveGhost(gIndex));
  980. }
  981. if (obj != (GameBase*)mOrbitObject)
  982. {
  983. if (mOrbitObject)
  984. {
  985. clearProcessAfter();
  986. clearNotify(mOrbitObject);
  987. }
  988. mOrbitObject = obj;
  989. if (mOrbitObject)
  990. {
  991. processAfter(mOrbitObject);
  992. deleteNotify(mOrbitObject);
  993. }
  994. }
  995. mNewtonMode = bstream->readFlag();
  996. if(mNewtonMode)
  997. {
  998. bstream->read(&mVelocity.x);
  999. bstream->read(&mVelocity.y);
  1000. bstream->read(&mVelocity.z);
  1001. }
  1002. mNewtonRotation = bstream->readFlag();
  1003. if(mNewtonRotation)
  1004. {
  1005. bstream->read(&mAngularVelocity.x);
  1006. bstream->read(&mAngularVelocity.y);
  1007. bstream->read(&mAngularVelocity.z);
  1008. }
  1009. mValidEditOrbitPoint = bstream->readFlag();
  1010. if(mMode == EditOrbitMode)
  1011. {
  1012. bstream->read(&mEditOrbitPoint.x);
  1013. bstream->read(&mEditOrbitPoint.y);
  1014. bstream->read(&mEditOrbitPoint.z);
  1015. bstream->read(&mCurrentEditOrbitDist);
  1016. }
  1017. _setPosition(pos,rot);
  1018. // Movement in OrbitObjectMode is not input-based - don't reset interpolation
  1019. if(mMode != OrbitObjectMode)
  1020. {
  1021. mDelta.pos = pos;
  1022. mDelta.posVec.set(0.0f, 0.0f, 0.0f);
  1023. mDelta.rot = rot;
  1024. mDelta.rotVec.set(0.0f, 0.0f, 0.0f);
  1025. }
  1026. }
  1027. //----------------------------------------------------------------------------
  1028. U32 Camera::packUpdate(NetConnection *con, U32 mask, BitStream *bstream)
  1029. {
  1030. Parent::packUpdate(con, mask, bstream);
  1031. if (bstream->writeFlag(mask & UpdateMask))
  1032. {
  1033. bstream->writeFlag(mLocked);
  1034. mathWrite(*bstream, mOffset);
  1035. }
  1036. if(bstream->writeFlag(mask & NewtonCameraMask))
  1037. {
  1038. bstream->write(mAngularForce);
  1039. bstream->write(mAngularDrag);
  1040. bstream->write(mMass);
  1041. bstream->write(mDrag);
  1042. bstream->write(mFlyForce);
  1043. bstream->write(mSpeedMultiplier);
  1044. bstream->write(mBrakeMultiplier);
  1045. }
  1046. if(bstream->writeFlag(mask & EditOrbitMask))
  1047. {
  1048. bstream->write(mEditOrbitPoint.x);
  1049. bstream->write(mEditOrbitPoint.y);
  1050. bstream->write(mEditOrbitPoint.z);
  1051. bstream->write(mCurrentEditOrbitDist);
  1052. }
  1053. // The rest of the data is part of the control object packet update.
  1054. // If we're controlled by this client, we don't need to send it.
  1055. if(bstream->writeFlag(getControllingClient() == con && !(mask & InitialUpdateMask)))
  1056. return 0;
  1057. if (bstream->writeFlag(mask & MoveMask))
  1058. {
  1059. Point3F pos;
  1060. mObjToWorld.getColumn(3,&pos);
  1061. bstream->write(pos.x);
  1062. bstream->write(pos.y);
  1063. bstream->write(pos.z);
  1064. bstream->write(mRot.x);
  1065. bstream->write(mRot.z);
  1066. // Only required if in NewtonFlyMode
  1067. F32 len = mVelocity.len();
  1068. if(bstream->writeFlag(mNewtonMode && len > 0.02f))
  1069. {
  1070. Point3F outVel = mVelocity;
  1071. outVel *= 1.0f/len;
  1072. bstream->writeNormalVector(outVel, 10);
  1073. len *= 32.0f; // 5 bits of fraction
  1074. if(len > 8191)
  1075. len = 8191;
  1076. bstream->writeInt((S32)len, 13);
  1077. }
  1078. // Rotation
  1079. len = mAngularVelocity.len();
  1080. if(bstream->writeFlag(mNewtonRotation && len > 0.02f))
  1081. {
  1082. Point3F outVel = mAngularVelocity;
  1083. outVel *= 1.0f/len;
  1084. bstream->writeNormalVector(outVel, 10);
  1085. len *= 32.0f; // 5 bits of fraction
  1086. if(len > 8191)
  1087. len = 8191;
  1088. bstream->writeInt((S32)len, 13);
  1089. }
  1090. }
  1091. return 0;
  1092. }
  1093. //----------------------------------------------------------------------------
  1094. void Camera::unpackUpdate(NetConnection *con, BitStream *bstream)
  1095. {
  1096. Parent::unpackUpdate(con,bstream);
  1097. if (bstream->readFlag())
  1098. {
  1099. mLocked = bstream->readFlag();
  1100. mathRead(*bstream, &mOffset);
  1101. }
  1102. // NewtonCameraMask
  1103. if(bstream->readFlag())
  1104. {
  1105. bstream->read(&mAngularForce);
  1106. bstream->read(&mAngularDrag);
  1107. bstream->read(&mMass);
  1108. bstream->read(&mDrag);
  1109. bstream->read(&mFlyForce);
  1110. bstream->read(&mSpeedMultiplier);
  1111. bstream->read(&mBrakeMultiplier);
  1112. }
  1113. // EditOrbitMask
  1114. if(bstream->readFlag())
  1115. {
  1116. bstream->read(&mEditOrbitPoint.x);
  1117. bstream->read(&mEditOrbitPoint.y);
  1118. bstream->read(&mEditOrbitPoint.z);
  1119. bstream->read(&mCurrentEditOrbitDist);
  1120. }
  1121. // controlled by the client?
  1122. if(bstream->readFlag())
  1123. return;
  1124. // MoveMask
  1125. if (bstream->readFlag())
  1126. {
  1127. Point3F pos,rot;
  1128. bstream->read(&pos.x);
  1129. bstream->read(&pos.y);
  1130. bstream->read(&pos.z);
  1131. bstream->read(&rot.x);
  1132. bstream->read(&rot.z);
  1133. _setPosition(pos,rot);
  1134. // NewtonMode
  1135. if(bstream->readFlag())
  1136. {
  1137. bstream->readNormalVector(&mVelocity, 10);
  1138. mVelocity *= bstream->readInt(13) / 32.0f;
  1139. }
  1140. // NewtonRotation
  1141. mNewtonRotation = bstream->readFlag();
  1142. if(mNewtonRotation)
  1143. {
  1144. bstream->readNormalVector(&mAngularVelocity, 10);
  1145. mAngularVelocity *= bstream->readInt(13) / 32.0f;
  1146. }
  1147. if(mMode != OrbitObjectMode)
  1148. {
  1149. // New delta for client side interpolation
  1150. mDelta.pos = pos;
  1151. mDelta.rot = rot;
  1152. mDelta.posVec = mDelta.rotVec = VectorF(0.0f, 0.0f, 0.0f);
  1153. }
  1154. }
  1155. }
  1156. //----------------------------------------------------------------------------
  1157. void Camera::initPersistFields()
  1158. {
  1159. addGroup( "Camera" );
  1160. addProtectedField( "controlMode", TYPEID< CameraMotionMode >(), Offset( mMode, Camera ),
  1161. &_setModeField, &defaultProtectedGetFn,
  1162. "The current camera control mode." );
  1163. endGroup( "Camera" );
  1164. addGroup( "Camera: Newton Mode" );
  1165. addField( "newtonMode", TypeBool, Offset(mNewtonMode, Camera),
  1166. "Apply smoothing (acceleration and damping) to camera movements." );
  1167. addField( "newtonRotation", TypeBool, Offset(mNewtonRotation, Camera),
  1168. "Apply smoothing (acceleration and damping) to camera rotations." );
  1169. addProtectedField( "mass", TypeF32, Offset(mMass, Camera), &_setNewtonField, &defaultProtectedGetFn,
  1170. "The camera's mass (Newton mode only). Default value is 10." );
  1171. addProtectedField( "drag", TypeF32, Offset(mDrag, Camera), &_setNewtonField, &defaultProtectedGetFn,
  1172. "Drag on camera when moving (Newton mode only). Default value is 2." );
  1173. addProtectedField( "force", TypeF32, Offset(mFlyForce, Camera), &_setNewtonField, &defaultProtectedGetFn,
  1174. "Force applied on camera when asked to move (Newton mode only). Default value is 500." );
  1175. addProtectedField( "angularDrag", TypeF32, Offset(mAngularDrag, Camera), &_setNewtonField, &defaultProtectedGetFn,
  1176. "Drag on camera when rotating (Newton mode only). Default value is 2." );
  1177. addProtectedField( "angularForce", TypeF32, Offset(mAngularForce, Camera), &_setNewtonField, &defaultProtectedGetFn,
  1178. "Force applied on camera when asked to rotate (Newton mode only). Default value is 100." );
  1179. addProtectedField( "speedMultiplier", TypeF32, Offset(mSpeedMultiplier, Camera), &_setNewtonField, &defaultProtectedGetFn,
  1180. "Speed multiplier when triggering the accelerator (Newton mode only). Default value is 2." );
  1181. addProtectedField( "brakeMultiplier", TypeF32, Offset(mBrakeMultiplier, Camera), &_setNewtonField, &defaultProtectedGetFn,
  1182. "Speed multiplier when triggering the brake (Newton mode only). Default value is 2." );
  1183. endGroup( "Camera: Newton Mode" );
  1184. Parent::initPersistFields();
  1185. }
  1186. //-----------------------------------------------------------------------------
  1187. void Camera::consoleInit()
  1188. {
  1189. Con::addVariable("$Camera::movementSpeed", TypeF32, &smMovementSpeed,
  1190. "@brief Global camera movement speed in units/s (typically m/s), with a base value of 40.\n\n"
  1191. "Used in the following camera modes:\n"
  1192. "- Edit Orbit Mode\n"
  1193. "- Fly Mode\n"
  1194. "- Overhead Mode\n"
  1195. "@ingroup BaseCamera\n");
  1196. // ExtendedMove support
  1197. Con::addVariable("$camera::extendedMovePosRotIndex", TypeS32, &smExtendedMovePosRotIndex,
  1198. "@brief The ExtendedMove position/rotation index used for camera movements.\n\n"
  1199. "@ingroup BaseCamera\n");
  1200. }
  1201. //-----------------------------------------------------------------------------
  1202. bool Camera::_setNewtonField( void *object, const char *index, const char *data )
  1203. {
  1204. static_cast<Camera*>(object)->setMaskBits(NewtonCameraMask);
  1205. return true; // ok to set value
  1206. }
  1207. //-----------------------------------------------------------------------------
  1208. bool Camera::_setModeField( void *object, const char *index, const char *data )
  1209. {
  1210. Camera *cam = static_cast<Camera*>( object );
  1211. if( dStricmp(data, "Fly") == 0 )
  1212. {
  1213. cam->setFlyMode();
  1214. return false; // already changed mode
  1215. }
  1216. else if( dStricmp(data, "EditOrbit" ) == 0 )
  1217. {
  1218. cam->setEditOrbitMode();
  1219. return false; // already changed mode
  1220. }
  1221. else if( (dStricmp(data, "OrbitObject") == 0 && cam->mMode != OrbitObjectMode) ||
  1222. (dStricmp(data, "TrackObject") == 0 && cam->mMode != TrackObjectMode) ||
  1223. (dStricmp(data, "OrbitPoint") == 0 && cam->mMode != OrbitPointMode) )
  1224. {
  1225. Con::warnf("Couldn't change Camera mode to %s: required information missing. Use camera.set%s().", data, data);
  1226. return false; // don't change the mode - not valid
  1227. }
  1228. else if( dStricmp(data, "OrbitObject") != 0 &&
  1229. dStricmp(data, "TrackObject") != 0 &&
  1230. bool(cam->mOrbitObject) )
  1231. {
  1232. cam->clearProcessAfter();
  1233. cam->clearNotify(cam->mOrbitObject);
  1234. cam->mOrbitObject = NULL;
  1235. }
  1236. // make sure the requested mode is supported, and set it
  1237. // NOTE: The _CameraMode namespace is generated by ImplementEnumType above
  1238. const EngineEnumTable& enums = *( TYPE< CameraMotionMode >()->getEnumTable() );
  1239. const U32 numValues = enums.getNumValues();
  1240. for( S32 i = 0; i < numValues; ++i)
  1241. {
  1242. if( dStricmp(data, enums[i].mName) == 0 )
  1243. {
  1244. cam->mMode = (CameraMotionMode) enums[i].mInt;
  1245. return false;
  1246. }
  1247. }
  1248. Con::warnf("Unsupported camera mode: %s", data);
  1249. return false;
  1250. }
  1251. //-----------------------------------------------------------------------------
  1252. Point3F Camera::getPosition()
  1253. {
  1254. static Point3F position;
  1255. mObjToWorld.getColumn(3, &position);
  1256. return position;
  1257. }
  1258. //-----------------------------------------------------------------------------
  1259. void Camera::setFlyMode()
  1260. {
  1261. mMode = FlyMode;
  1262. if (bool(mOrbitObject))
  1263. {
  1264. clearProcessAfter();
  1265. clearNotify(mOrbitObject);
  1266. }
  1267. mOrbitObject = NULL;
  1268. }
  1269. //-----------------------------------------------------------------------------
  1270. void Camera::setNewtonFlyMode()
  1271. {
  1272. mNewtonMode = true;
  1273. setFlyMode();
  1274. }
  1275. //-----------------------------------------------------------------------------
  1276. void Camera::setOrbitMode(GameBase *obj, const Point3F &pos, const Point3F &rot, const Point3F& offset, F32 minDist, F32 maxDist, F32 curDist, bool ownClientObject, bool locked)
  1277. {
  1278. mObservingClientObject = ownClientObject;
  1279. if (bool(mOrbitObject))
  1280. {
  1281. clearProcessAfter();
  1282. clearNotify(mOrbitObject);
  1283. }
  1284. mOrbitObject = obj;
  1285. if(bool(mOrbitObject))
  1286. {
  1287. processAfter(mOrbitObject);
  1288. deleteNotify(mOrbitObject);
  1289. mOrbitObject->getWorldBox().getCenter(&mPosition);
  1290. mMode = OrbitObjectMode;
  1291. }
  1292. else
  1293. {
  1294. mMode = OrbitPointMode;
  1295. mPosition = pos;
  1296. }
  1297. _setPosition(mPosition, rot);
  1298. mMinOrbitDist = minDist;
  1299. mMaxOrbitDist = maxDist;
  1300. mCurOrbitDist = curDist;
  1301. if (locked != mLocked || mOffset != offset)
  1302. {
  1303. mLocked = locked;
  1304. mOffset = offset;
  1305. setMaskBits(UpdateMask);
  1306. }
  1307. }
  1308. //-----------------------------------------------------------------------------
  1309. void Camera::setTrackObject(GameBase *obj, const Point3F &offset)
  1310. {
  1311. if(bool(mOrbitObject))
  1312. {
  1313. clearProcessAfter();
  1314. clearNotify(mOrbitObject);
  1315. }
  1316. mOrbitObject = obj;
  1317. if(bool(mOrbitObject))
  1318. {
  1319. processAfter(mOrbitObject);
  1320. deleteNotify(mOrbitObject);
  1321. }
  1322. mOffset = offset;
  1323. mMode = TrackObjectMode;
  1324. setMaskBits( UpdateMask );
  1325. }
  1326. //-----------------------------------------------------------------------------
  1327. void Camera::_validateEyePoint(F32 pos, MatrixF *mat)
  1328. {
  1329. if (pos != 0)
  1330. {
  1331. // Use the eye transform to orient the camera
  1332. Point3F dir;
  1333. mat->getColumn(1, &dir);
  1334. if (mMaxOrbitDist - mMinOrbitDist > 0.0f)
  1335. pos *= mMaxOrbitDist - mMinOrbitDist;
  1336. // Use the camera node's pos.
  1337. Point3F startPos = getRenderPosition();
  1338. Point3F endPos;
  1339. // Make sure we don't extend the camera into anything solid
  1340. if(mOrbitObject)
  1341. mOrbitObject->disableCollision();
  1342. disableCollision();
  1343. RayInfo collision;
  1344. U32 mask = TerrainObjectType |
  1345. WaterObjectType |
  1346. StaticShapeObjectType |
  1347. PlayerObjectType |
  1348. ItemObjectType |
  1349. VehicleObjectType;
  1350. SceneContainer* pContainer = isServerObject() ? &gServerContainer : &gClientContainer;
  1351. if (!pContainer->castRay(startPos, startPos - dir * 2.5 * pos, mask, &collision))
  1352. endPos = startPos - dir * pos;
  1353. else
  1354. {
  1355. float dot = mDot(dir, collision.normal);
  1356. if (dot > 0.01f)
  1357. {
  1358. F32 colDist = mDot(startPos - collision.point, dir) - (1 / dot) * CameraRadius;
  1359. if (colDist > pos)
  1360. colDist = pos;
  1361. if (colDist < 0.0f)
  1362. colDist = 0.0f;
  1363. endPos = startPos - dir * colDist;
  1364. }
  1365. else
  1366. endPos = startPos - dir * pos;
  1367. }
  1368. mat->setColumn(3, endPos);
  1369. enableCollision();
  1370. if(mOrbitObject)
  1371. mOrbitObject->enableCollision();
  1372. }
  1373. }
  1374. //-----------------------------------------------------------------------------
  1375. void Camera::setTransform(const MatrixF& mat)
  1376. {
  1377. // This method should never be called on the client.
  1378. // This currently converts all rotation in the mat into
  1379. // rotations around the z and x axis.
  1380. Point3F pos,vec;
  1381. mat.getColumn(1, &vec);
  1382. mat.getColumn(3, &pos);
  1383. Point3F rot(-mAtan2(vec.z, mSqrt(vec.x * vec.x + vec.y * vec.y)), 0.0f, -mAtan2(-vec.x, vec.y));
  1384. _setPosition(pos,rot);
  1385. }
  1386. //-----------------------------------------------------------------------------
  1387. void Camera::setRenderTransform(const MatrixF& mat)
  1388. {
  1389. // This method should never be called on the client.
  1390. // This currently converts all rotation in the mat into
  1391. // rotations around the z and x axis.
  1392. Point3F pos,vec;
  1393. mat.getColumn(1,&vec);
  1394. mat.getColumn(3,&pos);
  1395. Point3F rot(-mAtan2(vec.z, mSqrt(vec.x*vec.x + vec.y*vec.y)),0,-mAtan2(-vec.x,vec.y));
  1396. _setRenderPosition(pos,rot);
  1397. }
  1398. //-----------------------------------------------------------------------------
  1399. F32 Camera::getDamageFlash() const
  1400. {
  1401. if (mMode == OrbitObjectMode && isServerObject() && bool(mOrbitObject))
  1402. {
  1403. const GameBase *castObj = mOrbitObject;
  1404. const ShapeBase* psb = dynamic_cast<const ShapeBase*>(castObj);
  1405. if (psb)
  1406. return psb->getDamageFlash();
  1407. }
  1408. return mDamageFlash;
  1409. }
  1410. //-----------------------------------------------------------------------------
  1411. F32 Camera::getWhiteOut() const
  1412. {
  1413. if (mMode == OrbitObjectMode && isServerObject() && bool(mOrbitObject))
  1414. {
  1415. const GameBase *castObj = mOrbitObject;
  1416. const ShapeBase* psb = dynamic_cast<const ShapeBase*>(castObj);
  1417. if (psb)
  1418. return psb->getWhiteOut();
  1419. }
  1420. return mWhiteOut;
  1421. }
  1422. //-----------------------------------------------------------------------------
  1423. void Camera::setVelocity(const VectorF& vel)
  1424. {
  1425. mVelocity = vel;
  1426. setMaskBits(MoveMask);
  1427. }
  1428. //-----------------------------------------------------------------------------
  1429. void Camera::setAngularVelocity(const VectorF& vel)
  1430. {
  1431. mAngularVelocity = vel;
  1432. setMaskBits(MoveMask);
  1433. }
  1434. //-----------------------------------------------------------------------------
  1435. void Camera::setEditOrbitMode()
  1436. {
  1437. mMode = EditOrbitMode;
  1438. if (bool(mOrbitObject))
  1439. {
  1440. clearProcessAfter();
  1441. clearNotify(mOrbitObject);
  1442. }
  1443. mOrbitObject = NULL;
  1444. // If there is a valid orbit point, then point to it
  1445. // rather than move the camera.
  1446. if(mValidEditOrbitPoint)
  1447. {
  1448. Point3F currentPos;
  1449. mObjToWorld.getColumn(3,&currentPos);
  1450. Point3F dir = mEditOrbitPoint - currentPos;
  1451. mCurrentEditOrbitDist = dir.len();
  1452. dir.normalize();
  1453. F32 yaw, pitch;
  1454. MathUtils::getAnglesFromVector(dir, yaw, pitch);
  1455. mRot.x = -pitch;
  1456. mRot.z = yaw;
  1457. }
  1458. }
  1459. //-----------------------------------------------------------------------------
  1460. void Camera::_calcOrbitPoint( MatrixF* mat, const Point3F& rot )
  1461. {
  1462. Point3F pos;
  1463. pos.x = mCurOrbitDist * mSin( rot.x + mDegToRad( 90.0f ) ) * mCos( -1.0f * ( rot.z + mDegToRad( 90.0f ) ) ) + mPosition.x + mOffset.x;
  1464. pos.y = mCurOrbitDist * mSin( rot.x + mDegToRad( 90.0f ) ) * mSin( -1.0f * ( rot.z + mDegToRad( 90.0f ) ) ) + mPosition.y + mOffset.y;
  1465. pos.z = mCurOrbitDist * mSin( rot.x ) + mPosition.z + mOffset.z;
  1466. mat->setColumn( 3, pos );
  1467. }
  1468. //-----------------------------------------------------------------------------
  1469. void Camera::_calcEditOrbitPoint( MatrixF *mat, const Point3F& rot )
  1470. {
  1471. //Point3F dir;
  1472. //mat->getColumn(1, &dir);
  1473. //Point3F startPos = getRenderPosition();
  1474. //Point3F endPos = startPos - dir * mCurrentEditOrbitDist;
  1475. Point3F pos;
  1476. pos.x = mCurrentEditOrbitDist * mSin(rot.x + mDegToRad(90.0f)) * mCos(-1.0f * (rot.z + mDegToRad(90.0f))) + mEditOrbitPoint.x;
  1477. pos.y = mCurrentEditOrbitDist * mSin(rot.x + mDegToRad(90.0f)) * mSin(-1.0f * (rot.z + mDegToRad(90.0f))) + mEditOrbitPoint.y;
  1478. pos.z = mCurrentEditOrbitDist * mSin(rot.x) + mEditOrbitPoint.z;
  1479. mat->setColumn(3, pos);
  1480. }
  1481. //-----------------------------------------------------------------------------
  1482. void Camera::setValidEditOrbitPoint( bool state )
  1483. {
  1484. mValidEditOrbitPoint = state;
  1485. setMaskBits(EditOrbitMask);
  1486. }
  1487. //-----------------------------------------------------------------------------
  1488. Point3F Camera::getEditOrbitPoint() const
  1489. {
  1490. return mEditOrbitPoint;
  1491. }
  1492. //-----------------------------------------------------------------------------
  1493. void Camera::setEditOrbitPoint( const Point3F& pnt )
  1494. {
  1495. // Change the point that we orbit in EditOrbitMode.
  1496. // We'll also change the facing and distance of the
  1497. // camera so that it doesn't jump around.
  1498. Point3F currentPos;
  1499. mObjToWorld.getColumn(3,&currentPos);
  1500. Point3F dir = pnt - currentPos;
  1501. mCurrentEditOrbitDist = dir.len();
  1502. if(mMode == EditOrbitMode)
  1503. {
  1504. dir.normalize();
  1505. F32 yaw, pitch;
  1506. MathUtils::getAnglesFromVector(dir, yaw, pitch);
  1507. mRot.x = -pitch;
  1508. mRot.z = yaw;
  1509. }
  1510. mEditOrbitPoint = pnt;
  1511. setMaskBits(EditOrbitMask);
  1512. }
  1513. //----------------------------------------------------------------------------
  1514. void Camera::lookAt( const Point3F& pos )
  1515. {
  1516. Point3F vec;
  1517. mObjToWorld.getColumn(3, &mPosition);
  1518. vec = pos - mPosition;
  1519. vec.normalizeSafe();
  1520. F32 pitch, yaw;
  1521. MathUtils::getAnglesFromVector(vec, yaw, pitch);
  1522. mRot.x = -pitch;
  1523. mRot.z = yaw;
  1524. _setPosition(mPosition, mRot);
  1525. }
  1526. //----------------------------------------------------------------------------
  1527. void Camera::autoFitRadius( F32 radius )
  1528. {
  1529. F32 fov = mDegToRad( getCameraFov() );
  1530. F32 viewradius = (radius * 2.0f) / mTan(fov * 0.5f);
  1531. // Be careful of infinite sized objects. Clip to 16km
  1532. if(viewradius > 16000.0f)
  1533. viewradius = 16000.0f;
  1534. if(mMode == EditOrbitMode && mValidEditOrbitPoint)
  1535. {
  1536. mCurrentEditOrbitDist = viewradius;
  1537. }
  1538. else if(mValidEditOrbitPoint)
  1539. {
  1540. mCurrentEditOrbitDist = viewradius;
  1541. Point3F currentPos;
  1542. mObjToWorld.getColumn(3,&currentPos);
  1543. Point3F dir = mEditOrbitPoint - currentPos;
  1544. dir.normalize();
  1545. F32 yaw, pitch;
  1546. MathUtils::getAnglesFromVector(dir, yaw, pitch);
  1547. mRot.x = -pitch;
  1548. mRot.z = yaw;
  1549. mPosition = mEditOrbitPoint;
  1550. _setPosition(mPosition, mRot);
  1551. _calcEditOrbitPoint(&mObjToWorld, mRot);
  1552. }
  1553. }
  1554. //=============================================================================
  1555. // Console API.
  1556. //=============================================================================
  1557. // MARK: ---- Console API ----
  1558. //-----------------------------------------------------------------------------
  1559. DefineEngineMethod( Camera, getMode, Camera::CameraMotionMode, (), ,
  1560. "Returns the current camera control mode.\n\n"
  1561. "@see CameraMotionMode")
  1562. {
  1563. return object->getMode();
  1564. }
  1565. //-----------------------------------------------------------------------------
  1566. DefineEngineMethod( Camera, getPosition, Point3F, (), ,
  1567. "Get the camera's position in the world.\n\n"
  1568. "@returns The position in the form of \"x y z\".")
  1569. {
  1570. return object->getPosition();
  1571. }
  1572. //-----------------------------------------------------------------------------
  1573. DefineEngineMethod( Camera, getRotation, Point3F, (), ,
  1574. "Get the camera's Euler rotation in radians.\n\n"
  1575. "@returns The rotation in radians in the form of \"x y z\".")
  1576. {
  1577. return object->getRotation();
  1578. }
  1579. //-----------------------------------------------------------------------------
  1580. DefineEngineMethod( Camera, setRotation, void, ( Point3F rot ), ,
  1581. "Set the camera's Euler rotation in radians.\n\n"
  1582. "@param rot The rotation in radians in the form of \"x y z\"."
  1583. "@note Rotation around the Y axis is ignored" )
  1584. {
  1585. return object->setRotation( rot );
  1586. }
  1587. //-----------------------------------------------------------------------------
  1588. DefineEngineMethod( Camera, getOffset, Point3F, (), ,
  1589. "Get the camera's offset from its orbit or tracking point.\n\n"
  1590. "The offset is added to the camera's position when set to CameraMode::OrbitObject.\n"
  1591. "@returns The offset in the form of \"x y z\".")
  1592. {
  1593. return object->getOffset();
  1594. }
  1595. //-----------------------------------------------------------------------------
  1596. DefineEngineMethod( Camera, setOffset, void, (Point3F offset), ,
  1597. "Set the camera's offset.\n\n"
  1598. "The offset is added to the camera's position when set to CameraMode::OrbitObject.\n"
  1599. "@param offset The distance to offset the camera by in the form of \"x y z\".")
  1600. {
  1601. object->setOffset(offset);
  1602. }
  1603. //-----------------------------------------------------------------------------
  1604. DefineEngineMethod( Camera, setOrbitMode, void, (GameBase* orbitObject, TransformF orbitPoint, F32 minDistance, F32 maxDistance,
  1605. F32 initDistance, bool ownClientObj, Point3F offset, bool locked), (false, Point3F::Zero, false),
  1606. "Set the camera to orbit around the given object, or if none is given, around the given point.\n\n"
  1607. "@param orbitObject The object to orbit around. If no object is given (0 or blank string is passed in) use the orbitPoint instead\n"
  1608. "@param orbitPoint The point to orbit around when no object is given. In the form of \"x y z ax ay az aa\" such as returned by SceneObject::getTransform().\n"
  1609. "@param minDistance The minimum distance allowed to the orbit object or point.\n"
  1610. "@param maxDistance The maximum distance allowed from the orbit object or point.\n"
  1611. "@param initDistance The initial distance from the orbit object or point.\n"
  1612. "@param ownClientObj [optional] Are we orbiting an object that is owned by us? Default is false.\n"
  1613. "@param offset [optional] An offset added to the camera's position. Default is no offset.\n"
  1614. "@param locked [optional] Indicates the camera does not receive input from the player. Default is false.\n"
  1615. "@see Camera::setOrbitObject()\n"
  1616. "@see Camera::setOrbitPoint()\n")
  1617. {
  1618. MatrixF mat;
  1619. orbitPoint.mOrientation.setMatrix(&mat);
  1620. object->setOrbitMode(orbitObject, orbitPoint.mPosition, mat.toEuler(), offset,
  1621. minDistance, maxDistance, initDistance, ownClientObj, locked);
  1622. }
  1623. //-----------------------------------------------------------------------------
  1624. DefineEngineMethod( Camera, setOrbitObject, bool, (GameBase* orbitObject, VectorF rotation, F32 minDistance,
  1625. F32 maxDistance, F32 initDistance, bool ownClientObject, Point3F offset, bool locked),
  1626. (false, Point3F::Zero, false),
  1627. "Set the camera to orbit around a given object.\n\n"
  1628. "@param orbitObject The object to orbit around.\n"
  1629. "@param rotation The initial camera rotation about the object in radians in the form of \"x y z\".\n"
  1630. "@param minDistance The minimum distance allowed to the orbit object or point.\n"
  1631. "@param maxDistance The maximum distance allowed from the orbit object or point.\n"
  1632. "@param initDistance The initial distance from the orbit object or point.\n"
  1633. "@param ownClientObject [optional] Are we orbiting an object that is owned by us? Default is false.\n"
  1634. "@param offset [optional] An offset added to the camera's position. Default is no offset.\n"
  1635. "@param locked [optional] Indicates the camera does not receive input from the player. Default is false.\n"
  1636. "@returns false if the given object could not be found.\n"
  1637. "@see Camera::setOrbitMode()\n")
  1638. {
  1639. if( !orbitObject )
  1640. {
  1641. Con::errorf( "Camera::setOrbitObject - Invalid object");
  1642. return false;
  1643. }
  1644. object->setOrbitMode(orbitObject, Point3F(0.0f, 0.0f, 0.0f), rotation, offset,
  1645. minDistance, maxDistance, initDistance, ownClientObject, locked);
  1646. return true;
  1647. }
  1648. //-----------------------------------------------------------------------------
  1649. DefineEngineMethod( Camera, setOrbitPoint, void, (TransformF orbitPoint, F32 minDistance, F32 maxDistance, F32 initDistance,
  1650. Point3F offset, bool locked),
  1651. (Point3F::Zero, false),
  1652. "Set the camera to orbit around a given point.\n\n"
  1653. "@param orbitPoint The point to orbit around. In the form of \"x y z ax ay az aa\" such as returned by SceneObject::getTransform().\n"
  1654. "@param minDistance The minimum distance allowed to the orbit object or point.\n"
  1655. "@param maxDistance The maximum distance allowed from the orbit object or point.\n"
  1656. "@param initDistance The initial distance from the orbit object or point.\n"
  1657. "@param offset [optional] An offset added to the camera's position. Default is no offset.\n"
  1658. "@param locked [optional] Indicates the camera does not receive input from the player. Default is false.\n"
  1659. "@see Camera::setOrbitMode()\n")
  1660. {
  1661. MatrixF mat;
  1662. orbitPoint.mOrientation.setMatrix(&mat);
  1663. object->setOrbitMode(NULL, orbitPoint.mPosition, mat.toEuler(), offset,
  1664. minDistance, maxDistance, initDistance, false, locked);
  1665. }
  1666. //-----------------------------------------------------------------------------
  1667. DefineEngineMethod( Camera, setTrackObject, bool, (GameBase* trackObject, Point3F offset), (Point3F::Zero),
  1668. "Set the camera to track a given object.\n\n"
  1669. "@param trackObject The object to track.\n"
  1670. "@param offset [optional] An offset added to the camera's position. Default is no offset.\n"
  1671. "@returns false if the given object could not be found.\n")
  1672. {
  1673. if(!trackObject)
  1674. {
  1675. Con::warnf("Cannot track non-existing object.");
  1676. return false;
  1677. }
  1678. object->setTrackObject(trackObject, offset);
  1679. return true;
  1680. }
  1681. //-----------------------------------------------------------------------------
  1682. DefineEngineMethod( Camera, setEditOrbitMode, void, (), ,
  1683. "Set the editor camera to orbit around a point set with Camera::setEditOrbitPoint().\n\n"
  1684. "@note This method is generally used only within the World Editor and other tools. To "
  1685. "orbit about an object or point within a game, see Camera::setOrbitMode() and its helper methods.\n")
  1686. {
  1687. object->setEditOrbitMode();
  1688. }
  1689. //-----------------------------------------------------------------------------
  1690. DefineEngineMethod( Camera, setFlyMode, void, (), ,
  1691. "Set the camera to fly freely.\n\n"
  1692. "Allows the camera to have 6 degrees of freedom. Provides for instantaneous motion "
  1693. "and rotation unless one of the Newton fields has been set to true. See Camera::newtonMode "
  1694. "and Camera::newtonRotation.\n")
  1695. {
  1696. object->setFlyMode();
  1697. }
  1698. //-----------------------------------------------------------------------------
  1699. DefineEngineMethod( Camera, setNewtonFlyMode, void, (), ,
  1700. "Set the camera to fly freely, but with ease-in and ease-out.\n\n"
  1701. "This method allows for the same 6 degrees of freedom as Camera::setFlyMode() but "
  1702. "activates the ease-in and ease-out on the camera's movement. To also activate "
  1703. "Newton mode for the camera's rotation, set Camera::newtonRotation to true.")
  1704. {
  1705. object->setNewtonFlyMode();
  1706. }
  1707. //-----------------------------------------------------------------------------
  1708. DefineEngineMethod( Camera, isRotationDamped, bool, (), ,
  1709. "Is this a Newton Fly mode camera with damped rotation?\n\n"
  1710. "@returns true if the camera uses a damped rotation. i.e. Camera::newtonRotation is set to true.\n")
  1711. {
  1712. return object->isRotationDamped();
  1713. }
  1714. //-----------------------------------------------------------------------------
  1715. DefineEngineMethod( Camera, getAngularVelocity, VectorF, (), ,
  1716. "Get the angular velocity for a Newton mode camera.\n\n"
  1717. "@returns The angular velocity in the form of \"x y z\".\n"
  1718. "@note Only returns useful results when Camera::newtonRotation is set to true.")
  1719. {
  1720. return object->getAngularVelocity();
  1721. }
  1722. //-----------------------------------------------------------------------------
  1723. DefineEngineMethod( Camera, setAngularVelocity, void, (VectorF velocity), ,
  1724. "Set the angular velocity for a Newton mode camera.\n\n"
  1725. "@param velocity The angular velocity infor form of \"x y z\".\n"
  1726. "@note Only takes affect when Camera::newtonRotation is set to true.")
  1727. {
  1728. object->setAngularVelocity(velocity);
  1729. }
  1730. //-----------------------------------------------------------------------------
  1731. DefineEngineMethod( Camera, setAngularForce, void, (F32 force), ,
  1732. "Set the angular force for a Newton mode camera.\n\n"
  1733. "@param force The angular force applied when attempting to rotate the camera."
  1734. "@note Only takes affect when Camera::newtonRotation is set to true.")
  1735. {
  1736. object->setAngularForce(force);
  1737. }
  1738. //-----------------------------------------------------------------------------
  1739. DefineEngineMethod( Camera, setAngularDrag, void, (F32 drag), ,
  1740. "Set the angular drag for a Newton mode camera.\n\n"
  1741. "@param drag The angular drag applied while the camera is rotating."
  1742. "@note Only takes affect when Camera::newtonRotation is set to true.")
  1743. {
  1744. object->setAngularDrag(drag);
  1745. }
  1746. //-----------------------------------------------------------------------------
  1747. DefineEngineMethod( Camera, setMass, void, (F32 mass), ,
  1748. "Set the mass for a Newton mode camera.\n\n"
  1749. "@param mass The mass used during ease-in and ease-out calculations."
  1750. "@note Only used when Camera is in Newton mode.")
  1751. {
  1752. object->setMass(mass);
  1753. }
  1754. //-----------------------------------------------------------------------------
  1755. DefineEngineMethod( Camera, getVelocity, VectorF, (), ,
  1756. "Get the velocity for the camera.\n\n"
  1757. "@returns The camera's velocity in the form of \"x y z\"."
  1758. "@note Only useful when the Camera is in Newton mode.")
  1759. {
  1760. return object->getVelocity();
  1761. }
  1762. //-----------------------------------------------------------------------------
  1763. DefineEngineMethod( Camera, setVelocity, void, (VectorF velocity), ,
  1764. "Set the velocity for the camera.\n\n"
  1765. "@param velocity The camera's velocity in the form of \"x y z\"."
  1766. "@note Only affects the Camera when in Newton mode.")
  1767. {
  1768. object->setVelocity(velocity);
  1769. }
  1770. //-----------------------------------------------------------------------------
  1771. DefineEngineMethod( Camera, setDrag, void, (F32 drag), ,
  1772. "Set the drag for a Newton mode camera.\n\n"
  1773. "@param drag The drag applied to the camera while moving."
  1774. "@note Only used when Camera is in Newton mode.")
  1775. {
  1776. object->setDrag(drag);
  1777. }
  1778. //-----------------------------------------------------------------------------
  1779. DefineEngineMethod( Camera, setFlyForce, void, (F32 force), ,
  1780. "Set the force applied to a Newton mode camera while moving.\n\n"
  1781. "@param force The force applied to the camera while attempting to move."
  1782. "@note Only used when Camera is in Newton mode.")
  1783. {
  1784. object->setFlyForce(force);
  1785. }
  1786. //-----------------------------------------------------------------------------
  1787. DefineEngineMethod( Camera, setSpeedMultiplier, void, (F32 multiplier), ,
  1788. "Set the Newton mode camera speed multiplier when trigger[0] is active.\n\n"
  1789. "@param multiplier The speed multiplier to apply."
  1790. "@note Only used when Camera is in Newton mode.")
  1791. {
  1792. object->setSpeedMultiplier(multiplier);
  1793. }
  1794. //-----------------------------------------------------------------------------
  1795. DefineEngineMethod( Camera, setBrakeMultiplier, void, (F32 multiplier), ,
  1796. "Set the Newton mode camera brake multiplier when trigger[1] is active.\n\n"
  1797. "@param multiplier The brake multiplier to apply."
  1798. "@note Only used when Camera is in Newton mode.")
  1799. {
  1800. object->setBrakeMultiplier(multiplier);
  1801. }
  1802. //----------------------------------------------------------------------------
  1803. DefineEngineMethod( Camera, isEditOrbitMode, bool, (), ,
  1804. "Is the camera in edit orbit mode?\n\n"
  1805. "@returns true if the camera is in edit orbit mode.")
  1806. {
  1807. return object->isEditOrbitMode();
  1808. }
  1809. //----------------------------------------------------------------------------
  1810. DefineEngineMethod( Camera, setValidEditOrbitPoint, void, (bool validPoint), ,
  1811. "Set if there is a valid editor camera orbit point.\n"
  1812. "When validPoint is set to false the Camera operates as if it is "
  1813. "in Fly mode rather than an Orbit mode.\n\n"
  1814. "@param validPoint Indicates the validity of the orbit point."
  1815. "@note Only used when Camera is in Edit Orbit Mode.")
  1816. {
  1817. object->setValidEditOrbitPoint(validPoint);
  1818. }
  1819. //----------------------------------------------------------------------------
  1820. DefineEngineMethod( Camera, setEditOrbitPoint, void, (Point3F point), ,
  1821. "Set the editor camera's orbit point.\n\n"
  1822. "@param point The point the camera will orbit in the form of \"x y z\".")
  1823. {
  1824. object->setEditOrbitPoint(point);
  1825. }
  1826. //----------------------------------------------------------------------------
  1827. DefineEngineMethod( Camera, autoFitRadius, void, (F32 radius), ,
  1828. "Move the camera to fully view the given radius.\n\n"
  1829. "@note For this operation to take affect a valid edit orbit point must first be specified. See Camera::setEditOrbitPoint().\n"
  1830. "@param radius The radius to view.")
  1831. {
  1832. object->autoFitRadius(radius);
  1833. }
  1834. //----------------------------------------------------------------------------
  1835. DefineEngineMethod( Camera, lookAt, void, (Point3F point), ,
  1836. "Point the camera at the specified position. Does not work in Orbit or Track modes.\n\n"
  1837. "@param point The position to point the camera at.")
  1838. {
  1839. object->lookAt(point);
  1840. }