ArcballControls.js 78 KB

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