ArcballControls.js 84 KB

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