ArcballControls.js 78 KB

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