2
0

ArcballControls.js 78 KB

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