Camera.js 133 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297
  1. import BoundingSphere from '../Core/BoundingSphere.js';
  2. import Cartesian2 from '../Core/Cartesian2.js';
  3. import Cartesian3 from '../Core/Cartesian3.js';
  4. import Cartesian4 from '../Core/Cartesian4.js';
  5. import Cartographic from '../Core/Cartographic.js';
  6. import defaultValue from '../Core/defaultValue.js';
  7. import defined from '../Core/defined.js';
  8. import defineProperties from '../Core/defineProperties.js';
  9. import DeveloperError from '../Core/DeveloperError.js';
  10. import EasingFunction from '../Core/EasingFunction.js';
  11. import Ellipsoid from '../Core/Ellipsoid.js';
  12. import EllipsoidGeodesic from '../Core/EllipsoidGeodesic.js';
  13. import Event from '../Core/Event.js';
  14. import getTimestamp from '../Core/getTimestamp.js';
  15. import HeadingPitchRange from '../Core/HeadingPitchRange.js';
  16. import HeadingPitchRoll from '../Core/HeadingPitchRoll.js';
  17. import Intersect from '../Core/Intersect.js';
  18. import IntersectionTests from '../Core/IntersectionTests.js';
  19. import CesiumMath from '../Core/Math.js';
  20. import Matrix3 from '../Core/Matrix3.js';
  21. import Matrix4 from '../Core/Matrix4.js';
  22. import OrthographicFrustum from '../Core/OrthographicFrustum.js';
  23. import OrthographicOffCenterFrustum from '../Core/OrthographicOffCenterFrustum.js';
  24. import PerspectiveFrustum from '../Core/PerspectiveFrustum.js';
  25. import Quaternion from '../Core/Quaternion.js';
  26. import Ray from '../Core/Ray.js';
  27. import Rectangle from '../Core/Rectangle.js';
  28. import Transforms from '../Core/Transforms.js';
  29. import CameraFlightPath from './CameraFlightPath.js';
  30. import MapMode2D from './MapMode2D.js';
  31. import SceneMode from './SceneMode.js';
  32. /**
  33. * The camera is defined by a position, orientation, and view frustum.
  34. * <br /><br />
  35. * The orientation forms an orthonormal basis with a view, up and right = view x up unit vectors.
  36. * <br /><br />
  37. * The viewing frustum is defined by 6 planes.
  38. * Each plane is represented by a {@link Cartesian4} object, where the x, y, and z components
  39. * define the unit vector normal to the plane, and the w component is the distance of the
  40. * plane from the origin/camera position.
  41. *
  42. * @alias Camera
  43. *
  44. * @constructor
  45. *
  46. * @param {Scene} scene The scene.
  47. *
  48. * @demo {@link https://sandcastle.cesium.com/index.html?src=Camera.html|Cesium Sandcastle Camera Demo}
  49. * @demo {@link https://sandcastle.cesium.com/index.html?src=Camera%20Tutorial.html">Sandcastle Example</a> from the <a href="https://cesium.com/docs/tutorials/camera/|Camera Tutorial}
  50. *
  51. * @example
  52. * // Create a camera looking down the negative z-axis, positioned at the origin,
  53. * // with a field of view of 60 degrees, and 1:1 aspect ratio.
  54. * var camera = new Cesium.Camera(scene);
  55. * camera.position = new Cesium.Cartesian3();
  56. * camera.direction = Cesium.Cartesian3.negate(Cesium.Cartesian3.UNIT_Z, new Cesium.Cartesian3());
  57. * camera.up = Cesium.Cartesian3.clone(Cesium.Cartesian3.UNIT_Y);
  58. * camera.frustum.fov = Cesium.Math.PI_OVER_THREE;
  59. * camera.frustum.near = 1.0;
  60. * camera.frustum.far = 2.0;
  61. */
  62. function Camera(scene) {
  63. //>>includeStart('debug', pragmas.debug);
  64. if (!defined(scene)) {
  65. throw new DeveloperError('scene is required.');
  66. }
  67. //>>includeEnd('debug');
  68. this._scene = scene;
  69. this._transform = Matrix4.clone(Matrix4.IDENTITY);
  70. this._invTransform = Matrix4.clone(Matrix4.IDENTITY);
  71. this._actualTransform = Matrix4.clone(Matrix4.IDENTITY);
  72. this._actualInvTransform = Matrix4.clone(Matrix4.IDENTITY);
  73. this._transformChanged = false;
  74. /**
  75. * The position of the camera.
  76. *
  77. * @type {Cartesian3}
  78. */
  79. this.position = new Cartesian3();
  80. this._position = new Cartesian3();
  81. this._positionWC = new Cartesian3();
  82. this._positionCartographic = new Cartographic();
  83. this._oldPositionWC = undefined;
  84. /**
  85. * The position delta magnitude.
  86. *
  87. * @private
  88. */
  89. this.positionWCDeltaMagnitude = 0.0;
  90. /**
  91. * The position delta magnitude last frame.
  92. *
  93. * @private
  94. */
  95. this.positionWCDeltaMagnitudeLastFrame = 0.0;
  96. /**
  97. * How long in seconds since the camera has stopped moving
  98. *
  99. * @private
  100. */
  101. this.timeSinceMoved = 0.0;
  102. this._lastMovedTimestamp = 0.0;
  103. /**
  104. * The view direction of the camera.
  105. *
  106. * @type {Cartesian3}
  107. */
  108. this.direction = new Cartesian3();
  109. this._direction = new Cartesian3();
  110. this._directionWC = new Cartesian3();
  111. /**
  112. * The up direction of the camera.
  113. *
  114. * @type {Cartesian3}
  115. */
  116. this.up = new Cartesian3();
  117. this._up = new Cartesian3();
  118. this._upWC = new Cartesian3();
  119. /**
  120. * The right direction of the camera.
  121. *
  122. * @type {Cartesian3}
  123. */
  124. this.right = new Cartesian3();
  125. this._right = new Cartesian3();
  126. this._rightWC = new Cartesian3();
  127. /**
  128. * The region of space in view.
  129. *
  130. * @type {Frustum}
  131. * @default PerspectiveFrustum()
  132. *
  133. * @see PerspectiveFrustum
  134. * @see PerspectiveOffCenterFrustum
  135. * @see OrthographicFrustum
  136. */
  137. this.frustum = new PerspectiveFrustum();
  138. this.frustum.aspectRatio = scene.drawingBufferWidth / scene.drawingBufferHeight;
  139. this.frustum.fov = CesiumMath.toRadians(60.0);
  140. /**
  141. * The default amount to move the camera when an argument is not
  142. * provided to the move methods.
  143. * @type {Number}
  144. * @default 100000.0;
  145. */
  146. this.defaultMoveAmount = 100000.0;
  147. /**
  148. * The default amount to rotate the camera when an argument is not
  149. * provided to the look methods.
  150. * @type {Number}
  151. * @default Math.PI / 60.0
  152. */
  153. this.defaultLookAmount = Math.PI / 60.0;
  154. /**
  155. * The default amount to rotate the camera when an argument is not
  156. * provided to the rotate methods.
  157. * @type {Number}
  158. * @default Math.PI / 3600.0
  159. */
  160. this.defaultRotateAmount = Math.PI / 3600.0;
  161. /**
  162. * The default amount to move the camera when an argument is not
  163. * provided to the zoom methods.
  164. * @type {Number}
  165. * @default 100000.0;
  166. */
  167. this.defaultZoomAmount = 100000.0;
  168. /**
  169. * If set, the camera will not be able to rotate past this axis in either direction.
  170. * @type {Cartesian3}
  171. * @default undefined
  172. */
  173. this.constrainedAxis = undefined;
  174. /**
  175. * The factor multiplied by the the map size used to determine where to clamp the camera position
  176. * when zooming out from the surface. The default is 1.5. Only valid for 2D and the map is rotatable.
  177. * @type {Number}
  178. * @default 1.5
  179. */
  180. this.maximumZoomFactor = 1.5;
  181. this._moveStart = new Event();
  182. this._moveEnd = new Event();
  183. this._changed = new Event();
  184. this._changedPosition = undefined;
  185. this._changedDirection = undefined;
  186. this._changedFrustum = undefined;
  187. /**
  188. * The amount the camera has to change before the <code>changed</code> event is raised. The value is a percentage in the [0, 1] range.
  189. * @type {number}
  190. * @default 0.5
  191. */
  192. this.percentageChanged = 0.5;
  193. this._viewMatrix = new Matrix4();
  194. this._invViewMatrix = new Matrix4();
  195. updateViewMatrix(this);
  196. this._mode = SceneMode.SCENE3D;
  197. this._modeChanged = true;
  198. var projection = scene.mapProjection;
  199. this._projection = projection;
  200. this._maxCoord = projection.project(new Cartographic(Math.PI, CesiumMath.PI_OVER_TWO));
  201. this._max2Dfrustum = undefined;
  202. this._suspendTerrainAdjustment = false;
  203. // set default view
  204. rectangleCameraPosition3D(this, Camera.DEFAULT_VIEW_RECTANGLE, this.position, true);
  205. var mag = Cartesian3.magnitude(this.position);
  206. mag += mag * Camera.DEFAULT_VIEW_FACTOR;
  207. Cartesian3.normalize(this.position, this.position);
  208. Cartesian3.multiplyByScalar(this.position, mag, this.position);
  209. }
  210. /**
  211. * @private
  212. */
  213. Camera.TRANSFORM_2D = new Matrix4(
  214. 0.0, 0.0, 1.0, 0.0,
  215. 1.0, 0.0, 0.0, 0.0,
  216. 0.0, 1.0, 0.0, 0.0,
  217. 0.0, 0.0, 0.0, 1.0);
  218. /**
  219. * @private
  220. */
  221. Camera.TRANSFORM_2D_INVERSE = Matrix4.inverseTransformation(Camera.TRANSFORM_2D, new Matrix4());
  222. /**
  223. * The default rectangle the camera will view on creation.
  224. * @type Rectangle
  225. */
  226. Camera.DEFAULT_VIEW_RECTANGLE = Rectangle.fromDegrees(-95.0, -20.0, -70.0, 90.0);
  227. /**
  228. * A scalar to multiply to the camera position and add it back after setting the camera to view the rectangle.
  229. * A value of zero means the camera will view the entire {@link Camera#DEFAULT_VIEW_RECTANGLE}, a value greater than zero
  230. * will move it further away from the extent, and a value less than zero will move it close to the extent.
  231. * @type Number
  232. */
  233. Camera.DEFAULT_VIEW_FACTOR = 0.5;
  234. /**
  235. * The default heading/pitch/range that is used when the camera flies to a location that contains a bounding sphere.
  236. * @type HeadingPitchRange
  237. */
  238. Camera.DEFAULT_OFFSET = new HeadingPitchRange(0.0, -CesiumMath.PI_OVER_FOUR, 0.0);
  239. function updateViewMatrix(camera) {
  240. Matrix4.computeView(camera._position, camera._direction, camera._up, camera._right, camera._viewMatrix);
  241. Matrix4.multiply(camera._viewMatrix, camera._actualInvTransform, camera._viewMatrix);
  242. Matrix4.inverseTransformation(camera._viewMatrix, camera._invViewMatrix);
  243. }
  244. function updateCameraDeltas(camera) {
  245. if (!defined(camera._oldPositionWC)) {
  246. camera._oldPositionWC = Cartesian3.clone(camera.positionWC, camera._oldPositionWC);
  247. } else {
  248. camera.positionWCDeltaMagnitudeLastFrame = camera.positionWCDeltaMagnitude;
  249. var delta = Cartesian3.subtract(camera.positionWC, camera._oldPositionWC, camera._oldPositionWC);
  250. camera.positionWCDeltaMagnitude = Cartesian3.magnitude(delta);
  251. camera._oldPositionWC = Cartesian3.clone(camera.positionWC, camera._oldPositionWC);
  252. // Update move timers
  253. if (camera.positionWCDeltaMagnitude > 0.0) {
  254. camera.timeSinceMoved = 0.0;
  255. camera._lastMovedTimestamp = getTimestamp();
  256. } else {
  257. camera.timeSinceMoved = Math.max(getTimestamp() - camera._lastMovedTimestamp, 0.0) / 1000.0;
  258. }
  259. }
  260. }
  261. /**
  262. * Checks if there's a camera flight for this camera.
  263. *
  264. * @returns {Boolean} Whether or not this camera has a current flight with a valid preloadFlightCamera in scene.
  265. *
  266. * @private
  267. *
  268. */
  269. Camera.prototype.hasCurrentFlight = function() {
  270. // The preload flight camera defined check only here since it can be set to undefined when not 3D mode.
  271. return defined(this._currentFlight) && defined(this._scene.preloadFlightCamera);
  272. };
  273. Camera.prototype._updateCameraChanged = function() {
  274. var camera = this;
  275. updateCameraDeltas(camera);
  276. if (camera._changed.numberOfListeners === 0) {
  277. return;
  278. }
  279. var percentageChanged = camera.percentageChanged;
  280. if (camera._mode === SceneMode.SCENE2D) {
  281. if (!defined(camera._changedFrustum)) {
  282. camera._changedPosition = Cartesian3.clone(camera.position, camera._changedPosition);
  283. camera._changedFrustum = camera.frustum.clone();
  284. return;
  285. }
  286. var position = camera.position;
  287. var lastPosition = camera._changedPosition;
  288. var frustum = camera.frustum;
  289. var lastFrustum = camera._changedFrustum;
  290. var x0 = position.x + frustum.left;
  291. var x1 = position.x + frustum.right;
  292. var x2 = lastPosition.x + lastFrustum.left;
  293. var x3 = lastPosition.x + lastFrustum.right;
  294. var y0 = position.y + frustum.bottom;
  295. var y1 = position.y + frustum.top;
  296. var y2 = lastPosition.y + lastFrustum.bottom;
  297. var y3 = lastPosition.y + lastFrustum.top;
  298. var leftX = Math.max(x0, x2);
  299. var rightX = Math.min(x1, x3);
  300. var bottomY = Math.max(y0, y2);
  301. var topY = Math.min(y1, y3);
  302. var areaPercentage;
  303. if (leftX >= rightX || bottomY >= y1) {
  304. areaPercentage = 1.0;
  305. } else {
  306. var areaRef = lastFrustum;
  307. if (x0 < x2 && x1 > x3 && y0 < y2 && y1 > y3) {
  308. areaRef = frustum;
  309. }
  310. areaPercentage = 1.0 - ((rightX - leftX) * (topY - bottomY)) / ((areaRef.right - areaRef.left) * (areaRef.top - areaRef.bottom));
  311. }
  312. if (areaPercentage > percentageChanged) {
  313. camera._changed.raiseEvent(areaPercentage);
  314. camera._changedPosition = Cartesian3.clone(camera.position, camera._changedPosition);
  315. camera._changedFrustum = camera.frustum.clone(camera._changedFrustum);
  316. }
  317. return;
  318. }
  319. if (!defined(camera._changedDirection)) {
  320. camera._changedPosition = Cartesian3.clone(camera.positionWC, camera._changedPosition);
  321. camera._changedDirection = Cartesian3.clone(camera.directionWC, camera._changedDirection);
  322. return;
  323. }
  324. var dirAngle = CesiumMath.acosClamped(Cartesian3.dot(camera.directionWC, camera._changedDirection));
  325. var dirPercentage;
  326. if (defined(camera.frustum.fovy)) {
  327. dirPercentage = dirAngle / (camera.frustum.fovy * 0.5);
  328. } else {
  329. dirPercentage = dirAngle;
  330. }
  331. var distance = Cartesian3.distance(camera.positionWC, camera._changedPosition);
  332. var heightPercentage = distance / camera.positionCartographic.height;
  333. if (dirPercentage > percentageChanged || heightPercentage > percentageChanged) {
  334. camera._changed.raiseEvent(Math.max(dirPercentage, heightPercentage));
  335. camera._changedPosition = Cartesian3.clone(camera.positionWC, camera._changedPosition);
  336. camera._changedDirection = Cartesian3.clone(camera.directionWC, camera._changedDirection);
  337. }
  338. };
  339. var scratchAdjustHeightTransform = new Matrix4();
  340. var scratchAdjustHeightCartographic = new Cartographic();
  341. Camera.prototype._adjustHeightForTerrain = function() {
  342. var scene = this._scene;
  343. var screenSpaceCameraController = scene.screenSpaceCameraController;
  344. var enableCollisionDetection = screenSpaceCameraController.enableCollisionDetection;
  345. var minimumCollisionTerrainHeight = screenSpaceCameraController.minimumCollisionTerrainHeight;
  346. var minimumZoomDistance = screenSpaceCameraController.minimumZoomDistance;
  347. if (this._suspendTerrainAdjustment || !enableCollisionDetection) {
  348. return;
  349. }
  350. var mode = this._mode;
  351. var globe = scene.globe;
  352. if (!defined(globe) || mode === SceneMode.SCENE2D || mode === SceneMode.MORPHING) {
  353. return;
  354. }
  355. var ellipsoid = globe.ellipsoid;
  356. var projection = scene.mapProjection;
  357. var transform;
  358. var mag;
  359. if (!Matrix4.equals(this.transform, Matrix4.IDENTITY)) {
  360. transform = Matrix4.clone(this.transform, scratchAdjustHeightTransform);
  361. mag = Cartesian3.magnitude(this.position);
  362. this._setTransform(Matrix4.IDENTITY);
  363. }
  364. var cartographic = scratchAdjustHeightCartographic;
  365. if (mode === SceneMode.SCENE3D) {
  366. ellipsoid.cartesianToCartographic(this.position, cartographic);
  367. } else {
  368. projection.unproject(this.position, cartographic);
  369. }
  370. var heightUpdated = false;
  371. if (cartographic.height < minimumCollisionTerrainHeight) {
  372. var height = globe.getHeight(cartographic);
  373. if (defined(height)) {
  374. height += minimumZoomDistance;
  375. if (cartographic.height < height) {
  376. cartographic.height = height;
  377. if (mode === SceneMode.SCENE3D) {
  378. ellipsoid.cartographicToCartesian(cartographic, this.position);
  379. } else {
  380. projection.project(cartographic, this.position);
  381. }
  382. heightUpdated = true;
  383. }
  384. }
  385. }
  386. if (defined(transform)) {
  387. this._setTransform(transform);
  388. if (heightUpdated) {
  389. Cartesian3.normalize(this.position, this.position);
  390. Cartesian3.negate(this.position, this.direction);
  391. Cartesian3.multiplyByScalar(this.position, Math.max(mag, minimumZoomDistance), this.position);
  392. Cartesian3.normalize(this.direction, this.direction);
  393. Cartesian3.cross(this.direction, this.up, this.right);
  394. Cartesian3.cross(this.right, this.direction, this.up);
  395. }
  396. }
  397. };
  398. function convertTransformForColumbusView(camera) {
  399. Transforms.basisTo2D(camera._projection, camera._transform, camera._actualTransform);
  400. }
  401. var scratchCartographic = new Cartographic();
  402. var scratchCartesian3Projection = new Cartesian3();
  403. var scratchCartesian3 = new Cartesian3();
  404. var scratchCartesian4Origin = new Cartesian4();
  405. var scratchCartesian4NewOrigin = new Cartesian4();
  406. var scratchCartesian4NewXAxis = new Cartesian4();
  407. var scratchCartesian4NewYAxis = new Cartesian4();
  408. var scratchCartesian4NewZAxis = new Cartesian4();
  409. function convertTransformFor2D(camera) {
  410. var projection = camera._projection;
  411. var ellipsoid = projection.ellipsoid;
  412. var origin = Matrix4.getColumn(camera._transform, 3, scratchCartesian4Origin);
  413. var cartographic = ellipsoid.cartesianToCartographic(origin, scratchCartographic);
  414. var projectedPosition = projection.project(cartographic, scratchCartesian3Projection);
  415. var newOrigin = scratchCartesian4NewOrigin;
  416. newOrigin.x = projectedPosition.z;
  417. newOrigin.y = projectedPosition.x;
  418. newOrigin.z = projectedPosition.y;
  419. newOrigin.w = 1.0;
  420. var newZAxis = Cartesian4.clone(Cartesian4.UNIT_X, scratchCartesian4NewZAxis);
  421. var xAxis = Cartesian4.add(Matrix4.getColumn(camera._transform, 0, scratchCartesian3), origin, scratchCartesian3);
  422. ellipsoid.cartesianToCartographic(xAxis, cartographic);
  423. projection.project(cartographic, projectedPosition);
  424. var newXAxis = scratchCartesian4NewXAxis;
  425. newXAxis.x = projectedPosition.z;
  426. newXAxis.y = projectedPosition.x;
  427. newXAxis.z = projectedPosition.y;
  428. newXAxis.w = 0.0;
  429. Cartesian3.subtract(newXAxis, newOrigin, newXAxis);
  430. newXAxis.x = 0.0;
  431. var newYAxis = scratchCartesian4NewYAxis;
  432. if (Cartesian3.magnitudeSquared(newXAxis) > CesiumMath.EPSILON10) {
  433. Cartesian3.cross(newZAxis, newXAxis, newYAxis);
  434. } else {
  435. var yAxis = Cartesian4.add(Matrix4.getColumn(camera._transform, 1, scratchCartesian3), origin, scratchCartesian3);
  436. ellipsoid.cartesianToCartographic(yAxis, cartographic);
  437. projection.project(cartographic, projectedPosition);
  438. newYAxis.x = projectedPosition.z;
  439. newYAxis.y = projectedPosition.x;
  440. newYAxis.z = projectedPosition.y;
  441. newYAxis.w = 0.0;
  442. Cartesian3.subtract(newYAxis, newOrigin, newYAxis);
  443. newYAxis.x = 0.0;
  444. if (Cartesian3.magnitudeSquared(newYAxis) < CesiumMath.EPSILON10) {
  445. Cartesian4.clone(Cartesian4.UNIT_Y, newXAxis);
  446. Cartesian4.clone(Cartesian4.UNIT_Z, newYAxis);
  447. }
  448. }
  449. Cartesian3.cross(newYAxis, newZAxis, newXAxis);
  450. Cartesian3.normalize(newXAxis, newXAxis);
  451. Cartesian3.cross(newZAxis, newXAxis, newYAxis);
  452. Cartesian3.normalize(newYAxis, newYAxis);
  453. Matrix4.setColumn(camera._actualTransform, 0, newXAxis, camera._actualTransform);
  454. Matrix4.setColumn(camera._actualTransform, 1, newYAxis, camera._actualTransform);
  455. Matrix4.setColumn(camera._actualTransform, 2, newZAxis, camera._actualTransform);
  456. Matrix4.setColumn(camera._actualTransform, 3, newOrigin, camera._actualTransform);
  457. }
  458. var scratchCartesian = new Cartesian3();
  459. function updateMembers(camera) {
  460. var mode = camera._mode;
  461. var heightChanged = false;
  462. var height = 0.0;
  463. if (mode === SceneMode.SCENE2D) {
  464. height = camera.frustum.right - camera.frustum.left;
  465. heightChanged = height !== camera._positionCartographic.height;
  466. }
  467. var position = camera._position;
  468. var positionChanged = !Cartesian3.equals(position, camera.position) || heightChanged;
  469. if (positionChanged) {
  470. position = Cartesian3.clone(camera.position, camera._position);
  471. }
  472. var direction = camera._direction;
  473. var directionChanged = !Cartesian3.equals(direction, camera.direction);
  474. if (directionChanged) {
  475. Cartesian3.normalize(camera.direction, camera.direction);
  476. direction = Cartesian3.clone(camera.direction, camera._direction);
  477. }
  478. var up = camera._up;
  479. var upChanged = !Cartesian3.equals(up, camera.up);
  480. if (upChanged) {
  481. Cartesian3.normalize(camera.up, camera.up);
  482. up = Cartesian3.clone(camera.up, camera._up);
  483. }
  484. var right = camera._right;
  485. var rightChanged = !Cartesian3.equals(right, camera.right);
  486. if (rightChanged) {
  487. Cartesian3.normalize(camera.right, camera.right);
  488. right = Cartesian3.clone(camera.right, camera._right);
  489. }
  490. var transformChanged = camera._transformChanged || camera._modeChanged;
  491. camera._transformChanged = false;
  492. if (transformChanged) {
  493. Matrix4.inverseTransformation(camera._transform, camera._invTransform);
  494. if (camera._mode === SceneMode.COLUMBUS_VIEW || camera._mode === SceneMode.SCENE2D) {
  495. if (Matrix4.equals(Matrix4.IDENTITY, camera._transform)) {
  496. Matrix4.clone(Camera.TRANSFORM_2D, camera._actualTransform);
  497. } else if (camera._mode === SceneMode.COLUMBUS_VIEW) {
  498. convertTransformForColumbusView(camera);
  499. } else {
  500. convertTransformFor2D(camera);
  501. }
  502. } else {
  503. Matrix4.clone(camera._transform, camera._actualTransform);
  504. }
  505. Matrix4.inverseTransformation(camera._actualTransform, camera._actualInvTransform);
  506. camera._modeChanged = false;
  507. }
  508. var transform = camera._actualTransform;
  509. if (positionChanged || transformChanged) {
  510. camera._positionWC = Matrix4.multiplyByPoint(transform, position, camera._positionWC);
  511. // Compute the Cartographic position of the camera.
  512. if (mode === SceneMode.SCENE3D || mode === SceneMode.MORPHING) {
  513. camera._positionCartographic = camera._projection.ellipsoid.cartesianToCartographic(camera._positionWC, camera._positionCartographic);
  514. } else {
  515. // The camera position is expressed in the 2D coordinate system where the Y axis is to the East,
  516. // the Z axis is to the North, and the X axis is out of the map. Express them instead in the ENU axes where
  517. // X is to the East, Y is to the North, and Z is out of the local horizontal plane.
  518. var positionENU = scratchCartesian;
  519. positionENU.x = camera._positionWC.y;
  520. positionENU.y = camera._positionWC.z;
  521. positionENU.z = camera._positionWC.x;
  522. // In 2D, the camera height is always 12.7 million meters.
  523. // The apparent height is equal to half the frustum width.
  524. if (mode === SceneMode.SCENE2D) {
  525. positionENU.z = height;
  526. }
  527. camera._projection.unproject(positionENU, camera._positionCartographic);
  528. }
  529. }
  530. if (directionChanged || upChanged || rightChanged) {
  531. var det = Cartesian3.dot(direction, Cartesian3.cross(up, right, scratchCartesian));
  532. if (Math.abs(1.0 - det) > CesiumMath.EPSILON2) {
  533. //orthonormalize axes
  534. var invUpMag = 1.0 / Cartesian3.magnitudeSquared(up);
  535. var scalar = Cartesian3.dot(up, direction) * invUpMag;
  536. var w0 = Cartesian3.multiplyByScalar(direction, scalar, scratchCartesian);
  537. up = Cartesian3.normalize(Cartesian3.subtract(up, w0, camera._up), camera._up);
  538. Cartesian3.clone(up, camera.up);
  539. right = Cartesian3.cross(direction, up, camera._right);
  540. Cartesian3.clone(right, camera.right);
  541. }
  542. }
  543. if (directionChanged || transformChanged) {
  544. camera._directionWC = Matrix4.multiplyByPointAsVector(transform, direction, camera._directionWC);
  545. Cartesian3.normalize(camera._directionWC, camera._directionWC);
  546. }
  547. if (upChanged || transformChanged) {
  548. camera._upWC = Matrix4.multiplyByPointAsVector(transform, up, camera._upWC);
  549. Cartesian3.normalize(camera._upWC, camera._upWC);
  550. }
  551. if (rightChanged || transformChanged) {
  552. camera._rightWC = Matrix4.multiplyByPointAsVector(transform, right, camera._rightWC);
  553. Cartesian3.normalize(camera._rightWC, camera._rightWC);
  554. }
  555. if (positionChanged || directionChanged || upChanged || rightChanged || transformChanged) {
  556. updateViewMatrix(camera);
  557. }
  558. }
  559. function getHeading(direction, up) {
  560. var heading;
  561. if (!CesiumMath.equalsEpsilon(Math.abs(direction.z), 1.0, CesiumMath.EPSILON3)) {
  562. heading = Math.atan2(direction.y, direction.x) - CesiumMath.PI_OVER_TWO;
  563. } else {
  564. heading = Math.atan2(up.y, up.x) - CesiumMath.PI_OVER_TWO;
  565. }
  566. return CesiumMath.TWO_PI - CesiumMath.zeroToTwoPi(heading);
  567. }
  568. function getPitch(direction) {
  569. return CesiumMath.PI_OVER_TWO - CesiumMath.acosClamped(direction.z);
  570. }
  571. function getRoll(direction, up, right) {
  572. var roll = 0.0;
  573. if (!CesiumMath.equalsEpsilon(Math.abs(direction.z), 1.0, CesiumMath.EPSILON3)) {
  574. roll = Math.atan2(-right.z, up.z);
  575. roll = CesiumMath.zeroToTwoPi(roll + CesiumMath.TWO_PI);
  576. }
  577. return roll;
  578. }
  579. var scratchHPRMatrix1 = new Matrix4();
  580. var scratchHPRMatrix2 = new Matrix4();
  581. defineProperties(Camera.prototype, {
  582. /**
  583. * Gets the camera's reference frame. The inverse of this transformation is appended to the view matrix.
  584. * @memberof Camera.prototype
  585. *
  586. * @type {Matrix4}
  587. * @readonly
  588. *
  589. * @default {@link Matrix4.IDENTITY}
  590. */
  591. transform : {
  592. get : function() {
  593. return this._transform;
  594. }
  595. },
  596. /**
  597. * Gets the inverse camera transform.
  598. * @memberof Camera.prototype
  599. *
  600. * @type {Matrix4}
  601. * @readonly
  602. *
  603. * @default {@link Matrix4.IDENTITY}
  604. */
  605. inverseTransform : {
  606. get : function() {
  607. updateMembers(this);
  608. return this._invTransform;
  609. }
  610. },
  611. /**
  612. * Gets the view matrix.
  613. * @memberof Camera.prototype
  614. *
  615. * @type {Matrix4}
  616. * @readonly
  617. *
  618. * @see Camera#inverseViewMatrix
  619. */
  620. viewMatrix : {
  621. get : function() {
  622. updateMembers(this);
  623. return this._viewMatrix;
  624. }
  625. },
  626. /**
  627. * Gets the inverse view matrix.
  628. * @memberof Camera.prototype
  629. *
  630. * @type {Matrix4}
  631. * @readonly
  632. *
  633. * @see Camera#viewMatrix
  634. */
  635. inverseViewMatrix : {
  636. get : function() {
  637. updateMembers(this);
  638. return this._invViewMatrix;
  639. }
  640. },
  641. /**
  642. * Gets the {@link Cartographic} position of the camera, with longitude and latitude
  643. * expressed in radians and height in meters. In 2D and Columbus View, it is possible
  644. * for the returned longitude and latitude to be outside the range of valid longitudes
  645. * and latitudes when the camera is outside the map.
  646. * @memberof Camera.prototype
  647. *
  648. * @type {Cartographic}
  649. * @readonly
  650. */
  651. positionCartographic : {
  652. get : function() {
  653. updateMembers(this);
  654. return this._positionCartographic;
  655. }
  656. },
  657. /**
  658. * Gets the position of the camera in world coordinates.
  659. * @memberof Camera.prototype
  660. *
  661. * @type {Cartesian3}
  662. * @readonly
  663. */
  664. positionWC : {
  665. get : function() {
  666. updateMembers(this);
  667. return this._positionWC;
  668. }
  669. },
  670. /**
  671. * Gets the view direction of the camera in world coordinates.
  672. * @memberof Camera.prototype
  673. *
  674. * @type {Cartesian3}
  675. * @readonly
  676. */
  677. directionWC : {
  678. get : function() {
  679. updateMembers(this);
  680. return this._directionWC;
  681. }
  682. },
  683. /**
  684. * Gets the up direction of the camera in world coordinates.
  685. * @memberof Camera.prototype
  686. *
  687. * @type {Cartesian3}
  688. * @readonly
  689. */
  690. upWC : {
  691. get : function() {
  692. updateMembers(this);
  693. return this._upWC;
  694. }
  695. },
  696. /**
  697. * Gets the right direction of the camera in world coordinates.
  698. * @memberof Camera.prototype
  699. *
  700. * @type {Cartesian3}
  701. * @readonly
  702. */
  703. rightWC : {
  704. get : function() {
  705. updateMembers(this);
  706. return this._rightWC;
  707. }
  708. },
  709. /**
  710. * Gets the camera heading in radians.
  711. * @memberof Camera.prototype
  712. *
  713. * @type {Number}
  714. * @readonly
  715. */
  716. heading : {
  717. get : function() {
  718. if (this._mode !== SceneMode.MORPHING) {
  719. var ellipsoid = this._projection.ellipsoid;
  720. var oldTransform = Matrix4.clone(this._transform, scratchHPRMatrix1);
  721. var transform = Transforms.eastNorthUpToFixedFrame(this.positionWC, ellipsoid, scratchHPRMatrix2);
  722. this._setTransform(transform);
  723. var heading = getHeading(this.direction, this.up);
  724. this._setTransform(oldTransform);
  725. return heading;
  726. }
  727. return undefined;
  728. }
  729. },
  730. /**
  731. * Gets the camera pitch in radians.
  732. * @memberof Camera.prototype
  733. *
  734. * @type {Number}
  735. * @readonly
  736. */
  737. pitch : {
  738. get : function() {
  739. if (this._mode !== SceneMode.MORPHING) {
  740. var ellipsoid = this._projection.ellipsoid;
  741. var oldTransform = Matrix4.clone(this._transform, scratchHPRMatrix1);
  742. var transform = Transforms.eastNorthUpToFixedFrame(this.positionWC, ellipsoid, scratchHPRMatrix2);
  743. this._setTransform(transform);
  744. var pitch = getPitch(this.direction);
  745. this._setTransform(oldTransform);
  746. return pitch;
  747. }
  748. return undefined;
  749. }
  750. },
  751. /**
  752. * Gets the camera roll in radians.
  753. * @memberof Camera.prototype
  754. *
  755. * @type {Number}
  756. * @readonly
  757. */
  758. roll : {
  759. get : function() {
  760. if (this._mode !== SceneMode.MORPHING) {
  761. var ellipsoid = this._projection.ellipsoid;
  762. var oldTransform = Matrix4.clone(this._transform, scratchHPRMatrix1);
  763. var transform = Transforms.eastNorthUpToFixedFrame(this.positionWC, ellipsoid, scratchHPRMatrix2);
  764. this._setTransform(transform);
  765. var roll = getRoll(this.direction, this.up, this.right);
  766. this._setTransform(oldTransform);
  767. return roll;
  768. }
  769. return undefined;
  770. }
  771. },
  772. /**
  773. * Gets the event that will be raised at when the camera starts to move.
  774. * @memberof Camera.prototype
  775. * @type {Event}
  776. * @readonly
  777. */
  778. moveStart : {
  779. get : function() {
  780. return this._moveStart;
  781. }
  782. },
  783. /**
  784. * Gets the event that will be raised when the camera has stopped moving.
  785. * @memberof Camera.prototype
  786. * @type {Event}
  787. * @readonly
  788. */
  789. moveEnd : {
  790. get : function() {
  791. return this._moveEnd;
  792. }
  793. },
  794. /**
  795. * Gets the event that will be raised when the camera has changed by <code>percentageChanged</code>.
  796. * @memberof Camera.prototype
  797. * @type {Event}
  798. * @readonly
  799. */
  800. changed : {
  801. get : function() {
  802. return this._changed;
  803. }
  804. }
  805. });
  806. /**
  807. * @private
  808. */
  809. Camera.prototype.update = function(mode) {
  810. //>>includeStart('debug', pragmas.debug);
  811. if (!defined(mode)) {
  812. throw new DeveloperError('mode is required.');
  813. }
  814. if (mode === SceneMode.SCENE2D && !(this.frustum instanceof OrthographicOffCenterFrustum)) {
  815. throw new DeveloperError('An OrthographicOffCenterFrustum is required in 2D.');
  816. }
  817. if ((mode === SceneMode.SCENE3D || mode === SceneMode.COLUMBUS_VIEW) &&
  818. (!(this.frustum instanceof PerspectiveFrustum) && !(this.frustum instanceof OrthographicFrustum))) {
  819. throw new DeveloperError('A PerspectiveFrustum or OrthographicFrustum is required in 3D and Columbus view');
  820. }
  821. //>>includeEnd('debug');
  822. var updateFrustum = false;
  823. if (mode !== this._mode) {
  824. this._mode = mode;
  825. this._modeChanged = mode !== SceneMode.MORPHING;
  826. updateFrustum = this._mode === SceneMode.SCENE2D;
  827. }
  828. if (updateFrustum) {
  829. var frustum = this._max2Dfrustum = this.frustum.clone();
  830. //>>includeStart('debug', pragmas.debug);
  831. if (!(frustum instanceof OrthographicOffCenterFrustum)) {
  832. throw new DeveloperError('The camera frustum is expected to be orthographic for 2D camera control.');
  833. }
  834. //>>includeEnd('debug');
  835. var maxZoomOut = 2.0;
  836. var ratio = frustum.top / frustum.right;
  837. frustum.right = this._maxCoord.x * maxZoomOut;
  838. frustum.left = -frustum.right;
  839. frustum.top = ratio * frustum.right;
  840. frustum.bottom = -frustum.top;
  841. }
  842. if (this._mode === SceneMode.SCENE2D) {
  843. clampMove2D(this, this.position);
  844. }
  845. var globe = this._scene.globe;
  846. var globeFinishedUpdating = !defined(globe) || (globe._surface.tileProvider.ready && globe._surface._tileLoadQueueHigh.length === 0 && globe._surface._tileLoadQueueMedium.length === 0 && globe._surface._tileLoadQueueLow.length === 0 && globe._surface._debug.tilesWaitingForChildren === 0);
  847. if (this._suspendTerrainAdjustment) {
  848. this._suspendTerrainAdjustment = !globeFinishedUpdating;
  849. }
  850. if (globeFinishedUpdating) {
  851. this._adjustHeightForTerrain();
  852. }
  853. };
  854. var setTransformPosition = new Cartesian3();
  855. var setTransformUp = new Cartesian3();
  856. var setTransformDirection = new Cartesian3();
  857. Camera.prototype._setTransform = function(transform) {
  858. var position = Cartesian3.clone(this.positionWC, setTransformPosition);
  859. var up = Cartesian3.clone(this.upWC, setTransformUp);
  860. var direction = Cartesian3.clone(this.directionWC, setTransformDirection);
  861. Matrix4.clone(transform, this._transform);
  862. this._transformChanged = true;
  863. updateMembers(this);
  864. var inverse = this._actualInvTransform;
  865. Matrix4.multiplyByPoint(inverse, position, this.position);
  866. Matrix4.multiplyByPointAsVector(inverse, direction, this.direction);
  867. Matrix4.multiplyByPointAsVector(inverse, up, this.up);
  868. Cartesian3.cross(this.direction, this.up, this.right);
  869. updateMembers(this);
  870. };
  871. var scratchAdjustOrtghographicFrustumMousePosition = new Cartesian2();
  872. var pickGlobeScratchRay = new Ray();
  873. var scratchRayIntersection = new Cartesian3();
  874. var scratchDepthIntersection = new Cartesian3();
  875. Camera.prototype._adjustOrthographicFrustum = function(zooming) {
  876. if (!(this.frustum instanceof OrthographicFrustum)) {
  877. return;
  878. }
  879. if (!zooming && this._positionCartographic.height < 150000.0) {
  880. return;
  881. }
  882. if (!Matrix4.equals(Matrix4.IDENTITY, this.transform)) {
  883. this.frustum.width = Cartesian3.magnitude(this.position);
  884. return;
  885. }
  886. var scene = this._scene;
  887. var globe = scene.globe;
  888. var rayIntersection;
  889. var depthIntersection;
  890. if (defined(globe)) {
  891. var mousePosition = scratchAdjustOrtghographicFrustumMousePosition;
  892. mousePosition.x = scene.drawingBufferWidth / 2.0;
  893. mousePosition.y = scene.drawingBufferHeight / 2.0;
  894. var ray = this.getPickRay(mousePosition, pickGlobeScratchRay);
  895. rayIntersection = globe.pickWorldCoordinates(ray, scene, scratchRayIntersection);
  896. if (scene.pickPositionSupported) {
  897. depthIntersection = scene.pickPositionWorldCoordinates(mousePosition, scratchDepthIntersection);
  898. }
  899. if (defined(rayIntersection) && defined(depthIntersection)) {
  900. var depthDistance = defined(depthIntersection) ? Cartesian3.distance(depthIntersection, this.positionWC) : Number.POSITIVE_INFINITY;
  901. var rayDistance = defined(rayIntersection) ? Cartesian3.distance(rayIntersection, this.positionWC) : Number.POSITIVE_INFINITY;
  902. this.frustum.width = Math.min(depthDistance, rayDistance);
  903. } else if (defined(depthIntersection)) {
  904. this.frustum.width = Cartesian3.distance(depthIntersection, this.positionWC);
  905. } else if (defined(rayIntersection)) {
  906. this.frustum.width = Cartesian3.distance(rayIntersection, this.positionWC);
  907. }
  908. }
  909. if (!defined(globe) || (!defined(rayIntersection) && !defined(depthIntersection))) {
  910. var distance = Math.max(this.positionCartographic.height, 0.0);
  911. this.frustum.width = distance;
  912. }
  913. };
  914. var scratchSetViewCartesian = new Cartesian3();
  915. var scratchSetViewTransform1 = new Matrix4();
  916. var scratchSetViewTransform2 = new Matrix4();
  917. var scratchSetViewQuaternion = new Quaternion();
  918. var scratchSetViewMatrix3 = new Matrix3();
  919. var scratchSetViewCartographic = new Cartographic();
  920. function setView3D(camera, position, hpr) {
  921. var currentTransform = Matrix4.clone(camera.transform, scratchSetViewTransform1);
  922. var localTransform = Transforms.eastNorthUpToFixedFrame(position, camera._projection.ellipsoid, scratchSetViewTransform2);
  923. camera._setTransform(localTransform);
  924. Cartesian3.clone(Cartesian3.ZERO, camera.position);
  925. hpr.heading = hpr.heading - CesiumMath.PI_OVER_TWO;
  926. var rotQuat = Quaternion.fromHeadingPitchRoll(hpr, scratchSetViewQuaternion);
  927. var rotMat = Matrix3.fromQuaternion(rotQuat, scratchSetViewMatrix3);
  928. Matrix3.getColumn(rotMat, 0, camera.direction);
  929. Matrix3.getColumn(rotMat, 2, camera.up);
  930. Cartesian3.cross(camera.direction, camera.up, camera.right);
  931. camera._setTransform(currentTransform);
  932. camera._adjustOrthographicFrustum(true);
  933. }
  934. function setViewCV(camera, position,hpr, convert) {
  935. var currentTransform = Matrix4.clone(camera.transform, scratchSetViewTransform1);
  936. camera._setTransform(Matrix4.IDENTITY);
  937. if (!Cartesian3.equals(position, camera.positionWC)) {
  938. if (convert) {
  939. var projection = camera._projection;
  940. var cartographic = projection.ellipsoid.cartesianToCartographic(position, scratchSetViewCartographic);
  941. position = projection.project(cartographic, scratchSetViewCartesian);
  942. }
  943. Cartesian3.clone(position, camera.position);
  944. }
  945. hpr.heading = hpr.heading - CesiumMath.PI_OVER_TWO;
  946. var rotQuat = Quaternion.fromHeadingPitchRoll(hpr, scratchSetViewQuaternion);
  947. var rotMat = Matrix3.fromQuaternion(rotQuat, scratchSetViewMatrix3);
  948. Matrix3.getColumn(rotMat, 0, camera.direction);
  949. Matrix3.getColumn(rotMat, 2, camera.up);
  950. Cartesian3.cross(camera.direction, camera.up, camera.right);
  951. camera._setTransform(currentTransform);
  952. camera._adjustOrthographicFrustum(true);
  953. }
  954. function setView2D(camera, position, hpr, convert) {
  955. var currentTransform = Matrix4.clone(camera.transform, scratchSetViewTransform1);
  956. camera._setTransform(Matrix4.IDENTITY);
  957. if (!Cartesian3.equals(position, camera.positionWC)) {
  958. if (convert) {
  959. var projection = camera._projection;
  960. var cartographic = projection.ellipsoid.cartesianToCartographic(position, scratchSetViewCartographic);
  961. position = projection.project(cartographic, scratchSetViewCartesian);
  962. }
  963. Cartesian2.clone(position, camera.position);
  964. var newLeft = -position.z * 0.5;
  965. var newRight = -newLeft;
  966. var frustum = camera.frustum;
  967. if (newRight > newLeft) {
  968. var ratio = frustum.top / frustum.right;
  969. frustum.right = newRight;
  970. frustum.left = newLeft;
  971. frustum.top = frustum.right * ratio;
  972. frustum.bottom = -frustum.top;
  973. }
  974. }
  975. if (camera._scene.mapMode2D === MapMode2D.ROTATE) {
  976. hpr.heading = hpr.heading - CesiumMath.PI_OVER_TWO;
  977. hpr.pitch = -CesiumMath.PI_OVER_TWO;
  978. hpr.roll = 0.0;
  979. var rotQuat = Quaternion.fromHeadingPitchRoll(hpr, scratchSetViewQuaternion);
  980. var rotMat = Matrix3.fromQuaternion(rotQuat, scratchSetViewMatrix3);
  981. Matrix3.getColumn(rotMat, 2, camera.up);
  982. Cartesian3.cross(camera.direction, camera.up, camera.right);
  983. }
  984. camera._setTransform(currentTransform);
  985. }
  986. var scratchToHPRDirection = new Cartesian3();
  987. var scratchToHPRUp = new Cartesian3();
  988. var scratchToHPRRight = new Cartesian3();
  989. function directionUpToHeadingPitchRoll(camera, position, orientation, result) {
  990. var direction = Cartesian3.clone(orientation.direction, scratchToHPRDirection);
  991. var up = Cartesian3.clone(orientation.up, scratchToHPRUp);
  992. if (camera._scene.mode === SceneMode.SCENE3D) {
  993. var ellipsoid = camera._projection.ellipsoid;
  994. var transform = Transforms.eastNorthUpToFixedFrame(position, ellipsoid, scratchHPRMatrix1);
  995. var invTransform = Matrix4.inverseTransformation(transform, scratchHPRMatrix2);
  996. Matrix4.multiplyByPointAsVector(invTransform, direction, direction);
  997. Matrix4.multiplyByPointAsVector(invTransform, up, up);
  998. }
  999. var right = Cartesian3.cross(direction, up, scratchToHPRRight);
  1000. result.heading = getHeading(direction, up);
  1001. result.pitch = getPitch(direction);
  1002. result.roll = getRoll(direction, up, right);
  1003. return result;
  1004. }
  1005. var scratchSetViewOptions = {
  1006. destination : undefined,
  1007. orientation : {
  1008. direction : undefined,
  1009. up : undefined,
  1010. heading : undefined,
  1011. pitch : undefined,
  1012. roll : undefined
  1013. },
  1014. convert : undefined,
  1015. endTransform : undefined
  1016. };
  1017. var scratchHpr = new HeadingPitchRoll();
  1018. /**
  1019. * Sets the camera position, orientation and transform.
  1020. *
  1021. * @param {Object} options Object with the following properties:
  1022. * @param {Cartesian3|Rectangle} [options.destination] The final position of the camera in WGS84 (world) coordinates or a rectangle that would be visible from a top-down view.
  1023. * @param {Object} [options.orientation] An object that contains either direction and up properties or heading, pitch and roll properties. By default, the direction will point
  1024. * towards the center of the frame in 3D and in the negative z direction in Columbus view. The up direction will point towards local north in 3D and in the positive
  1025. * y direction in Columbus view. Orientation is not used in 2D when in infinite scrolling mode.
  1026. * @param {Matrix4} [options.endTransform] Transform matrix representing the reference frame of the camera.
  1027. * @param {Boolean} [options.convert] Whether to convert the destination from world coordinates to scene coordinates (only relevant when not using 3D). Defaults to <code>true</code>.
  1028. *
  1029. * @example
  1030. * // 1. Set position with a top-down view
  1031. * viewer.camera.setView({
  1032. * destination : Cesium.Cartesian3.fromDegrees(-117.16, 32.71, 15000.0)
  1033. * });
  1034. *
  1035. * // 2 Set view with heading, pitch and roll
  1036. * viewer.camera.setView({
  1037. * destination : cartesianPosition,
  1038. * orientation: {
  1039. * heading : Cesium.Math.toRadians(90.0), // east, default value is 0.0 (north)
  1040. * pitch : Cesium.Math.toRadians(-90), // default value (looking down)
  1041. * roll : 0.0 // default value
  1042. * }
  1043. * });
  1044. *
  1045. * // 3. Change heading, pitch and roll with the camera position remaining the same.
  1046. * viewer.camera.setView({
  1047. * orientation: {
  1048. * heading : Cesium.Math.toRadians(90.0), // east, default value is 0.0 (north)
  1049. * pitch : Cesium.Math.toRadians(-90), // default value (looking down)
  1050. * roll : 0.0 // default value
  1051. * }
  1052. * });
  1053. *
  1054. *
  1055. * // 4. View rectangle with a top-down view
  1056. * viewer.camera.setView({
  1057. * destination : Cesium.Rectangle.fromDegrees(west, south, east, north)
  1058. * });
  1059. *
  1060. * // 5. Set position with an orientation using unit vectors.
  1061. * viewer.camera.setView({
  1062. * destination : Cesium.Cartesian3.fromDegrees(-122.19, 46.25, 5000.0),
  1063. * orientation : {
  1064. * direction : new Cesium.Cartesian3(-0.04231243104240401, -0.20123236049443421, -0.97862924300734),
  1065. * up : new Cesium.Cartesian3(-0.47934589305293746, -0.8553216253114552, 0.1966022179118339)
  1066. * }
  1067. * });
  1068. */
  1069. Camera.prototype.setView = function(options) {
  1070. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  1071. var orientation = defaultValue(options.orientation, defaultValue.EMPTY_OBJECT);
  1072. var mode = this._mode;
  1073. if (mode === SceneMode.MORPHING) {
  1074. return;
  1075. }
  1076. if (defined(options.endTransform)) {
  1077. this._setTransform(options.endTransform);
  1078. }
  1079. var convert = defaultValue(options.convert, true);
  1080. var destination = defaultValue(options.destination, Cartesian3.clone(this.positionWC, scratchSetViewCartesian));
  1081. if (defined(destination) && defined(destination.west)) {
  1082. destination = this.getRectangleCameraCoordinates(destination, scratchSetViewCartesian);
  1083. convert = false;
  1084. }
  1085. if (defined(orientation.direction)) {
  1086. orientation = directionUpToHeadingPitchRoll(this, destination, orientation, scratchSetViewOptions.orientation);
  1087. }
  1088. scratchHpr.heading = defaultValue(orientation.heading, 0.0);
  1089. scratchHpr.pitch = defaultValue(orientation.pitch, -CesiumMath.PI_OVER_TWO);
  1090. scratchHpr.roll = defaultValue(orientation.roll, 0.0);
  1091. this._suspendTerrainAdjustment = true;
  1092. if (mode === SceneMode.SCENE3D) {
  1093. setView3D(this, destination, scratchHpr);
  1094. } else if (mode === SceneMode.SCENE2D) {
  1095. setView2D(this, destination, scratchHpr, convert);
  1096. } else {
  1097. setViewCV(this, destination, scratchHpr, convert);
  1098. }
  1099. };
  1100. var pitchScratch = new Cartesian3();
  1101. /**
  1102. * Fly the camera to the home view. Use {@link Camera#.DEFAULT_VIEW_RECTANGLE} to set
  1103. * the default view for the 3D scene. The home view for 2D and columbus view shows the
  1104. * entire map.
  1105. *
  1106. * @param {Number} [duration] The duration of the flight in seconds. If omitted, Cesium attempts to calculate an ideal duration based on the distance to be traveled by the flight. See {@link Camera#flyTo}
  1107. */
  1108. Camera.prototype.flyHome = function(duration) {
  1109. var mode = this._mode;
  1110. if (mode === SceneMode.MORPHING) {
  1111. this._scene.completeMorph();
  1112. }
  1113. if (mode === SceneMode.SCENE2D) {
  1114. this.flyTo({
  1115. destination : Camera.DEFAULT_VIEW_RECTANGLE,
  1116. duration : duration,
  1117. endTransform : Matrix4.IDENTITY
  1118. });
  1119. } else if (mode === SceneMode.SCENE3D) {
  1120. var destination = this.getRectangleCameraCoordinates(Camera.DEFAULT_VIEW_RECTANGLE);
  1121. var mag = Cartesian3.magnitude(destination);
  1122. mag += mag * Camera.DEFAULT_VIEW_FACTOR;
  1123. Cartesian3.normalize(destination, destination);
  1124. Cartesian3.multiplyByScalar(destination, mag, destination);
  1125. this.flyTo({
  1126. destination : destination,
  1127. duration : duration,
  1128. endTransform : Matrix4.IDENTITY
  1129. });
  1130. } else if (mode === SceneMode.COLUMBUS_VIEW) {
  1131. var maxRadii = this._projection.ellipsoid.maximumRadius;
  1132. var position = new Cartesian3(0.0, -1.0, 1.0);
  1133. position = Cartesian3.multiplyByScalar(Cartesian3.normalize(position, position), 5.0 * maxRadii, position);
  1134. this.flyTo({
  1135. destination : position,
  1136. duration : duration,
  1137. orientation : {
  1138. heading : 0.0,
  1139. pitch : -Math.acos(Cartesian3.normalize(position, pitchScratch).z),
  1140. roll : 0.0
  1141. },
  1142. endTransform : Matrix4.IDENTITY,
  1143. convert : false
  1144. });
  1145. }
  1146. };
  1147. /**
  1148. * Transform a vector or point from world coordinates to the camera's reference frame.
  1149. *
  1150. * @param {Cartesian4} cartesian The vector or point to transform.
  1151. * @param {Cartesian4} [result] The object onto which to store the result.
  1152. * @returns {Cartesian4} The transformed vector or point.
  1153. */
  1154. Camera.prototype.worldToCameraCoordinates = function(cartesian, result) {
  1155. //>>includeStart('debug', pragmas.debug);
  1156. if (!defined(cartesian)) {
  1157. throw new DeveloperError('cartesian is required.');
  1158. }
  1159. //>>includeEnd('debug');
  1160. if (!defined(result)) {
  1161. result = new Cartesian4();
  1162. }
  1163. updateMembers(this);
  1164. return Matrix4.multiplyByVector(this._actualInvTransform, cartesian, result);
  1165. };
  1166. /**
  1167. * Transform a point from world coordinates to the camera's reference frame.
  1168. *
  1169. * @param {Cartesian3} cartesian The point to transform.
  1170. * @param {Cartesian3} [result] The object onto which to store the result.
  1171. * @returns {Cartesian3} The transformed point.
  1172. */
  1173. Camera.prototype.worldToCameraCoordinatesPoint = function(cartesian, result) {
  1174. //>>includeStart('debug', pragmas.debug);
  1175. if (!defined(cartesian)) {
  1176. throw new DeveloperError('cartesian is required.');
  1177. }
  1178. //>>includeEnd('debug');
  1179. if (!defined(result)) {
  1180. result = new Cartesian3();
  1181. }
  1182. updateMembers(this);
  1183. return Matrix4.multiplyByPoint(this._actualInvTransform, cartesian, result);
  1184. };
  1185. /**
  1186. * Transform a vector from world coordinates to the camera's reference frame.
  1187. *
  1188. * @param {Cartesian3} cartesian The vector to transform.
  1189. * @param {Cartesian3} [result] The object onto which to store the result.
  1190. * @returns {Cartesian3} The transformed vector.
  1191. */
  1192. Camera.prototype.worldToCameraCoordinatesVector = function(cartesian, result) {
  1193. //>>includeStart('debug', pragmas.debug);
  1194. if (!defined(cartesian)) {
  1195. throw new DeveloperError('cartesian is required.');
  1196. }
  1197. //>>includeEnd('debug');
  1198. if (!defined(result)) {
  1199. result = new Cartesian3();
  1200. }
  1201. updateMembers(this);
  1202. return Matrix4.multiplyByPointAsVector(this._actualInvTransform, cartesian, result);
  1203. };
  1204. /**
  1205. * Transform a vector or point from the camera's reference frame to world coordinates.
  1206. *
  1207. * @param {Cartesian4} cartesian The vector or point to transform.
  1208. * @param {Cartesian4} [result] The object onto which to store the result.
  1209. * @returns {Cartesian4} The transformed vector or point.
  1210. */
  1211. Camera.prototype.cameraToWorldCoordinates = function(cartesian, result) {
  1212. //>>includeStart('debug', pragmas.debug);
  1213. if (!defined(cartesian)) {
  1214. throw new DeveloperError('cartesian is required.');
  1215. }
  1216. //>>includeEnd('debug');
  1217. if (!defined(result)) {
  1218. result = new Cartesian4();
  1219. }
  1220. updateMembers(this);
  1221. return Matrix4.multiplyByVector(this._actualTransform, cartesian, result);
  1222. };
  1223. /**
  1224. * Transform a point from the camera's reference frame to world coordinates.
  1225. *
  1226. * @param {Cartesian3} cartesian The point to transform.
  1227. * @param {Cartesian3} [result] The object onto which to store the result.
  1228. * @returns {Cartesian3} The transformed point.
  1229. */
  1230. Camera.prototype.cameraToWorldCoordinatesPoint = function(cartesian, result) {
  1231. //>>includeStart('debug', pragmas.debug);
  1232. if (!defined(cartesian)) {
  1233. throw new DeveloperError('cartesian is required.');
  1234. }
  1235. //>>includeEnd('debug');
  1236. if (!defined(result)) {
  1237. result = new Cartesian3();
  1238. }
  1239. updateMembers(this);
  1240. return Matrix4.multiplyByPoint(this._actualTransform, cartesian, result);
  1241. };
  1242. /**
  1243. * Transform a vector from the camera's reference frame to world coordinates.
  1244. *
  1245. * @param {Cartesian3} cartesian The vector to transform.
  1246. * @param {Cartesian3} [result] The object onto which to store the result.
  1247. * @returns {Cartesian3} The transformed vector.
  1248. */
  1249. Camera.prototype.cameraToWorldCoordinatesVector = function(cartesian, result) {
  1250. //>>includeStart('debug', pragmas.debug);
  1251. if (!defined(cartesian)) {
  1252. throw new DeveloperError('cartesian is required.');
  1253. }
  1254. //>>includeEnd('debug');
  1255. if (!defined(result)) {
  1256. result = new Cartesian3();
  1257. }
  1258. updateMembers(this);
  1259. return Matrix4.multiplyByPointAsVector(this._actualTransform, cartesian, result);
  1260. };
  1261. function clampMove2D(camera, position) {
  1262. var rotatable2D = camera._scene.mapMode2D === MapMode2D.ROTATE;
  1263. var maxProjectedX = camera._maxCoord.x;
  1264. var maxProjectedY = camera._maxCoord.y;
  1265. var minX;
  1266. var maxX;
  1267. if (rotatable2D) {
  1268. maxX = maxProjectedX;
  1269. minX = -maxX;
  1270. } else {
  1271. maxX = position.x - maxProjectedX * 2.0;
  1272. minX = position.x + maxProjectedX * 2.0;
  1273. }
  1274. if (position.x > maxProjectedX) {
  1275. position.x = maxX;
  1276. }
  1277. if (position.x < -maxProjectedX) {
  1278. position.x = minX;
  1279. }
  1280. if (position.y > maxProjectedY) {
  1281. position.y = maxProjectedY;
  1282. }
  1283. if (position.y < -maxProjectedY) {
  1284. position.y = -maxProjectedY;
  1285. }
  1286. }
  1287. var moveScratch = new Cartesian3();
  1288. /**
  1289. * Translates the camera's position by <code>amount</code> along <code>direction</code>.
  1290. *
  1291. * @param {Cartesian3} direction The direction to move.
  1292. * @param {Number} [amount] The amount, in meters, to move. Defaults to <code>defaultMoveAmount</code>.
  1293. *
  1294. * @see Camera#moveBackward
  1295. * @see Camera#moveForward
  1296. * @see Camera#moveLeft
  1297. * @see Camera#moveRight
  1298. * @see Camera#moveUp
  1299. * @see Camera#moveDown
  1300. */
  1301. Camera.prototype.move = function(direction, amount) {
  1302. //>>includeStart('debug', pragmas.debug);
  1303. if (!defined(direction)) {
  1304. throw new DeveloperError('direction is required.');
  1305. }
  1306. //>>includeEnd('debug');
  1307. var cameraPosition = this.position;
  1308. Cartesian3.multiplyByScalar(direction, amount, moveScratch);
  1309. Cartesian3.add(cameraPosition, moveScratch, cameraPosition);
  1310. if (this._mode === SceneMode.SCENE2D) {
  1311. clampMove2D(this, cameraPosition);
  1312. }
  1313. this._adjustOrthographicFrustum(true);
  1314. };
  1315. /**
  1316. * Translates the camera's position by <code>amount</code> along the camera's view vector.
  1317. * When in 2D mode, this will zoom in the camera instead of translating the camera's position.
  1318. *
  1319. * @param {Number} [amount] The amount, in meters, to move. Defaults to <code>defaultMoveAmount</code>.
  1320. *
  1321. * @see Camera#moveBackward
  1322. */
  1323. Camera.prototype.moveForward = function(amount) {
  1324. amount = defaultValue(amount, this.defaultMoveAmount);
  1325. if (this._mode === SceneMode.SCENE2D) {
  1326. // 2D mode
  1327. zoom2D(this, amount);
  1328. } else {
  1329. // 3D or Columbus view mode
  1330. this.move(this.direction, amount);
  1331. }
  1332. };
  1333. /**
  1334. * Translates the camera's position by <code>amount</code> along the opposite direction
  1335. * of the camera's view vector.
  1336. * When in 2D mode, this will zoom out the camera instead of translating the camera's position.
  1337. *
  1338. * @param {Number} [amount] The amount, in meters, to move. Defaults to <code>defaultMoveAmount</code>.
  1339. *
  1340. * @see Camera#moveForward
  1341. */
  1342. Camera.prototype.moveBackward = function(amount) {
  1343. amount = defaultValue(amount, this.defaultMoveAmount);
  1344. if (this._mode === SceneMode.SCENE2D) {
  1345. // 2D mode
  1346. zoom2D(this, -amount);
  1347. } else {
  1348. // 3D or Columbus view mode
  1349. this.move(this.direction, -amount);
  1350. }
  1351. };
  1352. /**
  1353. * Translates the camera's position by <code>amount</code> along the camera's up vector.
  1354. *
  1355. * @param {Number} [amount] The amount, in meters, to move. Defaults to <code>defaultMoveAmount</code>.
  1356. *
  1357. * @see Camera#moveDown
  1358. */
  1359. Camera.prototype.moveUp = function(amount) {
  1360. amount = defaultValue(amount, this.defaultMoveAmount);
  1361. this.move(this.up, amount);
  1362. };
  1363. /**
  1364. * Translates the camera's position by <code>amount</code> along the opposite direction
  1365. * of the camera's up vector.
  1366. *
  1367. * @param {Number} [amount] The amount, in meters, to move. Defaults to <code>defaultMoveAmount</code>.
  1368. *
  1369. * @see Camera#moveUp
  1370. */
  1371. Camera.prototype.moveDown = function(amount) {
  1372. amount = defaultValue(amount, this.defaultMoveAmount);
  1373. this.move(this.up, -amount);
  1374. };
  1375. /**
  1376. * Translates the camera's position by <code>amount</code> along the camera's right vector.
  1377. *
  1378. * @param {Number} [amount] The amount, in meters, to move. Defaults to <code>defaultMoveAmount</code>.
  1379. *
  1380. * @see Camera#moveLeft
  1381. */
  1382. Camera.prototype.moveRight = function(amount) {
  1383. amount = defaultValue(amount, this.defaultMoveAmount);
  1384. this.move(this.right, amount);
  1385. };
  1386. /**
  1387. * Translates the camera's position by <code>amount</code> along the opposite direction
  1388. * of the camera's right vector.
  1389. *
  1390. * @param {Number} [amount] The amount, in meters, to move. Defaults to <code>defaultMoveAmount</code>.
  1391. *
  1392. * @see Camera#moveRight
  1393. */
  1394. Camera.prototype.moveLeft = function(amount) {
  1395. amount = defaultValue(amount, this.defaultMoveAmount);
  1396. this.move(this.right, -amount);
  1397. };
  1398. /**
  1399. * Rotates the camera around its up vector by amount, in radians, in the opposite direction
  1400. * of its right vector if not in 2D mode.
  1401. *
  1402. * @param {Number} [amount] The amount, in radians, to rotate by. Defaults to <code>defaultLookAmount</code>.
  1403. *
  1404. * @see Camera#lookRight
  1405. */
  1406. Camera.prototype.lookLeft = function(amount) {
  1407. amount = defaultValue(amount, this.defaultLookAmount);
  1408. // only want view of map to change in 3D mode, 2D visual is incorrect when look changes
  1409. if (this._mode !== SceneMode.SCENE2D) {
  1410. this.look(this.up, -amount);
  1411. }
  1412. };
  1413. /**
  1414. * Rotates the camera around its up vector by amount, in radians, in the direction
  1415. * of its right vector if not in 2D mode.
  1416. *
  1417. * @param {Number} [amount] The amount, in radians, to rotate by. Defaults to <code>defaultLookAmount</code>.
  1418. *
  1419. * @see Camera#lookLeft
  1420. */
  1421. Camera.prototype.lookRight = function(amount) {
  1422. amount = defaultValue(amount, this.defaultLookAmount);
  1423. // only want view of map to change in 3D mode, 2D visual is incorrect when look changes
  1424. if (this._mode !== SceneMode.SCENE2D) {
  1425. this.look(this.up, amount);
  1426. }
  1427. };
  1428. /**
  1429. * Rotates the camera around its right vector by amount, in radians, in the direction
  1430. * of its up vector if not in 2D mode.
  1431. *
  1432. * @param {Number} [amount] The amount, in radians, to rotate by. Defaults to <code>defaultLookAmount</code>.
  1433. *
  1434. * @see Camera#lookDown
  1435. */
  1436. Camera.prototype.lookUp = function(amount) {
  1437. amount = defaultValue(amount, this.defaultLookAmount);
  1438. // only want view of map to change in 3D mode, 2D visual is incorrect when look changes
  1439. if (this._mode !== SceneMode.SCENE2D) {
  1440. this.look(this.right, -amount);
  1441. }
  1442. };
  1443. /**
  1444. * Rotates the camera around its right vector by amount, in radians, in the opposite direction
  1445. * of its up vector if not in 2D mode.
  1446. *
  1447. * @param {Number} [amount] The amount, in radians, to rotate by. Defaults to <code>defaultLookAmount</code>.
  1448. *
  1449. * @see Camera#lookUp
  1450. */
  1451. Camera.prototype.lookDown = function(amount) {
  1452. amount = defaultValue(amount, this.defaultLookAmount);
  1453. // only want view of map to change in 3D mode, 2D visual is incorrect when look changes
  1454. if (this._mode !== SceneMode.SCENE2D) {
  1455. this.look(this.right, amount);
  1456. }
  1457. };
  1458. var lookScratchQuaternion = new Quaternion();
  1459. var lookScratchMatrix = new Matrix3();
  1460. /**
  1461. * Rotate each of the camera's orientation vectors around <code>axis</code> by <code>angle</code>
  1462. *
  1463. * @param {Cartesian3} axis The axis to rotate around.
  1464. * @param {Number} [angle] The angle, in radians, to rotate by. Defaults to <code>defaultLookAmount</code>.
  1465. *
  1466. * @see Camera#lookUp
  1467. * @see Camera#lookDown
  1468. * @see Camera#lookLeft
  1469. * @see Camera#lookRight
  1470. */
  1471. Camera.prototype.look = function(axis, angle) {
  1472. //>>includeStart('debug', pragmas.debug);
  1473. if (!defined(axis)) {
  1474. throw new DeveloperError('axis is required.');
  1475. }
  1476. //>>includeEnd('debug');
  1477. var turnAngle = defaultValue(angle, this.defaultLookAmount);
  1478. var quaternion = Quaternion.fromAxisAngle(axis, -turnAngle, lookScratchQuaternion);
  1479. var rotation = Matrix3.fromQuaternion(quaternion, lookScratchMatrix);
  1480. var direction = this.direction;
  1481. var up = this.up;
  1482. var right = this.right;
  1483. Matrix3.multiplyByVector(rotation, direction, direction);
  1484. Matrix3.multiplyByVector(rotation, up, up);
  1485. Matrix3.multiplyByVector(rotation, right, right);
  1486. };
  1487. /**
  1488. * Rotate the camera counter-clockwise around its direction vector by amount, in radians.
  1489. *
  1490. * @param {Number} [amount] The amount, in radians, to rotate by. Defaults to <code>defaultLookAmount</code>.
  1491. *
  1492. * @see Camera#twistRight
  1493. */
  1494. Camera.prototype.twistLeft = function(amount) {
  1495. amount = defaultValue(amount, this.defaultLookAmount);
  1496. this.look(this.direction, amount);
  1497. };
  1498. /**
  1499. * Rotate the camera clockwise around its direction vector by amount, in radians.
  1500. *
  1501. * @param {Number} [amount] The amount, in radians, to rotate by. Defaults to <code>defaultLookAmount</code>.
  1502. *
  1503. * @see Camera#twistLeft
  1504. */
  1505. Camera.prototype.twistRight = function(amount) {
  1506. amount = defaultValue(amount, this.defaultLookAmount);
  1507. this.look(this.direction, -amount);
  1508. };
  1509. var rotateScratchQuaternion = new Quaternion();
  1510. var rotateScratchMatrix = new Matrix3();
  1511. /**
  1512. * Rotates the camera around <code>axis</code> by <code>angle</code>. The distance
  1513. * of the camera's position to the center of the camera's reference frame remains the same.
  1514. *
  1515. * @param {Cartesian3} axis The axis to rotate around given in world coordinates.
  1516. * @param {Number} [angle] The angle, in radians, to rotate by. Defaults to <code>defaultRotateAmount</code>.
  1517. *
  1518. * @see Camera#rotateUp
  1519. * @see Camera#rotateDown
  1520. * @see Camera#rotateLeft
  1521. * @see Camera#rotateRight
  1522. */
  1523. Camera.prototype.rotate = function(axis, angle) {
  1524. //>>includeStart('debug', pragmas.debug);
  1525. if (!defined(axis)) {
  1526. throw new DeveloperError('axis is required.');
  1527. }
  1528. //>>includeEnd('debug');
  1529. var turnAngle = defaultValue(angle, this.defaultRotateAmount);
  1530. var quaternion = Quaternion.fromAxisAngle(axis, -turnAngle, rotateScratchQuaternion);
  1531. var rotation = Matrix3.fromQuaternion(quaternion, rotateScratchMatrix);
  1532. Matrix3.multiplyByVector(rotation, this.position, this.position);
  1533. Matrix3.multiplyByVector(rotation, this.direction, this.direction);
  1534. Matrix3.multiplyByVector(rotation, this.up, this.up);
  1535. Cartesian3.cross(this.direction, this.up, this.right);
  1536. Cartesian3.cross(this.right, this.direction, this.up);
  1537. this._adjustOrthographicFrustum(false);
  1538. };
  1539. /**
  1540. * Rotates the camera around the center of the camera's reference frame by angle downwards.
  1541. *
  1542. * @param {Number} [angle] The angle, in radians, to rotate by. Defaults to <code>defaultRotateAmount</code>.
  1543. *
  1544. * @see Camera#rotateUp
  1545. * @see Camera#rotate
  1546. */
  1547. Camera.prototype.rotateDown = function(angle) {
  1548. angle = defaultValue(angle, this.defaultRotateAmount);
  1549. rotateVertical(this, angle);
  1550. };
  1551. /**
  1552. * Rotates the camera around the center of the camera's reference frame by angle upwards.
  1553. *
  1554. * @param {Number} [angle] The angle, in radians, to rotate by. Defaults to <code>defaultRotateAmount</code>.
  1555. *
  1556. * @see Camera#rotateDown
  1557. * @see Camera#rotate
  1558. */
  1559. Camera.prototype.rotateUp = function(angle) {
  1560. angle = defaultValue(angle, this.defaultRotateAmount);
  1561. rotateVertical(this, -angle);
  1562. };
  1563. var rotateVertScratchP = new Cartesian3();
  1564. var rotateVertScratchA = new Cartesian3();
  1565. var rotateVertScratchTan = new Cartesian3();
  1566. var rotateVertScratchNegate = new Cartesian3();
  1567. function rotateVertical(camera, angle) {
  1568. var position = camera.position;
  1569. if (defined(camera.constrainedAxis) && !Cartesian3.equalsEpsilon(camera.position, Cartesian3.ZERO, CesiumMath.EPSILON2)) {
  1570. var p = Cartesian3.normalize(position, rotateVertScratchP);
  1571. var northParallel = Cartesian3.equalsEpsilon(p, camera.constrainedAxis, CesiumMath.EPSILON2);
  1572. var southParallel = Cartesian3.equalsEpsilon(p, Cartesian3.negate(camera.constrainedAxis, rotateVertScratchNegate), CesiumMath.EPSILON2);
  1573. if ((!northParallel && !southParallel)) {
  1574. var constrainedAxis = Cartesian3.normalize(camera.constrainedAxis, rotateVertScratchA);
  1575. var dot = Cartesian3.dot(p, constrainedAxis);
  1576. var angleToAxis = CesiumMath.acosClamped(dot);
  1577. if (angle > 0 && angle > angleToAxis) {
  1578. angle = angleToAxis - CesiumMath.EPSILON4;
  1579. }
  1580. dot = Cartesian3.dot(p, Cartesian3.negate(constrainedAxis, rotateVertScratchNegate));
  1581. angleToAxis = CesiumMath.acosClamped(dot);
  1582. if (angle < 0 && -angle > angleToAxis) {
  1583. angle = -angleToAxis + CesiumMath.EPSILON4;
  1584. }
  1585. var tangent = Cartesian3.cross(constrainedAxis, p, rotateVertScratchTan);
  1586. camera.rotate(tangent, angle);
  1587. } else if ((northParallel && angle < 0) || (southParallel && angle > 0)) {
  1588. camera.rotate(camera.right, angle);
  1589. }
  1590. } else {
  1591. camera.rotate(camera.right, angle);
  1592. }
  1593. }
  1594. /**
  1595. * Rotates the camera around the center of the camera's reference frame by angle to the right.
  1596. *
  1597. * @param {Number} [angle] The angle, in radians, to rotate by. Defaults to <code>defaultRotateAmount</code>.
  1598. *
  1599. * @see Camera#rotateLeft
  1600. * @see Camera#rotate
  1601. */
  1602. Camera.prototype.rotateRight = function(angle) {
  1603. angle = defaultValue(angle, this.defaultRotateAmount);
  1604. rotateHorizontal(this, -angle);
  1605. };
  1606. /**
  1607. * Rotates the camera around the center of the camera's reference frame by angle to the left.
  1608. *
  1609. * @param {Number} [angle] The angle, in radians, to rotate by. Defaults to <code>defaultRotateAmount</code>.
  1610. *
  1611. * @see Camera#rotateRight
  1612. * @see Camera#rotate
  1613. */
  1614. Camera.prototype.rotateLeft = function(angle) {
  1615. angle = defaultValue(angle, this.defaultRotateAmount);
  1616. rotateHorizontal(this, angle);
  1617. };
  1618. function rotateHorizontal(camera, angle) {
  1619. if (defined(camera.constrainedAxis)) {
  1620. camera.rotate(camera.constrainedAxis, angle);
  1621. } else {
  1622. camera.rotate(camera.up, angle);
  1623. }
  1624. }
  1625. function zoom2D(camera, amount) {
  1626. var frustum = camera.frustum;
  1627. //>>includeStart('debug', pragmas.debug);
  1628. if (!(frustum instanceof OrthographicOffCenterFrustum) || !defined(frustum.left) || !defined(frustum.right) ||
  1629. !defined(frustum.bottom) || !defined(frustum.top)) {
  1630. throw new DeveloperError('The camera frustum is expected to be orthographic for 2D camera control.');
  1631. }
  1632. //>>includeEnd('debug');
  1633. var ratio;
  1634. amount = amount * 0.5;
  1635. if((Math.abs(frustum.top) + Math.abs(frustum.bottom)) > (Math.abs(frustum.left) + Math.abs(frustum.right))) {
  1636. var newTop = frustum.top - amount;
  1637. var newBottom = frustum.bottom + amount;
  1638. var maxBottom = camera._maxCoord.y;
  1639. if (camera._scene.mapMode2D === MapMode2D.ROTATE) {
  1640. maxBottom *= camera.maximumZoomFactor;
  1641. }
  1642. if (newBottom > maxBottom) {
  1643. newBottom = maxBottom;
  1644. newTop = -maxBottom;
  1645. }
  1646. if (newTop <= newBottom) {
  1647. newTop = 1.0;
  1648. newBottom = -1.0;
  1649. }
  1650. ratio = frustum.right / frustum.top;
  1651. frustum.top = newTop;
  1652. frustum.bottom = newBottom;
  1653. frustum.right = frustum.top * ratio;
  1654. frustum.left = -frustum.right;
  1655. } else {
  1656. var newRight = frustum.right - amount;
  1657. var newLeft = frustum.left + amount;
  1658. var maxRight = camera._maxCoord.x;
  1659. if (camera._scene.mapMode2D === MapMode2D.ROTATE) {
  1660. maxRight *= camera.maximumZoomFactor;
  1661. }
  1662. if (newRight > maxRight) {
  1663. newRight = maxRight;
  1664. newLeft = -maxRight;
  1665. }
  1666. if (newRight <= newLeft) {
  1667. newRight = 1.0;
  1668. newLeft = -1.0;
  1669. }
  1670. ratio = frustum.top / frustum.right;
  1671. frustum.right = newRight;
  1672. frustum.left = newLeft;
  1673. frustum.top = frustum.right * ratio;
  1674. frustum.bottom = -frustum.top;
  1675. }
  1676. }
  1677. function zoom3D(camera, amount) {
  1678. camera.move(camera.direction, amount);
  1679. }
  1680. /**
  1681. * Zooms <code>amount</code> along the camera's view vector.
  1682. *
  1683. * @param {Number} [amount] The amount to move. Defaults to <code>defaultZoomAmount</code>.
  1684. *
  1685. * @see Camera#zoomOut
  1686. */
  1687. Camera.prototype.zoomIn = function(amount) {
  1688. amount = defaultValue(amount, this.defaultZoomAmount);
  1689. if (this._mode === SceneMode.SCENE2D) {
  1690. zoom2D(this, amount);
  1691. } else {
  1692. zoom3D(this, amount);
  1693. }
  1694. };
  1695. /**
  1696. * Zooms <code>amount</code> along the opposite direction of
  1697. * the camera's view vector.
  1698. *
  1699. * @param {Number} [amount] The amount to move. Defaults to <code>defaultZoomAmount</code>.
  1700. *
  1701. * @see Camera#zoomIn
  1702. */
  1703. Camera.prototype.zoomOut = function(amount) {
  1704. amount = defaultValue(amount, this.defaultZoomAmount);
  1705. if (this._mode === SceneMode.SCENE2D) {
  1706. zoom2D(this, -amount);
  1707. } else {
  1708. zoom3D(this, -amount);
  1709. }
  1710. };
  1711. /**
  1712. * Gets the magnitude of the camera position. In 3D, this is the vector magnitude. In 2D and
  1713. * Columbus view, this is the distance to the map.
  1714. *
  1715. * @returns {Number} The magnitude of the position.
  1716. */
  1717. Camera.prototype.getMagnitude = function() {
  1718. if (this._mode === SceneMode.SCENE3D) {
  1719. return Cartesian3.magnitude(this.position);
  1720. } else if (this._mode === SceneMode.COLUMBUS_VIEW) {
  1721. return Math.abs(this.position.z);
  1722. } else if (this._mode === SceneMode.SCENE2D) {
  1723. return Math.max(this.frustum.right - this.frustum.left, this.frustum.top - this.frustum.bottom);
  1724. }
  1725. };
  1726. var scratchLookAtMatrix4 = new Matrix4();
  1727. /**
  1728. * Sets the camera position and orientation using a target and offset. The target must be given in
  1729. * world coordinates. The offset can be either a cartesian or heading/pitch/range in the local east-north-up reference frame centered at the target.
  1730. * If the offset is a cartesian, then it is an offset from the center of the reference frame defined by the transformation matrix. If the offset
  1731. * is heading/pitch/range, then the heading and the pitch angles are defined in the reference frame defined by the transformation matrix.
  1732. * The heading is the angle from y axis and increasing towards the x axis. Pitch is the rotation from the xy-plane. Positive pitch
  1733. * angles are below the plane. Negative pitch angles are above the plane. The range is the distance from the center.
  1734. *
  1735. * In 2D, there must be a top down view. The camera will be placed above the target looking down. The height above the
  1736. * target will be the magnitude of the offset. The heading will be determined from the offset. If the heading cannot be
  1737. * determined from the offset, the heading will be north.
  1738. *
  1739. * @param {Cartesian3} target The target position in world coordinates.
  1740. * @param {Cartesian3|HeadingPitchRange} offset The offset from the target in the local east-north-up reference frame centered at the target.
  1741. *
  1742. * @exception {DeveloperError} lookAt is not supported while morphing.
  1743. *
  1744. * @example
  1745. * // 1. Using a cartesian offset
  1746. * var center = Cesium.Cartesian3.fromDegrees(-98.0, 40.0);
  1747. * viewer.camera.lookAt(center, new Cesium.Cartesian3(0.0, -4790000.0, 3930000.0));
  1748. *
  1749. * // 2. Using a HeadingPitchRange offset
  1750. * var center = Cesium.Cartesian3.fromDegrees(-72.0, 40.0);
  1751. * var heading = Cesium.Math.toRadians(50.0);
  1752. * var pitch = Cesium.Math.toRadians(-20.0);
  1753. * var range = 5000.0;
  1754. * viewer.camera.lookAt(center, new Cesium.HeadingPitchRange(heading, pitch, range));
  1755. */
  1756. Camera.prototype.lookAt = function(target, offset) {
  1757. //>>includeStart('debug', pragmas.debug);
  1758. if (!defined(target)) {
  1759. throw new DeveloperError('target is required');
  1760. }
  1761. if (!defined(offset)) {
  1762. throw new DeveloperError('offset is required');
  1763. }
  1764. if (this._mode === SceneMode.MORPHING) {
  1765. throw new DeveloperError('lookAt is not supported while morphing.');
  1766. }
  1767. //>>includeEnd('debug');
  1768. var transform = Transforms.eastNorthUpToFixedFrame(target, Ellipsoid.WGS84, scratchLookAtMatrix4);
  1769. this.lookAtTransform(transform, offset);
  1770. };
  1771. var scratchLookAtHeadingPitchRangeOffset = new Cartesian3();
  1772. var scratchLookAtHeadingPitchRangeQuaternion1 = new Quaternion();
  1773. var scratchLookAtHeadingPitchRangeQuaternion2 = new Quaternion();
  1774. var scratchHeadingPitchRangeMatrix3 = new Matrix3();
  1775. function offsetFromHeadingPitchRange(heading, pitch, range) {
  1776. pitch = CesiumMath.clamp(pitch, -CesiumMath.PI_OVER_TWO, CesiumMath.PI_OVER_TWO);
  1777. heading = CesiumMath.zeroToTwoPi(heading) - CesiumMath.PI_OVER_TWO;
  1778. var pitchQuat = Quaternion.fromAxisAngle(Cartesian3.UNIT_Y, -pitch, scratchLookAtHeadingPitchRangeQuaternion1);
  1779. var headingQuat = Quaternion.fromAxisAngle(Cartesian3.UNIT_Z, -heading, scratchLookAtHeadingPitchRangeQuaternion2);
  1780. var rotQuat = Quaternion.multiply(headingQuat, pitchQuat, headingQuat);
  1781. var rotMatrix = Matrix3.fromQuaternion(rotQuat, scratchHeadingPitchRangeMatrix3);
  1782. var offset = Cartesian3.clone(Cartesian3.UNIT_X, scratchLookAtHeadingPitchRangeOffset);
  1783. Matrix3.multiplyByVector(rotMatrix, offset, offset);
  1784. Cartesian3.negate(offset, offset);
  1785. Cartesian3.multiplyByScalar(offset, range, offset);
  1786. return offset;
  1787. }
  1788. /**
  1789. * Sets the camera position and orientation using a target and transformation matrix. The offset can be either a cartesian or heading/pitch/range.
  1790. * If the offset is a cartesian, then it is an offset from the center of the reference frame defined by the transformation matrix. If the offset
  1791. * is heading/pitch/range, then the heading and the pitch angles are defined in the reference frame defined by the transformation matrix.
  1792. * The heading is the angle from y axis and increasing towards the x axis. Pitch is the rotation from the xy-plane. Positive pitch
  1793. * angles are below the plane. Negative pitch angles are above the plane. The range is the distance from the center.
  1794. *
  1795. * In 2D, there must be a top down view. The camera will be placed above the center of the reference frame. The height above the
  1796. * target will be the magnitude of the offset. The heading will be determined from the offset. If the heading cannot be
  1797. * determined from the offset, the heading will be north.
  1798. *
  1799. * @param {Matrix4} transform The transformation matrix defining the reference frame.
  1800. * @param {Cartesian3|HeadingPitchRange} [offset] The offset from the target in a reference frame centered at the target.
  1801. *
  1802. * @exception {DeveloperError} lookAtTransform is not supported while morphing.
  1803. *
  1804. * @example
  1805. * // 1. Using a cartesian offset
  1806. * var transform = Cesium.Transforms.eastNorthUpToFixedFrame(Cesium.Cartesian3.fromDegrees(-98.0, 40.0));
  1807. * viewer.camera.lookAtTransform(transform, new Cesium.Cartesian3(0.0, -4790000.0, 3930000.0));
  1808. *
  1809. * // 2. Using a HeadingPitchRange offset
  1810. * var transform = Cesium.Transforms.eastNorthUpToFixedFrame(Cesium.Cartesian3.fromDegrees(-72.0, 40.0));
  1811. * var heading = Cesium.Math.toRadians(50.0);
  1812. * var pitch = Cesium.Math.toRadians(-20.0);
  1813. * var range = 5000.0;
  1814. * viewer.camera.lookAtTransform(transform, new Cesium.HeadingPitchRange(heading, pitch, range));
  1815. */
  1816. Camera.prototype.lookAtTransform = function(transform, offset) {
  1817. //>>includeStart('debug', pragmas.debug);
  1818. if (!defined(transform)) {
  1819. throw new DeveloperError('transform is required');
  1820. }
  1821. if (this._mode === SceneMode.MORPHING) {
  1822. throw new DeveloperError('lookAtTransform is not supported while morphing.');
  1823. }
  1824. //>>includeEnd('debug');
  1825. this._setTransform(transform);
  1826. if (!defined(offset)) {
  1827. return;
  1828. }
  1829. var cartesianOffset;
  1830. if (defined(offset.heading)) {
  1831. cartesianOffset = offsetFromHeadingPitchRange(offset.heading, offset.pitch, offset.range);
  1832. } else {
  1833. cartesianOffset = offset;
  1834. }
  1835. if (this._mode === SceneMode.SCENE2D) {
  1836. Cartesian2.clone(Cartesian2.ZERO, this.position);
  1837. Cartesian3.negate(cartesianOffset, this.up);
  1838. this.up.z = 0.0;
  1839. if (Cartesian3.magnitudeSquared(this.up) < CesiumMath.EPSILON10) {
  1840. Cartesian3.clone(Cartesian3.UNIT_Y, this.up);
  1841. }
  1842. Cartesian3.normalize(this.up, this.up);
  1843. this._setTransform(Matrix4.IDENTITY);
  1844. Cartesian3.negate(Cartesian3.UNIT_Z, this.direction);
  1845. Cartesian3.cross(this.direction, this.up, this.right);
  1846. Cartesian3.normalize(this.right, this.right);
  1847. var frustum = this.frustum;
  1848. var ratio = frustum.top / frustum.right;
  1849. frustum.right = Cartesian3.magnitude(cartesianOffset) * 0.5;
  1850. frustum.left = -frustum.right;
  1851. frustum.top = ratio * frustum.right;
  1852. frustum.bottom = -frustum.top;
  1853. this._setTransform(transform);
  1854. return;
  1855. }
  1856. Cartesian3.clone(cartesianOffset, this.position);
  1857. Cartesian3.negate(this.position, this.direction);
  1858. Cartesian3.normalize(this.direction, this.direction);
  1859. Cartesian3.cross(this.direction, Cartesian3.UNIT_Z, this.right);
  1860. if (Cartesian3.magnitudeSquared(this.right) < CesiumMath.EPSILON10) {
  1861. Cartesian3.clone(Cartesian3.UNIT_X, this.right);
  1862. }
  1863. Cartesian3.normalize(this.right, this.right);
  1864. Cartesian3.cross(this.right, this.direction, this.up);
  1865. Cartesian3.normalize(this.up, this.up);
  1866. this._adjustOrthographicFrustum(true);
  1867. };
  1868. var viewRectangle3DCartographic1 = new Cartographic();
  1869. var viewRectangle3DCartographic2 = new Cartographic();
  1870. var viewRectangle3DNorthEast = new Cartesian3();
  1871. var viewRectangle3DSouthWest = new Cartesian3();
  1872. var viewRectangle3DNorthWest = new Cartesian3();
  1873. var viewRectangle3DSouthEast = new Cartesian3();
  1874. var viewRectangle3DNorthCenter = new Cartesian3();
  1875. var viewRectangle3DSouthCenter = new Cartesian3();
  1876. var viewRectangle3DCenter = new Cartesian3();
  1877. var viewRectangle3DEquator = new Cartesian3();
  1878. var defaultRF = {
  1879. direction : new Cartesian3(),
  1880. right : new Cartesian3(),
  1881. up : new Cartesian3()
  1882. };
  1883. var viewRectangle3DEllipsoidGeodesic;
  1884. function computeD(direction, upOrRight, corner, tanThetaOrPhi) {
  1885. var opposite = Math.abs(Cartesian3.dot(upOrRight, corner));
  1886. return opposite / tanThetaOrPhi - Cartesian3.dot(direction, corner);
  1887. }
  1888. function rectangleCameraPosition3D(camera, rectangle, result, updateCamera) {
  1889. var ellipsoid = camera._projection.ellipsoid;
  1890. var cameraRF = updateCamera ? camera : defaultRF;
  1891. var north = rectangle.north;
  1892. var south = rectangle.south;
  1893. var east = rectangle.east;
  1894. var west = rectangle.west;
  1895. // If we go across the International Date Line
  1896. if (west > east) {
  1897. east += CesiumMath.TWO_PI;
  1898. }
  1899. // Find the midpoint latitude.
  1900. //
  1901. // EllipsoidGeodesic will fail if the north and south edges are very close to being on opposite sides of the ellipsoid.
  1902. // Ideally we'd just call EllipsoidGeodesic.setEndPoints and let it throw when it detects this case, but sadly it doesn't
  1903. // even look for this case in optimized builds, so we have to test for it here instead.
  1904. //
  1905. // Fortunately, this case can only happen (here) when north is very close to the north pole and south is very close to the south pole,
  1906. // so handle it just by using 0 latitude as the center. It's certainliy possible to use a smaller tolerance
  1907. // than one degree here, but one degree is safe and putting the center at 0 latitude should be good enough for any
  1908. // rectangle that spans 178+ of the 180 degrees of latitude.
  1909. var longitude = (west + east) * 0.5;
  1910. var latitude;
  1911. if (south < -CesiumMath.PI_OVER_TWO + CesiumMath.RADIANS_PER_DEGREE && north > CesiumMath.PI_OVER_TWO - CesiumMath.RADIANS_PER_DEGREE) {
  1912. latitude = 0.0;
  1913. } else {
  1914. var northCartographic = viewRectangle3DCartographic1;
  1915. northCartographic.longitude = longitude;
  1916. northCartographic.latitude = north;
  1917. northCartographic.height = 0.0;
  1918. var southCartographic = viewRectangle3DCartographic2;
  1919. southCartographic.longitude = longitude;
  1920. southCartographic.latitude = south;
  1921. southCartographic.height = 0.0;
  1922. var ellipsoidGeodesic = viewRectangle3DEllipsoidGeodesic;
  1923. if (!defined(ellipsoidGeodesic) || ellipsoidGeodesic.ellipsoid !== ellipsoid) {
  1924. viewRectangle3DEllipsoidGeodesic = ellipsoidGeodesic = new EllipsoidGeodesic(undefined, undefined, ellipsoid);
  1925. }
  1926. ellipsoidGeodesic.setEndPoints(northCartographic, southCartographic);
  1927. latitude = ellipsoidGeodesic.interpolateUsingFraction(0.5, viewRectangle3DCartographic1).latitude;
  1928. }
  1929. var centerCartographic = viewRectangle3DCartographic1;
  1930. centerCartographic.longitude = longitude;
  1931. centerCartographic.latitude = latitude;
  1932. centerCartographic.height = 0.0;
  1933. var center = ellipsoid.cartographicToCartesian(centerCartographic, viewRectangle3DCenter);
  1934. var cart = viewRectangle3DCartographic1;
  1935. cart.longitude = east;
  1936. cart.latitude = north;
  1937. var northEast = ellipsoid.cartographicToCartesian(cart, viewRectangle3DNorthEast);
  1938. cart.longitude = west;
  1939. var northWest = ellipsoid.cartographicToCartesian(cart, viewRectangle3DNorthWest);
  1940. cart.longitude = longitude;
  1941. var northCenter = ellipsoid.cartographicToCartesian(cart, viewRectangle3DNorthCenter);
  1942. cart.latitude = south;
  1943. var southCenter = ellipsoid.cartographicToCartesian(cart, viewRectangle3DSouthCenter);
  1944. cart.longitude = east;
  1945. var southEast = ellipsoid.cartographicToCartesian(cart, viewRectangle3DSouthEast);
  1946. cart.longitude = west;
  1947. var southWest = ellipsoid.cartographicToCartesian(cart, viewRectangle3DSouthWest);
  1948. Cartesian3.subtract(northWest, center, northWest);
  1949. Cartesian3.subtract(southEast, center, southEast);
  1950. Cartesian3.subtract(northEast, center, northEast);
  1951. Cartesian3.subtract(southWest, center, southWest);
  1952. Cartesian3.subtract(northCenter, center, northCenter);
  1953. Cartesian3.subtract(southCenter, center, southCenter);
  1954. var direction = ellipsoid.geodeticSurfaceNormal(center, cameraRF.direction);
  1955. Cartesian3.negate(direction, direction);
  1956. var right = Cartesian3.cross(direction, Cartesian3.UNIT_Z, cameraRF.right);
  1957. Cartesian3.normalize(right, right);
  1958. var up = Cartesian3.cross(right, direction, cameraRF.up);
  1959. var d;
  1960. if (camera.frustum instanceof OrthographicFrustum) {
  1961. var width = Math.max(Cartesian3.distance(northEast, northWest), Cartesian3.distance(southEast, southWest));
  1962. var height = Math.max(Cartesian3.distance(northEast, southEast), Cartesian3.distance(northWest, southWest));
  1963. var rightScalar;
  1964. var topScalar;
  1965. var ratio = camera.frustum._offCenterFrustum.right / camera.frustum._offCenterFrustum.top;
  1966. var heightRatio = height * ratio;
  1967. if (width > heightRatio) {
  1968. rightScalar = width;
  1969. topScalar = rightScalar / ratio;
  1970. } else {
  1971. topScalar = height;
  1972. rightScalar = heightRatio;
  1973. }
  1974. d = Math.max(rightScalar, topScalar);
  1975. } else {
  1976. var tanPhi = Math.tan(camera.frustum.fovy * 0.5);
  1977. var tanTheta = camera.frustum.aspectRatio * tanPhi;
  1978. d = Math.max(
  1979. computeD(direction, up, northWest, tanPhi),
  1980. computeD(direction, up, southEast, tanPhi),
  1981. computeD(direction, up, northEast, tanPhi),
  1982. computeD(direction, up, southWest, tanPhi),
  1983. computeD(direction, up, northCenter, tanPhi),
  1984. computeD(direction, up, southCenter, tanPhi),
  1985. computeD(direction, right, northWest, tanTheta),
  1986. computeD(direction, right, southEast, tanTheta),
  1987. computeD(direction, right, northEast, tanTheta),
  1988. computeD(direction, right, southWest, tanTheta),
  1989. computeD(direction, right, northCenter, tanTheta),
  1990. computeD(direction, right, southCenter, tanTheta));
  1991. // If the rectangle crosses the equator, compute D at the equator, too, because that's the
  1992. // widest part of the rectangle when projected onto the globe.
  1993. if (south < 0 && north > 0) {
  1994. var equatorCartographic = viewRectangle3DCartographic1;
  1995. equatorCartographic.longitude = west;
  1996. equatorCartographic.latitude = 0.0;
  1997. equatorCartographic.height = 0.0;
  1998. var equatorPosition = ellipsoid.cartographicToCartesian(equatorCartographic, viewRectangle3DEquator);
  1999. Cartesian3.subtract(equatorPosition, center, equatorPosition);
  2000. d = Math.max(d, computeD(direction, up, equatorPosition, tanPhi), computeD(direction, right, equatorPosition, tanTheta));
  2001. equatorCartographic.longitude = east;
  2002. equatorPosition = ellipsoid.cartographicToCartesian(equatorCartographic, viewRectangle3DEquator);
  2003. Cartesian3.subtract(equatorPosition, center, equatorPosition);
  2004. d = Math.max(d, computeD(direction, up, equatorPosition, tanPhi), computeD(direction, right, equatorPosition, tanTheta));
  2005. }
  2006. }
  2007. return Cartesian3.add(center, Cartesian3.multiplyByScalar(direction, -d, viewRectangle3DEquator), result);
  2008. }
  2009. var viewRectangleCVCartographic = new Cartographic();
  2010. var viewRectangleCVNorthEast = new Cartesian3();
  2011. var viewRectangleCVSouthWest = new Cartesian3();
  2012. function rectangleCameraPositionColumbusView(camera, rectangle, result) {
  2013. var projection = camera._projection;
  2014. if (rectangle.west > rectangle.east) {
  2015. rectangle = Rectangle.MAX_VALUE;
  2016. }
  2017. var transform = camera._actualTransform;
  2018. var invTransform = camera._actualInvTransform;
  2019. var cart = viewRectangleCVCartographic;
  2020. cart.longitude = rectangle.east;
  2021. cart.latitude = rectangle.north;
  2022. var northEast = projection.project(cart, viewRectangleCVNorthEast);
  2023. Matrix4.multiplyByPoint(transform, northEast, northEast);
  2024. Matrix4.multiplyByPoint(invTransform, northEast, northEast);
  2025. cart.longitude = rectangle.west;
  2026. cart.latitude = rectangle.south;
  2027. var southWest = projection.project(cart, viewRectangleCVSouthWest);
  2028. Matrix4.multiplyByPoint(transform, southWest, southWest);
  2029. Matrix4.multiplyByPoint(invTransform, southWest, southWest);
  2030. result.x = (northEast.x - southWest.x) * 0.5 + southWest.x;
  2031. result.y = (northEast.y - southWest.y) * 0.5 + southWest.y;
  2032. if (defined(camera.frustum.fovy)) {
  2033. var tanPhi = Math.tan(camera.frustum.fovy * 0.5);
  2034. var tanTheta = camera.frustum.aspectRatio * tanPhi;
  2035. result.z = Math.max((northEast.x - southWest.x) / tanTheta, (northEast.y - southWest.y) / tanPhi) * 0.5;
  2036. } else {
  2037. var width = northEast.x - southWest.x;
  2038. var height = northEast.y - southWest.y;
  2039. result.z = Math.max(width, height);
  2040. }
  2041. return result;
  2042. }
  2043. var viewRectangle2DCartographic = new Cartographic();
  2044. var viewRectangle2DNorthEast = new Cartesian3();
  2045. var viewRectangle2DSouthWest = new Cartesian3();
  2046. function rectangleCameraPosition2D(camera, rectangle, result) {
  2047. var projection = camera._projection;
  2048. // Account for the rectangle crossing the International Date Line in 2D mode
  2049. var east = rectangle.east;
  2050. if (rectangle.west > rectangle.east) {
  2051. if(camera._scene.mapMode2D === MapMode2D.INFINITE_SCROLL) {
  2052. east += CesiumMath.TWO_PI;
  2053. } else {
  2054. rectangle = Rectangle.MAX_VALUE;
  2055. east = rectangle.east;
  2056. }
  2057. }
  2058. var cart = viewRectangle2DCartographic;
  2059. cart.longitude = east;
  2060. cart.latitude = rectangle.north;
  2061. var northEast = projection.project(cart, viewRectangle2DNorthEast);
  2062. cart.longitude = rectangle.west;
  2063. cart.latitude = rectangle.south;
  2064. var southWest = projection.project(cart, viewRectangle2DSouthWest);
  2065. var width = Math.abs(northEast.x - southWest.x) * 0.5;
  2066. var height = Math.abs(northEast.y - southWest.y) * 0.5;
  2067. var right, top;
  2068. var ratio = camera.frustum.right / camera.frustum.top;
  2069. var heightRatio = height * ratio;
  2070. if (width > heightRatio) {
  2071. right = width;
  2072. top = right / ratio;
  2073. } else {
  2074. top = height;
  2075. right = heightRatio;
  2076. }
  2077. height = Math.max(2.0 * right, 2.0 * top);
  2078. result.x = (northEast.x - southWest.x) * 0.5 + southWest.x;
  2079. result.y = (northEast.y - southWest.y) * 0.5 + southWest.y;
  2080. cart = projection.unproject(result, cart);
  2081. cart.height = height;
  2082. result = projection.project(cart, result);
  2083. return result;
  2084. }
  2085. /**
  2086. * Get the camera position needed to view a rectangle on an ellipsoid or map
  2087. *
  2088. * @param {Rectangle} rectangle The rectangle to view.
  2089. * @param {Cartesian3} [result] The camera position needed to view the rectangle
  2090. * @returns {Cartesian3} The camera position needed to view the rectangle
  2091. */
  2092. Camera.prototype.getRectangleCameraCoordinates = function(rectangle, result) {
  2093. //>>includeStart('debug', pragmas.debug);
  2094. if (!defined(rectangle)) {
  2095. throw new DeveloperError('rectangle is required');
  2096. }
  2097. //>>includeEnd('debug');
  2098. var mode = this._mode;
  2099. if (!defined(result)) {
  2100. result = new Cartesian3();
  2101. }
  2102. if (mode === SceneMode.SCENE3D) {
  2103. return rectangleCameraPosition3D(this, rectangle, result);
  2104. } else if (mode === SceneMode.COLUMBUS_VIEW) {
  2105. return rectangleCameraPositionColumbusView(this, rectangle, result);
  2106. } else if (mode === SceneMode.SCENE2D) {
  2107. return rectangleCameraPosition2D(this, rectangle, result);
  2108. }
  2109. return undefined;
  2110. };
  2111. var pickEllipsoid3DRay = new Ray();
  2112. function pickEllipsoid3D(camera, windowPosition, ellipsoid, result) {
  2113. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  2114. var ray = camera.getPickRay(windowPosition, pickEllipsoid3DRay);
  2115. var intersection = IntersectionTests.rayEllipsoid(ray, ellipsoid);
  2116. if (!intersection) {
  2117. return undefined;
  2118. }
  2119. var t = intersection.start > 0.0 ? intersection.start : intersection.stop;
  2120. return Ray.getPoint(ray, t, result);
  2121. }
  2122. var pickEllipsoid2DRay = new Ray();
  2123. function pickMap2D(camera, windowPosition, projection, result) {
  2124. var ray = camera.getPickRay(windowPosition, pickEllipsoid2DRay);
  2125. var position = ray.origin;
  2126. position = Cartesian3.fromElements(position.y, position.z, 0.0, position);
  2127. var cart = projection.unproject(position);
  2128. if (cart.latitude < -CesiumMath.PI_OVER_TWO || cart.latitude > CesiumMath.PI_OVER_TWO) {
  2129. return undefined;
  2130. }
  2131. return projection.ellipsoid.cartographicToCartesian(cart, result);
  2132. }
  2133. var pickEllipsoidCVRay = new Ray();
  2134. function pickMapColumbusView(camera, windowPosition, projection, result) {
  2135. var ray = camera.getPickRay(windowPosition, pickEllipsoidCVRay);
  2136. var scalar = -ray.origin.x / ray.direction.x;
  2137. Ray.getPoint(ray, scalar, result);
  2138. var cart = projection.unproject(new Cartesian3(result.y, result.z, 0.0));
  2139. if (cart.latitude < -CesiumMath.PI_OVER_TWO || cart.latitude > CesiumMath.PI_OVER_TWO ||
  2140. cart.longitude < -Math.PI || cart.longitude > Math.PI) {
  2141. return undefined;
  2142. }
  2143. return projection.ellipsoid.cartographicToCartesian(cart, result);
  2144. }
  2145. /**
  2146. * Pick an ellipsoid or map.
  2147. *
  2148. * @param {Cartesian2} windowPosition The x and y coordinates of a pixel.
  2149. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid to pick.
  2150. * @param {Cartesian3} [result] The object onto which to store the result.
  2151. * @returns {Cartesian3} If the ellipsoid or map was picked, returns the point on the surface of the ellipsoid or map
  2152. * in world coordinates. If the ellipsoid or map was not picked, returns undefined.
  2153. */
  2154. Camera.prototype.pickEllipsoid = function(windowPosition, ellipsoid, result) {
  2155. //>>includeStart('debug', pragmas.debug);
  2156. if (!defined(windowPosition)) {
  2157. throw new DeveloperError('windowPosition is required.');
  2158. }
  2159. //>>includeEnd('debug');
  2160. var canvas = this._scene.canvas;
  2161. if (canvas.clientWidth === 0 || canvas.clientHeight === 0) {
  2162. return undefined;
  2163. }
  2164. if (!defined(result)) {
  2165. result = new Cartesian3();
  2166. }
  2167. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  2168. if (this._mode === SceneMode.SCENE3D) {
  2169. result = pickEllipsoid3D(this, windowPosition, ellipsoid, result);
  2170. } else if (this._mode === SceneMode.SCENE2D) {
  2171. result = pickMap2D(this, windowPosition, this._projection, result);
  2172. } else if (this._mode === SceneMode.COLUMBUS_VIEW) {
  2173. result = pickMapColumbusView(this, windowPosition, this._projection, result);
  2174. } else {
  2175. return undefined;
  2176. }
  2177. return result;
  2178. };
  2179. var pickPerspCenter = new Cartesian3();
  2180. var pickPerspXDir = new Cartesian3();
  2181. var pickPerspYDir = new Cartesian3();
  2182. function getPickRayPerspective(camera, windowPosition, result) {
  2183. var canvas = camera._scene.canvas;
  2184. var width = canvas.clientWidth;
  2185. var height = canvas.clientHeight;
  2186. var tanPhi = Math.tan(camera.frustum.fovy * 0.5);
  2187. var tanTheta = camera.frustum.aspectRatio * tanPhi;
  2188. var near = camera.frustum.near;
  2189. var x = (2.0 / width) * windowPosition.x - 1.0;
  2190. var y = (2.0 / height) * (height - windowPosition.y) - 1.0;
  2191. var position = camera.positionWC;
  2192. Cartesian3.clone(position, result.origin);
  2193. var nearCenter = Cartesian3.multiplyByScalar(camera.directionWC, near, pickPerspCenter);
  2194. Cartesian3.add(position, nearCenter, nearCenter);
  2195. var xDir = Cartesian3.multiplyByScalar(camera.rightWC, x * near * tanTheta, pickPerspXDir);
  2196. var yDir = Cartesian3.multiplyByScalar(camera.upWC, y * near * tanPhi, pickPerspYDir);
  2197. var direction = Cartesian3.add(nearCenter, xDir, result.direction);
  2198. Cartesian3.add(direction, yDir, direction);
  2199. Cartesian3.subtract(direction, position, direction);
  2200. Cartesian3.normalize(direction, direction);
  2201. return result;
  2202. }
  2203. var scratchDirection = new Cartesian3();
  2204. function getPickRayOrthographic(camera, windowPosition, result) {
  2205. var canvas = camera._scene.canvas;
  2206. var width = canvas.clientWidth;
  2207. var height = canvas.clientHeight;
  2208. var frustum = camera.frustum;
  2209. if (defined(frustum._offCenterFrustum)) {
  2210. frustum = frustum._offCenterFrustum;
  2211. }
  2212. var x = (2.0 / width) * windowPosition.x - 1.0;
  2213. x *= (frustum.right - frustum.left) * 0.5;
  2214. var y = (2.0 / height) * (height - windowPosition.y) - 1.0;
  2215. y *= (frustum.top - frustum.bottom) * 0.5;
  2216. var origin = result.origin;
  2217. Cartesian3.clone(camera.position, origin);
  2218. Cartesian3.multiplyByScalar(camera.right, x, scratchDirection);
  2219. Cartesian3.add(scratchDirection, origin, origin);
  2220. Cartesian3.multiplyByScalar(camera.up, y, scratchDirection);
  2221. Cartesian3.add(scratchDirection, origin, origin);
  2222. Cartesian3.clone(camera.directionWC, result.direction);
  2223. if (camera._mode === SceneMode.COLUMBUS_VIEW || camera._mode === SceneMode.SCENE2D) {
  2224. Cartesian3.fromElements(result.origin.z, result.origin.x, result.origin.y, result.origin);
  2225. }
  2226. return result;
  2227. }
  2228. /**
  2229. * Create a ray from the camera position through the pixel at <code>windowPosition</code>
  2230. * in world coordinates.
  2231. *
  2232. * @param {Cartesian2} windowPosition The x and y coordinates of a pixel.
  2233. * @param {Ray} [result] The object onto which to store the result.
  2234. * @returns {Ray} Returns the {@link Cartesian3} position and direction of the ray.
  2235. */
  2236. Camera.prototype.getPickRay = function(windowPosition, result) {
  2237. //>>includeStart('debug', pragmas.debug);
  2238. if (!defined(windowPosition)) {
  2239. throw new DeveloperError('windowPosition is required.');
  2240. }
  2241. //>>includeEnd('debug');
  2242. if (!defined(result)) {
  2243. result = new Ray();
  2244. }
  2245. var frustum = this.frustum;
  2246. if (defined(frustum.aspectRatio) && defined(frustum.fov) && defined(frustum.near)) {
  2247. return getPickRayPerspective(this, windowPosition, result);
  2248. }
  2249. return getPickRayOrthographic(this, windowPosition, result);
  2250. };
  2251. var scratchToCenter = new Cartesian3();
  2252. var scratchProj = new Cartesian3();
  2253. /**
  2254. * Return the distance from the camera to the front of the bounding sphere.
  2255. *
  2256. * @param {BoundingSphere} boundingSphere The bounding sphere in world coordinates.
  2257. * @returns {Number} The distance to the bounding sphere.
  2258. */
  2259. Camera.prototype.distanceToBoundingSphere = function(boundingSphere) {
  2260. //>>includeStart('debug', pragmas.debug);
  2261. if (!defined(boundingSphere)) {
  2262. throw new DeveloperError('boundingSphere is required.');
  2263. }
  2264. //>>includeEnd('debug');
  2265. var toCenter = Cartesian3.subtract(this.positionWC, boundingSphere.center, scratchToCenter);
  2266. var proj = Cartesian3.multiplyByScalar(this.directionWC, Cartesian3.dot(toCenter, this.directionWC), scratchProj);
  2267. return Math.max(0.0, Cartesian3.magnitude(proj) - boundingSphere.radius);
  2268. };
  2269. var scratchPixelSize = new Cartesian2();
  2270. /**
  2271. * Return the pixel size in meters.
  2272. *
  2273. * @param {BoundingSphere} boundingSphere The bounding sphere in world coordinates.
  2274. * @param {Number} drawingBufferWidth The drawing buffer width.
  2275. * @param {Number} drawingBufferHeight The drawing buffer height.
  2276. * @returns {Number} The pixel size in meters.
  2277. */
  2278. Camera.prototype.getPixelSize = function(boundingSphere, drawingBufferWidth, drawingBufferHeight) {
  2279. //>>includeStart('debug', pragmas.debug);
  2280. if (!defined(boundingSphere)) {
  2281. throw new DeveloperError('boundingSphere is required.');
  2282. }
  2283. if (!defined(drawingBufferWidth)) {
  2284. throw new DeveloperError('drawingBufferWidth is required.');
  2285. }
  2286. if (!defined(drawingBufferHeight)) {
  2287. throw new DeveloperError('drawingBufferHeight is required.');
  2288. }
  2289. //>>includeEnd('debug');
  2290. var distance = this.distanceToBoundingSphere(boundingSphere);
  2291. var pixelSize = this.frustum.getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, this._scene.pixelRatio, scratchPixelSize);
  2292. return Math.max(pixelSize.x, pixelSize.y);
  2293. };
  2294. function createAnimationTemplateCV(camera, position, center, maxX, maxY, duration) {
  2295. var newPosition = Cartesian3.clone(position);
  2296. if (center.y > maxX) {
  2297. newPosition.y -= center.y - maxX;
  2298. } else if (center.y < -maxX) {
  2299. newPosition.y += -maxX - center.y;
  2300. }
  2301. if (center.z > maxY) {
  2302. newPosition.z -= center.z - maxY;
  2303. } else if (center.z < -maxY) {
  2304. newPosition.z += -maxY - center.z;
  2305. }
  2306. function updateCV(value) {
  2307. var interp = Cartesian3.lerp(position, newPosition, value.time, new Cartesian3());
  2308. camera.worldToCameraCoordinatesPoint(interp, camera.position);
  2309. }
  2310. return {
  2311. easingFunction : EasingFunction.EXPONENTIAL_OUT,
  2312. startObject : {
  2313. time : 0.0
  2314. },
  2315. stopObject : {
  2316. time : 1.0
  2317. },
  2318. duration : duration,
  2319. update : updateCV
  2320. };
  2321. }
  2322. var normalScratch = new Cartesian3();
  2323. var centerScratch = new Cartesian3();
  2324. var posScratch = new Cartesian3();
  2325. var scratchCartesian3Subtract = new Cartesian3();
  2326. function createAnimationCV(camera, duration) {
  2327. var position = camera.position;
  2328. var direction = camera.direction;
  2329. var normal = camera.worldToCameraCoordinatesVector(Cartesian3.UNIT_X, normalScratch);
  2330. var scalar = -Cartesian3.dot(normal, position) / Cartesian3.dot(normal, direction);
  2331. var center = Cartesian3.add(position, Cartesian3.multiplyByScalar(direction, scalar, centerScratch), centerScratch);
  2332. camera.cameraToWorldCoordinatesPoint(center, center);
  2333. position = camera.cameraToWorldCoordinatesPoint(camera.position, posScratch);
  2334. var tanPhi = Math.tan(camera.frustum.fovy * 0.5);
  2335. var tanTheta = camera.frustum.aspectRatio * tanPhi;
  2336. var distToC = Cartesian3.magnitude(Cartesian3.subtract(position, center, scratchCartesian3Subtract));
  2337. var dWidth = tanTheta * distToC;
  2338. var dHeight = tanPhi * distToC;
  2339. var mapWidth = camera._maxCoord.x;
  2340. var mapHeight = camera._maxCoord.y;
  2341. var maxX = Math.max(dWidth - mapWidth, mapWidth);
  2342. var maxY = Math.max(dHeight - mapHeight, mapHeight);
  2343. if (position.z < -maxX || position.z > maxX || position.y < -maxY || position.y > maxY) {
  2344. var translateX = center.y < -maxX || center.y > maxX;
  2345. var translateY = center.z < -maxY || center.z > maxY;
  2346. if (translateX || translateY) {
  2347. return createAnimationTemplateCV(camera, position, center, maxX, maxY, duration);
  2348. }
  2349. }
  2350. return undefined;
  2351. }
  2352. /**
  2353. * Create an animation to move the map into view. This method is only valid for 2D and Columbus modes.
  2354. *
  2355. * @param {Number} duration The duration, in seconds, of the animation.
  2356. * @returns {Object} The animation or undefined if the scene mode is 3D or the map is already ion view.
  2357. *
  2358. * @private
  2359. */
  2360. Camera.prototype.createCorrectPositionTween = function(duration) {
  2361. //>>includeStart('debug', pragmas.debug);
  2362. if (!defined(duration)) {
  2363. throw new DeveloperError('duration is required.');
  2364. }
  2365. //>>includeEnd('debug');
  2366. if (this._mode === SceneMode.COLUMBUS_VIEW) {
  2367. return createAnimationCV(this, duration);
  2368. }
  2369. return undefined;
  2370. };
  2371. var scratchFlyToDestination = new Cartesian3();
  2372. var newOptions = {
  2373. destination : undefined,
  2374. heading : undefined,
  2375. pitch : undefined,
  2376. roll : undefined,
  2377. duration : undefined,
  2378. complete : undefined,
  2379. cancel : undefined,
  2380. endTransform : undefined,
  2381. maximumHeight : undefined,
  2382. easingFunction : undefined
  2383. };
  2384. /**
  2385. * Cancels the current camera flight if one is in progress.
  2386. * The camera is left at it's current location.
  2387. */
  2388. Camera.prototype.cancelFlight = function () {
  2389. if (defined(this._currentFlight)) {
  2390. this._currentFlight.cancelTween();
  2391. this._currentFlight = undefined;
  2392. }
  2393. };
  2394. /**
  2395. * Flies the camera from its current position to a new position.
  2396. *
  2397. * @param {Object} options Object with the following properties:
  2398. * @param {Cartesian3|Rectangle} options.destination The final position of the camera in WGS84 (world) coordinates or a rectangle that would be visible from a top-down view.
  2399. * @param {Object} [options.orientation] An object that contains either direction and up properties or heading, pitch and roll properties. By default, the direction will point
  2400. * towards the center of the frame in 3D and in the negative z direction in Columbus view. The up direction will point towards local north in 3D and in the positive
  2401. * y direction in Columbus view. Orientation is not used in 2D when in infinite scrolling mode.
  2402. * @param {Number} [options.duration] The duration of the flight in seconds. If omitted, Cesium attempts to calculate an ideal duration based on the distance to be traveled by the flight.
  2403. * @param {Camera~FlightCompleteCallback} [options.complete] The function to execute when the flight is complete.
  2404. * @param {Camera~FlightCancelledCallback} [options.cancel] The function to execute if the flight is cancelled.
  2405. * @param {Matrix4} [options.endTransform] Transform matrix representing the reference frame the camera will be in when the flight is completed.
  2406. * @param {Number} [options.maximumHeight] The maximum height at the peak of the flight.
  2407. * @param {Number} [options.pitchAdjustHeight] If camera flyes higher than that value, adjust pitch duiring the flight to look down, and keep Earth in viewport.
  2408. * @param {Number} [options.flyOverLongitude] There are always two ways between 2 points on globe. This option force camera to choose fight direction to fly over that longitude.
  2409. * @param {Number} [options.flyOverLongitudeWeight] Fly over the lon specifyed via flyOverLongitude only if that way is not longer than short way times flyOverLongitudeWeight.
  2410. * @param {Boolean} [options.convert] Whether to convert the destination from world coordinates to scene coordinates (only relevant when not using 3D). Defaults to <code>true</code>.
  2411. * @param {EasingFunction|EasingFunction~Callback} [options.easingFunction] Controls how the time is interpolated over the duration of the flight.
  2412. *
  2413. * @exception {DeveloperError} If either direction or up is given, then both are required.
  2414. *
  2415. * @example
  2416. * // 1. Fly to a position with a top-down view
  2417. * viewer.camera.flyTo({
  2418. * destination : Cesium.Cartesian3.fromDegrees(-117.16, 32.71, 15000.0)
  2419. * });
  2420. *
  2421. * // 2. Fly to a Rectangle with a top-down view
  2422. * viewer.camera.flyTo({
  2423. * destination : Cesium.Rectangle.fromDegrees(west, south, east, north)
  2424. * });
  2425. *
  2426. * // 3. Fly to a position with an orientation using unit vectors.
  2427. * viewer.camera.flyTo({
  2428. * destination : Cesium.Cartesian3.fromDegrees(-122.19, 46.25, 5000.0),
  2429. * orientation : {
  2430. * direction : new Cesium.Cartesian3(-0.04231243104240401, -0.20123236049443421, -0.97862924300734),
  2431. * up : new Cesium.Cartesian3(-0.47934589305293746, -0.8553216253114552, 0.1966022179118339)
  2432. * }
  2433. * });
  2434. *
  2435. * // 4. Fly to a position with an orientation using heading, pitch and roll.
  2436. * viewer.camera.flyTo({
  2437. * destination : Cesium.Cartesian3.fromDegrees(-122.19, 46.25, 5000.0),
  2438. * orientation : {
  2439. * heading : Cesium.Math.toRadians(175.0),
  2440. * pitch : Cesium.Math.toRadians(-35.0),
  2441. * roll : 0.0
  2442. * }
  2443. * });
  2444. */
  2445. Camera.prototype.flyTo = function(options) {
  2446. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  2447. var destination = options.destination;
  2448. //>>includeStart('debug', pragmas.debug);
  2449. if (!defined(destination)) {
  2450. throw new DeveloperError('destination is required.');
  2451. }
  2452. //>>includeEnd('debug');
  2453. var mode = this._mode;
  2454. if (mode === SceneMode.MORPHING) {
  2455. return;
  2456. }
  2457. this.cancelFlight();
  2458. var orientation = defaultValue(options.orientation, defaultValue.EMPTY_OBJECT);
  2459. if (defined(orientation.direction)) {
  2460. orientation = directionUpToHeadingPitchRoll(this, destination, orientation, scratchSetViewOptions.orientation);
  2461. }
  2462. if (defined(options.duration) && options.duration <= 0.0) {
  2463. var setViewOptions = scratchSetViewOptions;
  2464. setViewOptions.destination = options.destination;
  2465. setViewOptions.orientation.heading = orientation.heading;
  2466. setViewOptions.orientation.pitch = orientation.pitch;
  2467. setViewOptions.orientation.roll = orientation.roll;
  2468. setViewOptions.convert = options.convert;
  2469. setViewOptions.endTransform = options.endTransform;
  2470. this.setView(setViewOptions);
  2471. if (typeof options.complete === 'function') {
  2472. options.complete();
  2473. }
  2474. return;
  2475. }
  2476. var isRectangle = defined(destination.west);
  2477. if (isRectangle) {
  2478. destination = this.getRectangleCameraCoordinates(destination, scratchFlyToDestination);
  2479. }
  2480. var that = this;
  2481. var flightTween;
  2482. newOptions.destination = destination;
  2483. newOptions.heading = orientation.heading;
  2484. newOptions.pitch = orientation.pitch;
  2485. newOptions.roll = orientation.roll;
  2486. newOptions.duration = options.duration;
  2487. newOptions.complete = function () {
  2488. if(flightTween === that._currentFlight){
  2489. that._currentFlight = undefined;
  2490. }
  2491. if (defined(options.complete)) {
  2492. options.complete();
  2493. }
  2494. };
  2495. newOptions.cancel = options.cancel;
  2496. newOptions.endTransform = options.endTransform;
  2497. newOptions.convert = isRectangle ? false : options.convert;
  2498. newOptions.maximumHeight = options.maximumHeight;
  2499. newOptions.pitchAdjustHeight = options.pitchAdjustHeight;
  2500. newOptions.flyOverLongitude = options.flyOverLongitude;
  2501. newOptions.flyOverLongitudeWeight = options.flyOverLongitudeWeight;
  2502. newOptions.easingFunction = options.easingFunction;
  2503. var scene = this._scene;
  2504. flightTween = scene.tweens.add(CameraFlightPath.createTween(scene, newOptions));
  2505. this._currentFlight = flightTween;
  2506. // Save the final destination view information for the PRELOAD_FLIGHT pass.
  2507. var preloadFlightCamera = this._scene.preloadFlightCamera;
  2508. if (this._mode !== SceneMode.SCENE2D) {
  2509. if (!defined(preloadFlightCamera)) {
  2510. preloadFlightCamera = Camera.clone(this);
  2511. }
  2512. preloadFlightCamera.setView({ destination: destination, orientation: orientation });
  2513. this._scene.preloadFlightCullingVolume = preloadFlightCamera.frustum.computeCullingVolume(preloadFlightCamera.positionWC, preloadFlightCamera.directionWC, preloadFlightCamera.upWC);
  2514. } else {
  2515. preloadFlightCamera = undefined;
  2516. }
  2517. };
  2518. function distanceToBoundingSphere3D(camera, radius) {
  2519. var frustum = camera.frustum;
  2520. var tanPhi = Math.tan(frustum.fovy * 0.5);
  2521. var tanTheta = frustum.aspectRatio * tanPhi;
  2522. return Math.max(radius / tanTheta, radius / tanPhi);
  2523. }
  2524. function distanceToBoundingSphere2D(camera, radius) {
  2525. var frustum = camera.frustum;
  2526. if (defined(frustum._offCenterFrustum)) {
  2527. frustum = frustum._offCenterFrustum;
  2528. }
  2529. var right, top;
  2530. var ratio = frustum.right / frustum.top;
  2531. var heightRatio = radius * ratio;
  2532. if (radius > heightRatio) {
  2533. right = radius;
  2534. top = right / ratio;
  2535. } else {
  2536. top = radius;
  2537. right = heightRatio;
  2538. }
  2539. return Math.max(right, top) * 1.50;
  2540. }
  2541. var MINIMUM_ZOOM = 100.0;
  2542. function adjustBoundingSphereOffset(camera, boundingSphere, offset) {
  2543. if (!defined(offset)) {
  2544. offset = HeadingPitchRange.clone(Camera.DEFAULT_OFFSET);
  2545. }
  2546. var minimumZoom = camera._scene.screenSpaceCameraController.minimumZoomDistance;
  2547. var maximumZoom = camera._scene.screenSpaceCameraController.maximumZoomDistance;
  2548. var range = offset.range;
  2549. if (!defined(range) || range === 0.0) {
  2550. var radius = boundingSphere.radius;
  2551. if (radius === 0.0) {
  2552. offset.range = MINIMUM_ZOOM;
  2553. } else if (camera.frustum instanceof OrthographicFrustum || camera._mode === SceneMode.SCENE2D) {
  2554. offset.range = distanceToBoundingSphere2D(camera, radius);
  2555. } else {
  2556. offset.range = distanceToBoundingSphere3D(camera, radius);
  2557. }
  2558. offset.range = CesiumMath.clamp(offset.range, minimumZoom, maximumZoom);
  2559. }
  2560. return offset;
  2561. }
  2562. /**
  2563. * Sets the camera so that the current view contains the provided bounding sphere.
  2564. *
  2565. * <p>The offset is heading/pitch/range in the local east-north-up reference frame centered at the center of the bounding sphere.
  2566. * The heading and the pitch angles are defined in the local east-north-up reference frame.
  2567. * The heading is the angle from y axis and increasing towards the x axis. Pitch is the rotation from the xy-plane. Positive pitch
  2568. * angles are below the plane. Negative pitch angles are above the plane. The range is the distance from the center. If the range is
  2569. * zero, a range will be computed such that the whole bounding sphere is visible.</p>
  2570. *
  2571. * <p>In 2D, there must be a top down view. The camera will be placed above the target looking down. The height above the
  2572. * target will be the range. The heading will be determined from the offset. If the heading cannot be
  2573. * determined from the offset, the heading will be north.</p>
  2574. *
  2575. * @param {BoundingSphere} boundingSphere The bounding sphere to view, in world coordinates.
  2576. * @param {HeadingPitchRange} [offset] The offset from the target in the local east-north-up reference frame centered at the target.
  2577. *
  2578. * @exception {DeveloperError} viewBoundingSphere is not supported while morphing.
  2579. */
  2580. Camera.prototype.viewBoundingSphere = function(boundingSphere, offset) {
  2581. //>>includeStart('debug', pragmas.debug);
  2582. if (!defined(boundingSphere)) {
  2583. throw new DeveloperError('boundingSphere is required.');
  2584. }
  2585. if (this._mode === SceneMode.MORPHING) {
  2586. throw new DeveloperError('viewBoundingSphere is not supported while morphing.');
  2587. }
  2588. //>>includeEnd('debug');
  2589. offset = adjustBoundingSphereOffset(this, boundingSphere, offset);
  2590. this.lookAt(boundingSphere.center, offset);
  2591. };
  2592. var scratchflyToBoundingSphereTransform = new Matrix4();
  2593. var scratchflyToBoundingSphereDestination = new Cartesian3();
  2594. var scratchflyToBoundingSphereDirection = new Cartesian3();
  2595. var scratchflyToBoundingSphereUp = new Cartesian3();
  2596. var scratchflyToBoundingSphereRight = new Cartesian3();
  2597. var scratchFlyToBoundingSphereCart4 = new Cartesian4();
  2598. var scratchFlyToBoundingSphereQuaternion = new Quaternion();
  2599. var scratchFlyToBoundingSphereMatrix3 = new Matrix3();
  2600. /**
  2601. * Flies the camera to a location where the current view contains the provided bounding sphere.
  2602. *
  2603. * <p> The offset is heading/pitch/range in the local east-north-up reference frame centered at the center of the bounding sphere.
  2604. * The heading and the pitch angles are defined in the local east-north-up reference frame.
  2605. * The heading is the angle from y axis and increasing towards the x axis. Pitch is the rotation from the xy-plane. Positive pitch
  2606. * angles are below the plane. Negative pitch angles are above the plane. The range is the distance from the center. If the range is
  2607. * zero, a range will be computed such that the whole bounding sphere is visible.</p>
  2608. *
  2609. * <p>In 2D and Columbus View, there must be a top down view. The camera will be placed above the target looking down. The height above the
  2610. * target will be the range. The heading will be aligned to local north.</p>
  2611. *
  2612. * @param {BoundingSphere} boundingSphere The bounding sphere to view, in world coordinates.
  2613. * @param {Object} [options] Object with the following properties:
  2614. * @param {Number} [options.duration] The duration of the flight in seconds. If omitted, Cesium attempts to calculate an ideal duration based on the distance to be traveled by the flight.
  2615. * @param {HeadingPitchRange} [options.offset] The offset from the target in the local east-north-up reference frame centered at the target.
  2616. * @param {Camera~FlightCompleteCallback} [options.complete] The function to execute when the flight is complete.
  2617. * @param {Camera~FlightCancelledCallback} [options.cancel] The function to execute if the flight is cancelled.
  2618. * @param {Matrix4} [options.endTransform] Transform matrix representing the reference frame the camera will be in when the flight is completed.
  2619. * @param {Number} [options.maximumHeight] The maximum height at the peak of the flight.
  2620. * @param {Number} [options.pitchAdjustHeight] If camera flyes higher than that value, adjust pitch duiring the flight to look down, and keep Earth in viewport.
  2621. * @param {Number} [options.flyOverLongitude] There are always two ways between 2 points on globe. This option force camera to choose fight direction to fly over that longitude.
  2622. * @param {Number} [options.flyOverLongitudeWeight] Fly over the lon specifyed via flyOverLongitude only if that way is not longer than short way times flyOverLongitudeWeight.
  2623. * @param {EasingFunction|EasingFunction~Callback} [options.easingFunction] Controls how the time is interpolated over the duration of the flight.
  2624. */
  2625. Camera.prototype.flyToBoundingSphere = function(boundingSphere, options) {
  2626. //>>includeStart('debug', pragmas.debug);
  2627. if (!defined(boundingSphere)) {
  2628. throw new DeveloperError('boundingSphere is required.');
  2629. }
  2630. //>>includeEnd('debug');
  2631. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  2632. var scene2D = this._mode === SceneMode.SCENE2D || this._mode === SceneMode.COLUMBUS_VIEW;
  2633. this._setTransform(Matrix4.IDENTITY);
  2634. var offset = adjustBoundingSphereOffset(this, boundingSphere, options.offset);
  2635. var position;
  2636. if (scene2D) {
  2637. position = Cartesian3.multiplyByScalar(Cartesian3.UNIT_Z, offset.range, scratchflyToBoundingSphereDestination);
  2638. } else {
  2639. position = offsetFromHeadingPitchRange(offset.heading, offset.pitch, offset.range);
  2640. }
  2641. var transform = Transforms.eastNorthUpToFixedFrame(boundingSphere.center, Ellipsoid.WGS84, scratchflyToBoundingSphereTransform);
  2642. Matrix4.multiplyByPoint(transform, position, position);
  2643. var direction;
  2644. var up;
  2645. if (!scene2D) {
  2646. direction = Cartesian3.subtract(boundingSphere.center, position, scratchflyToBoundingSphereDirection);
  2647. Cartesian3.normalize(direction, direction);
  2648. up = Matrix4.multiplyByPointAsVector(transform, Cartesian3.UNIT_Z, scratchflyToBoundingSphereUp);
  2649. if (1.0 - Math.abs(Cartesian3.dot(direction, up)) < CesiumMath.EPSILON6) {
  2650. var rotateQuat = Quaternion.fromAxisAngle(direction, offset.heading, scratchFlyToBoundingSphereQuaternion);
  2651. var rotation = Matrix3.fromQuaternion(rotateQuat, scratchFlyToBoundingSphereMatrix3);
  2652. Cartesian3.fromCartesian4(Matrix4.getColumn(transform, 1, scratchFlyToBoundingSphereCart4), up);
  2653. Matrix3.multiplyByVector(rotation, up, up);
  2654. }
  2655. var right = Cartesian3.cross(direction, up, scratchflyToBoundingSphereRight);
  2656. Cartesian3.cross(right, direction, up);
  2657. Cartesian3.normalize(up, up);
  2658. }
  2659. this.flyTo({
  2660. destination : position,
  2661. orientation : {
  2662. direction : direction,
  2663. up : up
  2664. },
  2665. duration : options.duration,
  2666. complete : options.complete,
  2667. cancel : options.cancel,
  2668. endTransform : options.endTransform,
  2669. maximumHeight : options.maximumHeight,
  2670. easingFunction : options.easingFunction,
  2671. flyOverLongitude : options.flyOverLongitude,
  2672. flyOverLongitudeWeight : options.flyOverLongitudeWeight,
  2673. pitchAdjustHeight : options.pitchAdjustHeight
  2674. });
  2675. };
  2676. var scratchCartesian3_1 = new Cartesian3();
  2677. var scratchCartesian3_2 = new Cartesian3();
  2678. var scratchCartesian3_3 = new Cartesian3();
  2679. var scratchCartesian3_4 = new Cartesian3();
  2680. var horizonPoints = [new Cartesian3(), new Cartesian3(), new Cartesian3(), new Cartesian3()];
  2681. function computeHorizonQuad(camera, ellipsoid) {
  2682. var radii = ellipsoid.radii;
  2683. var p = camera.positionWC;
  2684. // Find the corresponding position in the scaled space of the ellipsoid.
  2685. var q = Cartesian3.multiplyComponents(ellipsoid.oneOverRadii, p, scratchCartesian3_1);
  2686. var qMagnitude = Cartesian3.magnitude(q);
  2687. var qUnit = Cartesian3.normalize(q, scratchCartesian3_2);
  2688. // Determine the east and north directions at q.
  2689. var eUnit;
  2690. var nUnit;
  2691. if (Cartesian3.equalsEpsilon(qUnit, Cartesian3.UNIT_Z, CesiumMath.EPSILON10)) {
  2692. eUnit = new Cartesian3(0, 1, 0);
  2693. nUnit = new Cartesian3(0, 0, 1);
  2694. } else {
  2695. eUnit = Cartesian3.normalize(Cartesian3.cross(Cartesian3.UNIT_Z, qUnit, scratchCartesian3_3), scratchCartesian3_3);
  2696. nUnit = Cartesian3.normalize(Cartesian3.cross(qUnit, eUnit, scratchCartesian3_4), scratchCartesian3_4);
  2697. }
  2698. // Determine the radius of the 'limb' of the ellipsoid.
  2699. var wMagnitude = Math.sqrt(Cartesian3.magnitudeSquared(q) - 1.0);
  2700. // Compute the center and offsets.
  2701. var center = Cartesian3.multiplyByScalar(qUnit, 1.0 / qMagnitude, scratchCartesian3_1);
  2702. var scalar = wMagnitude / qMagnitude;
  2703. var eastOffset = Cartesian3.multiplyByScalar(eUnit, scalar, scratchCartesian3_2);
  2704. var northOffset = Cartesian3.multiplyByScalar(nUnit, scalar, scratchCartesian3_3);
  2705. // A conservative measure for the longitudes would be to use the min/max longitudes of the bounding frustum.
  2706. var upperLeft = Cartesian3.add(center, northOffset, horizonPoints[0]);
  2707. Cartesian3.subtract(upperLeft, eastOffset, upperLeft);
  2708. Cartesian3.multiplyComponents(radii, upperLeft, upperLeft);
  2709. var lowerLeft = Cartesian3.subtract(center, northOffset, horizonPoints[1]);
  2710. Cartesian3.subtract(lowerLeft, eastOffset, lowerLeft);
  2711. Cartesian3.multiplyComponents(radii, lowerLeft, lowerLeft);
  2712. var lowerRight = Cartesian3.subtract(center, northOffset, horizonPoints[2]);
  2713. Cartesian3.add(lowerRight, eastOffset, lowerRight);
  2714. Cartesian3.multiplyComponents(radii, lowerRight, lowerRight);
  2715. var upperRight = Cartesian3.add(center, northOffset, horizonPoints[3]);
  2716. Cartesian3.add(upperRight, eastOffset, upperRight);
  2717. Cartesian3.multiplyComponents(radii, upperRight, upperRight);
  2718. return horizonPoints;
  2719. }
  2720. var scratchPickCartesian2 = new Cartesian2();
  2721. var scratchRectCartesian = new Cartesian3();
  2722. var cartoArray = [new Cartographic(), new Cartographic(), new Cartographic(), new Cartographic()];
  2723. function addToResult(x, y, index, camera, ellipsoid, computedHorizonQuad) {
  2724. scratchPickCartesian2.x = x;
  2725. scratchPickCartesian2.y = y;
  2726. var r = camera.pickEllipsoid(scratchPickCartesian2, ellipsoid, scratchRectCartesian);
  2727. if (defined(r)) {
  2728. cartoArray[index] = ellipsoid.cartesianToCartographic(r, cartoArray[index]);
  2729. return 1;
  2730. }
  2731. cartoArray[index] = ellipsoid.cartesianToCartographic(computedHorizonQuad[index], cartoArray[index]);
  2732. return 0;
  2733. }
  2734. /**
  2735. * Computes the approximate visible rectangle on the ellipsoid.
  2736. *
  2737. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid that you want to know the visible region.
  2738. * @param {Rectangle} [result] The rectangle in which to store the result
  2739. *
  2740. * @returns {Rectangle|undefined} The visible rectangle or undefined if the ellipsoid isn't visible at all.
  2741. */
  2742. Camera.prototype.computeViewRectangle = function(ellipsoid, result) {
  2743. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  2744. var cullingVolume = this.frustum.computeCullingVolume(this.positionWC, this.directionWC, this.upWC);
  2745. var boundingSphere = new BoundingSphere(Cartesian3.ZERO, ellipsoid.maximumRadius);
  2746. var visibility = cullingVolume.computeVisibility(boundingSphere);
  2747. if (visibility === Intersect.OUTSIDE) {
  2748. return undefined;
  2749. }
  2750. var canvas = this._scene.canvas;
  2751. var width = canvas.clientWidth;
  2752. var height = canvas.clientHeight;
  2753. var successfulPickCount = 0;
  2754. var computedHorizonQuad = computeHorizonQuad(this, ellipsoid);
  2755. successfulPickCount += addToResult(0, 0, 0, this, ellipsoid, computedHorizonQuad);
  2756. successfulPickCount += addToResult(0, height, 1, this, ellipsoid, computedHorizonQuad);
  2757. successfulPickCount += addToResult(width, height, 2, this, ellipsoid, computedHorizonQuad);
  2758. successfulPickCount += addToResult(width, 0, 3, this, ellipsoid, computedHorizonQuad);
  2759. if (successfulPickCount < 2) {
  2760. // If we have space non-globe in 3 or 4 corners then return the whole globe
  2761. return Rectangle.MAX_VALUE;
  2762. }
  2763. result = Rectangle.fromCartographicArray(cartoArray, result);
  2764. // Detect if we go over the poles
  2765. var distance = 0;
  2766. var lastLon = cartoArray[3].longitude;
  2767. for (var i = 0; i < 4; ++i) {
  2768. var lon = cartoArray[i].longitude;
  2769. var diff = Math.abs(lon - lastLon);
  2770. if (diff > CesiumMath.PI) {
  2771. // Crossed the dateline
  2772. distance += CesiumMath.TWO_PI - diff;
  2773. } else {
  2774. distance += diff;
  2775. }
  2776. lastLon = lon;
  2777. }
  2778. // We are over one of the poles so adjust the rectangle accordingly
  2779. if (CesiumMath.equalsEpsilon(Math.abs(distance), CesiumMath.TWO_PI, CesiumMath.EPSILON9)) {
  2780. result.west = -CesiumMath.PI;
  2781. result.east = CesiumMath.PI;
  2782. if (cartoArray[0].latitude >= 0.0) {
  2783. result.north = CesiumMath.PI_OVER_TWO;
  2784. } else {
  2785. result.south = -CesiumMath.PI_OVER_TWO;
  2786. }
  2787. }
  2788. return result;
  2789. };
  2790. /**
  2791. * Switches the frustum/projection to perspective.
  2792. *
  2793. * This function is a no-op in 2D which must always be orthographic.
  2794. */
  2795. Camera.prototype.switchToPerspectiveFrustum = function() {
  2796. if (this._mode === SceneMode.SCENE2D || this.frustum instanceof PerspectiveFrustum) {
  2797. return;
  2798. }
  2799. var scene = this._scene;
  2800. this.frustum = new PerspectiveFrustum();
  2801. this.frustum.aspectRatio = scene.drawingBufferWidth / scene.drawingBufferHeight;
  2802. this.frustum.fov = CesiumMath.toRadians(60.0);
  2803. };
  2804. /**
  2805. * Switches the frustum/projection to orthographic.
  2806. *
  2807. * This function is a no-op in 2D which will always be orthographic.
  2808. */
  2809. Camera.prototype.switchToOrthographicFrustum = function() {
  2810. if (this._mode === SceneMode.SCENE2D || this.frustum instanceof OrthographicFrustum) {
  2811. return;
  2812. }
  2813. var scene = this._scene;
  2814. this.frustum = new OrthographicFrustum();
  2815. this.frustum.aspectRatio = scene.drawingBufferWidth / scene.drawingBufferHeight;
  2816. // It doesn't matter what we set this to. The adjust below will correct the width based on the camera position.
  2817. this.frustum.width = Cartesian3.magnitude(this.position);
  2818. // Check the projection matrix. It will always be defined, but we need to force an off-center update.
  2819. var projectionMatrix = this.frustum.projectionMatrix;
  2820. if (defined(projectionMatrix)) {
  2821. this._adjustOrthographicFrustum(true);
  2822. }
  2823. };
  2824. /**
  2825. * @private
  2826. */
  2827. Camera.clone = function(camera, result) {
  2828. if (!defined(result)) {
  2829. result = new Camera(camera._scene);
  2830. }
  2831. Cartesian3.clone(camera.position, result.position);
  2832. Cartesian3.clone(camera.direction, result.direction);
  2833. Cartesian3.clone(camera.up, result.up);
  2834. Cartesian3.clone(camera.right, result.right);
  2835. Matrix4.clone(camera._transform, result.transform);
  2836. result._transformChanged = true;
  2837. result.frustum = camera.frustum.clone();
  2838. return result;
  2839. };
  2840. /**
  2841. * A function that will execute when a flight completes.
  2842. * @callback Camera~FlightCompleteCallback
  2843. */
  2844. /**
  2845. * A function that will execute when a flight is cancelled.
  2846. * @callback Camera~FlightCancelledCallback
  2847. */
  2848. export default Camera;