ArcballControls.js 79 KB

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