| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989 |
- import BoundingSphere from "../Core/BoundingSphere.js";
- import Cartesian2 from "../Core/Cartesian2.js";
- import Cartesian3 from "../Core/Cartesian3.js";
- import Cartesian4 from "../Core/Cartesian4.js";
- import Cartographic from "../Core/Cartographic.js";
- import Frozen from "../Core/Frozen.js";
- import defined from "../Core/defined.js";
- import DeveloperError from "../Core/DeveloperError.js";
- import EasingFunction from "../Core/EasingFunction.js";
- import Ellipsoid from "../Core/Ellipsoid.js";
- import EllipsoidGeodesic from "../Core/EllipsoidGeodesic.js";
- import Event from "../Core/Event.js";
- import getTimestamp from "../Core/getTimestamp.js";
- import HeadingPitchRange from "../Core/HeadingPitchRange.js";
- import HeadingPitchRoll from "../Core/HeadingPitchRoll.js";
- import Intersect from "../Core/Intersect.js";
- import IntersectionTests from "../Core/IntersectionTests.js";
- import CesiumMath from "../Core/Math.js";
- import Matrix3 from "../Core/Matrix3.js";
- import Matrix4 from "../Core/Matrix4.js";
- import OrthographicFrustum from "../Core/OrthographicFrustum.js";
- import OrthographicOffCenterFrustum from "../Core/OrthographicOffCenterFrustum.js";
- import PerspectiveFrustum from "../Core/PerspectiveFrustum.js";
- import Quaternion from "../Core/Quaternion.js";
- import Ray from "../Core/Ray.js";
- import Rectangle from "../Core/Rectangle.js";
- import Transforms from "../Core/Transforms.js";
- import CameraFlightPath from "./CameraFlightPath.js";
- import MapMode2D from "./MapMode2D.js";
- import SceneMode from "./SceneMode.js";
-
- /**
- * @typedef {object} DirectionUp
- *
- * An orientation given by a pair of unit vectors
- *
- * @property {Cartesian3} direction The unit "direction" vector
- * @property {Cartesian3} up The unit "up" vector
- **/
- /**
- * @typedef {object} HeadingPitchRollValues
- *
- * An orientation given by numeric heading, pitch, and roll
- *
- * @property {number} [heading=0.0] The heading in radians
- * @property {number} [pitch=-CesiumMath.PI_OVER_TWO] The pitch in radians
- * @property {number} [roll=0.0] The roll in radians
- **/
-
- /**
- * The camera is defined by a position, orientation, and view frustum.
- * <br /><br />
- * The orientation forms an orthonormal basis with a view, up and right = view x up unit vectors.
- * <br /><br />
- * The viewing frustum is defined by 6 planes.
- * Each plane is represented by a {@link Cartesian4} object, where the x, y, and z components
- * define the unit vector normal to the plane, and the w component is the distance of the
- * plane from the origin/camera position.
- *
- * @alias Camera
- *
- * @constructor
- *
- * @param {Scene} scene The scene.
- *
- * @demo {@link https://sandcastle.cesium.com/index.html?id=camera|Cesium Sandcastle Camera Demo}
- * @demo {@link https://sandcastle.cesium.com/index.html?id=camera-tutorial|Cesium Sandcastle Camera Tutorial Example}
- * @demo {@link https://cesium.com/learn/cesiumjs-learn/cesiumjs-camera|Camera Tutorial}
- *
- * @example
- * // Create a camera looking down the negative z-axis, positioned at the origin,
- * // with a field of view of 60 degrees, and 1:1 aspect ratio.
- * const camera = new Cesium.Camera(scene);
- * camera.position = new Cesium.Cartesian3();
- * camera.direction = Cesium.Cartesian3.negate(Cesium.Cartesian3.UNIT_Z, new Cesium.Cartesian3());
- * camera.up = Cesium.Cartesian3.clone(Cesium.Cartesian3.UNIT_Y);
- * camera.frustum.fov = Cesium.Math.PI_OVER_THREE;
- * camera.frustum.near = 1.0;
- * camera.frustum.far = 2.0;
- */
- function Camera(scene) {
- //>>includeStart('debug', pragmas.debug);
- if (!defined(scene)) {
- throw new DeveloperError("scene is required.");
- }
- //>>includeEnd('debug');
- this._scene = scene;
-
- this._transform = Matrix4.clone(Matrix4.IDENTITY);
- this._invTransform = Matrix4.clone(Matrix4.IDENTITY);
- this._actualTransform = Matrix4.clone(Matrix4.IDENTITY);
- this._actualInvTransform = Matrix4.clone(Matrix4.IDENTITY);
- this._transformChanged = false;
-
- /**
- * The position of the camera.
- *
- * @type {Cartesian3}
- */
- this.position = new Cartesian3();
- this._position = new Cartesian3();
- this._positionWC = new Cartesian3();
- this._positionCartographic = new Cartographic();
- this._oldPositionWC = undefined;
-
- /**
- * The position delta magnitude.
- *
- * @private
- */
- this.positionWCDeltaMagnitude = 0.0;
-
- /**
- * The position delta magnitude last frame.
- *
- * @private
- */
- this.positionWCDeltaMagnitudeLastFrame = 0.0;
-
- /**
- * How long in seconds since the camera has stopped moving
- *
- * @private
- */
- this.timeSinceMoved = 0.0;
- this._lastMovedTimestamp = 0.0;
-
- /**
- * The view direction of the camera.
- *
- * @type {Cartesian3}
- */
- this.direction = new Cartesian3();
- this._direction = new Cartesian3();
- this._directionWC = new Cartesian3();
-
- /**
- * The up direction of the camera.
- *
- * @type {Cartesian3}
- */
- this.up = new Cartesian3();
- this._up = new Cartesian3();
- this._upWC = new Cartesian3();
-
- /**
- * The right direction of the camera.
- *
- * @type {Cartesian3}
- */
- this.right = new Cartesian3();
- this._right = new Cartesian3();
- this._rightWC = new Cartesian3();
-
- /**
- * The region of space in view.
- *
- * @type {PerspectiveFrustum|PerspectiveOffCenterFrustum|OrthographicFrustum}
- * @default PerspectiveFrustum()
- *
- * @see PerspectiveFrustum
- * @see PerspectiveOffCenterFrustum
- * @see OrthographicFrustum
- */
- this.frustum = new PerspectiveFrustum();
- this.frustum.aspectRatio =
- scene.drawingBufferWidth / scene.drawingBufferHeight;
- this.frustum.fov = CesiumMath.toRadians(60.0);
-
- /**
- * The default amount to move the camera when an argument is not
- * provided to the move methods.
- * @type {number}
- * @default 100000.0;
- */
- this.defaultMoveAmount = 100000.0;
- /**
- * The default amount to rotate the camera when an argument is not
- * provided to the look methods.
- * @type {number}
- * @default Math.PI / 60.0
- */
- this.defaultLookAmount = Math.PI / 60.0;
- /**
- * The default amount to rotate the camera when an argument is not
- * provided to the rotate methods.
- * @type {number}
- * @default Math.PI / 3600.0
- */
- this.defaultRotateAmount = Math.PI / 3600.0;
- /**
- * The default amount to move the camera when an argument is not
- * provided to the zoom methods.
- * @type {number}
- * @default 100000.0;
- */
- this.defaultZoomAmount = 100000.0;
- /**
- * If set, the camera will not be able to rotate past this axis in either direction.
- * @type {Cartesian3 | undefined}
- * @default undefined
- */
- this.constrainedAxis = undefined;
- /**
- * The factor multiplied by the the map size used to determine where to clamp the camera position
- * when zooming out from the surface. The default is 1.5. Only valid for 2D and the map is rotatable.
- * @type {number}
- * @default 1.5
- */
- this.maximumZoomFactor = 1.5;
-
- this._moveStart = new Event();
- this._moveEnd = new Event();
-
- this._changed = new Event();
- this._changedPosition = undefined;
- this._changedDirection = undefined;
- this._changedFrustum = undefined;
- this._changedHeading = undefined;
- this._changedRoll = undefined;
-
- /**
- * 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.
- * @type {number}
- * @default 0.5
- */
- this.percentageChanged = 0.5;
-
- this._viewMatrix = new Matrix4();
- this._invViewMatrix = new Matrix4();
- updateViewMatrix(this);
-
- this._mode = SceneMode.SCENE3D;
- this._modeChanged = true;
- const projection = scene.mapProjection;
- this._projection = projection;
- this._maxCoord = projection.project(
- new Cartographic(Math.PI, CesiumMath.PI_OVER_TWO),
- );
- this._max2Dfrustum = undefined;
-
- // set default view
- rectangleCameraPosition3D(
- this,
- Camera.DEFAULT_VIEW_RECTANGLE,
- this.position,
- true,
- );
-
- let mag = Cartesian3.magnitude(this.position);
- mag += mag * Camera.DEFAULT_VIEW_FACTOR;
- Cartesian3.normalize(this.position, this.position);
- Cartesian3.multiplyByScalar(this.position, mag, this.position);
- }
-
- /**
- * @private
- */
- Camera.TRANSFORM_2D = new Matrix4(
- 0.0,
- 0.0,
- 1.0,
- 0.0,
- 1.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 1.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 1.0,
- );
-
- /**
- * @private
- */
- Camera.TRANSFORM_2D_INVERSE = Matrix4.inverseTransformation(
- Camera.TRANSFORM_2D,
- new Matrix4(),
- );
-
- /**
- * The default rectangle the camera will view on creation.
- * @type Rectangle
- */
- Camera.DEFAULT_VIEW_RECTANGLE = Rectangle.fromDegrees(
- -95.0,
- -20.0,
- -70.0,
- 90.0,
- );
-
- /**
- * A scalar to multiply to the camera position and add it back after setting the camera to view the rectangle.
- * A value of zero means the camera will view the entire {@link Camera#DEFAULT_VIEW_RECTANGLE}, a value greater than zero
- * will move it further away from the extent, and a value less than zero will move it close to the extent.
- * @type {number}
- */
- Camera.DEFAULT_VIEW_FACTOR = 0.5;
-
- /**
- * The default heading/pitch/range that is used when the camera flies to a location that contains a bounding sphere.
- * @type HeadingPitchRange
- */
- Camera.DEFAULT_OFFSET = new HeadingPitchRange(
- 0.0,
- -CesiumMath.PI_OVER_FOUR,
- 0.0,
- );
-
- function updateViewMatrix(camera) {
- Matrix4.computeView(
- camera._position,
- camera._direction,
- camera._up,
- camera._right,
- camera._viewMatrix,
- );
- Matrix4.multiply(
- camera._viewMatrix,
- camera._actualInvTransform,
- camera._viewMatrix,
- );
- Matrix4.inverseTransformation(camera._viewMatrix, camera._invViewMatrix);
- }
-
- function updateCameraDeltas(camera) {
- if (!defined(camera._oldPositionWC)) {
- camera._oldPositionWC = Cartesian3.clone(
- camera.positionWC,
- camera._oldPositionWC,
- );
- } else {
- camera.positionWCDeltaMagnitudeLastFrame = camera.positionWCDeltaMagnitude;
- const delta = Cartesian3.subtract(
- camera.positionWC,
- camera._oldPositionWC,
- camera._oldPositionWC,
- );
- camera.positionWCDeltaMagnitude = Cartesian3.magnitude(delta);
- camera._oldPositionWC = Cartesian3.clone(
- camera.positionWC,
- camera._oldPositionWC,
- );
-
- // Update move timers
- if (camera.positionWCDeltaMagnitude > 0.0) {
- camera.timeSinceMoved = 0.0;
- camera._lastMovedTimestamp = getTimestamp();
- } else {
- camera.timeSinceMoved =
- Math.max(getTimestamp() - camera._lastMovedTimestamp, 0.0) / 1000.0;
- }
- }
- }
-
- /**
- * Checks if there's a camera flight with preload for this camera.
- *
- * @returns {boolean} Whether or not this camera has a current flight with a valid preloadFlightCamera in scene.
- *
- * @private
- *
- */
- Camera.prototype.canPreloadFlight = function () {
- return defined(this._currentFlight) && this._mode !== SceneMode.SCENE2D;
- };
-
- Camera.prototype._updateCameraChanged = function () {
- const camera = this;
-
- updateCameraDeltas(camera);
-
- if (camera._changed.numberOfListeners === 0) {
- return;
- }
-
- const percentageChanged = camera.percentageChanged;
-
- // check heading
- const currentHeading = camera.heading;
-
- if (!defined(camera._changedHeading)) {
- camera._changedHeading = currentHeading;
- }
-
- let headingDelta =
- Math.abs(camera._changedHeading - currentHeading) % CesiumMath.TWO_PI;
- headingDelta =
- headingDelta > CesiumMath.PI
- ? CesiumMath.TWO_PI - headingDelta
- : headingDelta;
-
- // Since delta is computed as the shortest distance between two angles
- // the percentage is relative to the half circle.
- const headingChangedPercentage = headingDelta / Math.PI;
-
- if (headingChangedPercentage > percentageChanged) {
- camera._changedHeading = currentHeading;
- }
-
- // check roll
- const currentRoll = camera.roll;
-
- if (!defined(camera._changedRoll)) {
- camera._changedRoll = currentRoll;
- }
-
- let rollDelta =
- Math.abs(camera._changedRoll - currentRoll) % CesiumMath.TWO_PI;
- rollDelta =
- rollDelta > CesiumMath.PI ? CesiumMath.TWO_PI - rollDelta : rollDelta;
-
- // Since delta is computed as the shortest distance between two angles
- // the percentage is relative to the half circle.
- const rollChangedPercentage = rollDelta / Math.PI;
-
- if (rollChangedPercentage > percentageChanged) {
- camera._changedRoll = currentRoll;
- }
- if (
- rollChangedPercentage > percentageChanged ||
- headingChangedPercentage > percentageChanged
- ) {
- camera._changed.raiseEvent(
- Math.max(rollChangedPercentage, headingChangedPercentage),
- );
- }
- if (camera._mode === SceneMode.SCENE2D) {
- if (!defined(camera._changedFrustum)) {
- camera._changedPosition = Cartesian3.clone(
- camera.position,
- camera._changedPosition,
- );
- camera._changedFrustum = camera.frustum.clone();
- return;
- }
-
- const position = camera.position;
- const lastPosition = camera._changedPosition;
-
- const frustum = camera.frustum;
- const lastFrustum = camera._changedFrustum;
-
- const x0 = position.x + frustum.left;
- const x1 = position.x + frustum.right;
- const x2 = lastPosition.x + lastFrustum.left;
- const x3 = lastPosition.x + lastFrustum.right;
-
- const y0 = position.y + frustum.bottom;
- const y1 = position.y + frustum.top;
- const y2 = lastPosition.y + lastFrustum.bottom;
- const y3 = lastPosition.y + lastFrustum.top;
-
- const leftX = Math.max(x0, x2);
- const rightX = Math.min(x1, x3);
- const bottomY = Math.max(y0, y2);
- const topY = Math.min(y1, y3);
-
- let areaPercentage;
- if (leftX >= rightX || bottomY >= y1) {
- areaPercentage = 1.0;
- } else {
- let areaRef = lastFrustum;
- if (x0 < x2 && x1 > x3 && y0 < y2 && y1 > y3) {
- areaRef = frustum;
- }
- areaPercentage =
- 1.0 -
- ((rightX - leftX) * (topY - bottomY)) /
- ((areaRef.right - areaRef.left) * (areaRef.top - areaRef.bottom));
- }
-
- if (areaPercentage > percentageChanged) {
- camera._changed.raiseEvent(areaPercentage);
- camera._changedPosition = Cartesian3.clone(
- camera.position,
- camera._changedPosition,
- );
- camera._changedFrustum = camera.frustum.clone(camera._changedFrustum);
- }
- return;
- }
-
- if (!defined(camera._changedDirection)) {
- camera._changedPosition = Cartesian3.clone(
- camera.positionWC,
- camera._changedPosition,
- );
- camera._changedDirection = Cartesian3.clone(
- camera.directionWC,
- camera._changedDirection,
- );
- return;
- }
-
- const dirAngle = CesiumMath.acosClamped(
- Cartesian3.dot(camera.directionWC, camera._changedDirection),
- );
-
- let dirPercentage;
- if (defined(camera.frustum.fovy)) {
- dirPercentage = dirAngle / (camera.frustum.fovy * 0.5);
- } else {
- dirPercentage = dirAngle;
- }
-
- const distance = Cartesian3.distance(
- camera.positionWC,
- camera._changedPosition,
- );
- const heightPercentage = distance / camera.positionCartographic.height;
-
- if (
- dirPercentage > percentageChanged ||
- heightPercentage > percentageChanged
- ) {
- camera._changed.raiseEvent(Math.max(dirPercentage, heightPercentage));
- camera._changedPosition = Cartesian3.clone(
- camera.positionWC,
- camera._changedPosition,
- );
- camera._changedDirection = Cartesian3.clone(
- camera.directionWC,
- camera._changedDirection,
- );
- }
- };
-
- function convertTransformForColumbusView(camera) {
- Transforms.basisTo2D(
- camera._projection,
- camera._transform,
- camera._actualTransform,
- );
- }
-
- const scratchCartographic = new Cartographic();
- const scratchCartesian3Projection = new Cartesian3();
- const scratchCartesian3 = new Cartesian3();
- const scratchCartesian4Origin = new Cartesian4();
- const scratchCartesian4NewOrigin = new Cartesian4();
- const scratchCartesian4NewXAxis = new Cartesian4();
- const scratchCartesian4NewYAxis = new Cartesian4();
- const scratchCartesian4NewZAxis = new Cartesian4();
-
- function convertTransformFor2D(camera) {
- const projection = camera._projection;
- const ellipsoid = projection.ellipsoid;
-
- const origin = Matrix4.getColumn(
- camera._transform,
- 3,
- scratchCartesian4Origin,
- );
- const cartographic = ellipsoid.cartesianToCartographic(
- origin,
- scratchCartographic,
- );
-
- const projectedPosition = projection.project(
- cartographic,
- scratchCartesian3Projection,
- );
- const newOrigin = scratchCartesian4NewOrigin;
- newOrigin.x = projectedPosition.z;
- newOrigin.y = projectedPosition.x;
- newOrigin.z = projectedPosition.y;
- newOrigin.w = 1.0;
-
- const newZAxis = Cartesian4.clone(
- Cartesian4.UNIT_X,
- scratchCartesian4NewZAxis,
- );
-
- const xAxis = Cartesian4.add(
- Matrix4.getColumn(camera._transform, 0, scratchCartesian3),
- origin,
- scratchCartesian3,
- );
- ellipsoid.cartesianToCartographic(xAxis, cartographic);
-
- projection.project(cartographic, projectedPosition);
- const newXAxis = scratchCartesian4NewXAxis;
- newXAxis.x = projectedPosition.z;
- newXAxis.y = projectedPosition.x;
- newXAxis.z = projectedPosition.y;
- newXAxis.w = 0.0;
-
- Cartesian3.subtract(newXAxis, newOrigin, newXAxis);
- newXAxis.x = 0.0;
-
- const newYAxis = scratchCartesian4NewYAxis;
- if (Cartesian3.magnitudeSquared(newXAxis) > CesiumMath.EPSILON10) {
- Cartesian3.cross(newZAxis, newXAxis, newYAxis);
- } else {
- const yAxis = Cartesian4.add(
- Matrix4.getColumn(camera._transform, 1, scratchCartesian3),
- origin,
- scratchCartesian3,
- );
- ellipsoid.cartesianToCartographic(yAxis, cartographic);
-
- projection.project(cartographic, projectedPosition);
- newYAxis.x = projectedPosition.z;
- newYAxis.y = projectedPosition.x;
- newYAxis.z = projectedPosition.y;
- newYAxis.w = 0.0;
-
- Cartesian3.subtract(newYAxis, newOrigin, newYAxis);
- newYAxis.x = 0.0;
-
- if (Cartesian3.magnitudeSquared(newYAxis) < CesiumMath.EPSILON10) {
- Cartesian4.clone(Cartesian4.UNIT_Y, newXAxis);
- Cartesian4.clone(Cartesian4.UNIT_Z, newYAxis);
- }
- }
-
- Cartesian3.cross(newYAxis, newZAxis, newXAxis);
- Cartesian3.normalize(newXAxis, newXAxis);
- Cartesian3.cross(newZAxis, newXAxis, newYAxis);
- Cartesian3.normalize(newYAxis, newYAxis);
-
- Matrix4.setColumn(
- camera._actualTransform,
- 0,
- newXAxis,
- camera._actualTransform,
- );
- Matrix4.setColumn(
- camera._actualTransform,
- 1,
- newYAxis,
- camera._actualTransform,
- );
- Matrix4.setColumn(
- camera._actualTransform,
- 2,
- newZAxis,
- camera._actualTransform,
- );
- Matrix4.setColumn(
- camera._actualTransform,
- 3,
- newOrigin,
- camera._actualTransform,
- );
- }
-
- const scratchCartesian = new Cartesian3();
-
- function updateMembers(camera) {
- const mode = camera._mode;
-
- let heightChanged = false;
- let height = 0.0;
- if (mode === SceneMode.SCENE2D) {
- height = camera.frustum.right - camera.frustum.left;
- heightChanged = height !== camera._positionCartographic.height;
- }
-
- let position = camera._position;
- const positionChanged =
- !Cartesian3.equals(position, camera.position) || heightChanged;
- if (positionChanged) {
- position = Cartesian3.clone(camera.position, camera._position);
- }
-
- let direction = camera._direction;
- const directionChanged = !Cartesian3.equals(direction, camera.direction);
- if (directionChanged) {
- Cartesian3.normalize(camera.direction, camera.direction);
- direction = Cartesian3.clone(camera.direction, camera._direction);
- }
-
- let up = camera._up;
- const upChanged = !Cartesian3.equals(up, camera.up);
- if (upChanged) {
- Cartesian3.normalize(camera.up, camera.up);
- up = Cartesian3.clone(camera.up, camera._up);
- }
-
- let right = camera._right;
- const rightChanged = !Cartesian3.equals(right, camera.right);
- if (rightChanged) {
- Cartesian3.normalize(camera.right, camera.right);
- right = Cartesian3.clone(camera.right, camera._right);
- }
-
- const transformChanged = camera._transformChanged || camera._modeChanged;
- camera._transformChanged = false;
-
- if (transformChanged) {
- Matrix4.inverseTransformation(camera._transform, camera._invTransform);
-
- if (
- camera._mode === SceneMode.COLUMBUS_VIEW ||
- camera._mode === SceneMode.SCENE2D
- ) {
- if (Matrix4.equals(Matrix4.IDENTITY, camera._transform)) {
- Matrix4.clone(Camera.TRANSFORM_2D, camera._actualTransform);
- } else if (camera._mode === SceneMode.COLUMBUS_VIEW) {
- convertTransformForColumbusView(camera);
- } else {
- convertTransformFor2D(camera);
- }
- } else {
- Matrix4.clone(camera._transform, camera._actualTransform);
- }
-
- Matrix4.inverseTransformation(
- camera._actualTransform,
- camera._actualInvTransform,
- );
-
- camera._modeChanged = false;
- }
-
- const transform = camera._actualTransform;
-
- if (positionChanged || transformChanged) {
- camera._positionWC = Matrix4.multiplyByPoint(
- transform,
- position,
- camera._positionWC,
- );
-
- // Compute the Cartographic position of the camera.
- if (mode === SceneMode.SCENE3D || mode === SceneMode.MORPHING) {
- camera._positionCartographic =
- camera._projection.ellipsoid.cartesianToCartographic(
- camera._positionWC,
- camera._positionCartographic,
- );
- } else {
- // The camera position is expressed in the 2D coordinate system where the Y axis is to the East,
- // the Z axis is to the North, and the X axis is out of the map. Express them instead in the ENU axes where
- // X is to the East, Y is to the North, and Z is out of the local horizontal plane.
- const positionENU = scratchCartesian;
- positionENU.x = camera._positionWC.y;
- positionENU.y = camera._positionWC.z;
- positionENU.z = camera._positionWC.x;
-
- // In 2D, the camera height is always 12.7 million meters.
- // The apparent height is equal to half the frustum width.
- if (mode === SceneMode.SCENE2D) {
- positionENU.z = height;
- }
-
- camera._projection.unproject(positionENU, camera._positionCartographic);
- }
- }
-
- if (directionChanged || upChanged || rightChanged) {
- const det = Cartesian3.dot(
- direction,
- Cartesian3.cross(up, right, scratchCartesian),
- );
- if (Math.abs(1.0 - det) > CesiumMath.EPSILON2) {
- //orthonormalize axes
- const invUpMag = 1.0 / Cartesian3.magnitudeSquared(up);
- const scalar = Cartesian3.dot(up, direction) * invUpMag;
- const w0 = Cartesian3.multiplyByScalar(
- direction,
- scalar,
- scratchCartesian,
- );
- up = Cartesian3.normalize(
- Cartesian3.subtract(up, w0, camera._up),
- camera._up,
- );
- Cartesian3.clone(up, camera.up);
-
- right = Cartesian3.cross(direction, up, camera._right);
- Cartesian3.clone(right, camera.right);
- }
- }
-
- if (directionChanged || transformChanged) {
- camera._directionWC = Matrix4.multiplyByPointAsVector(
- transform,
- direction,
- camera._directionWC,
- );
- Cartesian3.normalize(camera._directionWC, camera._directionWC);
- }
-
- if (upChanged || transformChanged) {
- camera._upWC = Matrix4.multiplyByPointAsVector(transform, up, camera._upWC);
- Cartesian3.normalize(camera._upWC, camera._upWC);
- }
-
- if (rightChanged || transformChanged) {
- camera._rightWC = Matrix4.multiplyByPointAsVector(
- transform,
- right,
- camera._rightWC,
- );
- Cartesian3.normalize(camera._rightWC, camera._rightWC);
- }
-
- if (
- positionChanged ||
- directionChanged ||
- upChanged ||
- rightChanged ||
- transformChanged
- ) {
- updateViewMatrix(camera);
- }
- }
-
- function getHeading(direction, up) {
- let heading;
- if (
- !CesiumMath.equalsEpsilon(Math.abs(direction.z), 1.0, CesiumMath.EPSILON3)
- ) {
- heading = Math.atan2(direction.y, direction.x) - CesiumMath.PI_OVER_TWO;
- } else {
- heading = Math.atan2(up.y, up.x) - CesiumMath.PI_OVER_TWO;
- }
-
- return CesiumMath.TWO_PI - CesiumMath.zeroToTwoPi(heading);
- }
-
- function getPitch(direction) {
- return CesiumMath.PI_OVER_TWO - CesiumMath.acosClamped(direction.z);
- }
-
- function getRoll(direction, up, right) {
- let roll = 0.0;
- if (
- !CesiumMath.equalsEpsilon(Math.abs(direction.z), 1.0, CesiumMath.EPSILON3)
- ) {
- roll = Math.atan2(-right.z, up.z);
- roll = CesiumMath.zeroToTwoPi(roll + CesiumMath.TWO_PI);
- }
-
- return roll;
- }
-
- const scratchHPRMatrix1 = new Matrix4();
- const scratchHPRMatrix2 = new Matrix4();
-
- Object.defineProperties(Camera.prototype, {
- /**
- * Gets the camera's reference frame. The inverse of this transformation is appended to the view matrix.
- * @memberof Camera.prototype
- *
- * @type {Matrix4}
- * @readonly
- *
- * @default {@link Matrix4.IDENTITY}
- */
- transform: {
- get: function () {
- return this._transform;
- },
- },
-
- /**
- * Gets the inverse camera transform.
- * @memberof Camera.prototype
- *
- * @type {Matrix4}
- * @readonly
- *
- * @default {@link Matrix4.IDENTITY}
- */
- inverseTransform: {
- get: function () {
- updateMembers(this);
- return this._invTransform;
- },
- },
-
- /**
- * Gets the view matrix.
- * @memberof Camera.prototype
- *
- * @type {Matrix4}
- * @readonly
- *
- * @see Camera#inverseViewMatrix
- */
- viewMatrix: {
- get: function () {
- updateMembers(this);
- return this._viewMatrix;
- },
- },
-
- /**
- * Gets the inverse view matrix.
- * @memberof Camera.prototype
- *
- * @type {Matrix4}
- * @readonly
- *
- * @see Camera#viewMatrix
- */
- inverseViewMatrix: {
- get: function () {
- updateMembers(this);
- return this._invViewMatrix;
- },
- },
-
- /**
- * Gets the {@link Cartographic} position of the camera, with longitude and latitude
- * expressed in radians and height in meters. In 2D and Columbus View, it is possible
- * for the returned longitude and latitude to be outside the range of valid longitudes
- * and latitudes when the camera is outside the map.
- * @memberof Camera.prototype
- *
- * @type {Cartographic}
- * @readonly
- */
- positionCartographic: {
- get: function () {
- updateMembers(this);
- return this._positionCartographic;
- },
- },
-
- /**
- * Gets the position of the camera in world coordinates.
- * @memberof Camera.prototype
- *
- * @type {Cartesian3}
- * @readonly
- */
- positionWC: {
- get: function () {
- updateMembers(this);
- return this._positionWC;
- },
- },
-
- /**
- * Gets the view direction of the camera in world coordinates.
- * @memberof Camera.prototype
- *
- * @type {Cartesian3}
- * @readonly
- */
- directionWC: {
- get: function () {
- updateMembers(this);
- return this._directionWC;
- },
- },
-
- /**
- * Gets the up direction of the camera in world coordinates.
- * @memberof Camera.prototype
- *
- * @type {Cartesian3}
- * @readonly
- */
- upWC: {
- get: function () {
- updateMembers(this);
- return this._upWC;
- },
- },
-
- /**
- * Gets the right direction of the camera in world coordinates.
- * @memberof Camera.prototype
- *
- * @type {Cartesian3}
- * @readonly
- */
- rightWC: {
- get: function () {
- updateMembers(this);
- return this._rightWC;
- },
- },
-
- /**
- * Gets the camera heading in radians.
- * @memberof Camera.prototype
- *
- * @type {number}
- * @readonly
- */
- heading: {
- get: function () {
- if (this._mode !== SceneMode.MORPHING) {
- const ellipsoid = this._projection.ellipsoid;
-
- const oldTransform = Matrix4.clone(this._transform, scratchHPRMatrix1);
- const transform = Transforms.eastNorthUpToFixedFrame(
- this.positionWC,
- ellipsoid,
- scratchHPRMatrix2,
- );
- this._setTransform(transform);
-
- const heading = getHeading(this.direction, this.up);
-
- this._setTransform(oldTransform);
-
- return heading;
- }
-
- return undefined;
- },
- },
-
- /**
- * Gets the camera pitch in radians.
- * @memberof Camera.prototype
- *
- * @type {number}
- * @readonly
- */
- pitch: {
- get: function () {
- if (this._mode !== SceneMode.MORPHING) {
- const ellipsoid = this._projection.ellipsoid;
-
- const oldTransform = Matrix4.clone(this._transform, scratchHPRMatrix1);
- const transform = Transforms.eastNorthUpToFixedFrame(
- this.positionWC,
- ellipsoid,
- scratchHPRMatrix2,
- );
- this._setTransform(transform);
-
- const pitch = getPitch(this.direction);
-
- this._setTransform(oldTransform);
-
- return pitch;
- }
-
- return undefined;
- },
- },
-
- /**
- * Gets the camera roll in radians.
- * @memberof Camera.prototype
- *
- * @type {number}
- * @readonly
- */
- roll: {
- get: function () {
- if (this._mode !== SceneMode.MORPHING) {
- const ellipsoid = this._projection.ellipsoid;
-
- const oldTransform = Matrix4.clone(this._transform, scratchHPRMatrix1);
- const transform = Transforms.eastNorthUpToFixedFrame(
- this.positionWC,
- ellipsoid,
- scratchHPRMatrix2,
- );
- this._setTransform(transform);
-
- const roll = getRoll(this.direction, this.up, this.right);
-
- this._setTransform(oldTransform);
-
- return roll;
- }
-
- return undefined;
- },
- },
-
- /**
- * Gets the event that will be raised at when the camera starts to move.
- * @memberof Camera.prototype
- * @type {Event}
- * @readonly
- */
- moveStart: {
- get: function () {
- return this._moveStart;
- },
- },
-
- /**
- * Gets the event that will be raised when the camera has stopped moving.
- * @memberof Camera.prototype
- * @type {Event}
- * @readonly
- */
- moveEnd: {
- get: function () {
- return this._moveEnd;
- },
- },
-
- /**
- * Gets the event that will be raised when the camera has changed by <code>percentageChanged</code>.
- * @memberof Camera.prototype
- * @type {Event}
- * @readonly
- */
- changed: {
- get: function () {
- return this._changed;
- },
- },
- });
-
- /**
- * @private
- */
- Camera.prototype.update = function (mode) {
- //>>includeStart('debug', pragmas.debug);
- if (!defined(mode)) {
- throw new DeveloperError("mode is required.");
- }
- if (
- mode === SceneMode.SCENE2D &&
- !(this.frustum instanceof OrthographicOffCenterFrustum)
- ) {
- throw new DeveloperError(
- "An OrthographicOffCenterFrustum is required in 2D.",
- );
- }
- if (
- (mode === SceneMode.SCENE3D || mode === SceneMode.COLUMBUS_VIEW) &&
- !(this.frustum instanceof PerspectiveFrustum) &&
- !(this.frustum instanceof OrthographicFrustum)
- ) {
- throw new DeveloperError(
- "A PerspectiveFrustum or OrthographicFrustum is required in 3D and Columbus view",
- );
- }
- //>>includeEnd('debug');
-
- let updateFrustum = false;
- if (mode !== this._mode) {
- this._mode = mode;
- this._modeChanged = mode !== SceneMode.MORPHING;
- updateFrustum = this._mode === SceneMode.SCENE2D;
- }
-
- if (updateFrustum) {
- const frustum = (this._max2Dfrustum = this.frustum.clone());
-
- //>>includeStart('debug', pragmas.debug);
- if (!(frustum instanceof OrthographicOffCenterFrustum)) {
- throw new DeveloperError(
- "The camera frustum is expected to be orthographic for 2D camera control.",
- );
- }
- //>>includeEnd('debug');
-
- const maxZoomOut = 2.0;
- const ratio = frustum.top / frustum.right;
- frustum.right = this._maxCoord.x * maxZoomOut;
- frustum.left = -frustum.right;
- frustum.top = ratio * frustum.right;
- frustum.bottom = -frustum.top;
- }
-
- if (this._mode === SceneMode.SCENE2D) {
- clampMove2D(this, this.position);
- }
- };
-
- const setTransformPosition = new Cartesian3();
- const setTransformUp = new Cartesian3();
- const setTransformDirection = new Cartesian3();
-
- Camera.prototype._setTransform = function (transform) {
- const position = Cartesian3.clone(this.positionWC, setTransformPosition);
- const up = Cartesian3.clone(this.upWC, setTransformUp);
- const direction = Cartesian3.clone(this.directionWC, setTransformDirection);
-
- Matrix4.clone(transform, this._transform);
- this._transformChanged = true;
- updateMembers(this);
- const inverse = this._actualInvTransform;
-
- Matrix4.multiplyByPoint(inverse, position, this.position);
- Matrix4.multiplyByPointAsVector(inverse, direction, this.direction);
- Matrix4.multiplyByPointAsVector(inverse, up, this.up);
- Cartesian3.cross(this.direction, this.up, this.right);
-
- updateMembers(this);
- };
-
- const scratchAdjustOrthographicFrustumMousePosition = new Cartesian2();
- const scratchPickRay = new Ray();
- const scratchRayIntersection = new Cartesian3();
- const scratchDepthIntersection = new Cartesian3();
-
- function calculateOrthographicFrustumWidth(camera) {
- // Camera is fixed to an object, so keep frustum width constant.
- if (!Matrix4.equals(Matrix4.IDENTITY, camera.transform)) {
- return Cartesian3.magnitude(camera.position);
- }
-
- const scene = camera._scene;
- const globe = scene.globe;
-
- const mousePosition = scratchAdjustOrthographicFrustumMousePosition;
- mousePosition.x = scene.drawingBufferWidth / scene.pixelRatio / 2.0;
- mousePosition.y = scene.drawingBufferHeight / scene.pixelRatio / 2.0;
-
- let rayIntersection;
- if (defined(globe)) {
- const ray = camera.getPickRay(mousePosition, scratchPickRay);
- rayIntersection = globe.pickWorldCoordinates(
- ray,
- scene,
- true,
- scratchRayIntersection,
- );
- }
-
- let depthIntersection;
- if (scene.pickPositionSupported) {
- depthIntersection = scene.pickPositionWorldCoordinates(
- mousePosition,
- scratchDepthIntersection,
- );
- }
-
- let distance;
- if (defined(rayIntersection) || defined(depthIntersection)) {
- const depthDistance = defined(depthIntersection)
- ? Cartesian3.distance(depthIntersection, camera.positionWC)
- : Number.POSITIVE_INFINITY;
- const rayDistance = defined(rayIntersection)
- ? Cartesian3.distance(rayIntersection, camera.positionWC)
- : Number.POSITIVE_INFINITY;
- distance = Math.min(depthDistance, rayDistance);
- } else {
- distance = Math.max(camera.positionCartographic.height, 0.0);
- }
- return distance;
- }
-
- Camera.prototype._adjustOrthographicFrustum = function (zooming) {
- if (!(this.frustum instanceof OrthographicFrustum)) {
- return;
- }
-
- if (!zooming && this._positionCartographic.height < 150000.0) {
- return;
- }
-
- this.frustum.width = calculateOrthographicFrustumWidth(this);
- };
-
- const scratchSetViewCartesian = new Cartesian3();
- const scratchSetViewTransform1 = new Matrix4();
- const scratchSetViewTransform2 = new Matrix4();
- const scratchSetViewQuaternion = new Quaternion();
- const scratchSetViewMatrix3 = new Matrix3();
- const scratchSetViewCartographic = new Cartographic();
-
- function setView3D(camera, position, hpr) {
- //>>includeStart('debug', pragmas.debug);
- if (isNaN(position.x) || isNaN(position.y) || isNaN(position.z)) {
- throw new DeveloperError("position has a NaN component");
- }
- //>>includeEnd('debug');
- const currentTransform = Matrix4.clone(
- camera.transform,
- scratchSetViewTransform1,
- );
- const localTransform = Transforms.eastNorthUpToFixedFrame(
- position,
- camera._projection.ellipsoid,
- scratchSetViewTransform2,
- );
- camera._setTransform(localTransform);
-
- Cartesian3.clone(Cartesian3.ZERO, camera.position);
- hpr.heading = hpr.heading - CesiumMath.PI_OVER_TWO;
-
- const rotQuat = Quaternion.fromHeadingPitchRoll(
- hpr,
- scratchSetViewQuaternion,
- );
- const rotMat = Matrix3.fromQuaternion(rotQuat, scratchSetViewMatrix3);
-
- Matrix3.getColumn(rotMat, 0, camera.direction);
- Matrix3.getColumn(rotMat, 2, camera.up);
- Cartesian3.cross(camera.direction, camera.up, camera.right);
-
- camera._setTransform(currentTransform);
-
- camera._adjustOrthographicFrustum(true);
- }
-
- function setViewCV(camera, position, hpr, convert) {
- const currentTransform = Matrix4.clone(
- camera.transform,
- scratchSetViewTransform1,
- );
- camera._setTransform(Matrix4.IDENTITY);
-
- if (!Cartesian3.equals(position, camera.positionWC)) {
- if (convert) {
- const projection = camera._projection;
- const cartographic = projection.ellipsoid.cartesianToCartographic(
- position,
- scratchSetViewCartographic,
- );
- position = projection.project(cartographic, scratchSetViewCartesian);
- }
- Cartesian3.clone(position, camera.position);
- }
- hpr.heading = hpr.heading - CesiumMath.PI_OVER_TWO;
-
- const rotQuat = Quaternion.fromHeadingPitchRoll(
- hpr,
- scratchSetViewQuaternion,
- );
- const rotMat = Matrix3.fromQuaternion(rotQuat, scratchSetViewMatrix3);
-
- Matrix3.getColumn(rotMat, 0, camera.direction);
- Matrix3.getColumn(rotMat, 2, camera.up);
- Cartesian3.cross(camera.direction, camera.up, camera.right);
-
- camera._setTransform(currentTransform);
-
- camera._adjustOrthographicFrustum(true);
- }
-
- function setView2D(camera, position, hpr, convert) {
- const currentTransform = Matrix4.clone(
- camera.transform,
- scratchSetViewTransform1,
- );
- camera._setTransform(Matrix4.IDENTITY);
-
- if (!Cartesian3.equals(position, camera.positionWC)) {
- if (convert) {
- const projection = camera._projection;
- const cartographic = projection.ellipsoid.cartesianToCartographic(
- position,
- scratchSetViewCartographic,
- );
- position = projection.project(cartographic, scratchSetViewCartesian);
- }
-
- Cartesian2.clone(position, camera.position);
-
- const newLeft = -position.z * 0.5;
- const newRight = -newLeft;
-
- const frustum = camera.frustum;
- if (newRight > newLeft) {
- const ratio = frustum.top / frustum.right;
- frustum.right = newRight;
- frustum.left = newLeft;
- frustum.top = frustum.right * ratio;
- frustum.bottom = -frustum.top;
- }
- }
-
- if (camera._scene.mapMode2D === MapMode2D.ROTATE) {
- hpr.heading = hpr.heading - CesiumMath.PI_OVER_TWO;
- hpr.pitch = -CesiumMath.PI_OVER_TWO;
- hpr.roll = 0.0;
- const rotQuat = Quaternion.fromHeadingPitchRoll(
- hpr,
- scratchSetViewQuaternion,
- );
- const rotMat = Matrix3.fromQuaternion(rotQuat, scratchSetViewMatrix3);
-
- Matrix3.getColumn(rotMat, 2, camera.up);
- Cartesian3.cross(camera.direction, camera.up, camera.right);
- }
-
- camera._setTransform(currentTransform);
- }
-
- const scratchToHPRDirection = new Cartesian3();
- const scratchToHPRUp = new Cartesian3();
- const scratchToHPRRight = new Cartesian3();
-
- function directionUpToHeadingPitchRoll(camera, position, orientation, result) {
- const direction = Cartesian3.clone(
- orientation.direction,
- scratchToHPRDirection,
- );
- const up = Cartesian3.clone(orientation.up, scratchToHPRUp);
-
- if (camera._scene.mode === SceneMode.SCENE3D) {
- const ellipsoid = camera._projection.ellipsoid;
- const transform = Transforms.eastNorthUpToFixedFrame(
- position,
- ellipsoid,
- scratchHPRMatrix1,
- );
- const invTransform = Matrix4.inverseTransformation(
- transform,
- scratchHPRMatrix2,
- );
-
- Matrix4.multiplyByPointAsVector(invTransform, direction, direction);
- Matrix4.multiplyByPointAsVector(invTransform, up, up);
- }
-
- const right = Cartesian3.cross(direction, up, scratchToHPRRight);
-
- result.heading = getHeading(direction, up);
- result.pitch = getPitch(direction);
- result.roll = getRoll(direction, up, right);
-
- return result;
- }
-
- const scratchSetViewOptions = {
- destination: undefined,
- orientation: {
- direction: undefined,
- up: undefined,
- heading: undefined,
- pitch: undefined,
- roll: undefined,
- },
- convert: undefined,
- endTransform: undefined,
- };
-
- const scratchHpr = new HeadingPitchRoll();
- /**
- * Sets the camera position, orientation and transform.
- *
- * @param {object} options Object with the following properties:
- * @param {Cartesian3|Rectangle} [options.destination] The final position of the camera in world coordinates or a rectangle that would be visible from a top-down view.
- * @param {HeadingPitchRollValues|DirectionUp} [options.orientation] An object that contains either direction and up properties or heading, pitch and roll properties. By default, the direction will point
- * 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
- * y direction in Columbus view. Orientation is not used in 2D when in infinite scrolling mode.
- * @param {Matrix4} [options.endTransform] Transform matrix representing the reference frame of the camera.
- * @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>.
- *
- * @example
- * // 1. Set position with a top-down view
- * viewer.camera.setView({
- * destination : Cesium.Cartesian3.fromDegrees(-117.16, 32.71, 15000.0)
- * });
- *
- * // 2 Set view with heading, pitch and roll
- * viewer.camera.setView({
- * destination : cartesianPosition,
- * orientation: {
- * heading : Cesium.Math.toRadians(90.0), // east, default value is 0.0 (north)
- * pitch : Cesium.Math.toRadians(-90), // default value (looking down)
- * roll : 0.0 // default value
- * }
- * });
- *
- * // 3. Change heading, pitch and roll with the camera position remaining the same.
- * viewer.camera.setView({
- * orientation: {
- * heading : Cesium.Math.toRadians(90.0), // east, default value is 0.0 (north)
- * pitch : Cesium.Math.toRadians(-90), // default value (looking down)
- * roll : 0.0 // default value
- * }
- * });
- *
- *
- * // 4. View rectangle with a top-down view
- * viewer.camera.setView({
- * destination : Cesium.Rectangle.fromDegrees(west, south, east, north)
- * });
- *
- * // 5. Set position with an orientation using unit vectors.
- * viewer.camera.setView({
- * destination : Cesium.Cartesian3.fromDegrees(-122.19, 46.25, 5000.0),
- * orientation : {
- * direction : new Cesium.Cartesian3(-0.04231243104240401, -0.20123236049443421, -0.97862924300734),
- * up : new Cesium.Cartesian3(-0.47934589305293746, -0.8553216253114552, 0.1966022179118339)
- * }
- * });
- */
- Camera.prototype.setView = function (options) {
- options = options ?? Frozen.EMPTY_OBJECT;
- let orientation = options.orientation ?? Frozen.EMPTY_OBJECT;
-
- const mode = this._mode;
- if (mode === SceneMode.MORPHING) {
- return;
- }
-
- if (defined(options.endTransform)) {
- this._setTransform(options.endTransform);
- }
-
- let convert = options.convert ?? true;
- let destination =
- options.destination ??
- Cartesian3.clone(this.positionWC, scratchSetViewCartesian);
- if (defined(destination) && defined(destination.west)) {
- destination = this.getRectangleCameraCoordinates(
- destination,
- scratchSetViewCartesian,
- );
- //>>includeStart('debug', pragmas.debug);
- // destination.z may be null in 2D, but .x and .y should be numeric
- if (isNaN(destination.x) || isNaN(destination.y)) {
- throw new DeveloperError(`destination has a NaN component`);
- }
- //>>includeEnd('debug');
- convert = false;
- }
-
- if (defined(orientation.direction)) {
- orientation = directionUpToHeadingPitchRoll(
- this,
- destination,
- orientation,
- scratchSetViewOptions.orientation,
- );
- }
-
- scratchHpr.heading = orientation.heading ?? 0.0;
- scratchHpr.pitch = orientation.pitch ?? -CesiumMath.PI_OVER_TWO;
- scratchHpr.roll = orientation.roll ?? 0.0;
-
- if (mode === SceneMode.SCENE3D) {
- setView3D(this, destination, scratchHpr);
- } else if (mode === SceneMode.SCENE2D) {
- setView2D(this, destination, scratchHpr, convert);
- } else {
- setViewCV(this, destination, scratchHpr, convert);
- }
- };
-
- const pitchScratch = new Cartesian3();
- /**
- * Fly the camera to the home view. Use {@link Camera#.DEFAULT_VIEW_RECTANGLE} to set
- * the default view for the 3D scene. The home view for 2D and columbus view shows the
- * entire map.
- *
- * @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}
- */
- Camera.prototype.flyHome = function (duration) {
- const mode = this._mode;
-
- if (mode === SceneMode.MORPHING) {
- this._scene.completeMorph();
- }
-
- if (mode === SceneMode.SCENE2D) {
- this.flyTo({
- destination: Camera.DEFAULT_VIEW_RECTANGLE,
- duration: duration,
- endTransform: Matrix4.IDENTITY,
- });
- } else if (mode === SceneMode.SCENE3D) {
- const destination = this.getRectangleCameraCoordinates(
- Camera.DEFAULT_VIEW_RECTANGLE,
- );
-
- let mag = Cartesian3.magnitude(destination);
- mag += mag * Camera.DEFAULT_VIEW_FACTOR;
- Cartesian3.normalize(destination, destination);
- Cartesian3.multiplyByScalar(destination, mag, destination);
-
- this.flyTo({
- destination: destination,
- duration: duration,
- endTransform: Matrix4.IDENTITY,
- });
- } else if (mode === SceneMode.COLUMBUS_VIEW) {
- const maxRadii = this._projection.ellipsoid.maximumRadius;
- let position = new Cartesian3(0.0, -1.0, 1.0);
- position = Cartesian3.multiplyByScalar(
- Cartesian3.normalize(position, position),
- 5.0 * maxRadii,
- position,
- );
- this.flyTo({
- destination: position,
- duration: duration,
- orientation: {
- heading: 0.0,
- pitch: -Math.acos(Cartesian3.normalize(position, pitchScratch).z),
- roll: 0.0,
- },
- endTransform: Matrix4.IDENTITY,
- convert: false,
- });
- }
- };
-
- /**
- * Transform a vector or point from world coordinates to the camera's reference frame.
- *
- * @param {Cartesian4} cartesian The vector or point to transform.
- * @param {Cartesian4} [result] The object onto which to store the result.
- * @returns {Cartesian4} The transformed vector or point.
- */
- Camera.prototype.worldToCameraCoordinates = function (cartesian, result) {
- //>>includeStart('debug', pragmas.debug);
- if (!defined(cartesian)) {
- throw new DeveloperError("cartesian is required.");
- }
- //>>includeEnd('debug');
-
- if (!defined(result)) {
- result = new Cartesian4();
- }
- updateMembers(this);
- return Matrix4.multiplyByVector(this._actualInvTransform, cartesian, result);
- };
-
- /**
- * Transform a point from world coordinates to the camera's reference frame.
- *
- * @param {Cartesian3} cartesian The point to transform.
- * @param {Cartesian3} [result] The object onto which to store the result.
- * @returns {Cartesian3} The transformed point.
- */
- Camera.prototype.worldToCameraCoordinatesPoint = function (cartesian, result) {
- //>>includeStart('debug', pragmas.debug);
- if (!defined(cartesian)) {
- throw new DeveloperError("cartesian is required.");
- }
- //>>includeEnd('debug');
-
- if (!defined(result)) {
- result = new Cartesian3();
- }
- updateMembers(this);
- return Matrix4.multiplyByPoint(this._actualInvTransform, cartesian, result);
- };
-
- /**
- * Transform a vector from world coordinates to the camera's reference frame.
- *
- * @param {Cartesian3} cartesian The vector to transform.
- * @param {Cartesian3} [result] The object onto which to store the result.
- * @returns {Cartesian3} The transformed vector.
- */
- Camera.prototype.worldToCameraCoordinatesVector = function (cartesian, result) {
- //>>includeStart('debug', pragmas.debug);
- if (!defined(cartesian)) {
- throw new DeveloperError("cartesian is required.");
- }
- //>>includeEnd('debug');
-
- if (!defined(result)) {
- result = new Cartesian3();
- }
- updateMembers(this);
- return Matrix4.multiplyByPointAsVector(
- this._actualInvTransform,
- cartesian,
- result,
- );
- };
-
- /**
- * Transform a vector or point from the camera's reference frame to world coordinates.
- *
- * @param {Cartesian4} cartesian The vector or point to transform.
- * @param {Cartesian4} [result] The object onto which to store the result.
- * @returns {Cartesian4} The transformed vector or point.
- */
- Camera.prototype.cameraToWorldCoordinates = function (cartesian, result) {
- //>>includeStart('debug', pragmas.debug);
- if (!defined(cartesian)) {
- throw new DeveloperError("cartesian is required.");
- }
- //>>includeEnd('debug');
-
- if (!defined(result)) {
- result = new Cartesian4();
- }
- updateMembers(this);
- return Matrix4.multiplyByVector(this._actualTransform, cartesian, result);
- };
-
- /**
- * Transform a point from the camera's reference frame to world coordinates.
- *
- * @param {Cartesian3} cartesian The point to transform.
- * @param {Cartesian3} [result] The object onto which to store the result.
- * @returns {Cartesian3} The transformed point.
- */
- Camera.prototype.cameraToWorldCoordinatesPoint = function (cartesian, result) {
- //>>includeStart('debug', pragmas.debug);
- if (!defined(cartesian)) {
- throw new DeveloperError("cartesian is required.");
- }
- //>>includeEnd('debug');
-
- if (!defined(result)) {
- result = new Cartesian3();
- }
- updateMembers(this);
- return Matrix4.multiplyByPoint(this._actualTransform, cartesian, result);
- };
-
- /**
- * Transform a vector from the camera's reference frame to world coordinates.
- *
- * @param {Cartesian3} cartesian The vector to transform.
- * @param {Cartesian3} [result] The object onto which to store the result.
- * @returns {Cartesian3} The transformed vector.
- */
- Camera.prototype.cameraToWorldCoordinatesVector = function (cartesian, result) {
- //>>includeStart('debug', pragmas.debug);
- if (!defined(cartesian)) {
- throw new DeveloperError("cartesian is required.");
- }
- //>>includeEnd('debug');
-
- if (!defined(result)) {
- result = new Cartesian3();
- }
- updateMembers(this);
- return Matrix4.multiplyByPointAsVector(
- this._actualTransform,
- cartesian,
- result,
- );
- };
-
- function clampMove2D(camera, position) {
- const rotatable2D = camera._scene.mapMode2D === MapMode2D.ROTATE;
- const maxProjectedX = camera._maxCoord.x;
- const maxProjectedY = camera._maxCoord.y;
-
- let minX;
- let maxX;
- if (rotatable2D) {
- maxX = maxProjectedX;
- minX = -maxX;
- } else {
- maxX = position.x - maxProjectedX * 2.0;
- minX = position.x + maxProjectedX * 2.0;
- }
-
- if (position.x > maxProjectedX) {
- position.x = maxX;
- }
- if (position.x < -maxProjectedX) {
- position.x = minX;
- }
-
- if (position.y > maxProjectedY) {
- position.y = maxProjectedY;
- }
- if (position.y < -maxProjectedY) {
- position.y = -maxProjectedY;
- }
- }
-
- const moveScratch = new Cartesian3();
- /**
- * Translates the camera's position by <code>amount</code> along <code>direction</code>.
- *
- * @param {Cartesian3} direction The direction to move.
- * @param {number} [amount] The amount, in meters, to move. Defaults to <code>defaultMoveAmount</code>.
- *
- * @see Camera#moveBackward
- * @see Camera#moveForward
- * @see Camera#moveLeft
- * @see Camera#moveRight
- * @see Camera#moveUp
- * @see Camera#moveDown
- */
- Camera.prototype.move = function (direction, amount) {
- //>>includeStart('debug', pragmas.debug);
- if (!defined(direction)) {
- throw new DeveloperError("direction is required.");
- }
- //>>includeEnd('debug');
-
- const cameraPosition = this.position;
- Cartesian3.multiplyByScalar(direction, amount, moveScratch);
- Cartesian3.add(cameraPosition, moveScratch, cameraPosition);
-
- if (this._mode === SceneMode.SCENE2D) {
- clampMove2D(this, cameraPosition);
- }
- this._adjustOrthographicFrustum(true);
- };
-
- /**
- * Translates the camera's position by <code>amount</code> along the camera's view vector.
- * When in 2D mode, this will zoom in the camera instead of translating the camera's position.
- *
- * @param {number} [amount] The amount, in meters, to move. Defaults to <code>defaultMoveAmount</code>.
- *
- * @see Camera#moveBackward
- */
- Camera.prototype.moveForward = function (amount) {
- amount = amount ?? this.defaultMoveAmount;
-
- if (this._mode === SceneMode.SCENE2D) {
- // 2D mode
- zoom2D(this, amount);
- } else {
- // 3D or Columbus view mode
- this.move(this.direction, amount);
- }
- };
-
- /**
- * Translates the camera's position by <code>amount</code> along the opposite direction
- * of the camera's view vector.
- * When in 2D mode, this will zoom out the camera instead of translating the camera's position.
- *
- * @param {number} [amount] The amount, in meters, to move. Defaults to <code>defaultMoveAmount</code>.
- *
- * @see Camera#moveForward
- */
- Camera.prototype.moveBackward = function (amount) {
- amount = amount ?? this.defaultMoveAmount;
-
- if (this._mode === SceneMode.SCENE2D) {
- // 2D mode
- zoom2D(this, -amount);
- } else {
- // 3D or Columbus view mode
- this.move(this.direction, -amount);
- }
- };
-
- /**
- * Translates the camera's position by <code>amount</code> along the camera's up vector.
- *
- * @param {number} [amount] The amount, in meters, to move. Defaults to <code>defaultMoveAmount</code>.
- *
- * @see Camera#moveDown
- */
- Camera.prototype.moveUp = function (amount) {
- amount = amount ?? this.defaultMoveAmount;
- this.move(this.up, amount);
- };
-
- /**
- * Translates the camera's position by <code>amount</code> along the opposite direction
- * of the camera's up vector.
- *
- * @param {number} [amount] The amount, in meters, to move. Defaults to <code>defaultMoveAmount</code>.
- *
- * @see Camera#moveUp
- */
- Camera.prototype.moveDown = function (amount) {
- amount = amount ?? this.defaultMoveAmount;
- this.move(this.up, -amount);
- };
-
- /**
- * Translates the camera's position by <code>amount</code> along the camera's right vector.
- *
- * @param {number} [amount] The amount, in meters, to move. Defaults to <code>defaultMoveAmount</code>.
- *
- * @see Camera#moveLeft
- */
- Camera.prototype.moveRight = function (amount) {
- amount = amount ?? this.defaultMoveAmount;
- this.move(this.right, amount);
- };
-
- /**
- * Translates the camera's position by <code>amount</code> along the opposite direction
- * of the camera's right vector.
- *
- * @param {number} [amount] The amount, in meters, to move. Defaults to <code>defaultMoveAmount</code>.
- *
- * @see Camera#moveRight
- */
- Camera.prototype.moveLeft = function (amount) {
- amount = amount ?? this.defaultMoveAmount;
- this.move(this.right, -amount);
- };
-
- /**
- * Rotates the camera around its up vector by amount, in radians, in the opposite direction
- * of its right vector if not in 2D mode.
- *
- * @param {number} [amount] The amount, in radians, to rotate by. Defaults to <code>defaultLookAmount</code>.
- *
- * @see Camera#lookRight
- */
- Camera.prototype.lookLeft = function (amount) {
- amount = amount ?? this.defaultLookAmount;
-
- // only want view of map to change in 3D mode, 2D visual is incorrect when look changes
- if (this._mode !== SceneMode.SCENE2D) {
- this.look(this.up, -amount);
- }
- };
-
- /**
- * Rotates the camera around its up vector by amount, in radians, in the direction
- * of its right vector if not in 2D mode.
- *
- * @param {number} [amount] The amount, in radians, to rotate by. Defaults to <code>defaultLookAmount</code>.
- *
- * @see Camera#lookLeft
- */
- Camera.prototype.lookRight = function (amount) {
- amount = amount ?? this.defaultLookAmount;
-
- // only want view of map to change in 3D mode, 2D visual is incorrect when look changes
- if (this._mode !== SceneMode.SCENE2D) {
- this.look(this.up, amount);
- }
- };
-
- /**
- * Rotates the camera around its right vector by amount, in radians, in the direction
- * of its up vector if not in 2D mode.
- *
- * @param {number} [amount] The amount, in radians, to rotate by. Defaults to <code>defaultLookAmount</code>.
- *
- * @see Camera#lookDown
- */
- Camera.prototype.lookUp = function (amount) {
- amount = amount ?? this.defaultLookAmount;
-
- // only want view of map to change in 3D mode, 2D visual is incorrect when look changes
- if (this._mode !== SceneMode.SCENE2D) {
- this.look(this.right, -amount);
- }
- };
-
- /**
- * Rotates the camera around its right vector by amount, in radians, in the opposite direction
- * of its up vector if not in 2D mode.
- *
- * @param {number} [amount] The amount, in radians, to rotate by. Defaults to <code>defaultLookAmount</code>.
- *
- * @see Camera#lookUp
- */
- Camera.prototype.lookDown = function (amount) {
- amount = amount ?? this.defaultLookAmount;
-
- // only want view of map to change in 3D mode, 2D visual is incorrect when look changes
- if (this._mode !== SceneMode.SCENE2D) {
- this.look(this.right, amount);
- }
- };
-
- const lookScratchQuaternion = new Quaternion();
- const lookScratchMatrix = new Matrix3();
- /**
- * Rotate each of the camera's orientation vectors around <code>axis</code> by <code>angle</code>
- *
- * @param {Cartesian3} axis The axis to rotate around.
- * @param {number} [angle] The angle, in radians, to rotate by. Defaults to <code>defaultLookAmount</code>.
- *
- * @see Camera#lookUp
- * @see Camera#lookDown
- * @see Camera#lookLeft
- * @see Camera#lookRight
- */
- Camera.prototype.look = function (axis, angle) {
- //>>includeStart('debug', pragmas.debug);
- if (!defined(axis)) {
- throw new DeveloperError("axis is required.");
- }
- //>>includeEnd('debug');
-
- const turnAngle = angle ?? this.defaultLookAmount;
- const quaternion = Quaternion.fromAxisAngle(
- axis,
- -turnAngle,
- lookScratchQuaternion,
- );
- const rotation = Matrix3.fromQuaternion(quaternion, lookScratchMatrix);
-
- const direction = this.direction;
- const up = this.up;
- const right = this.right;
-
- Matrix3.multiplyByVector(rotation, direction, direction);
- Matrix3.multiplyByVector(rotation, up, up);
- Matrix3.multiplyByVector(rotation, right, right);
- };
-
- /**
- * Rotate the camera counter-clockwise around its direction vector by amount, in radians.
- *
- * @param {number} [amount] The amount, in radians, to rotate by. Defaults to <code>defaultLookAmount</code>.
- *
- * @see Camera#twistRight
- */
- Camera.prototype.twistLeft = function (amount) {
- amount = amount ?? this.defaultLookAmount;
- this.look(this.direction, amount);
- };
-
- /**
- * Rotate the camera clockwise around its direction vector by amount, in radians.
- *
- * @param {number} [amount] The amount, in radians, to rotate by. Defaults to <code>defaultLookAmount</code>.
- *
- * @see Camera#twistLeft
- */
- Camera.prototype.twistRight = function (amount) {
- amount = amount ?? this.defaultLookAmount;
- this.look(this.direction, -amount);
- };
-
- const rotateScratchQuaternion = new Quaternion();
- const rotateScratchMatrix = new Matrix3();
- /**
- * Rotates the camera around <code>axis</code> by <code>angle</code>. The distance
- * of the camera's position to the center of the camera's reference frame remains the same.
- *
- * @param {Cartesian3} axis The axis to rotate around given in world coordinates.
- * @param {number} [angle] The angle, in radians, to rotate by. Defaults to <code>defaultRotateAmount</code>.
- *
- * @see Camera#rotateUp
- * @see Camera#rotateDown
- * @see Camera#rotateLeft
- * @see Camera#rotateRight
- */
- Camera.prototype.rotate = function (axis, angle) {
- //>>includeStart('debug', pragmas.debug);
- if (!defined(axis)) {
- throw new DeveloperError("axis is required.");
- }
- //>>includeEnd('debug');
-
- const turnAngle = angle ?? this.defaultRotateAmount;
- const quaternion = Quaternion.fromAxisAngle(
- axis,
- -turnAngle,
- rotateScratchQuaternion,
- );
- const rotation = Matrix3.fromQuaternion(quaternion, rotateScratchMatrix);
- Matrix3.multiplyByVector(rotation, this.position, this.position);
- Matrix3.multiplyByVector(rotation, this.direction, this.direction);
- Matrix3.multiplyByVector(rotation, this.up, this.up);
- Cartesian3.cross(this.direction, this.up, this.right);
- Cartesian3.cross(this.right, this.direction, this.up);
-
- this._adjustOrthographicFrustum(false);
- };
-
- /**
- * Rotates the camera around the center of the camera's reference frame by angle downwards.
- *
- * @param {number} [angle] The angle, in radians, to rotate by. Defaults to <code>defaultRotateAmount</code>.
- *
- * @see Camera#rotateUp
- * @see Camera#rotate
- */
- Camera.prototype.rotateDown = function (angle) {
- angle = angle ?? this.defaultRotateAmount;
- rotateVertical(this, angle);
- };
-
- /**
- * Rotates the camera around the center of the camera's reference frame by angle upwards.
- *
- * @param {number} [angle] The angle, in radians, to rotate by. Defaults to <code>defaultRotateAmount</code>.
- *
- * @see Camera#rotateDown
- * @see Camera#rotate
- */
- Camera.prototype.rotateUp = function (angle) {
- angle = angle ?? this.defaultRotateAmount;
- rotateVertical(this, -angle);
- };
-
- const rotateVertScratchP = new Cartesian3();
- const rotateVertScratchA = new Cartesian3();
- const rotateVertScratchTan = new Cartesian3();
- const rotateVertScratchNegate = new Cartesian3();
- function rotateVertical(camera, angle) {
- const position = camera.position;
- if (
- defined(camera.constrainedAxis) &&
- !Cartesian3.equalsEpsilon(
- camera.position,
- Cartesian3.ZERO,
- CesiumMath.EPSILON2,
- )
- ) {
- const p = Cartesian3.normalize(position, rotateVertScratchP);
- const northParallel = Cartesian3.equalsEpsilon(
- p,
- camera.constrainedAxis,
- CesiumMath.EPSILON2,
- );
- const southParallel = Cartesian3.equalsEpsilon(
- p,
- Cartesian3.negate(camera.constrainedAxis, rotateVertScratchNegate),
- CesiumMath.EPSILON2,
- );
- if (!northParallel && !southParallel) {
- const constrainedAxis = Cartesian3.normalize(
- camera.constrainedAxis,
- rotateVertScratchA,
- );
-
- let dot = Cartesian3.dot(p, constrainedAxis);
- let angleToAxis = CesiumMath.acosClamped(dot);
- if (angle > 0 && angle > angleToAxis) {
- angle = angleToAxis - CesiumMath.EPSILON4;
- }
-
- dot = Cartesian3.dot(
- p,
- Cartesian3.negate(constrainedAxis, rotateVertScratchNegate),
- );
- angleToAxis = CesiumMath.acosClamped(dot);
- if (angle < 0 && -angle > angleToAxis) {
- angle = -angleToAxis + CesiumMath.EPSILON4;
- }
-
- const tangent = Cartesian3.cross(
- constrainedAxis,
- p,
- rotateVertScratchTan,
- );
- camera.rotate(tangent, angle);
- } else if ((northParallel && angle < 0) || (southParallel && angle > 0)) {
- camera.rotate(camera.right, angle);
- }
- } else {
- camera.rotate(camera.right, angle);
- }
- }
-
- /**
- * Rotates the camera around the center of the camera's reference frame by angle to the right.
- *
- * @param {number} [angle] The angle, in radians, to rotate by. Defaults to <code>defaultRotateAmount</code>.
- *
- * @see Camera#rotateLeft
- * @see Camera#rotate
- */
- Camera.prototype.rotateRight = function (angle) {
- angle = angle ?? this.defaultRotateAmount;
- rotateHorizontal(this, -angle);
- };
-
- /**
- * Rotates the camera around the center of the camera's reference frame by angle to the left.
- *
- * @param {number} [angle] The angle, in radians, to rotate by. Defaults to <code>defaultRotateAmount</code>.
- *
- * @see Camera#rotateRight
- * @see Camera#rotate
- */
- Camera.prototype.rotateLeft = function (angle) {
- angle = angle ?? this.defaultRotateAmount;
- rotateHorizontal(this, angle);
- };
-
- function rotateHorizontal(camera, angle) {
- if (defined(camera.constrainedAxis)) {
- camera.rotate(camera.constrainedAxis, angle);
- } else {
- camera.rotate(camera.up, angle);
- }
- }
-
- function zoom2D(camera, amount) {
- const frustum = camera.frustum;
-
- //>>includeStart('debug', pragmas.debug);
- if (
- !(frustum instanceof OrthographicOffCenterFrustum) ||
- !defined(frustum.left) ||
- !defined(frustum.right) ||
- !defined(frustum.bottom) ||
- !defined(frustum.top)
- ) {
- throw new DeveloperError(
- "The camera frustum is expected to be orthographic for 2D camera control.",
- );
- }
- //>>includeEnd('debug');
-
- let ratio;
- amount = amount * 0.5;
-
- if (
- Math.abs(frustum.top) + Math.abs(frustum.bottom) >
- Math.abs(frustum.left) + Math.abs(frustum.right)
- ) {
- let newTop = frustum.top - amount;
- let newBottom = frustum.bottom + amount;
-
- let maxBottom = camera._maxCoord.y;
- if (camera._scene.mapMode2D === MapMode2D.ROTATE) {
- maxBottom *= camera.maximumZoomFactor;
- }
-
- if (newBottom > maxBottom) {
- newBottom = maxBottom;
- newTop = -maxBottom;
- }
-
- if (newTop <= newBottom) {
- newTop = 1.0;
- newBottom = -1.0;
- }
-
- ratio = frustum.right / frustum.top;
- frustum.top = newTop;
- frustum.bottom = newBottom;
- frustum.right = frustum.top * ratio;
- frustum.left = -frustum.right;
- } else {
- let newRight = frustum.right - amount;
- let newLeft = frustum.left + amount;
-
- let maxRight = camera._maxCoord.x;
- if (camera._scene.mapMode2D === MapMode2D.ROTATE) {
- maxRight *= camera.maximumZoomFactor;
- }
-
- if (newRight > maxRight) {
- newRight = maxRight;
- newLeft = -maxRight;
- }
-
- if (newRight <= newLeft) {
- newRight = 1.0;
- newLeft = -1.0;
- }
- ratio = frustum.top / frustum.right;
- frustum.right = newRight;
- frustum.left = newLeft;
- frustum.top = frustum.right * ratio;
- frustum.bottom = -frustum.top;
- }
- }
-
- function zoom3D(camera, amount) {
- camera.move(camera.direction, amount);
- }
-
- /**
- * Zooms <code>amount</code> along the camera's view vector.
- *
- * @param {number} [amount] The amount to move. Defaults to <code>defaultZoomAmount</code>.
- *
- * @see Camera#zoomOut
- */
- Camera.prototype.zoomIn = function (amount) {
- amount = amount ?? this.defaultZoomAmount;
- if (this._mode === SceneMode.SCENE2D) {
- zoom2D(this, amount);
- } else {
- zoom3D(this, amount);
- }
- };
-
- /**
- * Zooms <code>amount</code> along the opposite direction of
- * the camera's view vector.
- *
- * @param {number} [amount] The amount to move. Defaults to <code>defaultZoomAmount</code>.
- *
- * @see Camera#zoomIn
- */
- Camera.prototype.zoomOut = function (amount) {
- amount = amount ?? this.defaultZoomAmount;
- if (this._mode === SceneMode.SCENE2D) {
- zoom2D(this, -amount);
- } else {
- zoom3D(this, -amount);
- }
- };
-
- /**
- * Gets the magnitude of the camera position. In 3D, this is the vector magnitude. In 2D and
- * Columbus view, this is the distance to the map.
- *
- * @returns {number} The magnitude of the position.
- */
- Camera.prototype.getMagnitude = function () {
- if (this._mode === SceneMode.SCENE3D) {
- return Cartesian3.magnitude(this.position);
- } else if (this._mode === SceneMode.COLUMBUS_VIEW) {
- return Math.abs(this.position.z);
- } else if (this._mode === SceneMode.SCENE2D) {
- return Math.max(
- this.frustum.right - this.frustum.left,
- this.frustum.top - this.frustum.bottom,
- );
- }
- };
-
- const scratchLookAtMatrix4 = new Matrix4();
-
- /**
- * Sets the camera position and orientation using a target and offset. The target must be given in
- * 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.
- * 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
- * is heading/pitch/range, then the heading and the pitch angles are defined in the reference frame defined by the transformation matrix.
- * The heading is the angle from y axis and increasing towards the x axis. Pitch is the rotation from the xy-plane. Positive pitch
- * angles are below the plane. Negative pitch angles are above the plane. The range is the distance from the center.
- *
- * In 2D, there must be a top down view. The camera will be placed above the target looking down. The height above the
- * target will be the magnitude of the offset. The heading will be determined from the offset. If the heading cannot be
- * determined from the offset, the heading will be north.
- *
- * @param {Cartesian3} target The target position in world coordinates.
- * @param {Cartesian3|HeadingPitchRange} offset The offset from the target in the local east-north-up reference frame centered at the target.
- *
- * @exception {DeveloperError} lookAt is not supported while morphing.
- *
- * @example
- * // 1. Using a cartesian offset
- * const center = Cesium.Cartesian3.fromDegrees(-98.0, 40.0);
- * viewer.camera.lookAt(center, new Cesium.Cartesian3(0.0, -4790000.0, 3930000.0));
- *
- * // 2. Using a HeadingPitchRange offset
- * const center = Cesium.Cartesian3.fromDegrees(-72.0, 40.0);
- * const heading = Cesium.Math.toRadians(50.0);
- * const pitch = Cesium.Math.toRadians(-20.0);
- * const range = 5000.0;
- * viewer.camera.lookAt(center, new Cesium.HeadingPitchRange(heading, pitch, range));
- */
- Camera.prototype.lookAt = function (target, offset) {
- //>>includeStart('debug', pragmas.debug);
- if (!defined(target)) {
- throw new DeveloperError("target is required");
- }
- if (!defined(offset)) {
- throw new DeveloperError("offset is required");
- }
- if (this._mode === SceneMode.MORPHING) {
- throw new DeveloperError("lookAt is not supported while morphing.");
- }
- //>>includeEnd('debug');
-
- const scene = this._scene;
- const ellipsoid = scene.ellipsoid ?? Ellipsoid.default;
-
- const transform = Transforms.eastNorthUpToFixedFrame(
- target,
- ellipsoid,
- scratchLookAtMatrix4,
- );
- this.lookAtTransform(transform, offset);
- };
-
- const scratchLookAtHeadingPitchRangeOffset = new Cartesian3();
- const scratchLookAtHeadingPitchRangeQuaternion1 = new Quaternion();
- const scratchLookAtHeadingPitchRangeQuaternion2 = new Quaternion();
- const scratchHeadingPitchRangeMatrix3 = new Matrix3();
-
- function offsetFromHeadingPitchRange(heading, pitch, range) {
- pitch = CesiumMath.clamp(
- pitch,
- -CesiumMath.PI_OVER_TWO,
- CesiumMath.PI_OVER_TWO,
- );
- heading = CesiumMath.zeroToTwoPi(heading) - CesiumMath.PI_OVER_TWO;
-
- const pitchQuat = Quaternion.fromAxisAngle(
- Cartesian3.UNIT_Y,
- -pitch,
- scratchLookAtHeadingPitchRangeQuaternion1,
- );
- const headingQuat = Quaternion.fromAxisAngle(
- Cartesian3.UNIT_Z,
- -heading,
- scratchLookAtHeadingPitchRangeQuaternion2,
- );
- const rotQuat = Quaternion.multiply(headingQuat, pitchQuat, headingQuat);
- const rotMatrix = Matrix3.fromQuaternion(
- rotQuat,
- scratchHeadingPitchRangeMatrix3,
- );
-
- const offset = Cartesian3.clone(
- Cartesian3.UNIT_X,
- scratchLookAtHeadingPitchRangeOffset,
- );
- Matrix3.multiplyByVector(rotMatrix, offset, offset);
- Cartesian3.negate(offset, offset);
- Cartesian3.multiplyByScalar(offset, range, offset);
- return offset;
- }
-
- /**
- * Sets the camera position and orientation using a target and transformation matrix. The offset can be either a cartesian or heading/pitch/range.
- * 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
- * is heading/pitch/range, then the heading and the pitch angles are defined in the reference frame defined by the transformation matrix.
- * The heading is the angle from y axis and increasing towards the x axis. Pitch is the rotation from the xy-plane. Positive pitch
- * angles are below the plane. Negative pitch angles are above the plane. The range is the distance from the center.
- *
- * 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
- * target will be the magnitude of the offset. The heading will be determined from the offset. If the heading cannot be
- * determined from the offset, the heading will be north.
- *
- * @param {Matrix4} transform The transformation matrix defining the reference frame.
- * @param {Cartesian3|HeadingPitchRange} [offset] The offset from the target in a reference frame centered at the target.
- *
- * @exception {DeveloperError} lookAtTransform is not supported while morphing.
- *
- * @example
- * // 1. Using a cartesian offset
- * const transform = Cesium.Transforms.eastNorthUpToFixedFrame(Cesium.Cartesian3.fromDegrees(-98.0, 40.0));
- * viewer.camera.lookAtTransform(transform, new Cesium.Cartesian3(0.0, -4790000.0, 3930000.0));
- *
- * // 2. Using a HeadingPitchRange offset
- * const transform = Cesium.Transforms.eastNorthUpToFixedFrame(Cesium.Cartesian3.fromDegrees(-72.0, 40.0));
- * const heading = Cesium.Math.toRadians(50.0);
- * const pitch = Cesium.Math.toRadians(-20.0);
- * const range = 5000.0;
- * viewer.camera.lookAtTransform(transform, new Cesium.HeadingPitchRange(heading, pitch, range));
- */
- Camera.prototype.lookAtTransform = function (transform, offset) {
- //>>includeStart('debug', pragmas.debug);
- if (!defined(transform)) {
- throw new DeveloperError("transform is required");
- }
- if (this._mode === SceneMode.MORPHING) {
- throw new DeveloperError(
- "lookAtTransform is not supported while morphing.",
- );
- }
- //>>includeEnd('debug');
-
- this._setTransform(transform);
- if (!defined(offset)) {
- return;
- }
-
- let cartesianOffset;
- if (defined(offset.heading)) {
- cartesianOffset = offsetFromHeadingPitchRange(
- offset.heading,
- offset.pitch,
- offset.range,
- );
- } else {
- cartesianOffset = offset;
- }
-
- if (this._mode === SceneMode.SCENE2D) {
- Cartesian2.clone(Cartesian2.ZERO, this.position);
-
- Cartesian3.negate(cartesianOffset, this.up);
- this.up.z = 0.0;
-
- if (Cartesian3.magnitudeSquared(this.up) < CesiumMath.EPSILON10) {
- Cartesian3.clone(Cartesian3.UNIT_Y, this.up);
- }
-
- Cartesian3.normalize(this.up, this.up);
-
- this._setTransform(Matrix4.IDENTITY);
-
- Cartesian3.negate(Cartesian3.UNIT_Z, this.direction);
- Cartesian3.cross(this.direction, this.up, this.right);
- Cartesian3.normalize(this.right, this.right);
-
- const frustum = this.frustum;
- const ratio = frustum.top / frustum.right;
- frustum.right = Cartesian3.magnitude(cartesianOffset) * 0.5;
- frustum.left = -frustum.right;
- frustum.top = ratio * frustum.right;
- frustum.bottom = -frustum.top;
-
- this._setTransform(transform);
-
- return;
- }
-
- Cartesian3.clone(cartesianOffset, this.position);
- Cartesian3.negate(this.position, this.direction);
- Cartesian3.normalize(this.direction, this.direction);
- Cartesian3.cross(this.direction, Cartesian3.UNIT_Z, this.right);
-
- if (Cartesian3.magnitudeSquared(this.right) < CesiumMath.EPSILON10) {
- Cartesian3.clone(Cartesian3.UNIT_X, this.right);
- }
-
- Cartesian3.normalize(this.right, this.right);
- Cartesian3.cross(this.right, this.direction, this.up);
- Cartesian3.normalize(this.up, this.up);
-
- this._adjustOrthographicFrustum(true);
- };
-
- const viewRectangle3DCartographic1 = new Cartographic();
- const viewRectangle3DCartographic2 = new Cartographic();
- const viewRectangle3DNorthEast = new Cartesian3();
- const viewRectangle3DSouthWest = new Cartesian3();
- const viewRectangle3DNorthWest = new Cartesian3();
- const viewRectangle3DSouthEast = new Cartesian3();
- const viewRectangle3DNorthCenter = new Cartesian3();
- const viewRectangle3DSouthCenter = new Cartesian3();
- const viewRectangle3DCenter = new Cartesian3();
- const viewRectangle3DEquator = new Cartesian3();
- const defaultRF = {
- direction: new Cartesian3(),
- right: new Cartesian3(),
- up: new Cartesian3(),
- };
- let viewRectangle3DEllipsoidGeodesic;
-
- function computeD(direction, upOrRight, corner, tanThetaOrPhi) {
- const opposite = Math.abs(Cartesian3.dot(upOrRight, corner));
- return opposite / tanThetaOrPhi - Cartesian3.dot(direction, corner);
- }
-
- function rectangleCameraPosition3D(camera, rectangle, result, updateCamera) {
- const ellipsoid = camera._projection.ellipsoid;
- const cameraRF = updateCamera ? camera : defaultRF;
-
- const { north, south, west } = rectangle;
- let { east } = rectangle;
-
- // If we go across the International Date Line
- if (west > east) {
- east += CesiumMath.TWO_PI;
- }
-
- // Find the midpoint latitude.
- //
- // EllipsoidGeodesic will fail if the north and south edges are very close to being on opposite sides of the ellipsoid.
- // Ideally we'd just call EllipsoidGeodesic.setEndPoints and let it throw when it detects this case, but sadly it doesn't
- // even look for this case in optimized builds, so we have to test for it here instead.
- //
- // 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,
- // so handle it just by using 0 latitude as the center. It's certainliy possible to use a smaller tolerance
- // than one degree here, but one degree is safe and putting the center at 0 latitude should be good enough for any
- // rectangle that spans 178+ of the 180 degrees of latitude.
- const longitude = (west + east) * 0.5;
- let latitude;
- if (
- south < -CesiumMath.PI_OVER_TWO + CesiumMath.RADIANS_PER_DEGREE &&
- north > CesiumMath.PI_OVER_TWO - CesiumMath.RADIANS_PER_DEGREE
- ) {
- latitude = 0.0;
- } else {
- const northCartographic = viewRectangle3DCartographic1;
- northCartographic.longitude = longitude;
- northCartographic.latitude = north;
- northCartographic.height = 0.0;
-
- const southCartographic = viewRectangle3DCartographic2;
- southCartographic.longitude = longitude;
- southCartographic.latitude = south;
- southCartographic.height = 0.0;
-
- let ellipsoidGeodesic = viewRectangle3DEllipsoidGeodesic;
- if (
- !defined(ellipsoidGeodesic) ||
- ellipsoidGeodesic.ellipsoid !== ellipsoid
- ) {
- viewRectangle3DEllipsoidGeodesic = ellipsoidGeodesic =
- new EllipsoidGeodesic(undefined, undefined, ellipsoid);
- }
-
- ellipsoidGeodesic.setEndPoints(northCartographic, southCartographic);
- latitude = ellipsoidGeodesic.interpolateUsingFraction(
- 0.5,
- viewRectangle3DCartographic1,
- ).latitude;
- }
-
- const centerCartographic = viewRectangle3DCartographic1;
- centerCartographic.longitude = longitude;
- centerCartographic.latitude = latitude;
- centerCartographic.height = 0.0;
-
- const center = ellipsoid.cartographicToCartesian(
- centerCartographic,
- viewRectangle3DCenter,
- );
-
- const cart = viewRectangle3DCartographic1;
- cart.longitude = east;
- cart.latitude = north;
- const northEast = ellipsoid.cartographicToCartesian(
- cart,
- viewRectangle3DNorthEast,
- );
- cart.longitude = west;
- const northWest = ellipsoid.cartographicToCartesian(
- cart,
- viewRectangle3DNorthWest,
- );
- cart.longitude = longitude;
- const northCenter = ellipsoid.cartographicToCartesian(
- cart,
- viewRectangle3DNorthCenter,
- );
- cart.latitude = south;
- const southCenter = ellipsoid.cartographicToCartesian(
- cart,
- viewRectangle3DSouthCenter,
- );
- cart.longitude = east;
- const southEast = ellipsoid.cartographicToCartesian(
- cart,
- viewRectangle3DSouthEast,
- );
- cart.longitude = west;
- const southWest = ellipsoid.cartographicToCartesian(
- cart,
- viewRectangle3DSouthWest,
- );
-
- Cartesian3.subtract(northWest, center, northWest);
- Cartesian3.subtract(southEast, center, southEast);
- Cartesian3.subtract(northEast, center, northEast);
- Cartesian3.subtract(southWest, center, southWest);
- Cartesian3.subtract(northCenter, center, northCenter);
- Cartesian3.subtract(southCenter, center, southCenter);
-
- const direction = ellipsoid.geodeticSurfaceNormal(center, cameraRF.direction);
- Cartesian3.negate(direction, direction);
- const right = Cartesian3.cross(direction, Cartesian3.UNIT_Z, cameraRF.right);
- Cartesian3.normalize(right, right);
- const up = Cartesian3.cross(right, direction, cameraRF.up);
-
- let d;
- if (camera.frustum instanceof OrthographicFrustum) {
- const width = Math.max(
- Cartesian3.distance(northEast, northWest),
- Cartesian3.distance(southEast, southWest),
- );
- const height = Math.max(
- Cartesian3.distance(northEast, southEast),
- Cartesian3.distance(northWest, southWest),
- );
-
- let rightScalar;
- let topScalar;
- const offCenterFrustum = camera.frustum._offCenterFrustum;
- const ratio = offCenterFrustum.right / offCenterFrustum.top;
- const heightRatio = height * ratio;
- if (width > heightRatio) {
- rightScalar = width;
- topScalar = rightScalar / ratio;
- } else {
- topScalar = height;
- rightScalar = heightRatio;
- }
-
- d = Math.max(rightScalar, topScalar);
- } else {
- const tanPhi = Math.tan(camera.frustum.fovy * 0.5);
- const tanTheta = camera.frustum.aspectRatio * tanPhi;
-
- d = Math.max(
- computeD(direction, up, northWest, tanPhi),
- computeD(direction, up, southEast, tanPhi),
- computeD(direction, up, northEast, tanPhi),
- computeD(direction, up, southWest, tanPhi),
- computeD(direction, up, northCenter, tanPhi),
- computeD(direction, up, southCenter, tanPhi),
- computeD(direction, right, northWest, tanTheta),
- computeD(direction, right, southEast, tanTheta),
- computeD(direction, right, northEast, tanTheta),
- computeD(direction, right, southWest, tanTheta),
- computeD(direction, right, northCenter, tanTheta),
- computeD(direction, right, southCenter, tanTheta),
- );
-
- // If the rectangle crosses the equator, compute D at the equator, too, because that's the
- // widest part of the rectangle when projected onto the globe.
- if (south < 0 && north > 0) {
- const equatorCartographic = viewRectangle3DCartographic1;
- equatorCartographic.longitude = west;
- equatorCartographic.latitude = 0.0;
- equatorCartographic.height = 0.0;
- let equatorPosition = ellipsoid.cartographicToCartesian(
- equatorCartographic,
- viewRectangle3DEquator,
- );
- Cartesian3.subtract(equatorPosition, center, equatorPosition);
- d = Math.max(
- d,
- computeD(direction, up, equatorPosition, tanPhi),
- computeD(direction, right, equatorPosition, tanTheta),
- );
-
- equatorCartographic.longitude = east;
- equatorPosition = ellipsoid.cartographicToCartesian(
- equatorCartographic,
- viewRectangle3DEquator,
- );
- Cartesian3.subtract(equatorPosition, center, equatorPosition);
- d = Math.max(
- d,
- computeD(direction, up, equatorPosition, tanPhi),
- computeD(direction, right, equatorPosition, tanTheta),
- );
- }
- }
-
- return Cartesian3.add(
- center,
- Cartesian3.multiplyByScalar(direction, -d, viewRectangle3DEquator),
- result,
- );
- }
-
- const viewRectangleCVCartographic = new Cartographic();
- const viewRectangleCVNorthEast = new Cartesian3();
- const viewRectangleCVSouthWest = new Cartesian3();
- function rectangleCameraPositionColumbusView(camera, rectangle, result) {
- const projection = camera._projection;
- if (rectangle.west > rectangle.east) {
- rectangle = Rectangle.MAX_VALUE;
- }
- const transform = camera._actualTransform;
- const invTransform = camera._actualInvTransform;
-
- const cart = viewRectangleCVCartographic;
- cart.longitude = rectangle.east;
- cart.latitude = rectangle.north;
- const northEast = projection.project(cart, viewRectangleCVNorthEast);
- Matrix4.multiplyByPoint(transform, northEast, northEast);
- Matrix4.multiplyByPoint(invTransform, northEast, northEast);
-
- cart.longitude = rectangle.west;
- cart.latitude = rectangle.south;
- const southWest = projection.project(cart, viewRectangleCVSouthWest);
- Matrix4.multiplyByPoint(transform, southWest, southWest);
- Matrix4.multiplyByPoint(invTransform, southWest, southWest);
-
- result.x = (northEast.x - southWest.x) * 0.5 + southWest.x;
- result.y = (northEast.y - southWest.y) * 0.5 + southWest.y;
-
- if (defined(camera.frustum.fovy)) {
- const tanPhi = Math.tan(camera.frustum.fovy * 0.5);
- const tanTheta = camera.frustum.aspectRatio * tanPhi;
- result.z =
- Math.max(
- (northEast.x - southWest.x) / tanTheta,
- (northEast.y - southWest.y) / tanPhi,
- ) * 0.5;
- } else {
- const width = northEast.x - southWest.x;
- const height = northEast.y - southWest.y;
- result.z = Math.max(width, height);
- }
-
- return result;
- }
-
- const viewRectangle2DCartographic = new Cartographic();
- const viewRectangle2DNorthEast = new Cartesian3();
- const viewRectangle2DSouthWest = new Cartesian3();
- function rectangleCameraPosition2D(camera, rectangle, result) {
- const projection = camera._projection;
-
- // Account for the rectangle crossing the International Date Line in 2D mode
- let east = rectangle.east;
- if (rectangle.west > rectangle.east) {
- if (camera._scene.mapMode2D === MapMode2D.INFINITE_SCROLL) {
- east += CesiumMath.TWO_PI;
- } else {
- rectangle = Rectangle.MAX_VALUE;
- east = rectangle.east;
- }
- }
-
- let cart = viewRectangle2DCartographic;
- cart.longitude = east;
- cart.latitude = rectangle.north;
- const northEast = projection.project(cart, viewRectangle2DNorthEast);
- cart.longitude = rectangle.west;
- cart.latitude = rectangle.south;
- const southWest = projection.project(cart, viewRectangle2DSouthWest);
-
- const width = Math.abs(northEast.x - southWest.x) * 0.5;
- let height = Math.abs(northEast.y - southWest.y) * 0.5;
-
- let right, top;
- const ratio = camera.frustum.right / camera.frustum.top;
- const heightRatio = height * ratio;
- if (width > heightRatio) {
- right = width;
- top = right / ratio;
- } else {
- top = height;
- right = heightRatio;
- }
-
- height = Math.max(2.0 * right, 2.0 * top);
-
- result.x = (northEast.x - southWest.x) * 0.5 + southWest.x;
- result.y = (northEast.y - southWest.y) * 0.5 + southWest.y;
-
- cart = projection.unproject(result, cart);
- cart.height = height;
- result = projection.project(cart, result);
-
- return result;
- }
-
- /**
- * Get the camera position needed to view a rectangle on an ellipsoid or map
- *
- * @param {Rectangle} rectangle The rectangle to view.
- * @param {Cartesian3} [result] The camera position needed to view the rectangle
- * @returns {Cartesian3} The camera position needed to view the rectangle
- */
- Camera.prototype.getRectangleCameraCoordinates = function (rectangle, result) {
- //>>includeStart('debug', pragmas.debug);
- if (!defined(rectangle)) {
- throw new DeveloperError("rectangle is required");
- }
- //>>includeEnd('debug');
- const mode = this._mode;
-
- if (!defined(result)) {
- result = new Cartesian3();
- }
-
- if (mode === SceneMode.SCENE3D) {
- return rectangleCameraPosition3D(this, rectangle, result);
- } else if (mode === SceneMode.COLUMBUS_VIEW) {
- return rectangleCameraPositionColumbusView(this, rectangle, result);
- } else if (mode === SceneMode.SCENE2D) {
- return rectangleCameraPosition2D(this, rectangle, result);
- }
-
- return undefined;
- };
-
- const pickEllipsoid3DRay = new Ray();
- function pickEllipsoid3D(camera, windowPosition, ellipsoid, result) {
- ellipsoid = ellipsoid ?? Ellipsoid.default;
- const ray = camera.getPickRay(windowPosition, pickEllipsoid3DRay);
- const intersection = IntersectionTests.rayEllipsoid(ray, ellipsoid);
- if (!intersection) {
- return undefined;
- }
-
- const t = intersection.start > 0.0 ? intersection.start : intersection.stop;
- return Ray.getPoint(ray, t, result);
- }
-
- const pickEllipsoid2DRay = new Ray();
- function pickMap2D(camera, windowPosition, projection, result) {
- const ray = camera.getPickRay(windowPosition, pickEllipsoid2DRay);
- let position = ray.origin;
- position = Cartesian3.fromElements(position.y, position.z, 0.0, position);
- const cart = projection.unproject(position);
-
- if (
- cart.latitude < -CesiumMath.PI_OVER_TWO ||
- cart.latitude > CesiumMath.PI_OVER_TWO
- ) {
- return undefined;
- }
-
- return projection.ellipsoid.cartographicToCartesian(cart, result);
- }
-
- const pickEllipsoidCVRay = new Ray();
- function pickMapColumbusView(camera, windowPosition, projection, result) {
- const ray = camera.getPickRay(windowPosition, pickEllipsoidCVRay);
- const scalar = -ray.origin.x / ray.direction.x;
- Ray.getPoint(ray, scalar, result);
-
- const cart = projection.unproject(new Cartesian3(result.y, result.z, 0.0));
-
- if (
- cart.latitude < -CesiumMath.PI_OVER_TWO ||
- cart.latitude > CesiumMath.PI_OVER_TWO ||
- cart.longitude < -Math.PI ||
- cart.longitude > Math.PI
- ) {
- return undefined;
- }
-
- return projection.ellipsoid.cartographicToCartesian(cart, result);
- }
-
- /**
- * Pick an ellipsoid or map.
- *
- * @param {Cartesian2} windowPosition The x and y coordinates of a pixel.
- * @param {Ellipsoid} [ellipsoid=Ellipsoid.default] The ellipsoid to pick.
- * @param {Cartesian3} [result] The object onto which to store the result.
- * @returns {Cartesian3 | undefined} If the ellipsoid or map was picked,
- * returns the point on the surface of the ellipsoid or map in world
- * coordinates. If the ellipsoid or map was not picked, returns undefined.
- *
- * @example
- * const canvas = viewer.scene.canvas;
- * const center = new Cesium.Cartesian2(canvas.clientWidth / 2.0, canvas.clientHeight / 2.0);
- * const ellipsoid = viewer.scene.ellipsoid;
- * const result = viewer.camera.pickEllipsoid(center, ellipsoid);
- */
- Camera.prototype.pickEllipsoid = function (windowPosition, ellipsoid, result) {
- //>>includeStart('debug', pragmas.debug);
- if (!defined(windowPosition)) {
- throw new DeveloperError("windowPosition is required.");
- }
- //>>includeEnd('debug');
-
- const canvas = this._scene.canvas;
- if (canvas.clientWidth === 0 || canvas.clientHeight === 0) {
- return undefined;
- }
-
- if (!defined(result)) {
- result = new Cartesian3();
- }
-
- ellipsoid = ellipsoid ?? Ellipsoid.default;
-
- if (this._mode === SceneMode.SCENE3D) {
- result = pickEllipsoid3D(this, windowPosition, ellipsoid, result);
- } else if (this._mode === SceneMode.SCENE2D) {
- result = pickMap2D(this, windowPosition, this._projection, result);
- } else if (this._mode === SceneMode.COLUMBUS_VIEW) {
- result = pickMapColumbusView(
- this,
- windowPosition,
- this._projection,
- result,
- );
- } else {
- return undefined;
- }
-
- return result;
- };
-
- const pickPerspCenter = new Cartesian3();
- const pickPerspXDir = new Cartesian3();
- const pickPerspYDir = new Cartesian3();
- function getPickRayPerspective(camera, windowPosition, result) {
- const canvas = camera._scene.canvas;
- const width = canvas.clientWidth;
- const height = canvas.clientHeight;
-
- const tanPhi = Math.tan(camera.frustum.fovy * 0.5);
- const tanTheta = camera.frustum.aspectRatio * tanPhi;
- const near = camera.frustum.near;
-
- const x = (2.0 / width) * windowPosition.x - 1.0;
- const y = (2.0 / height) * (height - windowPosition.y) - 1.0;
-
- const position = camera.positionWC;
- Cartesian3.clone(position, result.origin);
-
- const nearCenter = Cartesian3.multiplyByScalar(
- camera.directionWC,
- near,
- pickPerspCenter,
- );
- Cartesian3.add(position, nearCenter, nearCenter);
- const xDir = Cartesian3.multiplyByScalar(
- camera.rightWC,
- x * near * tanTheta,
- pickPerspXDir,
- );
- const yDir = Cartesian3.multiplyByScalar(
- camera.upWC,
- y * near * tanPhi,
- pickPerspYDir,
- );
- const direction = Cartesian3.add(nearCenter, xDir, result.direction);
- Cartesian3.add(direction, yDir, direction);
- Cartesian3.subtract(direction, position, direction);
- Cartesian3.normalize(direction, direction);
-
- return result;
- }
-
- const scratchDirection = new Cartesian3();
-
- function getPickRayOrthographic(camera, windowPosition, result) {
- const canvas = camera._scene.canvas;
- const width = canvas.clientWidth;
- const height = canvas.clientHeight;
-
- let frustum = camera.frustum;
- const offCenterFrustum = frustum.offCenterFrustum;
- if (defined(offCenterFrustum)) {
- frustum = offCenterFrustum;
- }
- let x = (2.0 / width) * windowPosition.x - 1.0;
- x *= (frustum.right - frustum.left) * 0.5;
- let y = (2.0 / height) * (height - windowPosition.y) - 1.0;
- y *= (frustum.top - frustum.bottom) * 0.5;
-
- const origin = result.origin;
- Cartesian3.clone(camera.positionWC, origin);
-
- Cartesian3.multiplyByScalar(camera.rightWC, x, scratchDirection);
- Cartesian3.add(scratchDirection, origin, origin);
- Cartesian3.multiplyByScalar(camera.upWC, y, scratchDirection);
- Cartesian3.add(scratchDirection, origin, origin);
-
- Cartesian3.clone(camera.directionWC, result.direction);
-
- // Account for wrap-around in 2D infinite scroll mode
- if (
- camera._mode === SceneMode.SCENE2D &&
- camera._scene.mapMode2D === MapMode2D.INFINITE_SCROLL
- ) {
- const maxHorizontal = camera._maxCoord.x;
- origin.y =
- CesiumMath.mod(origin.y + maxHorizontal, 2.0 * maxHorizontal) -
- maxHorizontal;
- }
-
- return result;
- }
-
- /**
- * Create a ray from the camera position through the pixel at <code>windowPosition</code>
- * in world coordinates.
- *
- * @param {Cartesian2} windowPosition The x and y coordinates of a pixel.
- * @param {Ray} [result] The object onto which to store the result.
- * @returns {Ray|undefined} Returns the {@link Cartesian3} position and direction of the ray, or undefined if the pick ray cannot be determined.
- */
- Camera.prototype.getPickRay = function (windowPosition, result) {
- //>>includeStart('debug', pragmas.debug);
- if (!defined(windowPosition)) {
- throw new DeveloperError("windowPosition is required.");
- }
- //>>includeEnd('debug');
-
- if (!defined(result)) {
- result = new Ray();
- }
-
- const canvas = this._scene.canvas;
- if (canvas.clientWidth <= 0 || canvas.clientHeight <= 0) {
- return undefined;
- }
-
- const frustum = this.frustum;
- if (
- defined(frustum.aspectRatio) &&
- defined(frustum.fov) &&
- defined(frustum.near)
- ) {
- return getPickRayPerspective(this, windowPosition, result);
- }
-
- return getPickRayOrthographic(this, windowPosition, result);
- };
-
- const scratchToCenter = new Cartesian3();
- const scratchProj = new Cartesian3();
-
- /**
- * Return the distance from the camera to the front of the bounding sphere.
- *
- * @param {BoundingSphere} boundingSphere The bounding sphere in world coordinates.
- * @returns {number} The distance to the bounding sphere.
- */
- Camera.prototype.distanceToBoundingSphere = function (boundingSphere) {
- //>>includeStart('debug', pragmas.debug);
- if (!defined(boundingSphere)) {
- throw new DeveloperError("boundingSphere is required.");
- }
- //>>includeEnd('debug');
-
- const toCenter = Cartesian3.subtract(
- this.positionWC,
- boundingSphere.center,
- scratchToCenter,
- );
- const proj = Cartesian3.multiplyByScalar(
- this.directionWC,
- Cartesian3.dot(toCenter, this.directionWC),
- scratchProj,
- );
- return Math.max(0.0, Cartesian3.magnitude(proj) - boundingSphere.radius);
- };
-
- const scratchPixelSize = new Cartesian2();
-
- /**
- * Return the pixel size in meters.
- *
- * @param {BoundingSphere} boundingSphere The bounding sphere in world coordinates.
- * @param {number} drawingBufferWidth The drawing buffer width.
- * @param {number} drawingBufferHeight The drawing buffer height.
- * @returns {number} The pixel size in meters.
- */
- Camera.prototype.getPixelSize = function (
- boundingSphere,
- drawingBufferWidth,
- drawingBufferHeight,
- ) {
- //>>includeStart('debug', pragmas.debug);
- if (!defined(boundingSphere)) {
- throw new DeveloperError("boundingSphere is required.");
- }
- if (!defined(drawingBufferWidth)) {
- throw new DeveloperError("drawingBufferWidth is required.");
- }
- if (!defined(drawingBufferHeight)) {
- throw new DeveloperError("drawingBufferHeight is required.");
- }
- //>>includeEnd('debug');
-
- const distance = this.distanceToBoundingSphere(boundingSphere);
- const pixelSize = this.frustum.getPixelDimensions(
- drawingBufferWidth,
- drawingBufferHeight,
- distance,
- this._scene.pixelRatio,
- scratchPixelSize,
- );
- return Math.max(pixelSize.x, pixelSize.y);
- };
-
- function createAnimationTemplateCV(
- camera,
- position,
- center,
- maxX,
- maxY,
- duration,
- ) {
- const newPosition = Cartesian3.clone(position);
-
- if (center.y > maxX) {
- newPosition.y -= center.y - maxX;
- } else if (center.y < -maxX) {
- newPosition.y += -maxX - center.y;
- }
-
- if (center.z > maxY) {
- newPosition.z -= center.z - maxY;
- } else if (center.z < -maxY) {
- newPosition.z += -maxY - center.z;
- }
-
- function updateCV(value) {
- const interp = Cartesian3.lerp(
- position,
- newPosition,
- value.time,
- new Cartesian3(),
- );
- camera.worldToCameraCoordinatesPoint(interp, camera.position);
- }
- return {
- easingFunction: EasingFunction.EXPONENTIAL_OUT,
- startObject: {
- time: 0.0,
- },
- stopObject: {
- time: 1.0,
- },
- duration: duration,
- update: updateCV,
- };
- }
-
- const normalScratch = new Cartesian3();
- const centerScratch = new Cartesian3();
- const posScratch = new Cartesian3();
- const scratchCartesian3Subtract = new Cartesian3();
-
- function createAnimationCV(camera, duration) {
- let position = camera.position;
- const direction = camera.direction;
-
- const normal = camera.worldToCameraCoordinatesVector(
- Cartesian3.UNIT_X,
- normalScratch,
- );
- const scalar =
- -Cartesian3.dot(normal, position) / Cartesian3.dot(normal, direction);
- const center = Cartesian3.add(
- position,
- Cartesian3.multiplyByScalar(direction, scalar, centerScratch),
- centerScratch,
- );
- camera.cameraToWorldCoordinatesPoint(center, center);
-
- position = camera.cameraToWorldCoordinatesPoint(camera.position, posScratch);
-
- const tanPhi = Math.tan(camera.frustum.fovy * 0.5);
- const tanTheta = camera.frustum.aspectRatio * tanPhi;
- const distToC = Cartesian3.magnitude(
- Cartesian3.subtract(position, center, scratchCartesian3Subtract),
- );
- const dWidth = tanTheta * distToC;
- const dHeight = tanPhi * distToC;
-
- const mapWidth = camera._maxCoord.x;
- const mapHeight = camera._maxCoord.y;
-
- const maxX = Math.max(dWidth - mapWidth, mapWidth);
- const maxY = Math.max(dHeight - mapHeight, mapHeight);
-
- if (
- position.z < -maxX ||
- position.z > maxX ||
- position.y < -maxY ||
- position.y > maxY
- ) {
- const translateX = center.y < -maxX || center.y > maxX;
- const translateY = center.z < -maxY || center.z > maxY;
- if (translateX || translateY) {
- return createAnimationTemplateCV(
- camera,
- position,
- center,
- maxX,
- maxY,
- duration,
- );
- }
- }
-
- return undefined;
- }
-
- /**
- * Create an animation to move the map into view. This method is only valid for 2D and Columbus modes.
- *
- * @param {number} duration The duration, in seconds, of the animation.
- * @returns {object} The animation or undefined if the scene mode is 3D or the map is already ion view.
- *
- * @private
- */
- Camera.prototype.createCorrectPositionTween = function (duration) {
- //>>includeStart('debug', pragmas.debug);
- if (!defined(duration)) {
- throw new DeveloperError("duration is required.");
- }
- //>>includeEnd('debug');
-
- if (this._mode === SceneMode.COLUMBUS_VIEW) {
- return createAnimationCV(this, duration);
- }
-
- return undefined;
- };
-
- const scratchFlyToDestination = new Cartesian3();
- const newOptions = {
- destination: undefined,
- heading: undefined,
- pitch: undefined,
- roll: undefined,
- duration: undefined,
- complete: undefined,
- cancel: undefined,
- endTransform: undefined,
- maximumHeight: undefined,
- easingFunction: undefined,
- };
-
- /**
- * Cancels the current camera flight and leaves the camera at its current location.
- * If no flight is in progress, this function does nothing.
- */
- Camera.prototype.cancelFlight = function () {
- if (defined(this._currentFlight)) {
- this._currentFlight.cancelTween();
- this._currentFlight = undefined;
- }
- };
-
- /**
- * Completes the current camera flight and moves the camera immediately to its final destination.
- * If no flight is in progress, this function does nothing.
- */
- Camera.prototype.completeFlight = function () {
- if (defined(this._currentFlight)) {
- this._currentFlight.cancelTween();
-
- const options = {
- destination: undefined,
- orientation: {
- heading: undefined,
- pitch: undefined,
- roll: undefined,
- },
- };
-
- options.destination = newOptions.destination;
- options.orientation.heading = newOptions.heading;
- options.orientation.pitch = newOptions.pitch;
- options.orientation.roll = newOptions.roll;
-
- this.setView(options);
-
- if (defined(this._currentFlight.complete)) {
- this._currentFlight.complete();
- }
-
- this._currentFlight = undefined;
- }
- };
-
- /**
- * Flies the camera from its current position to a new position.
- *
- * @param {object} options Object with the following properties:
- * @param {Cartesian3|Rectangle} options.destination The final position of the camera in world coordinates or a rectangle that would be visible from a top-down view.
- * @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
- * 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
- * y direction in Columbus view. Orientation is not used in 2D when in infinite scrolling mode.
- * @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.
- * @param {Camera.FlightCompleteCallback} [options.complete] The function to execute when the flight is complete.
- * @param {Camera.FlightCancelledCallback} [options.cancel] The function to execute if the flight is cancelled.
- * @param {Matrix4} [options.endTransform] Transform matrix representing the reference frame the camera will be in when the flight is completed.
- * @param {number} [options.maximumHeight] The maximum height at the peak of the flight.
- * @param {number} [options.pitchAdjustHeight] If camera flyes higher than that value, adjust pitch duiring the flight to look down, and keep Earth in viewport.
- * @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.
- * @param {number} [options.flyOverLongitudeWeight] Fly over the lon specifyed via flyOverLongitude only if that way is not longer than short way times flyOverLongitudeWeight.
- * @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>.
- * @param {EasingFunction.Callback} [options.easingFunction] Controls how the time is interpolated over the duration of the flight.
- *
- * @exception {DeveloperError} If either direction or up is given, then both are required.
- *
- * @example
- * // 1. Fly to a position with a top-down view
- * viewer.camera.flyTo({
- * destination : Cesium.Cartesian3.fromDegrees(-117.16, 32.71, 15000.0)
- * });
- *
- * // 2. Fly to a Rectangle with a top-down view
- * viewer.camera.flyTo({
- * destination : Cesium.Rectangle.fromDegrees(west, south, east, north)
- * });
- *
- * // 3. Fly to a position with an orientation using unit vectors.
- * viewer.camera.flyTo({
- * destination : Cesium.Cartesian3.fromDegrees(-122.19, 46.25, 5000.0),
- * orientation : {
- * direction : new Cesium.Cartesian3(-0.04231243104240401, -0.20123236049443421, -0.97862924300734),
- * up : new Cesium.Cartesian3(-0.47934589305293746, -0.8553216253114552, 0.1966022179118339)
- * }
- * });
- *
- * // 4. Fly to a position with an orientation using heading, pitch and roll.
- * viewer.camera.flyTo({
- * destination : Cesium.Cartesian3.fromDegrees(-122.19, 46.25, 5000.0),
- * orientation : {
- * heading : Cesium.Math.toRadians(175.0),
- * pitch : Cesium.Math.toRadians(-35.0),
- * roll : 0.0
- * }
- * });
- */
- Camera.prototype.flyTo = function (options) {
- options = options ?? Frozen.EMPTY_OBJECT;
- let destination = options.destination;
- //>>includeStart('debug', pragmas.debug);
- if (!defined(destination)) {
- throw new DeveloperError("destination is required.");
- }
- //>>includeEnd('debug');
-
- const mode = this._mode;
- if (mode === SceneMode.MORPHING) {
- return;
- }
-
- this.cancelFlight();
-
- const isRectangle = destination instanceof Rectangle;
- if (isRectangle) {
- destination = this.getRectangleCameraCoordinates(
- destination,
- scratchFlyToDestination,
- );
- }
-
- let orientation = options.orientation ?? Frozen.EMPTY_OBJECT;
- if (defined(orientation.direction)) {
- orientation = directionUpToHeadingPitchRoll(
- this,
- destination,
- orientation,
- scratchSetViewOptions.orientation,
- );
- }
-
- if (defined(options.duration) && options.duration <= 0.0) {
- const setViewOptions = scratchSetViewOptions;
- setViewOptions.destination = options.destination;
- setViewOptions.orientation.heading = orientation.heading;
- setViewOptions.orientation.pitch = orientation.pitch;
- setViewOptions.orientation.roll = orientation.roll;
- setViewOptions.convert = options.convert;
- setViewOptions.endTransform = options.endTransform;
- this.setView(setViewOptions);
- if (typeof options.complete === "function") {
- options.complete();
- }
- return;
- }
-
- const that = this;
- /* eslint-disable-next-line prefer-const */
- let flightTween;
-
- newOptions.destination = destination;
- newOptions.heading = orientation.heading;
- newOptions.pitch = orientation.pitch;
- newOptions.roll = orientation.roll;
- newOptions.duration = options.duration;
- newOptions.complete = function () {
- if (flightTween === that._currentFlight) {
- that._currentFlight = undefined;
- }
- if (defined(options.complete)) {
- options.complete();
- }
- };
- newOptions.cancel = options.cancel;
- newOptions.endTransform = options.endTransform;
- newOptions.convert = isRectangle ? false : options.convert;
- newOptions.maximumHeight = options.maximumHeight;
- newOptions.pitchAdjustHeight = options.pitchAdjustHeight;
- newOptions.flyOverLongitude = options.flyOverLongitude;
- newOptions.flyOverLongitudeWeight = options.flyOverLongitudeWeight;
- newOptions.easingFunction = options.easingFunction;
-
- const scene = this._scene;
- const tweenOptions = CameraFlightPath.createTween(scene, newOptions);
- // If the camera doesn't actually need to go anywhere, duration
- // will be 0 and we can just complete the current flight.
- if (tweenOptions.duration === 0) {
- if (typeof tweenOptions.complete === "function") {
- tweenOptions.complete();
- }
- return;
- }
- flightTween = scene.tweens.add(tweenOptions);
- this._currentFlight = flightTween;
-
- // Save the final destination view information for the PRELOAD_FLIGHT pass.
- let preloadFlightCamera = this._scene.preloadFlightCamera;
- if (this._mode !== SceneMode.SCENE2D) {
- if (!defined(preloadFlightCamera)) {
- preloadFlightCamera = Camera.clone(this);
- }
- preloadFlightCamera.setView({
- destination: destination,
- orientation: orientation,
- });
-
- this._scene.preloadFlightCullingVolume =
- preloadFlightCamera.frustum.computeCullingVolume(
- preloadFlightCamera.positionWC,
- preloadFlightCamera.directionWC,
- preloadFlightCamera.upWC,
- );
- }
- };
-
- function distanceToBoundingSphere3D(camera, radius) {
- const frustum = camera.frustum;
- const tanPhi = Math.tan(frustum.fovy * 0.5);
- const tanTheta = frustum.aspectRatio * tanPhi;
- return Math.max(radius / tanTheta, radius / tanPhi);
- }
-
- function distanceToBoundingSphere2D(camera, radius) {
- let frustum = camera.frustum;
- const offCenterFrustum = frustum.offCenterFrustum;
- if (defined(offCenterFrustum)) {
- frustum = offCenterFrustum;
- }
-
- let right, top;
- const ratio = frustum.right / frustum.top;
- const heightRatio = radius * ratio;
- if (radius > heightRatio) {
- right = radius;
- top = right / ratio;
- } else {
- top = radius;
- right = heightRatio;
- }
-
- return Math.max(right, top) * 1.5;
- }
-
- const MINIMUM_ZOOM = 100.0;
-
- function adjustBoundingSphereOffset(camera, boundingSphere, offset) {
- offset = HeadingPitchRange.clone(
- defined(offset) ? offset : Camera.DEFAULT_OFFSET,
- );
-
- const minimumZoom =
- camera._scene.screenSpaceCameraController.minimumZoomDistance;
- const maximumZoom =
- camera._scene.screenSpaceCameraController.maximumZoomDistance;
- const range = offset.range;
- if (!defined(range) || range === 0.0) {
- const radius = boundingSphere.radius;
- if (radius === 0.0) {
- offset.range = MINIMUM_ZOOM;
- } else if (
- camera.frustum instanceof OrthographicFrustum ||
- camera._mode === SceneMode.SCENE2D
- ) {
- offset.range = distanceToBoundingSphere2D(camera, radius);
- } else {
- offset.range = distanceToBoundingSphere3D(camera, radius);
- }
- offset.range = CesiumMath.clamp(offset.range, minimumZoom, maximumZoom);
- }
-
- return offset;
- }
-
- /**
- * Sets the camera so that the current view contains the provided bounding sphere.
- *
- * <p>The offset is heading/pitch/range in the local east-north-up reference frame centered at the center of the bounding sphere.
- * The heading and the pitch angles are defined in the local east-north-up reference frame.
- * The heading is the angle from y axis and increasing towards the x axis. Pitch is the rotation from the xy-plane. Positive pitch
- * angles are below the plane. Negative pitch angles are above the plane. The range is the distance from the center. If the range is
- * zero, a range will be computed such that the whole bounding sphere is visible.</p>
- *
- * <p>In 2D, there must be a top down view. The camera will be placed above the target looking down. The height above the
- * target will be the range. The heading will be determined from the offset. If the heading cannot be
- * determined from the offset, the heading will be north.</p>
- *
- * @param {BoundingSphere} boundingSphere The bounding sphere to view, in world coordinates.
- * @param {HeadingPitchRange} [offset] The offset from the target in the local east-north-up reference frame centered at the target.
- *
- * @exception {DeveloperError} viewBoundingSphere is not supported while morphing.
- */
- Camera.prototype.viewBoundingSphere = function (boundingSphere, offset) {
- //>>includeStart('debug', pragmas.debug);
- if (!defined(boundingSphere)) {
- throw new DeveloperError("boundingSphere is required.");
- }
-
- if (this._mode === SceneMode.MORPHING) {
- throw new DeveloperError(
- "viewBoundingSphere is not supported while morphing.",
- );
- }
- //>>includeEnd('debug');
-
- offset = adjustBoundingSphereOffset(this, boundingSphere, offset);
- this.lookAt(boundingSphere.center, offset);
- };
-
- const scratchflyToBoundingSphereTransform = new Matrix4();
- const scratchflyToBoundingSphereDestination = new Cartesian3();
- const scratchflyToBoundingSphereDirection = new Cartesian3();
- const scratchflyToBoundingSphereUp = new Cartesian3();
- const scratchflyToBoundingSphereRight = new Cartesian3();
- const scratchFlyToBoundingSphereCart4 = new Cartesian4();
- const scratchFlyToBoundingSphereQuaternion = new Quaternion();
- const scratchFlyToBoundingSphereMatrix3 = new Matrix3();
-
- /**
- * Flies the camera to a location where the current view contains the provided bounding sphere.
- *
- * <p> The offset is heading/pitch/range in the local east-north-up reference frame centered at the center of the bounding sphere.
- * The heading and the pitch angles are defined in the local east-north-up reference frame.
- * The heading is the angle from y axis and increasing towards the x axis. Pitch is the rotation from the xy-plane. Positive pitch
- * angles are below the plane. Negative pitch angles are above the plane. The range is the distance from the center. If the range is
- * zero, a range will be computed such that the whole bounding sphere is visible.</p>
- *
- * <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
- * target will be the range. The heading will be aligned to local north.</p>
- *
- * @param {BoundingSphere} boundingSphere The bounding sphere to view, in world coordinates.
- * @param {object} [options] Object with the following properties:
- * @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.
- * @param {HeadingPitchRange} [options.offset] The offset from the target in the local east-north-up reference frame centered at the target.
- * @param {Camera.FlightCompleteCallback} [options.complete] The function to execute when the flight is complete.
- * @param {Camera.FlightCancelledCallback} [options.cancel] The function to execute if the flight is cancelled.
- * @param {Matrix4} [options.endTransform] Transform matrix representing the reference frame the camera will be in when the flight is completed.
- * @param {number} [options.maximumHeight] The maximum height at the peak of the flight.
- * @param {number} [options.pitchAdjustHeight] If camera flyes higher than that value, adjust pitch duiring the flight to look down, and keep Earth in viewport.
- * @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.
- * @param {number} [options.flyOverLongitudeWeight] Fly over the lon specifyed via flyOverLongitude only if that way is not longer than short way times flyOverLongitudeWeight.
- * @param {EasingFunction.Callback} [options.easingFunction] Controls how the time is interpolated over the duration of the flight.
- */
- Camera.prototype.flyToBoundingSphere = function (boundingSphere, options) {
- //>>includeStart('debug', pragmas.debug);
- if (!defined(boundingSphere)) {
- throw new DeveloperError("boundingSphere is required.");
- }
- //>>includeEnd('debug');
-
- options = options ?? Frozen.EMPTY_OBJECT;
- const scene2D =
- this._mode === SceneMode.SCENE2D || this._mode === SceneMode.COLUMBUS_VIEW;
- this._setTransform(Matrix4.IDENTITY);
- const offset = adjustBoundingSphereOffset(
- this,
- boundingSphere,
- options.offset,
- );
-
- let position;
- if (scene2D) {
- position = Cartesian3.multiplyByScalar(
- Cartesian3.UNIT_Z,
- offset.range,
- scratchflyToBoundingSphereDestination,
- );
- } else {
- position = offsetFromHeadingPitchRange(
- offset.heading,
- offset.pitch,
- offset.range,
- );
- }
-
- const scene = this._scene;
- const ellipsoid = scene.ellipsoid ?? Ellipsoid.default;
-
- const transform = Transforms.eastNorthUpToFixedFrame(
- boundingSphere.center,
- ellipsoid,
- scratchflyToBoundingSphereTransform,
- );
- Matrix4.multiplyByPoint(transform, position, position);
-
- let direction;
- let up;
-
- if (!scene2D) {
- direction = Cartesian3.subtract(
- boundingSphere.center,
- position,
- scratchflyToBoundingSphereDirection,
- );
- Cartesian3.normalize(direction, direction);
-
- up = Matrix4.multiplyByPointAsVector(
- transform,
- Cartesian3.UNIT_Z,
- scratchflyToBoundingSphereUp,
- );
- if (1.0 - Math.abs(Cartesian3.dot(direction, up)) < CesiumMath.EPSILON6) {
- const rotateQuat = Quaternion.fromAxisAngle(
- direction,
- offset.heading,
- scratchFlyToBoundingSphereQuaternion,
- );
- const rotation = Matrix3.fromQuaternion(
- rotateQuat,
- scratchFlyToBoundingSphereMatrix3,
- );
-
- Cartesian3.fromCartesian4(
- Matrix4.getColumn(transform, 1, scratchFlyToBoundingSphereCart4),
- up,
- );
- Matrix3.multiplyByVector(rotation, up, up);
- }
-
- const right = Cartesian3.cross(
- direction,
- up,
- scratchflyToBoundingSphereRight,
- );
- Cartesian3.cross(right, direction, up);
- Cartesian3.normalize(up, up);
- }
-
- this.flyTo({
- destination: position,
- orientation: {
- direction: direction,
- up: up,
- },
- duration: options.duration,
- complete: options.complete,
- cancel: options.cancel,
- endTransform: options.endTransform,
- maximumHeight: options.maximumHeight,
- easingFunction: options.easingFunction,
- flyOverLongitude: options.flyOverLongitude,
- flyOverLongitudeWeight: options.flyOverLongitudeWeight,
- pitchAdjustHeight: options.pitchAdjustHeight,
- });
- };
-
- const scratchCartesian3_1 = new Cartesian3();
- const scratchCartesian3_2 = new Cartesian3();
- const scratchCartesian3_3 = new Cartesian3();
- const scratchCartesian3_4 = new Cartesian3();
- const horizonPoints = [
- new Cartesian3(),
- new Cartesian3(),
- new Cartesian3(),
- new Cartesian3(),
- ];
-
- function computeHorizonQuad(camera, ellipsoid) {
- const radii = ellipsoid.radii;
- const p = camera.positionWC;
-
- // Find the corresponding position in the scaled space of the ellipsoid.
- const q = Cartesian3.multiplyComponents(
- ellipsoid.oneOverRadii,
- p,
- scratchCartesian3_1,
- );
-
- const qMagnitude = Cartesian3.magnitude(q);
- const qUnit = Cartesian3.normalize(q, scratchCartesian3_2);
-
- // Determine the east and north directions at q.
- let eUnit;
- let nUnit;
- if (
- Cartesian3.equalsEpsilon(qUnit, Cartesian3.UNIT_Z, CesiumMath.EPSILON10)
- ) {
- eUnit = new Cartesian3(0, 1, 0);
- nUnit = new Cartesian3(0, 0, 1);
- } else {
- eUnit = Cartesian3.normalize(
- Cartesian3.cross(Cartesian3.UNIT_Z, qUnit, scratchCartesian3_3),
- scratchCartesian3_3,
- );
- nUnit = Cartesian3.normalize(
- Cartesian3.cross(qUnit, eUnit, scratchCartesian3_4),
- scratchCartesian3_4,
- );
- }
-
- // Determine the radius of the 'limb' of the ellipsoid.
- const wMagnitude = Math.sqrt(Cartesian3.magnitudeSquared(q) - 1.0);
-
- // Compute the center and offsets.
- const center = Cartesian3.multiplyByScalar(
- qUnit,
- 1.0 / qMagnitude,
- scratchCartesian3_1,
- );
- const scalar = wMagnitude / qMagnitude;
- const eastOffset = Cartesian3.multiplyByScalar(
- eUnit,
- scalar,
- scratchCartesian3_2,
- );
- const northOffset = Cartesian3.multiplyByScalar(
- nUnit,
- scalar,
- scratchCartesian3_3,
- );
-
- // A conservative measure for the longitudes would be to use the min/max longitudes of the bounding frustum.
- const upperLeft = Cartesian3.add(center, northOffset, horizonPoints[0]);
- Cartesian3.subtract(upperLeft, eastOffset, upperLeft);
- Cartesian3.multiplyComponents(radii, upperLeft, upperLeft);
-
- const lowerLeft = Cartesian3.subtract(center, northOffset, horizonPoints[1]);
- Cartesian3.subtract(lowerLeft, eastOffset, lowerLeft);
- Cartesian3.multiplyComponents(radii, lowerLeft, lowerLeft);
-
- const lowerRight = Cartesian3.subtract(center, northOffset, horizonPoints[2]);
- Cartesian3.add(lowerRight, eastOffset, lowerRight);
- Cartesian3.multiplyComponents(radii, lowerRight, lowerRight);
-
- const upperRight = Cartesian3.add(center, northOffset, horizonPoints[3]);
- Cartesian3.add(upperRight, eastOffset, upperRight);
- Cartesian3.multiplyComponents(radii, upperRight, upperRight);
-
- return horizonPoints;
- }
-
- const scratchPickCartesian2 = new Cartesian2();
- const scratchRectCartesian = new Cartesian3();
- const cartoArray = [
- new Cartographic(),
- new Cartographic(),
- new Cartographic(),
- new Cartographic(),
- ];
- function addToResult(x, y, index, camera, ellipsoid, computedHorizonQuad) {
- scratchPickCartesian2.x = x;
- scratchPickCartesian2.y = y;
- const r = camera.pickEllipsoid(
- scratchPickCartesian2,
- ellipsoid,
- scratchRectCartesian,
- );
- if (defined(r)) {
- cartoArray[index] = ellipsoid.cartesianToCartographic(r, cartoArray[index]);
- return 1;
- }
- cartoArray[index] = ellipsoid.cartesianToCartographic(
- computedHorizonQuad[index],
- cartoArray[index],
- );
- return 0;
- }
- /**
- * Computes the approximate visible rectangle on the ellipsoid.
- *
- * @param {Ellipsoid} [ellipsoid=Ellipsoid.default] The ellipsoid that you want to know the visible region.
- * @param {Rectangle} [result] The rectangle in which to store the result
- *
- * @returns {Rectangle|undefined} The visible rectangle or undefined if the ellipsoid isn't visible at all.
- */
- Camera.prototype.computeViewRectangle = function (ellipsoid, result) {
- ellipsoid = ellipsoid ?? Ellipsoid.default;
- const cullingVolume = this.frustum.computeCullingVolume(
- this.positionWC,
- this.directionWC,
- this.upWC,
- );
- const boundingSphere = new BoundingSphere(
- Cartesian3.ZERO,
- ellipsoid.maximumRadius,
- );
- const visibility = cullingVolume.computeVisibility(boundingSphere);
- if (visibility === Intersect.OUTSIDE) {
- return undefined;
- }
-
- const canvas = this._scene.canvas;
- const width = canvas.clientWidth;
- const height = canvas.clientHeight;
-
- let successfulPickCount = 0;
-
- const computedHorizonQuad = computeHorizonQuad(this, ellipsoid);
-
- successfulPickCount += addToResult(
- 0,
- 0,
- 0,
- this,
- ellipsoid,
- computedHorizonQuad,
- );
- successfulPickCount += addToResult(
- 0,
- height,
- 1,
- this,
- ellipsoid,
- computedHorizonQuad,
- );
- successfulPickCount += addToResult(
- width,
- height,
- 2,
- this,
- ellipsoid,
- computedHorizonQuad,
- );
- successfulPickCount += addToResult(
- width,
- 0,
- 3,
- this,
- ellipsoid,
- computedHorizonQuad,
- );
-
- if (successfulPickCount < 2) {
- // If we have space non-globe in 3 or 4 corners then return the whole globe
- return Rectangle.MAX_VALUE;
- }
-
- result = Rectangle.fromCartographicArray(cartoArray, result);
-
- // Detect if we go over the poles
- let distance = 0;
- let lastLon = cartoArray[3].longitude;
- for (let i = 0; i < 4; ++i) {
- const lon = cartoArray[i].longitude;
- const diff = Math.abs(lon - lastLon);
- if (diff > CesiumMath.PI) {
- // Crossed the dateline
- distance += CesiumMath.TWO_PI - diff;
- } else {
- distance += diff;
- }
-
- lastLon = lon;
- }
-
- // We are over one of the poles so adjust the rectangle accordingly
- if (
- CesiumMath.equalsEpsilon(
- Math.abs(distance),
- CesiumMath.TWO_PI,
- CesiumMath.EPSILON9,
- )
- ) {
- result.west = -CesiumMath.PI;
- result.east = CesiumMath.PI;
- if (cartoArray[0].latitude >= 0.0) {
- result.north = CesiumMath.PI_OVER_TWO;
- } else {
- result.south = -CesiumMath.PI_OVER_TWO;
- }
- }
-
- return result;
- };
-
- /**
- * Switches the frustum/projection to perspective.
- *
- * This function is a no-op in 2D which must always be orthographic.
- */
- Camera.prototype.switchToPerspectiveFrustum = function () {
- if (
- this._mode === SceneMode.SCENE2D ||
- this.frustum instanceof PerspectiveFrustum
- ) {
- return;
- }
-
- const scene = this._scene;
- this.frustum = new PerspectiveFrustum();
- this.frustum.aspectRatio =
- scene.drawingBufferWidth / scene.drawingBufferHeight;
- this.frustum.fov = CesiumMath.toRadians(60.0);
- };
-
- /**
- * Switches the frustum/projection to orthographic.
- *
- * This function is a no-op in 2D which will always be orthographic.
- */
- Camera.prototype.switchToOrthographicFrustum = function () {
- if (
- this._mode === SceneMode.SCENE2D ||
- this.frustum instanceof OrthographicFrustum
- ) {
- return;
- }
-
- // This must be called before changing the frustum because it uses the previous
- // frustum to reconstruct the world space position from the depth buffer.
- const frustumWidth = calculateOrthographicFrustumWidth(this);
-
- const scene = this._scene;
- this.frustum = new OrthographicFrustum();
- this.frustum.aspectRatio =
- scene.drawingBufferWidth / scene.drawingBufferHeight;
- this.frustum.width = frustumWidth;
- };
-
- /**
- * @private
- */
- Camera.clone = function (camera, result) {
- if (!defined(result)) {
- result = new Camera(camera._scene);
- }
-
- Cartesian3.clone(camera.position, result.position);
- Cartesian3.clone(camera.direction, result.direction);
- Cartesian3.clone(camera.up, result.up);
- Cartesian3.clone(camera.right, result.right);
- Matrix4.clone(camera._transform, result.transform);
- result._transformChanged = true;
- result.frustum = camera.frustum.clone();
-
- return result;
- };
-
- /**
- * A function that will execute when a flight completes.
- * @callback Camera.FlightCompleteCallback
- */
-
- /**
- * A function that will execute when a flight is cancelled.
- * @callback Camera.FlightCancelledCallback
- */
- export default Camera;
|