ArcballControls.js 78 KB

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