ArcballControls.js 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543
  1. import {
  2. Controls,
  3. GridHelper,
  4. EllipseCurve,
  5. BufferGeometry,
  6. Line,
  7. LineBasicMaterial,
  8. Raycaster,
  9. Group,
  10. Box3,
  11. Sphere,
  12. Quaternion,
  13. Vector2,
  14. Vector3,
  15. Matrix4,
  16. MathUtils
  17. } from 'three';
  18. //trackball state
  19. const STATE = {
  20. IDLE: Symbol(),
  21. ROTATE: Symbol(),
  22. PAN: Symbol(),
  23. SCALE: Symbol(),
  24. FOV: Symbol(),
  25. FOCUS: Symbol(),
  26. ZROTATE: Symbol(),
  27. TOUCH_MULTI: Symbol(),
  28. ANIMATION_FOCUS: Symbol(),
  29. ANIMATION_ROTATE: Symbol()
  30. };
  31. const INPUT = {
  32. NONE: Symbol(),
  33. ONE_FINGER: Symbol(),
  34. ONE_FINGER_SWITCHED: Symbol(),
  35. TWO_FINGER: Symbol(),
  36. MULT_FINGER: Symbol(),
  37. CURSOR: Symbol()
  38. };
  39. //cursor center coordinates
  40. const _center = {
  41. x: 0,
  42. y: 0
  43. };
  44. //transformation matrices for gizmos and camera
  45. const _transformation = {
  46. camera: new Matrix4(),
  47. gizmos: new Matrix4()
  48. };
  49. /**
  50. * Fires when the camera has been transformed by the controls.
  51. *
  52. * @event ArcballControls#change
  53. * @type {Object}
  54. */
  55. const _changeEvent = { type: 'change' };
  56. /**
  57. * Fires when an interaction was initiated.
  58. *
  59. * @event ArcballControls#start
  60. * @type {Object}
  61. */
  62. const _startEvent = { type: 'start' };
  63. /**
  64. * Fires when an interaction has finished.
  65. *
  66. * @event ArcballControls#end
  67. * @type {Object}
  68. */
  69. const _endEvent = { type: 'end' };
  70. const _raycaster = new Raycaster();
  71. const _offset = new Vector3();
  72. const _gizmoMatrixStateTemp = new Matrix4();
  73. const _cameraMatrixStateTemp = new Matrix4();
  74. const _scalePointTemp = new Vector3();
  75. const _EPS = 0.000001;
  76. /**
  77. * Arcball controls allow the camera to be controlled by a virtual trackball with full touch support and advanced navigation functionality.
  78. * Cursor/finger positions and movements are mapped over a virtual trackball surface represented by a gizmo and mapped in intuitive and
  79. * consistent camera movements. Dragging cursor/fingers will cause camera to orbit around the center of the trackball in a conservative
  80. * way (returning to the starting point will make the camera return to its starting orientation).
  81. *
  82. * In addition to supporting pan, zoom and pinch gestures, double clicking/tapping focuses on a point, intuitively moving the object's
  83. * point of interest to the center of the virtual trackball. Focus allows a much better inspection and navigation in complex environment.
  84. * Moreover Arcball controls allow FOV manipulation (in a vertigo-style method) and z-rotation. Saving and restoring of Camera State
  85. * is supported also through clipboard (use ctrl+c and ctrl+v shortcuts for copy and paste the state).
  86. *
  87. * Unlike {@link OrbitControls} and {@link TrackballControls}, `ArcballControls` doesn't require `update()` to be called externally in an
  88. * animation loop when animations are on.
  89. *
  90. * @augments Controls
  91. * @three_import import { ArcballControls } from 'three/addons/controls/ArcballControls.js';
  92. */
  93. class ArcballControls extends Controls {
  94. /**
  95. * Constructs a new controls instance.
  96. *
  97. * @param {Camera} camera - The camera to be controlled. The camera must not be a child of another object, unless that object is the scene itself.
  98. * @param {?HTMLElement} [domElement=null] - The HTML element used for event listeners.
  99. * @param {?Scene} [scene=null] The scene rendered by the camera. If not given, gizmos cannot be shown.
  100. */
  101. constructor( camera, domElement = null, scene = null ) {
  102. super( camera, domElement );
  103. /**
  104. * The scene rendered by the camera. If not given, gizmos cannot be shown.
  105. *
  106. * @type {?Scene}
  107. * @default null
  108. */
  109. this.scene = scene;
  110. /**
  111. * The control's focus point.
  112. *
  113. * @type {Vector3}
  114. */
  115. this.target = new Vector3();
  116. this._currentTarget = new Vector3();
  117. /**
  118. * The size of the gizmo relative to the screen width and height.
  119. *
  120. * @type {number}
  121. * @default 0.67
  122. */
  123. this.radiusFactor = 0.67;
  124. /**
  125. * Holds the mouse actions of this controls. This property is maintained by the methods
  126. * `setMouseAction()` and `unsetMouseAction()`.
  127. *
  128. * @type {Array<Object>}
  129. */
  130. this.mouseActions = [];
  131. this._mouseOp = null;
  132. //global vectors and matrices that are used in some operations to avoid creating new objects every time (e.g. every time cursor moves)
  133. this._v2_1 = new Vector2();
  134. this._v3_1 = new Vector3();
  135. this._v3_2 = new Vector3();
  136. this._m4_1 = new Matrix4();
  137. this._m4_2 = new Matrix4();
  138. this._quat = new Quaternion();
  139. //transformation matrices
  140. this._translationMatrix = new Matrix4(); //matrix for translation operation
  141. this._rotationMatrix = new Matrix4(); //matrix for rotation operation
  142. this._scaleMatrix = new Matrix4(); //matrix for scaling operation
  143. this._rotationAxis = new Vector3(); //axis for rotate operation
  144. //camera state
  145. this._cameraMatrixState = new Matrix4();
  146. this._cameraProjectionState = new Matrix4();
  147. this._fovState = 1;
  148. this._upState = new Vector3();
  149. this._zoomState = 1;
  150. this._nearPos = 0;
  151. this._farPos = 0;
  152. this._gizmoMatrixState = new Matrix4();
  153. //initial values
  154. this._up0 = new Vector3();
  155. this._zoom0 = 1;
  156. this._fov0 = 0;
  157. this._initialNear = 0;
  158. this._nearPos0 = 0;
  159. this._initialFar = 0;
  160. this._farPos0 = 0;
  161. this._cameraMatrixState0 = new Matrix4();
  162. this._gizmoMatrixState0 = new Matrix4();
  163. this._target0 = new Vector3();
  164. //pointers array
  165. this._button = - 1;
  166. this._touchStart = [];
  167. this._touchCurrent = [];
  168. this._input = INPUT.NONE;
  169. //two fingers touch interaction
  170. this._switchSensibility = 32; //minimum movement to be performed to fire single pan start after the second finger has been released
  171. this._startFingerDistance = 0; //distance between two fingers
  172. this._currentFingerDistance = 0;
  173. this._startFingerRotation = 0; //amount of rotation performed with two fingers
  174. this._currentFingerRotation = 0;
  175. //double tap
  176. this._devPxRatio = 0;
  177. this._downValid = true;
  178. this._nclicks = 0;
  179. this._downEvents = [];
  180. this._downStart = 0; //pointerDown time
  181. this._clickStart = 0; //first click time
  182. this._maxDownTime = 250;
  183. this._maxInterval = 300;
  184. this._posThreshold = 24;
  185. this._movementThreshold = 24;
  186. //cursor positions
  187. this._currentCursorPosition = new Vector3();
  188. this._startCursorPosition = new Vector3();
  189. //grid
  190. this._grid = null; //grid to be visualized during pan operation
  191. this._gridPosition = new Vector3();
  192. //gizmos
  193. this._gizmos = new Group();
  194. this._curvePts = 128;
  195. //animations
  196. this._timeStart = - 1; //initial time
  197. this._animationId = - 1;
  198. /**
  199. * Duration of focus animations in ms.
  200. *
  201. * @type {number}
  202. * @default 500
  203. */
  204. this.focusAnimationTime = 500;
  205. //rotate animation
  206. this._timePrev = 0; //time at which previous rotate operation has been detected
  207. this._timeCurrent = 0; //time at which current rotate operation has been detected
  208. this._anglePrev = 0; //angle of previous rotation
  209. this._angleCurrent = 0; //angle of current rotation
  210. this._cursorPosPrev = new Vector3(); //cursor position when previous rotate operation has been detected
  211. this._cursorPosCurr = new Vector3();//cursor position when current rotate operation has been detected
  212. this._wPrev = 0; //angular velocity of the previous rotate operation
  213. this._wCurr = 0; //angular velocity of the current rotate operation
  214. //parameters
  215. /**
  216. * If set to `true`, the camera's near and far values will be adjusted every time zoom is
  217. * performed trying to maintain the same visible portion given by initial near and far
  218. * values. Only works with perspective cameras.
  219. *
  220. * This feature only works as expected if the camera's initial state (position, near and far values)
  221. * is correctly configured before creating the controls. Otherwise {@link ArcballControls#setCamera}
  222. * must be called by the application.
  223. *
  224. * @type {boolean}
  225. * @default false
  226. */
  227. this.adjustNearFar = false;
  228. /**
  229. * The scaling factor used when performing zoom operation.
  230. *
  231. * @type {number}
  232. * @default 1.1
  233. */
  234. this.scaleFactor = 1.1;
  235. /**
  236. * The damping inertia used if 'enableAnimations` is set to `true`.
  237. *
  238. * @type {number}
  239. * @default 25
  240. */
  241. this.dampingFactor = 25;
  242. /**
  243. * Maximum angular velocity allowed on rotation animation start.
  244. *
  245. * @type {number}
  246. * @default 20
  247. */
  248. this.wMax = 20;
  249. /**
  250. * Set to `true` to enable animations for rotation (damping) and focus operation.
  251. *
  252. * @type {boolean}
  253. * @default true
  254. */
  255. this.enableAnimations = true;
  256. /**
  257. * If set to `true`, a grid will appear when panning operation is being performed
  258. * (desktop interaction only).
  259. *
  260. * @type {boolean}
  261. * @default false
  262. */
  263. this.enableGrid = false;
  264. /**
  265. * Set to `true` to make zoom become cursor centered.
  266. *
  267. * @type {boolean}
  268. * @default false
  269. */
  270. this.cursorZoom = false;
  271. /**
  272. * The minimum FOV in degrees.
  273. *
  274. * @type {number}
  275. * @default 5
  276. */
  277. this.minFov = 5;
  278. /**
  279. * The maximum FOV in degrees.
  280. *
  281. * @type {number}
  282. * @default 90
  283. */
  284. this.maxFov = 90;
  285. /**
  286. * Speed of rotation.
  287. *
  288. * @type {number}
  289. * @default 1
  290. */
  291. this.rotateSpeed = 1;
  292. /**
  293. * Enable or disable camera panning.
  294. *
  295. * @type {boolean}
  296. * @default true
  297. */
  298. this.enablePan = true;
  299. /**
  300. * Enable or disable camera rotation.
  301. *
  302. * @type {boolean}
  303. * @default true
  304. */
  305. this.enableRotate = true;
  306. /**
  307. * Enable or disable camera zoom.
  308. *
  309. * @type {boolean}
  310. * @default true
  311. */
  312. this.enableZoom = true;
  313. /**
  314. * Enable or disable gizmos.
  315. *
  316. * @type {boolean}
  317. * @default true
  318. */
  319. this.enableGizmos = true;
  320. /**
  321. * Enable or disable camera focusing on double-tap (or click) operations.
  322. *
  323. * @type {boolean}
  324. * @default true
  325. */
  326. this.enableFocus = true;
  327. /**
  328. * How far you can dolly in. For perspective cameras only.
  329. *
  330. * @type {number}
  331. * @default 0
  332. */
  333. this.minDistance = 0;
  334. /**
  335. * How far you can dolly out. For perspective cameras only.
  336. *
  337. * @type {number}
  338. * @default Infinity
  339. */
  340. this.maxDistance = Infinity;
  341. /**
  342. * How far you can zoom in. For orthographic cameras only.
  343. *
  344. * @type {number}
  345. * @default 0
  346. */
  347. this.minZoom = 0;
  348. /**
  349. * How far you can zoom out. For orthographic cameras only.
  350. *
  351. * @type {number}
  352. * @default Infinity
  353. */
  354. this.maxZoom = Infinity;
  355. //trackball parameters
  356. this._tbRadius = 1;
  357. //FSA
  358. this._state = STATE.IDLE;
  359. this.setCamera( camera );
  360. if ( this.scene != null ) {
  361. this.scene.add( this._gizmos );
  362. }
  363. this.initializeMouseActions();
  364. // event listeners
  365. this._onContextMenu = onContextMenu.bind( this );
  366. this._onWheel = onWheel.bind( this );
  367. this._onPointerUp = onPointerUp.bind( this );
  368. this._onPointerMove = onPointerMove.bind( this );
  369. this._onPointerDown = onPointerDown.bind( this );
  370. this._onPointerCancel = onPointerCancel.bind( this );
  371. this._onWindowResize = onWindowResize.bind( this );
  372. if ( domElement !== null ) {
  373. this.connect( domElement );
  374. }
  375. }
  376. connect( element ) {
  377. super.connect( element );
  378. this._devPxRatio = window.devicePixelRatio;
  379. this.domElement.addEventListener( 'contextmenu', this._onContextMenu );
  380. this.domElement.addEventListener( 'wheel', this._onWheel, { passive: false } );
  381. this.domElement.addEventListener( 'pointerdown', this._onPointerDown );
  382. this.domElement.addEventListener( 'pointercancel', this._onPointerCancel );
  383. window.addEventListener( 'resize', this._onWindowResize );
  384. this.domElement.style.touchAction = 'none'; // Disable touch scroll
  385. }
  386. disconnect() {
  387. this.domElement.removeEventListener( 'pointerdown', this._onPointerDown );
  388. this.domElement.removeEventListener( 'pointercancel', this._onPointerCancel );
  389. this.domElement.removeEventListener( 'wheel', this._onWheel );
  390. this.domElement.removeEventListener( 'contextmenu', this._onContextMenu );
  391. window.removeEventListener( 'pointermove', this._onPointerMove );
  392. window.removeEventListener( 'pointerup', this._onPointerUp );
  393. window.removeEventListener( 'resize', this._onWindowResize );
  394. this.domElement.style.touchAction = ''; // Restore touch scroll
  395. }
  396. onSinglePanStart( event, operation ) {
  397. if ( this.enabled ) {
  398. this.dispatchEvent( _startEvent );
  399. this.setCenter( event.clientX, event.clientY );
  400. switch ( operation ) {
  401. case 'PAN':
  402. if ( ! this.enablePan ) {
  403. return;
  404. }
  405. if ( this._animationId != - 1 ) {
  406. cancelAnimationFrame( this._animationId );
  407. this._animationId = - 1;
  408. this._timeStart = - 1;
  409. this.activateGizmos( false );
  410. this.dispatchEvent( _changeEvent );
  411. }
  412. this.updateTbState( STATE.PAN, true );
  413. this._startCursorPosition.copy( this.unprojectOnTbPlane( this.object, _center.x, _center.y, this.domElement ) );
  414. if ( this.enableGrid ) {
  415. this.drawGrid();
  416. this.dispatchEvent( _changeEvent );
  417. }
  418. break;
  419. case 'ROTATE':
  420. if ( ! this.enableRotate ) {
  421. return;
  422. }
  423. if ( this._animationId != - 1 ) {
  424. cancelAnimationFrame( this._animationId );
  425. this._animationId = - 1;
  426. this._timeStart = - 1;
  427. }
  428. this.updateTbState( STATE.ROTATE, true );
  429. this._startCursorPosition.copy( this.unprojectOnTbSurface( this.object, _center.x, _center.y, this.domElement, this._tbRadius ) );
  430. this.activateGizmos( true );
  431. if ( this.enableAnimations ) {
  432. this._timePrev = this._timeCurrent = performance.now();
  433. this._angleCurrent = this._anglePrev = 0;
  434. this._cursorPosPrev.copy( this._startCursorPosition );
  435. this._cursorPosCurr.copy( this._cursorPosPrev );
  436. this._wCurr = 0;
  437. this._wPrev = this._wCurr;
  438. }
  439. this.dispatchEvent( _changeEvent );
  440. break;
  441. case 'FOV':
  442. if ( ! this.object.isPerspectiveCamera || ! this.enableZoom ) {
  443. return;
  444. }
  445. if ( this._animationId != - 1 ) {
  446. cancelAnimationFrame( this._animationId );
  447. this._animationId = - 1;
  448. this._timeStart = - 1;
  449. this.activateGizmos( false );
  450. this.dispatchEvent( _changeEvent );
  451. }
  452. this.updateTbState( STATE.FOV, true );
  453. this._startCursorPosition.setY( this.getCursorNDC( _center.x, _center.y, this.domElement ).y * 0.5 );
  454. this._currentCursorPosition.copy( this._startCursorPosition );
  455. break;
  456. case 'ZOOM':
  457. if ( ! this.enableZoom ) {
  458. return;
  459. }
  460. if ( this._animationId != - 1 ) {
  461. cancelAnimationFrame( this._animationId );
  462. this._animationId = - 1;
  463. this._timeStart = - 1;
  464. this.activateGizmos( false );
  465. this.dispatchEvent( _changeEvent );
  466. }
  467. this.updateTbState( STATE.SCALE, true );
  468. this._startCursorPosition.setY( this.getCursorNDC( _center.x, _center.y, this.domElement ).y * 0.5 );
  469. this._currentCursorPosition.copy( this._startCursorPosition );
  470. break;
  471. }
  472. }
  473. }
  474. onSinglePanMove( event, opState ) {
  475. if ( this.enabled ) {
  476. const restart = opState != this._state;
  477. this.setCenter( event.clientX, event.clientY );
  478. switch ( opState ) {
  479. case STATE.PAN:
  480. if ( this.enablePan ) {
  481. if ( restart ) {
  482. //switch to pan operation
  483. this.dispatchEvent( _endEvent );
  484. this.dispatchEvent( _startEvent );
  485. this.updateTbState( opState, true );
  486. this._startCursorPosition.copy( this.unprojectOnTbPlane( this.object, _center.x, _center.y, this.domElement ) );
  487. if ( this.enableGrid ) {
  488. this.drawGrid();
  489. }
  490. this.activateGizmos( false );
  491. } else {
  492. //continue with pan operation
  493. this._currentCursorPosition.copy( this.unprojectOnTbPlane( this.object, _center.x, _center.y, this.domElement ) );
  494. this.applyTransformMatrix( this.pan( this._startCursorPosition, this._currentCursorPosition ) );
  495. }
  496. }
  497. break;
  498. case STATE.ROTATE:
  499. if ( this.enableRotate ) {
  500. if ( restart ) {
  501. //switch to rotate operation
  502. this.dispatchEvent( _endEvent );
  503. this.dispatchEvent( _startEvent );
  504. this.updateTbState( opState, true );
  505. this._startCursorPosition.copy( this.unprojectOnTbSurface( this.object, _center.x, _center.y, this.domElement, this._tbRadius ) );
  506. if ( this.enableGrid ) {
  507. this.disposeGrid();
  508. }
  509. this.activateGizmos( true );
  510. } else {
  511. //continue with rotate operation
  512. this._currentCursorPosition.copy( this.unprojectOnTbSurface( this.object, _center.x, _center.y, this.domElement, this._tbRadius ) );
  513. const distance = this._startCursorPosition.distanceTo( this._currentCursorPosition );
  514. const angle = this._startCursorPosition.angleTo( this._currentCursorPosition );
  515. const amount = Math.max( distance / this._tbRadius, angle ) * this.rotateSpeed; //effective rotation angle
  516. this.applyTransformMatrix( this.rotate( this.calculateRotationAxis( this._startCursorPosition, this._currentCursorPosition ), amount ) );
  517. if ( this.enableAnimations ) {
  518. this._timePrev = this._timeCurrent;
  519. this._timeCurrent = performance.now();
  520. this._anglePrev = this._angleCurrent;
  521. this._angleCurrent = amount;
  522. this._cursorPosPrev.copy( this._cursorPosCurr );
  523. this._cursorPosCurr.copy( this._currentCursorPosition );
  524. this._wPrev = this._wCurr;
  525. this._wCurr = this.calculateAngularSpeed( this._anglePrev, this._angleCurrent, this._timePrev, this._timeCurrent );
  526. }
  527. }
  528. }
  529. break;
  530. case STATE.SCALE:
  531. if ( this.enableZoom ) {
  532. if ( restart ) {
  533. //switch to zoom operation
  534. this.dispatchEvent( _endEvent );
  535. this.dispatchEvent( _startEvent );
  536. this.updateTbState( opState, true );
  537. this._startCursorPosition.setY( this.getCursorNDC( _center.x, _center.y, this.domElement ).y * 0.5 );
  538. this._currentCursorPosition.copy( this._startCursorPosition );
  539. if ( this.enableGrid ) {
  540. this.disposeGrid();
  541. }
  542. this.activateGizmos( false );
  543. } else {
  544. //continue with zoom operation
  545. const screenNotches = 8; //how many wheel notches corresponds to a full screen pan
  546. this._currentCursorPosition.setY( this.getCursorNDC( _center.x, _center.y, this.domElement ).y * 0.5 );
  547. const movement = this._currentCursorPosition.y - this._startCursorPosition.y;
  548. let size = 1;
  549. if ( movement < 0 ) {
  550. size = 1 / ( Math.pow( this.scaleFactor, - movement * screenNotches ) );
  551. } else if ( movement > 0 ) {
  552. size = Math.pow( this.scaleFactor, movement * screenNotches );
  553. }
  554. this._v3_1.setFromMatrixPosition( this._gizmoMatrixState );
  555. this.applyTransformMatrix( this.scale( size, this._v3_1 ) );
  556. }
  557. }
  558. break;
  559. case STATE.FOV:
  560. if ( this.enableZoom && this.object.isPerspectiveCamera ) {
  561. if ( restart ) {
  562. //switch to fov operation
  563. this.dispatchEvent( _endEvent );
  564. this.dispatchEvent( _startEvent );
  565. this.updateTbState( opState, true );
  566. this._startCursorPosition.setY( this.getCursorNDC( _center.x, _center.y, this.domElement ).y * 0.5 );
  567. this._currentCursorPosition.copy( this._startCursorPosition );
  568. if ( this.enableGrid ) {
  569. this.disposeGrid();
  570. }
  571. this.activateGizmos( false );
  572. } else {
  573. //continue with fov operation
  574. const screenNotches = 8; //how many wheel notches corresponds to a full screen pan
  575. this._currentCursorPosition.setY( this.getCursorNDC( _center.x, _center.y, this.domElement ).y * 0.5 );
  576. const movement = this._currentCursorPosition.y - this._startCursorPosition.y;
  577. let size = 1;
  578. if ( movement < 0 ) {
  579. size = 1 / ( Math.pow( this.scaleFactor, - movement * screenNotches ) );
  580. } else if ( movement > 0 ) {
  581. size = Math.pow( this.scaleFactor, movement * screenNotches );
  582. }
  583. this._v3_1.setFromMatrixPosition( this._cameraMatrixState );
  584. const x = this._v3_1.distanceTo( this._gizmos.position );
  585. let xNew = x / size; //distance between camera and gizmos if scale(size, scalepoint) would be performed
  586. //check min and max distance
  587. xNew = MathUtils.clamp( xNew, this.minDistance, this.maxDistance );
  588. const y = x * Math.tan( MathUtils.DEG2RAD * this._fovState * 0.5 );
  589. //calculate new fov
  590. let newFov = MathUtils.RAD2DEG * ( Math.atan( y / xNew ) * 2 );
  591. //check min and max fov
  592. newFov = MathUtils.clamp( newFov, this.minFov, this.maxFov );
  593. const newDistance = y / Math.tan( MathUtils.DEG2RAD * ( newFov / 2 ) );
  594. size = x / newDistance;
  595. this._v3_2.setFromMatrixPosition( this._gizmoMatrixState );
  596. this.setFov( newFov );
  597. this.applyTransformMatrix( this.scale( size, this._v3_2, false ) );
  598. //adjusting distance
  599. _offset.copy( this._gizmos.position ).sub( this.object.position ).normalize().multiplyScalar( newDistance / x );
  600. this._m4_1.makeTranslation( _offset.x, _offset.y, _offset.z );
  601. }
  602. }
  603. break;
  604. }
  605. this.dispatchEvent( _changeEvent );
  606. }
  607. }
  608. onSinglePanEnd() {
  609. if ( this._state == STATE.ROTATE ) {
  610. if ( ! this.enableRotate ) {
  611. return;
  612. }
  613. if ( this.enableAnimations ) {
  614. //perform rotation animation
  615. const deltaTime = ( performance.now() - this._timeCurrent );
  616. if ( deltaTime < 120 ) {
  617. const w = Math.abs( ( this._wPrev + this._wCurr ) / 2 );
  618. const self = this;
  619. this._animationId = window.requestAnimationFrame( function ( t ) {
  620. self.updateTbState( STATE.ANIMATION_ROTATE, true );
  621. const rotationAxis = self.calculateRotationAxis( self._cursorPosPrev, self._cursorPosCurr );
  622. self.onRotationAnim( t, rotationAxis, Math.min( w, self.wMax ) );
  623. } );
  624. } else {
  625. //cursor has been standing still for over 120 ms since last movement
  626. this.updateTbState( STATE.IDLE, false );
  627. this.activateGizmos( false );
  628. this.dispatchEvent( _changeEvent );
  629. }
  630. } else {
  631. this.updateTbState( STATE.IDLE, false );
  632. this.activateGizmos( false );
  633. this.dispatchEvent( _changeEvent );
  634. }
  635. } else if ( this._state == STATE.PAN || this._state == STATE.IDLE ) {
  636. this.updateTbState( STATE.IDLE, false );
  637. if ( this.enableGrid ) {
  638. this.disposeGrid();
  639. }
  640. this.activateGizmos( false );
  641. this.dispatchEvent( _changeEvent );
  642. }
  643. this.dispatchEvent( _endEvent );
  644. }
  645. onDoubleTap( event ) {
  646. if ( this.enabled && this.enablePan && this.enableFocus && this.scene != null ) {
  647. this.dispatchEvent( _startEvent );
  648. this.setCenter( event.clientX, event.clientY );
  649. const hitP = this.unprojectOnObj( this.getCursorNDC( _center.x, _center.y, this.domElement ), this.object );
  650. if ( hitP != null && this.enableAnimations ) {
  651. const self = this;
  652. if ( this._animationId != - 1 ) {
  653. window.cancelAnimationFrame( this._animationId );
  654. }
  655. this._timeStart = - 1;
  656. this._animationId = window.requestAnimationFrame( function ( t ) {
  657. self.updateTbState( STATE.ANIMATION_FOCUS, true );
  658. self.onFocusAnim( t, hitP, self._cameraMatrixState, self._gizmoMatrixState );
  659. } );
  660. } else if ( hitP != null && ! this.enableAnimations ) {
  661. this.updateTbState( STATE.FOCUS, true );
  662. this.focus( hitP, this.scaleFactor );
  663. this.updateTbState( STATE.IDLE, false );
  664. this.dispatchEvent( _changeEvent );
  665. }
  666. }
  667. this.dispatchEvent( _endEvent );
  668. }
  669. onDoublePanStart() {
  670. if ( this.enabled && this.enablePan ) {
  671. this.dispatchEvent( _startEvent );
  672. this.updateTbState( STATE.PAN, true );
  673. this.setCenter( ( this._touchCurrent[ 0 ].clientX + this._touchCurrent[ 1 ].clientX ) / 2, ( this._touchCurrent[ 0 ].clientY + this._touchCurrent[ 1 ].clientY ) / 2 );
  674. this._startCursorPosition.copy( this.unprojectOnTbPlane( this.object, _center.x, _center.y, this.domElement, true ) );
  675. this._currentCursorPosition.copy( this._startCursorPosition );
  676. this.activateGizmos( false );
  677. }
  678. }
  679. onDoublePanMove() {
  680. if ( this.enabled && this.enablePan ) {
  681. this.setCenter( ( this._touchCurrent[ 0 ].clientX + this._touchCurrent[ 1 ].clientX ) / 2, ( this._touchCurrent[ 0 ].clientY + this._touchCurrent[ 1 ].clientY ) / 2 );
  682. if ( this._state != STATE.PAN ) {
  683. this.updateTbState( STATE.PAN, true );
  684. this._startCursorPosition.copy( this._currentCursorPosition );
  685. }
  686. this._currentCursorPosition.copy( this.unprojectOnTbPlane( this.object, _center.x, _center.y, this.domElement, true ) );
  687. this.applyTransformMatrix( this.pan( this._startCursorPosition, this._currentCursorPosition, true ) );
  688. this.dispatchEvent( _changeEvent );
  689. }
  690. }
  691. onDoublePanEnd() {
  692. this.updateTbState( STATE.IDLE, false );
  693. this.dispatchEvent( _endEvent );
  694. }
  695. onRotateStart() {
  696. if ( this.enabled && this.enableRotate ) {
  697. this.dispatchEvent( _startEvent );
  698. this.updateTbState( STATE.ZROTATE, true );
  699. //this._startFingerRotation = event.rotation;
  700. this._startFingerRotation = this.getAngle( this._touchCurrent[ 1 ], this._touchCurrent[ 0 ] ) + this.getAngle( this._touchStart[ 1 ], this._touchStart[ 0 ] );
  701. this._currentFingerRotation = this._startFingerRotation;
  702. this.object.getWorldDirection( this._rotationAxis ); //rotation axis
  703. if ( ! this.enablePan && ! this.enableZoom ) {
  704. this.activateGizmos( true );
  705. }
  706. }
  707. }
  708. onRotateMove() {
  709. if ( this.enabled && this.enableRotate ) {
  710. this.setCenter( ( this._touchCurrent[ 0 ].clientX + this._touchCurrent[ 1 ].clientX ) / 2, ( this._touchCurrent[ 0 ].clientY + this._touchCurrent[ 1 ].clientY ) / 2 );
  711. let rotationPoint;
  712. if ( this._state != STATE.ZROTATE ) {
  713. this.updateTbState( STATE.ZROTATE, true );
  714. this._startFingerRotation = this._currentFingerRotation;
  715. }
  716. //this._currentFingerRotation = event.rotation;
  717. this._currentFingerRotation = this.getAngle( this._touchCurrent[ 1 ], this._touchCurrent[ 0 ] ) + this.getAngle( this._touchStart[ 1 ], this._touchStart[ 0 ] );
  718. if ( ! this.enablePan ) {
  719. rotationPoint = new Vector3().setFromMatrixPosition( this._gizmoMatrixState );
  720. } else {
  721. this._v3_2.setFromMatrixPosition( this._gizmoMatrixState );
  722. rotationPoint = this.unprojectOnTbPlane( this.object, _center.x, _center.y, this.domElement ).applyQuaternion( this.object.quaternion ).multiplyScalar( 1 / this.object.zoom ).add( this._v3_2 );
  723. }
  724. const amount = MathUtils.DEG2RAD * ( this._startFingerRotation - this._currentFingerRotation );
  725. this.applyTransformMatrix( this.zRotate( rotationPoint, amount ) );
  726. this.dispatchEvent( _changeEvent );
  727. }
  728. }
  729. onRotateEnd() {
  730. this.updateTbState( STATE.IDLE, false );
  731. this.activateGizmos( false );
  732. this.dispatchEvent( _endEvent );
  733. }
  734. onPinchStart() {
  735. if ( this.enabled && this.enableZoom ) {
  736. this.dispatchEvent( _startEvent );
  737. this.updateTbState( STATE.SCALE, true );
  738. this._startFingerDistance = this.calculatePointersDistance( this._touchCurrent[ 0 ], this._touchCurrent[ 1 ] );
  739. this._currentFingerDistance = this._startFingerDistance;
  740. this.activateGizmos( false );
  741. }
  742. }
  743. onPinchMove() {
  744. if ( this.enabled && this.enableZoom ) {
  745. this.setCenter( ( this._touchCurrent[ 0 ].clientX + this._touchCurrent[ 1 ].clientX ) / 2, ( this._touchCurrent[ 0 ].clientY + this._touchCurrent[ 1 ].clientY ) / 2 );
  746. const minDistance = 12; //minimum distance between fingers (in css pixels)
  747. if ( this._state != STATE.SCALE ) {
  748. this._startFingerDistance = this._currentFingerDistance;
  749. this.updateTbState( STATE.SCALE, true );
  750. }
  751. this._currentFingerDistance = Math.max( this.calculatePointersDistance( this._touchCurrent[ 0 ], this._touchCurrent[ 1 ] ), minDistance * this._devPxRatio );
  752. const amount = this._currentFingerDistance / this._startFingerDistance;
  753. let scalePoint;
  754. if ( ! this.enablePan ) {
  755. scalePoint = this._gizmos.position;
  756. } else {
  757. if ( this.object.isOrthographicCamera ) {
  758. scalePoint = this.unprojectOnTbPlane( this.object, _center.x, _center.y, this.domElement )
  759. .applyQuaternion( this.object.quaternion )
  760. .multiplyScalar( 1 / this.object.zoom )
  761. .add( this._gizmos.position );
  762. } else if ( this.object.isPerspectiveCamera ) {
  763. scalePoint = this.unprojectOnTbPlane( this.object, _center.x, _center.y, this.domElement )
  764. .applyQuaternion( this.object.quaternion )
  765. .add( this._gizmos.position );
  766. }
  767. }
  768. this.applyTransformMatrix( this.scale( amount, scalePoint ) );
  769. this.dispatchEvent( _changeEvent );
  770. }
  771. }
  772. onPinchEnd() {
  773. this.updateTbState( STATE.IDLE, false );
  774. this.dispatchEvent( _endEvent );
  775. }
  776. onTriplePanStart() {
  777. if ( this.enabled && this.enableZoom ) {
  778. this.dispatchEvent( _startEvent );
  779. this.updateTbState( STATE.SCALE, true );
  780. //const center = event.center;
  781. let clientX = 0;
  782. let clientY = 0;
  783. const nFingers = this._touchCurrent.length;
  784. for ( let i = 0; i < nFingers; i ++ ) {
  785. clientX += this._touchCurrent[ i ].clientX;
  786. clientY += this._touchCurrent[ i ].clientY;
  787. }
  788. this.setCenter( clientX / nFingers, clientY / nFingers );
  789. this._startCursorPosition.setY( this.getCursorNDC( _center.x, _center.y, this.domElement ).y * 0.5 );
  790. this._currentCursorPosition.copy( this._startCursorPosition );
  791. }
  792. }
  793. onTriplePanMove() {
  794. if ( this.enabled && this.enableZoom ) {
  795. // fov / 2
  796. // |\
  797. // | \
  798. // | \
  799. // x | \
  800. // | \
  801. // | \
  802. // | _ _ _\
  803. // y
  804. //const center = event.center;
  805. let clientX = 0;
  806. let clientY = 0;
  807. const nFingers = this._touchCurrent.length;
  808. for ( let i = 0; i < nFingers; i ++ ) {
  809. clientX += this._touchCurrent[ i ].clientX;
  810. clientY += this._touchCurrent[ i ].clientY;
  811. }
  812. this.setCenter( clientX / nFingers, clientY / nFingers );
  813. const screenNotches = 8; //how many wheel notches corresponds to a full screen pan
  814. this._currentCursorPosition.setY( this.getCursorNDC( _center.x, _center.y, this.domElement ).y * 0.5 );
  815. const movement = this._currentCursorPosition.y - this._startCursorPosition.y;
  816. let size = 1;
  817. if ( movement < 0 ) {
  818. size = 1 / ( Math.pow( this.scaleFactor, - movement * screenNotches ) );
  819. } else if ( movement > 0 ) {
  820. size = Math.pow( this.scaleFactor, movement * screenNotches );
  821. }
  822. this._v3_1.setFromMatrixPosition( this._cameraMatrixState );
  823. const x = this._v3_1.distanceTo( this._gizmos.position );
  824. let xNew = x / size; //distance between camera and gizmos if scale(size, scalepoint) would be performed
  825. //check min and max distance
  826. xNew = MathUtils.clamp( xNew, this.minDistance, this.maxDistance );
  827. const y = x * Math.tan( MathUtils.DEG2RAD * this._fovState * 0.5 );
  828. //calculate new fov
  829. let newFov = MathUtils.RAD2DEG * ( Math.atan( y / xNew ) * 2 );
  830. //check min and max fov
  831. newFov = MathUtils.clamp( newFov, this.minFov, this.maxFov );
  832. const newDistance = y / Math.tan( MathUtils.DEG2RAD * ( newFov / 2 ) );
  833. size = x / newDistance;
  834. this._v3_2.setFromMatrixPosition( this._gizmoMatrixState );
  835. this.setFov( newFov );
  836. this.applyTransformMatrix( this.scale( size, this._v3_2, false ) );
  837. //adjusting distance
  838. _offset.copy( this._gizmos.position ).sub( this.object.position ).normalize().multiplyScalar( newDistance / x );
  839. this._m4_1.makeTranslation( _offset.x, _offset.y, _offset.z );
  840. this.dispatchEvent( _changeEvent );
  841. }
  842. }
  843. onTriplePanEnd() {
  844. this.updateTbState( STATE.IDLE, false );
  845. this.dispatchEvent( _endEvent );
  846. //this.dispatchEvent( _changeEvent );
  847. }
  848. /**
  849. * Set _center's x/y coordinates.
  850. *
  851. * @private
  852. * @param {number} clientX - The x coordinate.
  853. * @param {number} clientY - The y coordinate.
  854. */
  855. setCenter( clientX, clientY ) {
  856. _center.x = clientX;
  857. _center.y = clientY;
  858. }
  859. /**
  860. * Set default mouse actions.
  861. *
  862. * @private
  863. */
  864. initializeMouseActions() {
  865. this.setMouseAction( 'PAN', 0, 'CTRL' );
  866. this.setMouseAction( 'PAN', 2 );
  867. this.setMouseAction( 'ROTATE', 0 );
  868. this.setMouseAction( 'ZOOM', 'WHEEL' );
  869. this.setMouseAction( 'ZOOM', 1 );
  870. this.setMouseAction( 'FOV', 'WHEEL', 'SHIFT' );
  871. this.setMouseAction( 'FOV', 1, 'SHIFT' );
  872. }
  873. /**
  874. * Compare two mouse actions.
  875. *
  876. * @private
  877. * @param {Object} action1 - The first mouse action.
  878. * @param {Object} action2 - The second mouse action.
  879. * @returns {boolean} `true` if action1 and action 2 are the same mouse action, `false` otherwise.
  880. */
  881. compareMouseAction( action1, action2 ) {
  882. if ( action1.operation == action2.operation ) {
  883. if ( action1.mouse == action2.mouse && action1.key == action2.key ) {
  884. return true;
  885. } else {
  886. return false;
  887. }
  888. } else {
  889. return false;
  890. }
  891. }
  892. /**
  893. * Set a new mouse action by specifying the operation to be performed and a mouse/key combination. In case of conflict, replaces the existing one.
  894. *
  895. * @param {'PAN'|'ROTATE'|'ZOOM'|'FOV'} operation - The operation to be performed ('PAN', 'ROTATE', 'ZOOM', 'FOV').
  896. * @param {0|1|2|'WHEEL'} mouse - A mouse button (0, 1, 2) or 'WHEEL' for wheel notches.
  897. * @param {?('CTRL'|'SHIFT')} [key=null] - The keyboard modifier ('CTRL', 'SHIFT') or null if key is not needed.
  898. * @returns {boolean} `true` if the mouse action has been successfully added, `false` otherwise.
  899. */
  900. setMouseAction( operation, mouse, key = null ) {
  901. const operationInput = [ 'PAN', 'ROTATE', 'ZOOM', 'FOV' ];
  902. const mouseInput = [ 0, 1, 2, 'WHEEL' ];
  903. const keyInput = [ 'CTRL', 'SHIFT', null ];
  904. let state;
  905. if ( ! operationInput.includes( operation ) || ! mouseInput.includes( mouse ) || ! keyInput.includes( key ) ) {
  906. //invalid parameters
  907. return false;
  908. }
  909. if ( mouse == 'WHEEL' ) {
  910. if ( operation != 'ZOOM' && operation != 'FOV' ) {
  911. //cannot associate 2D operation to 1D input
  912. return false;
  913. }
  914. }
  915. switch ( operation ) {
  916. case 'PAN':
  917. state = STATE.PAN;
  918. break;
  919. case 'ROTATE':
  920. state = STATE.ROTATE;
  921. break;
  922. case 'ZOOM':
  923. state = STATE.SCALE;
  924. break;
  925. case 'FOV':
  926. state = STATE.FOV;
  927. break;
  928. }
  929. const action = {
  930. operation: operation,
  931. mouse: mouse,
  932. key: key,
  933. state: state
  934. };
  935. for ( let i = 0; i < this.mouseActions.length; i ++ ) {
  936. if ( this.mouseActions[ i ].mouse == action.mouse && this.mouseActions[ i ].key == action.key ) {
  937. this.mouseActions.splice( i, 1, action );
  938. return true;
  939. }
  940. }
  941. this.mouseActions.push( action );
  942. return true;
  943. }
  944. /**
  945. * Remove a mouse action by specifying its mouse/key combination.
  946. *
  947. * @param {0|1|2|'WHEEL'} mouse - A mouse button (0, 1, 2) or 'WHEEL' for wheel notches.
  948. * @param {?('CTRL'|'SHIFT')} key - The keyboard modifier ('CTRL', 'SHIFT') or null if key is not needed.
  949. * @returns {boolean} `true` if the operation has been successfully removed, `false` otherwise.
  950. */
  951. unsetMouseAction( mouse, key = null ) {
  952. for ( let i = 0; i < this.mouseActions.length; i ++ ) {
  953. if ( this.mouseActions[ i ].mouse == mouse && this.mouseActions[ i ].key == key ) {
  954. this.mouseActions.splice( i, 1 );
  955. return true;
  956. }
  957. }
  958. return false;
  959. }
  960. /**
  961. * Return the operation associated to a mouse/keyboard combination.
  962. *
  963. * @private
  964. * @param {0|1|2|'WHEEL'} mouse - Mouse button index (0, 1, 2) or 'WHEEL' for wheel notches.
  965. * @param {?('CTRL'|'SHIFT')} key - Keyboard modifier.
  966. * @returns {?('PAN'|'ROTATE'|'ZOOM'|'FOV')} The operation if it has been found, `null` otherwise.
  967. */
  968. getOpFromAction( mouse, key ) {
  969. let action;
  970. for ( let i = 0; i < this.mouseActions.length; i ++ ) {
  971. action = this.mouseActions[ i ];
  972. if ( action.mouse == mouse && action.key == key ) {
  973. return action.operation;
  974. }
  975. }
  976. if ( key != null ) {
  977. for ( let i = 0; i < this.mouseActions.length; i ++ ) {
  978. action = this.mouseActions[ i ];
  979. if ( action.mouse == mouse && action.key == null ) {
  980. return action.operation;
  981. }
  982. }
  983. }
  984. return null;
  985. }
  986. /**
  987. * Get the operation associated to mouse and key combination and returns the corresponding FSA state.
  988. *
  989. * @private
  990. * @param {0|1|2} mouse - Mouse button index (0, 1, 2)
  991. * @param {?('CTRL'|'SHIFT')} key - Keyboard modifier
  992. * @returns {?STATE} The FSA state obtained from the operation associated to mouse/keyboard combination.
  993. */
  994. getOpStateFromAction( mouse, key ) {
  995. let action;
  996. for ( let i = 0; i < this.mouseActions.length; i ++ ) {
  997. action = this.mouseActions[ i ];
  998. if ( action.mouse == mouse && action.key == key ) {
  999. return action.state;
  1000. }
  1001. }
  1002. if ( key != null ) {
  1003. for ( let i = 0; i < this.mouseActions.length; i ++ ) {
  1004. action = this.mouseActions[ i ];
  1005. if ( action.mouse == mouse && action.key == null ) {
  1006. return action.state;
  1007. }
  1008. }
  1009. }
  1010. return null;
  1011. }
  1012. /**
  1013. * Calculate the angle between two pointers.
  1014. *
  1015. * @private
  1016. * @param {PointerEvent} p1 - The first pointer event.
  1017. * @param {PointerEvent} p2 - The second pointer event.
  1018. * @returns {number} The angle between two pointers in degrees.
  1019. */
  1020. getAngle( p1, p2 ) {
  1021. return Math.atan2( p2.clientY - p1.clientY, p2.clientX - p1.clientX ) * 180 / Math.PI;
  1022. }
  1023. /**
  1024. * Updates a PointerEvent inside current pointerevents array.
  1025. *
  1026. * @private
  1027. * @param {PointerEvent} event - The pointer event.
  1028. */
  1029. updateTouchEvent( event ) {
  1030. for ( let i = 0; i < this._touchCurrent.length; i ++ ) {
  1031. if ( this._touchCurrent[ i ].pointerId == event.pointerId ) {
  1032. this._touchCurrent.splice( i, 1, event );
  1033. break;
  1034. }
  1035. }
  1036. }
  1037. /**
  1038. * Applies a transformation matrix, to the camera and gizmos.
  1039. *
  1040. * @private
  1041. * @param {Object} transformation - Object containing matrices to apply to camera and gizmos.
  1042. */
  1043. applyTransformMatrix( transformation ) {
  1044. if ( transformation.camera != null ) {
  1045. this._m4_1.copy( this._cameraMatrixState ).premultiply( transformation.camera );
  1046. this._m4_1.decompose( this.object.position, this.object.quaternion, this.object.scale );
  1047. this.object.updateMatrix();
  1048. //update camera up vector
  1049. if ( this._state == STATE.ROTATE || this._state == STATE.ZROTATE || this._state == STATE.ANIMATION_ROTATE ) {
  1050. this.object.up.copy( this._upState ).applyQuaternion( this.object.quaternion );
  1051. }
  1052. }
  1053. if ( transformation.gizmos != null ) {
  1054. this._m4_1.copy( this._gizmoMatrixState ).premultiply( transformation.gizmos );
  1055. this._m4_1.decompose( this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale );
  1056. this._gizmos.updateMatrix();
  1057. }
  1058. if ( this._state == STATE.SCALE || this._state == STATE.FOCUS || this._state == STATE.ANIMATION_FOCUS ) {
  1059. this._tbRadius = this.calculateTbRadius( this.object );
  1060. if ( this.adjustNearFar ) {
  1061. const cameraDistance = this.object.position.distanceTo( this._gizmos.position );
  1062. const bb = new Box3();
  1063. bb.setFromObject( this._gizmos );
  1064. const sphere = new Sphere();
  1065. bb.getBoundingSphere( sphere );
  1066. const adjustedNearPosition = Math.max( this._nearPos0, sphere.radius + sphere.center.length() );
  1067. const regularNearPosition = cameraDistance - this._initialNear;
  1068. const minNearPos = Math.min( adjustedNearPosition, regularNearPosition );
  1069. this.object.near = cameraDistance - minNearPos;
  1070. const adjustedFarPosition = Math.min( this._farPos0, - sphere.radius + sphere.center.length() );
  1071. const regularFarPosition = cameraDistance - this._initialFar;
  1072. const minFarPos = Math.min( adjustedFarPosition, regularFarPosition );
  1073. this.object.far = cameraDistance - minFarPos;
  1074. this.object.updateProjectionMatrix();
  1075. } else {
  1076. let update = false;
  1077. if ( this.object.near != this._initialNear ) {
  1078. this.object.near = this._initialNear;
  1079. update = true;
  1080. }
  1081. if ( this.object.far != this._initialFar ) {
  1082. this.object.far = this._initialFar;
  1083. update = true;
  1084. }
  1085. if ( update ) {
  1086. this.object.updateProjectionMatrix();
  1087. }
  1088. }
  1089. }
  1090. }
  1091. /**
  1092. * Calculates the angular speed.
  1093. *
  1094. * @private
  1095. * @param {number} p0 - Position at t0.
  1096. * @param {number} p1 - Position at t1.
  1097. * @param {number} t0 - Initial time in milliseconds.
  1098. * @param {number} t1 - Ending time in milliseconds.
  1099. * @returns {number} The angular speed.
  1100. */
  1101. calculateAngularSpeed( p0, p1, t0, t1 ) {
  1102. const s = p1 - p0;
  1103. const t = ( t1 - t0 ) / 1000;
  1104. if ( t == 0 ) {
  1105. return 0;
  1106. }
  1107. return s / t;
  1108. }
  1109. /**
  1110. * Calculates the distance between two pointers.
  1111. *
  1112. * @private
  1113. * @param {PointerEvent} p0 - The first pointer.
  1114. * @param {PointerEvent} p1 - The second pointer.
  1115. * @returns {number} The distance between the two pointers.
  1116. */
  1117. calculatePointersDistance( p0, p1 ) {
  1118. return Math.sqrt( Math.pow( p1.clientX - p0.clientX, 2 ) + Math.pow( p1.clientY - p0.clientY, 2 ) );
  1119. }
  1120. /**
  1121. * Calculates the rotation axis as the vector perpendicular between two vectors.
  1122. *
  1123. * @private
  1124. * @param {Vector3} vec1 - The first vector.
  1125. * @param {Vector3} vec2 - The second vector.
  1126. * @returns {Vector3} The normalized rotation axis.
  1127. */
  1128. calculateRotationAxis( vec1, vec2 ) {
  1129. this._rotationMatrix.extractRotation( this._cameraMatrixState );
  1130. this._quat.setFromRotationMatrix( this._rotationMatrix );
  1131. this._rotationAxis.crossVectors( vec1, vec2 ).applyQuaternion( this._quat );
  1132. return this._rotationAxis.normalize().clone();
  1133. }
  1134. /**
  1135. * Calculates the trackball radius so that gizmo's diameter will be 2/3 of the minimum side of the camera frustum.
  1136. *
  1137. * @private
  1138. * @param {Camera} camera - The camera.
  1139. * @returns {number} The trackball radius.
  1140. */
  1141. calculateTbRadius( camera ) {
  1142. const distance = camera.position.distanceTo( this._gizmos.position );
  1143. if ( camera.type == 'PerspectiveCamera' ) {
  1144. const halfFovV = MathUtils.DEG2RAD * camera.fov * 0.5; //vertical fov/2 in radians
  1145. const halfFovH = Math.atan( ( camera.aspect ) * Math.tan( halfFovV ) ); //horizontal fov/2 in radians
  1146. return Math.tan( Math.min( halfFovV, halfFovH ) ) * distance * this.radiusFactor;
  1147. } else if ( camera.type == 'OrthographicCamera' ) {
  1148. return Math.min( camera.top, camera.right ) * this.radiusFactor;
  1149. }
  1150. }
  1151. /**
  1152. * Focus operation consist of positioning the point of interest in front of the camera and a slightly zoom in.
  1153. *
  1154. * @private
  1155. * @param {Vector3} point - The point of interest.
  1156. * @param {number} size - Scale factor.
  1157. * @param {number} [amount=1] - Amount of operation to be completed (used for focus animations, default is complete full operation).
  1158. */
  1159. focus( point, size, amount = 1 ) {
  1160. //move center of camera (along with gizmos) towards point of interest
  1161. _offset.copy( point ).sub( this._gizmos.position ).multiplyScalar( amount );
  1162. this._translationMatrix.makeTranslation( _offset.x, _offset.y, _offset.z );
  1163. _gizmoMatrixStateTemp.copy( this._gizmoMatrixState );
  1164. this._gizmoMatrixState.premultiply( this._translationMatrix );
  1165. this._gizmoMatrixState.decompose( this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale );
  1166. _cameraMatrixStateTemp.copy( this._cameraMatrixState );
  1167. this._cameraMatrixState.premultiply( this._translationMatrix );
  1168. this._cameraMatrixState.decompose( this.object.position, this.object.quaternion, this.object.scale );
  1169. //apply zoom
  1170. if ( this.enableZoom ) {
  1171. this.applyTransformMatrix( this.scale( size, this._gizmos.position ) );
  1172. }
  1173. this._gizmoMatrixState.copy( _gizmoMatrixStateTemp );
  1174. this._cameraMatrixState.copy( _cameraMatrixStateTemp );
  1175. }
  1176. /**
  1177. * Creates a grid if necessary and adds it to the scene.
  1178. *
  1179. * @private
  1180. */
  1181. drawGrid() {
  1182. if ( this.scene != null ) {
  1183. const color = 0x888888;
  1184. const multiplier = 3;
  1185. let size, divisions, maxLength, tick;
  1186. if ( this.object.isOrthographicCamera ) {
  1187. const width = this.object.right - this.object.left;
  1188. const height = this.object.bottom - this.object.top;
  1189. maxLength = Math.max( width, height );
  1190. tick = maxLength / 20;
  1191. size = maxLength / this.object.zoom * multiplier;
  1192. divisions = size / tick * this.object.zoom;
  1193. } else if ( this.object.isPerspectiveCamera ) {
  1194. const distance = this.object.position.distanceTo( this._gizmos.position );
  1195. const halfFovV = MathUtils.DEG2RAD * this.object.fov * 0.5;
  1196. const halfFovH = Math.atan( ( this.object.aspect ) * Math.tan( halfFovV ) );
  1197. maxLength = Math.tan( Math.max( halfFovV, halfFovH ) ) * distance * 2;
  1198. tick = maxLength / 20;
  1199. size = maxLength * multiplier;
  1200. divisions = size / tick;
  1201. }
  1202. if ( this._grid == null ) {
  1203. this._grid = new GridHelper( size, divisions, color, color );
  1204. this._grid.position.copy( this._gizmos.position );
  1205. this._gridPosition.copy( this._grid.position );
  1206. this._grid.quaternion.copy( this.object.quaternion );
  1207. this._grid.rotateX( Math.PI * 0.5 );
  1208. this.scene.add( this._grid );
  1209. }
  1210. }
  1211. }
  1212. dispose() {
  1213. if ( this._animationId != - 1 ) {
  1214. window.cancelAnimationFrame( this._animationId );
  1215. }
  1216. this.disconnect();
  1217. if ( this.scene !== null ) this.scene.remove( this._gizmos );
  1218. this.disposeGrid();
  1219. }
  1220. /**
  1221. * Removes the grid from the scene.
  1222. */
  1223. disposeGrid() {
  1224. if ( this._grid != null && this.scene != null ) {
  1225. this.scene.remove( this._grid );
  1226. this._grid = null;
  1227. }
  1228. }
  1229. /**
  1230. * Computes the easing out cubic function for ease out effect in animation.
  1231. *
  1232. * @private
  1233. * @param {number} t - The absolute progress of the animation in the bound of `0` (beginning of the) and `1` (ending of animation).
  1234. * @returns {number} Result of easing out cubic at time `t`.
  1235. */
  1236. easeOutCubic( t ) {
  1237. return 1 - Math.pow( 1 - t, 3 );
  1238. }
  1239. /**
  1240. * Makes rotation gizmos more or less visible.
  1241. *
  1242. * @param {boolean} isActive - If set to `true`, gizmos are more visible.
  1243. */
  1244. activateGizmos( isActive ) {
  1245. const gizmoX = this._gizmos.children[ 0 ];
  1246. const gizmoY = this._gizmos.children[ 1 ];
  1247. const gizmoZ = this._gizmos.children[ 2 ];
  1248. if ( isActive ) {
  1249. gizmoX.material.setValues( { opacity: 1 } );
  1250. gizmoY.material.setValues( { opacity: 1 } );
  1251. gizmoZ.material.setValues( { opacity: 1 } );
  1252. } else {
  1253. gizmoX.material.setValues( { opacity: 0.6 } );
  1254. gizmoY.material.setValues( { opacity: 0.6 } );
  1255. gizmoZ.material.setValues( { opacity: 0.6 } );
  1256. }
  1257. }
  1258. /**
  1259. * Calculates the cursor position in NDC.
  1260. *
  1261. * @private
  1262. * @param {number} cursorX - Cursor horizontal coordinate within the canvas.
  1263. * @param {number} cursorY - Cursor vertical coordinate within the canvas.
  1264. * @param {HTMLElement} canvas - The canvas where the renderer draws its output.
  1265. * @returns {Vector2} Cursor normalized position inside the canvas.
  1266. */
  1267. getCursorNDC( cursorX, cursorY, canvas ) {
  1268. const canvasRect = canvas.getBoundingClientRect();
  1269. this._v2_1.setX( ( ( cursorX - canvasRect.left ) / canvasRect.width ) * 2 - 1 );
  1270. this._v2_1.setY( ( ( canvasRect.bottom - cursorY ) / canvasRect.height ) * 2 - 1 );
  1271. return this._v2_1.clone();
  1272. }
  1273. /**
  1274. * Calculates the cursor position inside the canvas x/y coordinates with the origin being in the center of the canvas.
  1275. *
  1276. * @private
  1277. * @param {number} cursorX - Cursor horizontal coordinate within the canvas.
  1278. * @param {number} cursorY - Cursor vertical coordinate within the canvas.
  1279. * @param {HTMLElement} canvas - The canvas where the renderer draws its output.
  1280. * @returns {Vector2} Cursor position inside the canvas.
  1281. */
  1282. getCursorPosition( cursorX, cursorY, canvas ) {
  1283. this._v2_1.copy( this.getCursorNDC( cursorX, cursorY, canvas ) );
  1284. this._v2_1.x *= ( this.object.right - this.object.left ) * 0.5;
  1285. this._v2_1.y *= ( this.object.top - this.object.bottom ) * 0.5;
  1286. return this._v2_1.clone();
  1287. }
  1288. /**
  1289. * Sets the camera to be controlled. Must be called in order to set a new camera to be controlled.
  1290. *
  1291. * @param {Camera} camera - The camera to be controlled.
  1292. */
  1293. setCamera( camera ) {
  1294. camera.lookAt( this.target );
  1295. camera.updateMatrix();
  1296. //setting state
  1297. if ( camera.type == 'PerspectiveCamera' ) {
  1298. this._fov0 = camera.fov;
  1299. this._fovState = camera.fov;
  1300. }
  1301. this._cameraMatrixState0.copy( camera.matrix );
  1302. this._cameraMatrixState.copy( this._cameraMatrixState0 );
  1303. this._cameraProjectionState.copy( camera.projectionMatrix );
  1304. this._zoom0 = camera.zoom;
  1305. this._zoomState = this._zoom0;
  1306. this._initialNear = camera.near;
  1307. this._nearPos0 = camera.position.distanceTo( this.target ) - camera.near;
  1308. this._nearPos = this._initialNear;
  1309. this._initialFar = camera.far;
  1310. this._farPos0 = camera.position.distanceTo( this.target ) - camera.far;
  1311. this._farPos = this._initialFar;
  1312. this._up0.copy( camera.up );
  1313. this._upState.copy( camera.up );
  1314. this.object = camera;
  1315. this.object.updateProjectionMatrix();
  1316. //making gizmos
  1317. this._tbRadius = this.calculateTbRadius( camera );
  1318. this.makeGizmos( this.target, this._tbRadius );
  1319. }
  1320. /**
  1321. * Sets gizmos visibility.
  1322. *
  1323. * @param {boolean} value - Value of gizmos visibility.
  1324. */
  1325. setGizmosVisible( value ) {
  1326. this._gizmos.visible = value;
  1327. this.dispatchEvent( _changeEvent );
  1328. }
  1329. /**
  1330. * Sets gizmos radius factor and redraws gizmos.
  1331. *
  1332. * @param {number} value - Value of radius factor.
  1333. */
  1334. setTbRadius( value ) {
  1335. this.radiusFactor = value;
  1336. this._tbRadius = this.calculateTbRadius( this.object );
  1337. const curve = new EllipseCurve( 0, 0, this._tbRadius, this._tbRadius );
  1338. const points = curve.getPoints( this._curvePts );
  1339. const curveGeometry = new BufferGeometry().setFromPoints( points );
  1340. for ( const gizmo in this._gizmos.children ) {
  1341. this._gizmos.children[ gizmo ].geometry = curveGeometry;
  1342. }
  1343. this.dispatchEvent( _changeEvent );
  1344. }
  1345. /**
  1346. * Creates the rotation gizmos matching trackball center and radius.
  1347. *
  1348. * @private
  1349. * @param {Vector3} tbCenter - The trackball center.
  1350. * @param {number} tbRadius - The trackball radius.
  1351. */
  1352. makeGizmos( tbCenter, tbRadius ) {
  1353. const curve = new EllipseCurve( 0, 0, tbRadius, tbRadius );
  1354. const points = curve.getPoints( this._curvePts );
  1355. //geometry
  1356. const curveGeometry = new BufferGeometry().setFromPoints( points );
  1357. //material
  1358. const curveMaterialX = new LineBasicMaterial( { color: 0xff8080, fog: false, transparent: true, opacity: 0.6 } );
  1359. const curveMaterialY = new LineBasicMaterial( { color: 0x80ff80, fog: false, transparent: true, opacity: 0.6 } );
  1360. const curveMaterialZ = new LineBasicMaterial( { color: 0x8080ff, fog: false, transparent: true, opacity: 0.6 } );
  1361. //line
  1362. const gizmoX = new Line( curveGeometry, curveMaterialX );
  1363. const gizmoY = new Line( curveGeometry, curveMaterialY );
  1364. const gizmoZ = new Line( curveGeometry, curveMaterialZ );
  1365. const rotation = Math.PI * 0.5;
  1366. gizmoX.rotation.y = rotation;
  1367. gizmoY.rotation.x = rotation;
  1368. //setting state
  1369. this._gizmoMatrixState0.identity().setPosition( tbCenter );
  1370. this._gizmoMatrixState.copy( this._gizmoMatrixState0 );
  1371. if ( this.object.zoom !== 1 ) {
  1372. //adapt gizmos size to camera zoom
  1373. const size = 1 / this.object.zoom;
  1374. this._scaleMatrix.makeScale( size, size, size );
  1375. this._translationMatrix.makeTranslation( - tbCenter.x, - tbCenter.y, - tbCenter.z );
  1376. this._gizmoMatrixState.premultiply( this._translationMatrix ).premultiply( this._scaleMatrix );
  1377. this._translationMatrix.makeTranslation( tbCenter.x, tbCenter.y, tbCenter.z );
  1378. this._gizmoMatrixState.premultiply( this._translationMatrix );
  1379. }
  1380. this._gizmoMatrixState.decompose( this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale );
  1381. //
  1382. this._gizmos.traverse( function ( object ) {
  1383. if ( object.isLine ) {
  1384. object.geometry.dispose();
  1385. object.material.dispose();
  1386. }
  1387. } );
  1388. this._gizmos.clear();
  1389. //
  1390. this._gizmos.add( gizmoX );
  1391. this._gizmos.add( gizmoY );
  1392. this._gizmos.add( gizmoZ );
  1393. }
  1394. /**
  1395. * Performs animation for focus operation.
  1396. *
  1397. * @private
  1398. * @param {number} time - Instant in which this function is called as performance.now().
  1399. * @param {Vector3} point - Point of interest for focus operation.
  1400. * @param {Matrix4} cameraMatrix - Camera matrix.
  1401. * @param {Matrix4} gizmoMatrix - Gizmos matrix.
  1402. */
  1403. onFocusAnim( time, point, cameraMatrix, gizmoMatrix ) {
  1404. if ( this._timeStart == - 1 ) {
  1405. //animation start
  1406. this._timeStart = time;
  1407. }
  1408. if ( this._state == STATE.ANIMATION_FOCUS ) {
  1409. const deltaTime = time - this._timeStart;
  1410. const animTime = deltaTime / this.focusAnimationTime;
  1411. this._gizmoMatrixState.copy( gizmoMatrix );
  1412. if ( animTime >= 1 ) {
  1413. //animation end
  1414. this._gizmoMatrixState.decompose( this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale );
  1415. this.focus( point, this.scaleFactor );
  1416. this._timeStart = - 1;
  1417. this.updateTbState( STATE.IDLE, false );
  1418. this.activateGizmos( false );
  1419. this.dispatchEvent( _changeEvent );
  1420. } else {
  1421. const amount = this.easeOutCubic( animTime );
  1422. const size = ( ( 1 - amount ) + ( this.scaleFactor * amount ) );
  1423. this._gizmoMatrixState.decompose( this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale );
  1424. this.focus( point, size, amount );
  1425. this.dispatchEvent( _changeEvent );
  1426. const self = this;
  1427. this._animationId = window.requestAnimationFrame( function ( t ) {
  1428. self.onFocusAnim( t, point, cameraMatrix, gizmoMatrix.clone() );
  1429. } );
  1430. }
  1431. } else {
  1432. //interrupt animation
  1433. this._animationId = - 1;
  1434. this._timeStart = - 1;
  1435. }
  1436. }
  1437. /**
  1438. * Performs animation for rotation operation.
  1439. *
  1440. * @private
  1441. * @param {number} time - Instant in which this function is called as performance.now().
  1442. * @param {Vector3} rotationAxis - Rotation axis.
  1443. * @param {number} w0 - Initial angular velocity.
  1444. */
  1445. onRotationAnim( time, rotationAxis, w0 ) {
  1446. if ( this._timeStart == - 1 ) {
  1447. //animation start
  1448. this._anglePrev = 0;
  1449. this._angleCurrent = 0;
  1450. this._timeStart = time;
  1451. }
  1452. if ( this._state == STATE.ANIMATION_ROTATE ) {
  1453. //w = w0 + alpha * t
  1454. const deltaTime = ( time - this._timeStart ) / 1000;
  1455. const w = w0 + ( ( - this.dampingFactor ) * deltaTime );
  1456. if ( w > 0 ) {
  1457. //tetha = 0.5 * alpha * t^2 + w0 * t + tetha0
  1458. this._angleCurrent = 0.5 * ( - this.dampingFactor ) * Math.pow( deltaTime, 2 ) + w0 * deltaTime + 0;
  1459. this.applyTransformMatrix( this.rotate( rotationAxis, this._angleCurrent ) );
  1460. this.dispatchEvent( _changeEvent );
  1461. const self = this;
  1462. this._animationId = window.requestAnimationFrame( function ( t ) {
  1463. self.onRotationAnim( t, rotationAxis, w0 );
  1464. } );
  1465. } else {
  1466. this._animationId = - 1;
  1467. this._timeStart = - 1;
  1468. this.updateTbState( STATE.IDLE, false );
  1469. this.activateGizmos( false );
  1470. this.dispatchEvent( _changeEvent );
  1471. }
  1472. } else {
  1473. //interrupt animation
  1474. this._animationId = - 1;
  1475. this._timeStart = - 1;
  1476. if ( this._state != STATE.ROTATE ) {
  1477. this.activateGizmos( false );
  1478. this.dispatchEvent( _changeEvent );
  1479. }
  1480. }
  1481. }
  1482. /**
  1483. * Performs pan operation moving camera between two points.
  1484. *
  1485. * @private
  1486. * @param {Vector3} p0 - Initial point.
  1487. * @param {Vector3} p1 - Ending point.
  1488. * @param {boolean} [adjust=false] - If movement should be adjusted considering camera distance (Perspective only).
  1489. * @returns {Object}
  1490. */
  1491. pan( p0, p1, adjust = false ) {
  1492. const movement = p0.clone().sub( p1 );
  1493. if ( this.object.isOrthographicCamera ) {
  1494. //adjust movement amount
  1495. movement.multiplyScalar( 1 / this.object.zoom );
  1496. } else if ( this.object.isPerspectiveCamera && adjust ) {
  1497. //adjust movement amount
  1498. this._v3_1.setFromMatrixPosition( this._cameraMatrixState0 ); //camera's initial position
  1499. this._v3_2.setFromMatrixPosition( this._gizmoMatrixState0 ); //gizmo's initial position
  1500. const distanceFactor = this._v3_1.distanceTo( this._v3_2 ) / this.object.position.distanceTo( this._gizmos.position );
  1501. movement.multiplyScalar( 1 / distanceFactor );
  1502. }
  1503. this._v3_1.set( movement.x, movement.y, 0 ).applyQuaternion( this.object.quaternion );
  1504. this._m4_1.makeTranslation( this._v3_1.x, this._v3_1.y, this._v3_1.z );
  1505. this.setTransformationMatrices( this._m4_1, this._m4_1 );
  1506. return _transformation;
  1507. }
  1508. /**
  1509. * Resets the controls.
  1510. */
  1511. reset() {
  1512. this.target.copy( this._target0 );
  1513. this.object.zoom = this._zoom0;
  1514. if ( this.object.isPerspectiveCamera ) {
  1515. this.object.fov = this._fov0;
  1516. }
  1517. this.object.near = this._nearPos;
  1518. this.object.far = this._farPos;
  1519. this._cameraMatrixState.copy( this._cameraMatrixState0 );
  1520. this._cameraMatrixState.decompose( this.object.position, this.object.quaternion, this.object.scale );
  1521. this.object.up.copy( this._up0 );
  1522. this.object.updateMatrix();
  1523. this.object.updateProjectionMatrix();
  1524. this._gizmoMatrixState.copy( this._gizmoMatrixState0 );
  1525. this._gizmoMatrixState0.decompose( this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale );
  1526. this._gizmos.updateMatrix();
  1527. this._tbRadius = this.calculateTbRadius( this.object );
  1528. this.makeGizmos( this._gizmos.position, this._tbRadius );
  1529. this.object.lookAt( this._gizmos.position );
  1530. this.updateTbState( STATE.IDLE, false );
  1531. this.dispatchEvent( _changeEvent );
  1532. }
  1533. /**
  1534. * Rotates the camera around an axis passing by trackball's center.
  1535. *
  1536. * @private
  1537. * @param {Vector3} axis - Rotation axis.
  1538. * @param {number} angle - Angle in radians.
  1539. * @returns {Object} Object with 'camera' field containing transformation matrix resulting from the operation to be applied to the camera.
  1540. */
  1541. rotate( axis, angle ) {
  1542. const point = this._gizmos.position; //rotation center
  1543. this._translationMatrix.makeTranslation( - point.x, - point.y, - point.z );
  1544. this._rotationMatrix.makeRotationAxis( axis, - angle );
  1545. //rotate camera
  1546. this._m4_1.makeTranslation( point.x, point.y, point.z );
  1547. this._m4_1.multiply( this._rotationMatrix );
  1548. this._m4_1.multiply( this._translationMatrix );
  1549. this.setTransformationMatrices( this._m4_1 );
  1550. return _transformation;
  1551. }
  1552. /**
  1553. * Copy the current state to clipboard (as a readable JSON text).
  1554. */
  1555. copyState() {
  1556. let state;
  1557. if ( this.object.isOrthographicCamera ) {
  1558. state = JSON.stringify( {
  1559. arcballState: {
  1560. cameraFar: this.object.far,
  1561. cameraMatrix: this.object.matrix,
  1562. cameraNear: this.object.near,
  1563. cameraUp: this.object.up,
  1564. cameraZoom: this.object.zoom,
  1565. gizmoMatrix: this._gizmos.matrix,
  1566. target: this.target
  1567. }
  1568. } );
  1569. } else if ( this.object.isPerspectiveCamera ) {
  1570. state = JSON.stringify( {
  1571. arcballState: {
  1572. cameraFar: this.object.far,
  1573. cameraFov: this.object.fov,
  1574. cameraMatrix: this.object.matrix,
  1575. cameraNear: this.object.near,
  1576. cameraUp: this.object.up,
  1577. cameraZoom: this.object.zoom,
  1578. gizmoMatrix: this._gizmos.matrix,
  1579. target: this.target
  1580. }
  1581. } );
  1582. }
  1583. navigator.clipboard.writeText( state );
  1584. }
  1585. /**
  1586. * Set the controls state from the clipboard, assumes that the clipboard stores a JSON
  1587. * text as saved from `copyState()`.
  1588. */
  1589. pasteState() {
  1590. const self = this;
  1591. navigator.clipboard.readText().then( function resolved( value ) {
  1592. self.setStateFromJSON( value );
  1593. } );
  1594. }
  1595. /**
  1596. * Saves the current state of the control. This can later be recover with `reset()`.
  1597. */
  1598. saveState() {
  1599. this.object.updateMatrix();
  1600. this._gizmos.updateMatrix();
  1601. this._target0.copy( this.target );
  1602. this._cameraMatrixState0.copy( this.object.matrix );
  1603. this._gizmoMatrixState0.copy( this._gizmos.matrix );
  1604. this._nearPos = this.object.near;
  1605. this._farPos = this.object.far;
  1606. this._zoom0 = this.object.zoom;
  1607. this._up0.copy( this.object.up );
  1608. if ( this.object.isPerspectiveCamera ) {
  1609. this._fov0 = this.object.fov;
  1610. }
  1611. }
  1612. /**
  1613. * Performs uniform scale operation around a given point.
  1614. *
  1615. * @private
  1616. * @param {number} size - Scale factor.
  1617. * @param {Vector3} point - Point around which scale.
  1618. * @param {boolean} scaleGizmos - If gizmos should be scaled (Perspective only).
  1619. * @returns {Object} Object with 'camera' and 'gizmo' fields containing transformation matrices resulting from the operation to be applied to the camera and gizmos.
  1620. */
  1621. scale( size, point, scaleGizmos = true ) {
  1622. _scalePointTemp.copy( point );
  1623. let sizeInverse = 1 / size;
  1624. if ( this.object.isOrthographicCamera ) {
  1625. //camera zoom
  1626. this.object.zoom = this._zoomState;
  1627. this.object.zoom *= size;
  1628. //check min and max zoom
  1629. if ( this.object.zoom > this.maxZoom ) {
  1630. this.object.zoom = this.maxZoom;
  1631. sizeInverse = this._zoomState / this.maxZoom;
  1632. } else if ( this.object.zoom < this.minZoom ) {
  1633. this.object.zoom = this.minZoom;
  1634. sizeInverse = this._zoomState / this.minZoom;
  1635. }
  1636. this.object.updateProjectionMatrix();
  1637. this._v3_1.setFromMatrixPosition( this._gizmoMatrixState ); //gizmos position
  1638. //scale gizmos so they appear in the same spot having the same dimension
  1639. this._scaleMatrix.makeScale( sizeInverse, sizeInverse, sizeInverse );
  1640. this._translationMatrix.makeTranslation( - this._v3_1.x, - this._v3_1.y, - this._v3_1.z );
  1641. this._m4_2.makeTranslation( this._v3_1.x, this._v3_1.y, this._v3_1.z ).multiply( this._scaleMatrix );
  1642. this._m4_2.multiply( this._translationMatrix );
  1643. //move camera and gizmos to obtain pinch effect
  1644. _scalePointTemp.sub( this._v3_1 );
  1645. const amount = _scalePointTemp.clone().multiplyScalar( sizeInverse );
  1646. _scalePointTemp.sub( amount );
  1647. this._m4_1.makeTranslation( _scalePointTemp.x, _scalePointTemp.y, _scalePointTemp.z );
  1648. this._m4_2.premultiply( this._m4_1 );
  1649. this.setTransformationMatrices( this._m4_1, this._m4_2 );
  1650. return _transformation;
  1651. } else if ( this.object.isPerspectiveCamera ) {
  1652. this._v3_1.setFromMatrixPosition( this._cameraMatrixState );
  1653. this._v3_2.setFromMatrixPosition( this._gizmoMatrixState );
  1654. //move camera
  1655. let distance = this._v3_1.distanceTo( _scalePointTemp );
  1656. let amount = distance - ( distance * sizeInverse );
  1657. //check min and max distance
  1658. const newDistance = distance - amount;
  1659. if ( newDistance < this.minDistance ) {
  1660. sizeInverse = this.minDistance / distance;
  1661. amount = distance - ( distance * sizeInverse );
  1662. } else if ( newDistance > this.maxDistance ) {
  1663. sizeInverse = this.maxDistance / distance;
  1664. amount = distance - ( distance * sizeInverse );
  1665. }
  1666. _offset.copy( _scalePointTemp ).sub( this._v3_1 ).normalize().multiplyScalar( amount );
  1667. this._m4_1.makeTranslation( _offset.x, _offset.y, _offset.z );
  1668. if ( scaleGizmos ) {
  1669. //scale gizmos so they appear in the same spot having the same dimension
  1670. const pos = this._v3_2;
  1671. distance = pos.distanceTo( _scalePointTemp );
  1672. amount = distance - ( distance * sizeInverse );
  1673. _offset.copy( _scalePointTemp ).sub( this._v3_2 ).normalize().multiplyScalar( amount );
  1674. this._translationMatrix.makeTranslation( pos.x, pos.y, pos.z );
  1675. this._scaleMatrix.makeScale( sizeInverse, sizeInverse, sizeInverse );
  1676. this._m4_2.makeTranslation( _offset.x, _offset.y, _offset.z ).multiply( this._translationMatrix );
  1677. this._m4_2.multiply( this._scaleMatrix );
  1678. this._translationMatrix.makeTranslation( - pos.x, - pos.y, - pos.z );
  1679. this._m4_2.multiply( this._translationMatrix );
  1680. this.setTransformationMatrices( this._m4_1, this._m4_2 );
  1681. } else {
  1682. this.setTransformationMatrices( this._m4_1 );
  1683. }
  1684. return _transformation;
  1685. }
  1686. }
  1687. /**
  1688. * Sets camera fov.
  1689. *
  1690. * @private
  1691. * @param {number} value - The FOV to be set.
  1692. */
  1693. setFov( value ) {
  1694. if ( this.object.isPerspectiveCamera ) {
  1695. this.object.fov = MathUtils.clamp( value, this.minFov, this.maxFov );
  1696. this.object.updateProjectionMatrix();
  1697. }
  1698. }
  1699. /**
  1700. * Sets values in transformation object.
  1701. *
  1702. * @private
  1703. * @param {?Matrix4} [camera=null] - Transformation to be applied to the camera.
  1704. * @param {?Matrix4} [gizmos=null] - Transformation to be applied to gizmos.
  1705. */
  1706. setTransformationMatrices( camera = null, gizmos = null ) {
  1707. if ( camera != null ) {
  1708. if ( _transformation.camera != null ) {
  1709. _transformation.camera.copy( camera );
  1710. } else {
  1711. _transformation.camera = camera.clone();
  1712. }
  1713. } else {
  1714. _transformation.camera = null;
  1715. }
  1716. if ( gizmos != null ) {
  1717. if ( _transformation.gizmos != null ) {
  1718. _transformation.gizmos.copy( gizmos );
  1719. } else {
  1720. _transformation.gizmos = gizmos.clone();
  1721. }
  1722. } else {
  1723. _transformation.gizmos = null;
  1724. }
  1725. }
  1726. /**
  1727. * Rotates camera around its direction axis passing by a given point by a given angle.
  1728. *
  1729. * @private
  1730. * @param {Vector3} point - The point where the rotation axis is passing trough.
  1731. * @param {number} angle - Angle in radians.
  1732. * @returns {Object} The computed transformation matrix.
  1733. */
  1734. zRotate( point, angle ) {
  1735. this._rotationMatrix.makeRotationAxis( this._rotationAxis, angle );
  1736. this._translationMatrix.makeTranslation( - point.x, - point.y, - point.z );
  1737. this._m4_1.makeTranslation( point.x, point.y, point.z );
  1738. this._m4_1.multiply( this._rotationMatrix );
  1739. this._m4_1.multiply( this._translationMatrix );
  1740. this._v3_1.setFromMatrixPosition( this._gizmoMatrixState ).sub( point ); //vector from rotation center to gizmos position
  1741. this._v3_2.copy( this._v3_1 ).applyAxisAngle( this._rotationAxis, angle ); //apply rotation
  1742. this._v3_2.sub( this._v3_1 );
  1743. this._m4_2.makeTranslation( this._v3_2.x, this._v3_2.y, this._v3_2.z );
  1744. this.setTransformationMatrices( this._m4_1, this._m4_2 );
  1745. return _transformation;
  1746. }
  1747. /**
  1748. * Returns the raycaster that is used for user interaction. This object is shared between all
  1749. * instances of `ArcballControls`.
  1750. *
  1751. * @returns {Raycaster} The internal raycaster.
  1752. */
  1753. getRaycaster() {
  1754. return _raycaster;
  1755. }
  1756. /**
  1757. * Unprojects the cursor on the 3D object surface.
  1758. *
  1759. * @private
  1760. * @param {Vector2} cursor - Cursor coordinates in NDC.
  1761. * @param {Camera} camera - Virtual camera.
  1762. * @returns {?Vector3} The point of intersection with the model, if exist, null otherwise.
  1763. */
  1764. unprojectOnObj( cursor, camera ) {
  1765. const raycaster = this.getRaycaster();
  1766. raycaster.near = camera.near;
  1767. raycaster.far = camera.far;
  1768. raycaster.setFromCamera( cursor, camera );
  1769. const intersect = raycaster.intersectObjects( this.scene.children, true );
  1770. for ( let i = 0; i < intersect.length; i ++ ) {
  1771. if ( intersect[ i ].object.uuid != this._gizmos.uuid && intersect[ i ].face != null ) {
  1772. return intersect[ i ].point.clone();
  1773. }
  1774. }
  1775. return null;
  1776. }
  1777. /**
  1778. * Unproject the cursor on the trackball surface.
  1779. *
  1780. * @private
  1781. * @param {Camera} camera - The virtual camera.
  1782. * @param {number} cursorX - Cursor horizontal coordinate on screen.
  1783. * @param {number} cursorY - Cursor vertical coordinate on screen.
  1784. * @param {HTMLElement} canvas - The canvas where the renderer draws its output.
  1785. * @param {number} tbRadius - The trackball radius.
  1786. * @returns {Vector3} The unprojected point on the trackball surface.
  1787. */
  1788. unprojectOnTbSurface( camera, cursorX, cursorY, canvas, tbRadius ) {
  1789. if ( camera.type == 'OrthographicCamera' ) {
  1790. this._v2_1.copy( this.getCursorPosition( cursorX, cursorY, canvas ) );
  1791. this._v3_1.set( this._v2_1.x, this._v2_1.y, 0 );
  1792. const x2 = Math.pow( this._v2_1.x, 2 );
  1793. const y2 = Math.pow( this._v2_1.y, 2 );
  1794. const r2 = Math.pow( this._tbRadius, 2 );
  1795. if ( x2 + y2 <= r2 * 0.5 ) {
  1796. //intersection with sphere
  1797. this._v3_1.setZ( Math.sqrt( r2 - ( x2 + y2 ) ) );
  1798. } else {
  1799. //intersection with hyperboloid
  1800. this._v3_1.setZ( ( r2 * 0.5 ) / ( Math.sqrt( x2 + y2 ) ) );
  1801. }
  1802. return this._v3_1;
  1803. } else if ( camera.type == 'PerspectiveCamera' ) {
  1804. //unproject cursor on the near plane
  1805. this._v2_1.copy( this.getCursorNDC( cursorX, cursorY, canvas ) );
  1806. this._v3_1.set( this._v2_1.x, this._v2_1.y, - 1 );
  1807. this._v3_1.applyMatrix4( camera.projectionMatrixInverse );
  1808. const rayDir = this._v3_1.clone().normalize(); //unprojected ray direction
  1809. const cameraGizmoDistance = camera.position.distanceTo( this._gizmos.position );
  1810. const radius2 = Math.pow( tbRadius, 2 );
  1811. // camera
  1812. // |\
  1813. // | \
  1814. // | \
  1815. // h | \
  1816. // | \
  1817. // | \
  1818. // _ _ | _ _ _\ _ _ near plane
  1819. // l
  1820. const h = this._v3_1.z;
  1821. const l = Math.sqrt( Math.pow( this._v3_1.x, 2 ) + Math.pow( this._v3_1.y, 2 ) );
  1822. if ( l == 0 ) {
  1823. //ray aligned with camera
  1824. rayDir.set( this._v3_1.x, this._v3_1.y, tbRadius );
  1825. return rayDir;
  1826. }
  1827. const m = h / l;
  1828. const q = cameraGizmoDistance;
  1829. /*
  1830. * calculate intersection point between unprojected ray and trackball surface
  1831. *|y = m * x + q
  1832. *|x^2 + y^2 = r^2
  1833. *
  1834. * (m^2 + 1) * x^2 + (2 * m * q) * x + q^2 - r^2 = 0
  1835. */
  1836. let a = Math.pow( m, 2 ) + 1;
  1837. let b = 2 * m * q;
  1838. let c = Math.pow( q, 2 ) - radius2;
  1839. let delta = Math.pow( b, 2 ) - ( 4 * a * c );
  1840. if ( delta >= 0 ) {
  1841. //intersection with sphere
  1842. this._v2_1.setX( ( - b - Math.sqrt( delta ) ) / ( 2 * a ) );
  1843. this._v2_1.setY( m * this._v2_1.x + q );
  1844. const angle = MathUtils.RAD2DEG * this._v2_1.angle();
  1845. if ( angle >= 45 ) {
  1846. //if angle between intersection point and X' axis is >= 45°, return that point
  1847. //otherwise, calculate intersection point with hyperboloid
  1848. const rayLength = Math.sqrt( Math.pow( this._v2_1.x, 2 ) + Math.pow( ( cameraGizmoDistance - this._v2_1.y ), 2 ) );
  1849. rayDir.multiplyScalar( rayLength );
  1850. rayDir.z += cameraGizmoDistance;
  1851. return rayDir;
  1852. }
  1853. }
  1854. //intersection with hyperboloid
  1855. /*
  1856. *|y = m * x + q
  1857. *|y = (1 / x) * (r^2 / 2)
  1858. *
  1859. * m * x^2 + q * x - r^2 / 2 = 0
  1860. */
  1861. a = m;
  1862. b = q;
  1863. c = - radius2 * 0.5;
  1864. delta = Math.pow( b, 2 ) - ( 4 * a * c );
  1865. this._v2_1.setX( ( - b - Math.sqrt( delta ) ) / ( 2 * a ) );
  1866. this._v2_1.setY( m * this._v2_1.x + q );
  1867. const rayLength = Math.sqrt( Math.pow( this._v2_1.x, 2 ) + Math.pow( ( cameraGizmoDistance - this._v2_1.y ), 2 ) );
  1868. rayDir.multiplyScalar( rayLength );
  1869. rayDir.z += cameraGizmoDistance;
  1870. return rayDir;
  1871. }
  1872. }
  1873. /**
  1874. * Unprojects the cursor on the plane passing through the center of the trackball orthogonal to the camera.
  1875. *
  1876. * @private
  1877. * @param {Camera} camera - The virtual camera.
  1878. * @param {number} cursorX - Cursor horizontal coordinate on screen.
  1879. * @param {number} cursorY - Cursor vertical coordinate on screen.
  1880. * @param {HTMLElement} canvas - The canvas where the renderer draws its output.
  1881. * @param {boolean} [initialDistance=false] - If initial distance between camera and gizmos should be used for calculations instead of current (Perspective only).
  1882. * @returns {Vector3} The unprojected point on the trackball plane.
  1883. */
  1884. unprojectOnTbPlane( camera, cursorX, cursorY, canvas, initialDistance = false ) {
  1885. if ( camera.type == 'OrthographicCamera' ) {
  1886. this._v2_1.copy( this.getCursorPosition( cursorX, cursorY, canvas ) );
  1887. this._v3_1.set( this._v2_1.x, this._v2_1.y, 0 );
  1888. return this._v3_1.clone();
  1889. } else if ( camera.type == 'PerspectiveCamera' ) {
  1890. this._v2_1.copy( this.getCursorNDC( cursorX, cursorY, canvas ) );
  1891. //unproject cursor on the near plane
  1892. this._v3_1.set( this._v2_1.x, this._v2_1.y, - 1 );
  1893. this._v3_1.applyMatrix4( camera.projectionMatrixInverse );
  1894. const rayDir = this._v3_1.clone().normalize(); //unprojected ray direction
  1895. // camera
  1896. // |\
  1897. // | \
  1898. // | \
  1899. // h | \
  1900. // | \
  1901. // | \
  1902. // _ _ | _ _ _\ _ _ near plane
  1903. // l
  1904. const h = this._v3_1.z;
  1905. const l = Math.sqrt( Math.pow( this._v3_1.x, 2 ) + Math.pow( this._v3_1.y, 2 ) );
  1906. let cameraGizmoDistance;
  1907. if ( initialDistance ) {
  1908. cameraGizmoDistance = this._v3_1.setFromMatrixPosition( this._cameraMatrixState0 ).distanceTo( this._v3_2.setFromMatrixPosition( this._gizmoMatrixState0 ) );
  1909. } else {
  1910. cameraGizmoDistance = camera.position.distanceTo( this._gizmos.position );
  1911. }
  1912. /*
  1913. * calculate intersection point between unprojected ray and the plane
  1914. *|y = mx + q
  1915. *|y = 0
  1916. *
  1917. * x = -q/m
  1918. */
  1919. if ( l == 0 ) {
  1920. //ray aligned with camera
  1921. rayDir.set( 0, 0, 0 );
  1922. return rayDir;
  1923. }
  1924. const m = h / l;
  1925. const q = cameraGizmoDistance;
  1926. const x = - q / m;
  1927. const rayLength = Math.sqrt( Math.pow( q, 2 ) + Math.pow( x, 2 ) );
  1928. rayDir.multiplyScalar( rayLength );
  1929. rayDir.z = 0;
  1930. return rayDir;
  1931. }
  1932. }
  1933. /**
  1934. * Updates camera and gizmos state.
  1935. *
  1936. * @private
  1937. */
  1938. updateMatrixState() {
  1939. //update camera and gizmos state
  1940. this._cameraMatrixState.copy( this.object.matrix );
  1941. this._gizmoMatrixState.copy( this._gizmos.matrix );
  1942. if ( this.object.isOrthographicCamera ) {
  1943. this._cameraProjectionState.copy( this.object.projectionMatrix );
  1944. this.object.updateProjectionMatrix();
  1945. this._zoomState = this.object.zoom;
  1946. } else if ( this.object.isPerspectiveCamera ) {
  1947. this._fovState = this.object.fov;
  1948. }
  1949. }
  1950. /**
  1951. * Updates the trackball FSA.
  1952. *
  1953. * @private
  1954. * @param {STATE} newState - New state of the FSA.
  1955. * @param {boolean} updateMatrices - If matrices state should be updated.
  1956. */
  1957. updateTbState( newState, updateMatrices ) {
  1958. this._state = newState;
  1959. if ( updateMatrices ) {
  1960. this.updateMatrixState();
  1961. }
  1962. }
  1963. update() {
  1964. if ( this.target.equals( this._currentTarget ) === false ) {
  1965. this._gizmos.position.copy( this.target ); //for correct radius calculation
  1966. this._tbRadius = this.calculateTbRadius( this.object );
  1967. this.makeGizmos( this.target, this._tbRadius );
  1968. this._currentTarget.copy( this.target );
  1969. }
  1970. //check min/max parameters
  1971. if ( this.object.isOrthographicCamera ) {
  1972. //check zoom
  1973. if ( this.object.zoom > this.maxZoom || this.object.zoom < this.minZoom ) {
  1974. const newZoom = MathUtils.clamp( this.object.zoom, this.minZoom, this.maxZoom );
  1975. this.applyTransformMatrix( this.scale( newZoom / this.object.zoom, this._gizmos.position, true ) );
  1976. }
  1977. } else if ( this.object.isPerspectiveCamera ) {
  1978. //check distance
  1979. const distance = this.object.position.distanceTo( this._gizmos.position );
  1980. if ( distance > this.maxDistance + _EPS || distance < this.minDistance - _EPS ) {
  1981. const newDistance = MathUtils.clamp( distance, this.minDistance, this.maxDistance );
  1982. this.applyTransformMatrix( this.scale( newDistance / distance, this._gizmos.position ) );
  1983. this.updateMatrixState();
  1984. }
  1985. //check fov
  1986. if ( this.object.fov < this.minFov || this.object.fov > this.maxFov ) {
  1987. this.object.fov = MathUtils.clamp( this.object.fov, this.minFov, this.maxFov );
  1988. this.object.updateProjectionMatrix();
  1989. }
  1990. const oldRadius = this._tbRadius;
  1991. this._tbRadius = this.calculateTbRadius( this.object );
  1992. if ( oldRadius < this._tbRadius - _EPS || oldRadius > this._tbRadius + _EPS ) {
  1993. const scale = ( this._gizmos.scale.x + this._gizmos.scale.y + this._gizmos.scale.z ) / 3;
  1994. const newRadius = this._tbRadius / scale;
  1995. const curve = new EllipseCurve( 0, 0, newRadius, newRadius );
  1996. const points = curve.getPoints( this._curvePts );
  1997. const curveGeometry = new BufferGeometry().setFromPoints( points );
  1998. for ( const gizmo in this._gizmos.children ) {
  1999. this._gizmos.children[ gizmo ].geometry = curveGeometry;
  2000. }
  2001. }
  2002. }
  2003. this.object.lookAt( this._gizmos.position );
  2004. }
  2005. setStateFromJSON( json ) {
  2006. const state = JSON.parse( json );
  2007. if ( state.arcballState != undefined ) {
  2008. this.target.fromArray( state.arcballState.target );
  2009. this._cameraMatrixState.fromArray( state.arcballState.cameraMatrix.elements );
  2010. this._cameraMatrixState.decompose( this.object.position, this.object.quaternion, this.object.scale );
  2011. this.object.up.copy( state.arcballState.cameraUp );
  2012. this.object.near = state.arcballState.cameraNear;
  2013. this.object.far = state.arcballState.cameraFar;
  2014. this.object.zoom = state.arcballState.cameraZoom;
  2015. if ( this.object.isPerspectiveCamera ) {
  2016. this.object.fov = state.arcballState.cameraFov;
  2017. }
  2018. this._gizmoMatrixState.fromArray( state.arcballState.gizmoMatrix.elements );
  2019. this._gizmoMatrixState.decompose( this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale );
  2020. this.object.updateMatrix();
  2021. this.object.updateProjectionMatrix();
  2022. this._gizmos.updateMatrix();
  2023. this._tbRadius = this.calculateTbRadius( this.object );
  2024. const gizmoTmp = new Matrix4().copy( this._gizmoMatrixState0 );
  2025. this.makeGizmos( this._gizmos.position, this._tbRadius );
  2026. this._gizmoMatrixState0.copy( gizmoTmp );
  2027. this.object.lookAt( this._gizmos.position );
  2028. this.updateTbState( STATE.IDLE, false );
  2029. this.dispatchEvent( _changeEvent );
  2030. }
  2031. }
  2032. }
  2033. //listeners
  2034. function onWindowResize() {
  2035. const scale = ( this._gizmos.scale.x + this._gizmos.scale.y + this._gizmos.scale.z ) / 3;
  2036. this._tbRadius = this.calculateTbRadius( this.object );
  2037. const newRadius = this._tbRadius / scale;
  2038. const curve = new EllipseCurve( 0, 0, newRadius, newRadius );
  2039. const points = curve.getPoints( this._curvePts );
  2040. const curveGeometry = new BufferGeometry().setFromPoints( points );
  2041. for ( const gizmo in this._gizmos.children ) {
  2042. this._gizmos.children[ gizmo ].geometry = curveGeometry;
  2043. }
  2044. this.dispatchEvent( _changeEvent );
  2045. }
  2046. function onContextMenu( event ) {
  2047. if ( ! this.enabled ) {
  2048. return;
  2049. }
  2050. for ( let i = 0; i < this.mouseActions.length; i ++ ) {
  2051. if ( this.mouseActions[ i ].mouse == 2 ) {
  2052. //prevent only if button 2 is actually used
  2053. event.preventDefault();
  2054. break;
  2055. }
  2056. }
  2057. }
  2058. function onPointerCancel() {
  2059. this._touchStart.splice( 0, this._touchStart.length );
  2060. this._touchCurrent.splice( 0, this._touchCurrent.length );
  2061. this._input = INPUT.NONE;
  2062. }
  2063. function onPointerDown( event ) {
  2064. if ( event.button == 0 && event.isPrimary ) {
  2065. this._downValid = true;
  2066. this._downEvents.push( event );
  2067. this._downStart = performance.now();
  2068. } else {
  2069. this._downValid = false;
  2070. }
  2071. if ( event.pointerType == 'touch' && this._input != INPUT.CURSOR ) {
  2072. this._touchStart.push( event );
  2073. this._touchCurrent.push( event );
  2074. switch ( this._input ) {
  2075. case INPUT.NONE:
  2076. //singleStart
  2077. this._input = INPUT.ONE_FINGER;
  2078. this.onSinglePanStart( event, 'ROTATE' );
  2079. window.addEventListener( 'pointermove', this._onPointerMove );
  2080. window.addEventListener( 'pointerup', this._onPointerUp );
  2081. break;
  2082. case INPUT.ONE_FINGER:
  2083. case INPUT.ONE_FINGER_SWITCHED:
  2084. //doubleStart
  2085. this._input = INPUT.TWO_FINGER;
  2086. this.onRotateStart();
  2087. this.onPinchStart();
  2088. this.onDoublePanStart();
  2089. break;
  2090. case INPUT.TWO_FINGER:
  2091. //multipleStart
  2092. this._input = INPUT.MULT_FINGER;
  2093. this.onTriplePanStart( event );
  2094. break;
  2095. }
  2096. } else if ( event.pointerType != 'touch' && this._input == INPUT.NONE ) {
  2097. let modifier = null;
  2098. if ( event.ctrlKey || event.metaKey ) {
  2099. modifier = 'CTRL';
  2100. } else if ( event.shiftKey ) {
  2101. modifier = 'SHIFT';
  2102. }
  2103. this._mouseOp = this.getOpFromAction( event.button, modifier );
  2104. if ( this._mouseOp != null ) {
  2105. window.addEventListener( 'pointermove', this._onPointerMove );
  2106. window.addEventListener( 'pointerup', this._onPointerUp );
  2107. //singleStart
  2108. this._input = INPUT.CURSOR;
  2109. this._button = event.button;
  2110. this.onSinglePanStart( event, this._mouseOp );
  2111. }
  2112. }
  2113. }
  2114. function onPointerMove( event ) {
  2115. if ( event.pointerType == 'touch' && this._input != INPUT.CURSOR ) {
  2116. switch ( this._input ) {
  2117. case INPUT.ONE_FINGER:
  2118. //singleMove
  2119. this.updateTouchEvent( event );
  2120. this.onSinglePanMove( event, STATE.ROTATE );
  2121. break;
  2122. case INPUT.ONE_FINGER_SWITCHED:
  2123. const movement = this.calculatePointersDistance( this._touchCurrent[ 0 ], event ) * this._devPxRatio;
  2124. if ( movement >= this._switchSensibility ) {
  2125. //singleMove
  2126. this._input = INPUT.ONE_FINGER;
  2127. this.updateTouchEvent( event );
  2128. this.onSinglePanStart( event, 'ROTATE' );
  2129. break;
  2130. }
  2131. break;
  2132. case INPUT.TWO_FINGER:
  2133. //rotate/pan/pinchMove
  2134. this.updateTouchEvent( event );
  2135. this.onRotateMove();
  2136. this.onPinchMove();
  2137. this.onDoublePanMove();
  2138. break;
  2139. case INPUT.MULT_FINGER:
  2140. //multMove
  2141. this.updateTouchEvent( event );
  2142. this.onTriplePanMove( event );
  2143. break;
  2144. }
  2145. } else if ( event.pointerType != 'touch' && this._input == INPUT.CURSOR ) {
  2146. let modifier = null;
  2147. if ( event.ctrlKey || event.metaKey ) {
  2148. modifier = 'CTRL';
  2149. } else if ( event.shiftKey ) {
  2150. modifier = 'SHIFT';
  2151. }
  2152. const mouseOpState = this.getOpStateFromAction( this._button, modifier );
  2153. if ( mouseOpState != null ) {
  2154. this.onSinglePanMove( event, mouseOpState );
  2155. }
  2156. }
  2157. //checkDistance
  2158. if ( this._downValid ) {
  2159. const movement = this.calculatePointersDistance( this._downEvents[ this._downEvents.length - 1 ], event ) * this._devPxRatio;
  2160. if ( movement > this._movementThreshold ) {
  2161. this._downValid = false;
  2162. }
  2163. }
  2164. }
  2165. function onPointerUp( event ) {
  2166. if ( event.pointerType == 'touch' && this._input != INPUT.CURSOR ) {
  2167. const nTouch = this._touchCurrent.length;
  2168. for ( let i = 0; i < nTouch; i ++ ) {
  2169. if ( this._touchCurrent[ i ].pointerId == event.pointerId ) {
  2170. this._touchCurrent.splice( i, 1 );
  2171. this._touchStart.splice( i, 1 );
  2172. break;
  2173. }
  2174. }
  2175. switch ( this._input ) {
  2176. case INPUT.ONE_FINGER:
  2177. case INPUT.ONE_FINGER_SWITCHED:
  2178. //singleEnd
  2179. window.removeEventListener( 'pointermove', this._onPointerMove );
  2180. window.removeEventListener( 'pointerup', this._onPointerUp );
  2181. this._input = INPUT.NONE;
  2182. this.onSinglePanEnd();
  2183. break;
  2184. case INPUT.TWO_FINGER:
  2185. //doubleEnd
  2186. this.onDoublePanEnd( event );
  2187. this.onPinchEnd( event );
  2188. this.onRotateEnd( event );
  2189. //switching to singleStart
  2190. this._input = INPUT.ONE_FINGER_SWITCHED;
  2191. break;
  2192. case INPUT.MULT_FINGER:
  2193. if ( this._touchCurrent.length == 0 ) {
  2194. window.removeEventListener( 'pointermove', this._onPointerMove );
  2195. window.removeEventListener( 'pointerup', this._onPointerUp );
  2196. //multCancel
  2197. this._input = INPUT.NONE;
  2198. this.onTriplePanEnd();
  2199. }
  2200. break;
  2201. }
  2202. } else if ( event.pointerType != 'touch' && this._input == INPUT.CURSOR ) {
  2203. window.removeEventListener( 'pointermove', this._onPointerMove );
  2204. window.removeEventListener( 'pointerup', this._onPointerUp );
  2205. this._input = INPUT.NONE;
  2206. this.onSinglePanEnd();
  2207. this._button = - 1;
  2208. }
  2209. if ( event.isPrimary ) {
  2210. if ( this._downValid ) {
  2211. const downTime = event.timeStamp - this._downEvents[ this._downEvents.length - 1 ].timeStamp;
  2212. if ( downTime <= this._maxDownTime ) {
  2213. if ( this._nclicks == 0 ) {
  2214. //first valid click detected
  2215. this._nclicks = 1;
  2216. this._clickStart = performance.now();
  2217. } else {
  2218. const clickInterval = event.timeStamp - this._clickStart;
  2219. const movement = this.calculatePointersDistance( this._downEvents[ 1 ], this._downEvents[ 0 ] ) * this._devPxRatio;
  2220. if ( clickInterval <= this._maxInterval && movement <= this._posThreshold ) {
  2221. //second valid click detected
  2222. //fire double tap and reset values
  2223. this._nclicks = 0;
  2224. this._downEvents.splice( 0, this._downEvents.length );
  2225. this.onDoubleTap( event );
  2226. } else {
  2227. //new 'first click'
  2228. this._nclicks = 1;
  2229. this._downEvents.shift();
  2230. this._clickStart = performance.now();
  2231. }
  2232. }
  2233. } else {
  2234. this._downValid = false;
  2235. this._nclicks = 0;
  2236. this._downEvents.splice( 0, this._downEvents.length );
  2237. }
  2238. } else {
  2239. this._nclicks = 0;
  2240. this._downEvents.splice( 0, this._downEvents.length );
  2241. }
  2242. }
  2243. }
  2244. function onWheel( event ) {
  2245. if ( this.enabled && this.enableZoom ) {
  2246. let modifier = null;
  2247. if ( event.ctrlKey || event.metaKey ) {
  2248. modifier = 'CTRL';
  2249. } else if ( event.shiftKey ) {
  2250. modifier = 'SHIFT';
  2251. }
  2252. const mouseOp = this.getOpFromAction( 'WHEEL', modifier );
  2253. if ( mouseOp != null ) {
  2254. event.preventDefault();
  2255. this.dispatchEvent( _startEvent );
  2256. const notchDeltaY = 125; //distance of one notch of mouse wheel
  2257. let sgn = event.deltaY / notchDeltaY;
  2258. let size = 1;
  2259. if ( sgn > 0 ) {
  2260. size = 1 / this.scaleFactor;
  2261. } else if ( sgn < 0 ) {
  2262. size = this.scaleFactor;
  2263. }
  2264. switch ( mouseOp ) {
  2265. case 'ZOOM':
  2266. this.updateTbState( STATE.SCALE, true );
  2267. if ( sgn > 0 ) {
  2268. size = 1 / ( Math.pow( this.scaleFactor, sgn ) );
  2269. } else if ( sgn < 0 ) {
  2270. size = Math.pow( this.scaleFactor, - sgn );
  2271. }
  2272. if ( this.cursorZoom && this.enablePan ) {
  2273. let scalePoint;
  2274. if ( this.object.isOrthographicCamera ) {
  2275. scalePoint = this.unprojectOnTbPlane( this.object, event.clientX, event.clientY, this.domElement ).applyQuaternion( this.object.quaternion ).multiplyScalar( 1 / this.object.zoom ).add( this._gizmos.position );
  2276. } else if ( this.object.isPerspectiveCamera ) {
  2277. scalePoint = this.unprojectOnTbPlane( this.object, event.clientX, event.clientY, this.domElement ).applyQuaternion( this.object.quaternion ).add( this._gizmos.position );
  2278. }
  2279. this.applyTransformMatrix( this.scale( size, scalePoint ) );
  2280. } else {
  2281. this.applyTransformMatrix( this.scale( size, this._gizmos.position ) );
  2282. }
  2283. if ( this._grid != null ) {
  2284. this.disposeGrid();
  2285. this.drawGrid();
  2286. }
  2287. this.updateTbState( STATE.IDLE, false );
  2288. this.dispatchEvent( _changeEvent );
  2289. this.dispatchEvent( _endEvent );
  2290. break;
  2291. case 'FOV':
  2292. if ( this.object.isPerspectiveCamera ) {
  2293. this.updateTbState( STATE.FOV, true );
  2294. //Vertigo effect
  2295. // fov / 2
  2296. // |\
  2297. // | \
  2298. // | \
  2299. // x | \
  2300. // | \
  2301. // | \
  2302. // | _ _ _\
  2303. // y
  2304. //check for iOs shift shortcut
  2305. if ( event.deltaX != 0 ) {
  2306. sgn = event.deltaX / notchDeltaY;
  2307. size = 1;
  2308. if ( sgn > 0 ) {
  2309. size = 1 / ( Math.pow( this.scaleFactor, sgn ) );
  2310. } else if ( sgn < 0 ) {
  2311. size = Math.pow( this.scaleFactor, - sgn );
  2312. }
  2313. }
  2314. this._v3_1.setFromMatrixPosition( this._cameraMatrixState );
  2315. const x = this._v3_1.distanceTo( this._gizmos.position );
  2316. let xNew = x / size; //distance between camera and gizmos if scale(size, scalepoint) would be performed
  2317. //check min and max distance
  2318. xNew = MathUtils.clamp( xNew, this.minDistance, this.maxDistance );
  2319. const y = x * Math.tan( MathUtils.DEG2RAD * this.object.fov * 0.5 );
  2320. //calculate new fov
  2321. let newFov = MathUtils.RAD2DEG * ( Math.atan( y / xNew ) * 2 );
  2322. //check min and max fov
  2323. if ( newFov > this.maxFov ) {
  2324. newFov = this.maxFov;
  2325. } else if ( newFov < this.minFov ) {
  2326. newFov = this.minFov;
  2327. }
  2328. const newDistance = y / Math.tan( MathUtils.DEG2RAD * ( newFov / 2 ) );
  2329. size = x / newDistance;
  2330. this.setFov( newFov );
  2331. this.applyTransformMatrix( this.scale( size, this._gizmos.position, false ) );
  2332. }
  2333. if ( this._grid != null ) {
  2334. this.disposeGrid();
  2335. this.drawGrid();
  2336. }
  2337. this.updateTbState( STATE.IDLE, false );
  2338. this.dispatchEvent( _changeEvent );
  2339. this.dispatchEvent( _endEvent );
  2340. break;
  2341. }
  2342. }
  2343. }
  2344. }
  2345. export { ArcballControls };
粤ICP备19079148号