ArcballControls.js 79 KB

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