ArcballControls.js 78 KB

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