ArcballControls.js 79 KB

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