orbit_control.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. // Copyright 2016 The G3N Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package control
  5. import (
  6. "github.com/g3n/engine/camera"
  7. "github.com/g3n/engine/core"
  8. "github.com/g3n/engine/gui"
  9. "github.com/g3n/engine/math32"
  10. "github.com/g3n/engine/util/logger"
  11. "github.com/g3n/engine/window"
  12. "math"
  13. )
  14. // OrbitControl is a camera controller that allows orbiting a center point while looking at it.
  15. type OrbitControl struct {
  16. core.Dispatcher // Embedded event dispatcher
  17. Enabled bool // Control enabled state
  18. EnableRotate bool // Rotate enabled state
  19. EnableZoom bool // Zoom enabled state
  20. EnablePan bool // Pan enabled state
  21. EnableKeys bool // Enable keys state
  22. ZoomSpeed float32 // Zoom speed factor. Default is 1.0
  23. RotateSpeed float32 // Rotate speed factor. Default is 1.0
  24. MinDistance float32 // Minimum distance from target. Default is 0.01
  25. MaxDistance float32 // Maximum distance from target. Default is infinity
  26. MinPolarAngle float32 // Minimum polar angle for rotation
  27. MaxPolarAngle float32
  28. MinAzimuthAngle float32
  29. MaxAzimuthAngle float32
  30. KeyRotateSpeed float32
  31. KeyPanSpeed float32
  32. // Internal
  33. icam camera.ICamera
  34. cam *camera.Camera
  35. camPersp *camera.Perspective
  36. camOrtho *camera.Orthographic
  37. win window.IWindow
  38. position0 math32.Vector3 // Initial camera position
  39. target0 math32.Vector3 // Initial camera target position
  40. state int // current active state
  41. phiDelta float32 // rotation delta in the XZ plane
  42. thetaDelta float32 // rotation delta in the YX plane
  43. rotateStart math32.Vector2
  44. rotateEnd math32.Vector2
  45. rotateDelta math32.Vector2
  46. panStart math32.Vector2 // initial pan screen coordinates
  47. panEnd math32.Vector2 // final pan screen coordinates
  48. panDelta math32.Vector2
  49. panOffset math32.Vector2
  50. zoomStart float32
  51. zoomEnd float32
  52. zoomDelta float32
  53. subsEvents int // Address of this field is used as events subscription id
  54. subsPos int // Address of this field is used as cursor pos events subscription id
  55. }
  56. const (
  57. stateNone = iota
  58. stateRotate
  59. stateZoom
  60. statePan
  61. )
  62. // Package logger
  63. var log = logger.New("ORBIT", logger.Default)
  64. // NewOrbitControl creates and returns a pointer to a new orbit control for the specified camera.
  65. func NewOrbitControl(icam camera.ICamera) *OrbitControl {
  66. oc := new(OrbitControl)
  67. oc.Dispatcher.Initialize()
  68. oc.icam = icam
  69. oc.cam = icam.GetCamera()
  70. if persp, ok := icam.(*camera.Perspective); ok {
  71. oc.camPersp = persp
  72. } else if ortho, ok := icam.(*camera.Orthographic); ok {
  73. oc.camOrtho = ortho
  74. } else {
  75. panic("Invalid camera type")
  76. }
  77. // Set defaults
  78. oc.Enabled = true
  79. oc.EnableRotate = true
  80. oc.EnableZoom = true
  81. oc.EnablePan = true
  82. oc.EnableKeys = true
  83. oc.ZoomSpeed = 1.0
  84. oc.RotateSpeed = 1.0
  85. oc.MinDistance = 0.01
  86. oc.MaxDistance = float32(math.Inf(1))
  87. oc.MinPolarAngle = 0
  88. oc.MaxPolarAngle = math32.Pi
  89. oc.MinAzimuthAngle = float32(math.Inf(-1))
  90. oc.MaxAzimuthAngle = float32(math.Inf(1))
  91. oc.KeyPanSpeed = 5.0
  92. oc.KeyRotateSpeed = 0.02
  93. // Saves initial camera parameters
  94. oc.position0 = oc.cam.Position()
  95. oc.target0 = oc.cam.Target()
  96. // Subscribe to events
  97. gui.Manager().SubscribeID(window.OnMouseUp, &oc.subsEvents, oc.onMouse)
  98. gui.Manager().SubscribeID(window.OnMouseDown, &oc.subsEvents, oc.onMouse)
  99. gui.Manager().SubscribeID(window.OnScroll, &oc.subsEvents, oc.onScroll)
  100. gui.Manager().SubscribeID(window.OnKeyDown, &oc.subsEvents, oc.onKey)
  101. oc.SubscribeID(window.OnCursor, &oc.subsPos, oc.onCursorPos)
  102. return oc
  103. }
  104. // Dispose unsubscribes from all events
  105. func (oc *OrbitControl) Dispose() {
  106. // Unsubscribe to event handlers
  107. gui.Manager().UnsubscribeID(window.OnMouseUp, &oc.subsEvents)
  108. gui.Manager().UnsubscribeID(window.OnMouseDown, &oc.subsEvents)
  109. gui.Manager().UnsubscribeID(window.OnScroll, &oc.subsEvents)
  110. gui.Manager().UnsubscribeID(window.OnKeyDown, &oc.subsEvents)
  111. oc.UnsubscribeID(window.OnCursor, &oc.subsPos)
  112. }
  113. // Reset to initial camera position
  114. func (oc *OrbitControl) Reset() {
  115. oc.state = stateNone
  116. oc.cam.SetPositionVec(&oc.position0)
  117. oc.cam.LookAt(&oc.target0)
  118. }
  119. // Pan the camera and target by the specified deltas
  120. func (oc *OrbitControl) Pan(deltaX, deltaY float32) {
  121. width, height := window.Get().GetSize()
  122. oc.pan(deltaX, deltaY, width, height)
  123. oc.updatePan()
  124. }
  125. // Zoom in or out
  126. func (oc *OrbitControl) Zoom(delta float32) {
  127. oc.zoomDelta = delta
  128. oc.updateZoom()
  129. }
  130. // RotateLeft rotates the camera left by specified angle
  131. func (oc *OrbitControl) RotateLeft(angle float32) {
  132. oc.thetaDelta -= angle
  133. oc.updateRotate()
  134. }
  135. // RotateUp rotates the camera up by specified angle
  136. func (oc *OrbitControl) RotateUp(angle float32) {
  137. oc.phiDelta -= angle
  138. oc.updateRotate()
  139. }
  140. // Updates the camera rotation from thetaDelta and phiDelta
  141. func (oc *OrbitControl) updateRotate() {
  142. const EPS = 0.01
  143. // Get camera parameters
  144. position := oc.cam.Position()
  145. target := oc.cam.Target()
  146. up := oc.cam.Up()
  147. // Camera UP is the orbit axis
  148. var quat math32.Quaternion
  149. quat.SetFromUnitVectors(&up, &math32.Vector3{0, 1, 0})
  150. quatInverse := quat
  151. quatInverse.Inverse()
  152. // Calculates direction vector from camera position to target
  153. vdir := position
  154. vdir.Sub(&target)
  155. vdir.ApplyQuaternion(&quat)
  156. // Calculate angles from current camera position
  157. radius := vdir.Length()
  158. theta := math32.Atan2(vdir.X, vdir.Z)
  159. phi := math32.Acos(vdir.Y / radius)
  160. // Add deltas to the angles
  161. theta += oc.thetaDelta
  162. phi += oc.phiDelta
  163. // Restrict phi (elevation) to be between desired limits
  164. phi = math32.Max(oc.MinPolarAngle, math32.Min(oc.MaxPolarAngle, phi))
  165. phi = math32.Max(EPS, math32.Min(math32.Pi-EPS, phi))
  166. // Restrict theta to be between desired limits
  167. theta = math32.Max(oc.MinAzimuthAngle, math32.Min(oc.MaxAzimuthAngle, theta))
  168. // Calculate new cartesian coordinates
  169. vdir.X = radius * math32.Sin(phi) * math32.Sin(theta)
  170. vdir.Y = radius * math32.Cos(phi)
  171. vdir.Z = radius * math32.Sin(phi) * math32.Cos(theta)
  172. // Rotate offset back to "camera-up-vector-is-up" space
  173. vdir.ApplyQuaternion(&quatInverse)
  174. position = target
  175. position.Add(&vdir)
  176. oc.cam.SetPositionVec(&position)
  177. oc.cam.LookAt(&target)
  178. // Reset deltas
  179. oc.thetaDelta = 0
  180. oc.phiDelta = 0
  181. }
  182. // Updates camera rotation from thetaDelta and phiDelta
  183. // ALTERNATIVE rotation algorithm
  184. func (oc *OrbitControl) updateRotate2() {
  185. const EPS = 0.01
  186. // Get camera parameters
  187. position := oc.cam.Position()
  188. target := oc.cam.Target()
  189. up := oc.cam.Up()
  190. // Calculates direction vector from target to camera
  191. vdir := position
  192. vdir.Sub(&target)
  193. // Calculates right and up vectors
  194. var vright math32.Vector3
  195. vright.CrossVectors(&up, &vdir)
  196. vright.Normalize()
  197. var vup math32.Vector3
  198. vup.CrossVectors(&vdir, &vright)
  199. vup.Normalize()
  200. phi := vdir.AngleTo(&math32.Vector3{0, 1, 0})
  201. newphi := phi + oc.phiDelta
  202. if newphi < EPS || newphi > math32.Pi-EPS {
  203. oc.phiDelta = 0
  204. } else if newphi < oc.MinPolarAngle || newphi > oc.MaxPolarAngle {
  205. oc.phiDelta = 0
  206. }
  207. // Rotates position around the two vectors
  208. vdir.ApplyAxisAngle(&vup, oc.thetaDelta)
  209. vdir.ApplyAxisAngle(&vright, oc.phiDelta)
  210. // Adds target back get final position
  211. position = target
  212. position.Add(&vdir)
  213. log.Debug("orbit set position")
  214. oc.cam.SetPositionVec(&position)
  215. oc.cam.LookAt(&target)
  216. // Reset deltas
  217. oc.thetaDelta = 0
  218. oc.phiDelta = 0
  219. }
  220. // Updates camera pan from panOffset
  221. func (oc *OrbitControl) updatePan() {
  222. // Get camera parameters
  223. position := oc.cam.Position()
  224. target := oc.cam.Target()
  225. up := oc.cam.Up()
  226. // Calculates direction vector from camera position to target
  227. vdir := target
  228. vdir.Sub(&position)
  229. vdir.Normalize()
  230. // Calculates vector perpendicular to direction and up (side vector)
  231. var vpanx math32.Vector3
  232. vpanx.CrossVectors(&up, &vdir)
  233. vpanx.Normalize()
  234. // Calculates vector perpendicular to direction and vpanx
  235. var vpany math32.Vector3
  236. vpany.CrossVectors(&vdir, &vpanx)
  237. vpany.Normalize()
  238. // Adds pan offsets
  239. vpanx.MultiplyScalar(oc.panOffset.X)
  240. vpany.MultiplyScalar(oc.panOffset.Y)
  241. var vpan math32.Vector3
  242. vpan.AddVectors(&vpanx, &vpany)
  243. // Adds offsets to camera position and target
  244. position.Add(&vpan)
  245. target.Add(&vpan)
  246. // Sets new camera parameters
  247. oc.cam.SetPositionVec(&position)
  248. oc.cam.LookAt(&target)
  249. // Reset deltas
  250. oc.panOffset.Set(0, 0)
  251. }
  252. // Updates camera zoom from zoomDelta
  253. func (oc *OrbitControl) updateZoom() {
  254. if oc.camOrtho != nil {
  255. zoom := oc.camOrtho.Zoom() - 0.01*oc.zoomDelta
  256. oc.camOrtho.SetZoom(zoom)
  257. // Reset delta
  258. oc.zoomDelta = 0
  259. return
  260. }
  261. // Get camera and target positions
  262. position := oc.cam.Position()
  263. target := oc.cam.Target()
  264. // Calculates direction vector from target to camera position
  265. vdir := position
  266. vdir.Sub(&target)
  267. // Calculates new distance from target and applies limits
  268. dist := vdir.Length() * (1.0 + oc.zoomDelta*oc.ZoomSpeed/10.0)
  269. dist = math32.Max(oc.MinDistance, math32.Min(oc.MaxDistance, dist))
  270. vdir.SetLength(dist)
  271. // Adds new distance to target to get new camera position
  272. target.Add(&vdir)
  273. oc.cam.SetPositionVec(&target)
  274. // Reset delta
  275. oc.zoomDelta = 0
  276. }
  277. // Called when mouse button event is received
  278. func (oc *OrbitControl) onMouse(evname string, ev interface{}) {
  279. // If control not enabled ignore event
  280. if !oc.Enabled {
  281. return
  282. }
  283. mev := ev.(*window.MouseEvent)
  284. // Mouse button pressed
  285. switch evname {
  286. case window.OnMouseDown:
  287. gui.Manager().SetCursorFocus(oc)
  288. // Left button pressed sets Rotate state
  289. if mev.Button == window.MouseButtonLeft {
  290. if !oc.EnableRotate {
  291. return
  292. }
  293. oc.state = stateRotate
  294. oc.rotateStart.Set(float32(mev.Xpos), float32(mev.Ypos))
  295. } else
  296. // Middle button pressed sets Zoom state
  297. if mev.Button == window.MouseButtonMiddle {
  298. if !oc.EnableZoom {
  299. return
  300. }
  301. oc.state = stateZoom
  302. oc.zoomStart = float32(mev.Ypos)
  303. } else
  304. // Right button pressed sets Pan state
  305. if mev.Button == window.MouseButtonRight {
  306. if !oc.EnablePan {
  307. return
  308. }
  309. oc.state = statePan
  310. oc.panStart.Set(float32(mev.Xpos), float32(mev.Ypos))
  311. }
  312. return
  313. case window.OnMouseUp:
  314. gui.Manager().SetCursorFocus(nil)
  315. oc.state = stateNone
  316. }
  317. }
  318. // Called when cursor position event is received
  319. func (oc *OrbitControl) onCursorPos(evname string, ev interface{}) {
  320. // If control not enabled ignore event
  321. if !oc.Enabled {
  322. return
  323. }
  324. mev := ev.(*window.CursorEvent)
  325. // Rotation
  326. if oc.state == stateRotate {
  327. oc.rotateEnd.Set(float32(mev.Xpos), float32(mev.Ypos))
  328. oc.rotateDelta.SubVectors(&oc.rotateEnd, &oc.rotateStart)
  329. oc.rotateStart = oc.rotateEnd
  330. // rotating across whole screen goes 360 degrees around
  331. width, height := window.Get().GetSize()
  332. oc.RotateLeft(2 * math32.Pi * oc.rotateDelta.X / float32(width) * oc.RotateSpeed)
  333. // rotating up and down along whole screen attempts to go 360, but limited to 180
  334. oc.RotateUp(2 * math32.Pi * oc.rotateDelta.Y / float32(height) * oc.RotateSpeed)
  335. return
  336. }
  337. // Panning
  338. if oc.state == statePan {
  339. oc.panEnd.Set(float32(mev.Xpos), float32(mev.Ypos))
  340. oc.panDelta.SubVectors(&oc.panEnd, &oc.panStart)
  341. oc.panStart = oc.panEnd
  342. oc.Pan(oc.panDelta.X, oc.panDelta.Y)
  343. return
  344. }
  345. // Zooming
  346. if oc.state == stateZoom {
  347. oc.zoomEnd = float32(mev.Ypos)
  348. oc.zoomDelta = oc.zoomEnd - oc.zoomStart
  349. oc.zoomStart = oc.zoomEnd
  350. oc.Zoom(oc.zoomDelta)
  351. }
  352. }
  353. // Called when mouse button scroll event is received
  354. func (oc *OrbitControl) onScroll(evname string, ev interface{}) {
  355. if !oc.Enabled || !oc.EnableZoom || oc.state != stateNone {
  356. return
  357. }
  358. sev := ev.(*window.ScrollEvent)
  359. oc.Zoom(float32(-sev.Yoffset))
  360. }
  361. // Called when key is pressed, released or repeats.
  362. func (oc *OrbitControl) onKey(evname string, ev interface{}) {
  363. if !oc.Enabled || !oc.EnableKeys {
  364. return
  365. }
  366. kev := ev.(*window.KeyEvent)
  367. if oc.EnablePan && kev.Mods == 0 {
  368. switch kev.Key {
  369. case window.KeyUp:
  370. oc.Pan(0, oc.KeyPanSpeed)
  371. case window.KeyDown:
  372. oc.Pan(0, -oc.KeyPanSpeed)
  373. case window.KeyLeft:
  374. oc.Pan(oc.KeyPanSpeed, 0)
  375. case window.KeyRight:
  376. oc.Pan(-oc.KeyPanSpeed, 0)
  377. }
  378. }
  379. if oc.EnableRotate && kev.Mods == window.ModShift {
  380. switch kev.Key {
  381. case window.KeyUp:
  382. oc.RotateUp(oc.KeyRotateSpeed)
  383. case window.KeyDown:
  384. oc.RotateUp(-oc.KeyRotateSpeed)
  385. case window.KeyLeft:
  386. oc.RotateLeft(-oc.KeyRotateSpeed)
  387. case window.KeyRight:
  388. oc.RotateLeft(oc.KeyRotateSpeed)
  389. }
  390. }
  391. if oc.EnableZoom && kev.Mods == window.ModControl {
  392. switch kev.Key {
  393. case window.KeyUp:
  394. oc.Zoom(-1.0)
  395. case window.KeyDown:
  396. oc.Zoom(1.0)
  397. }
  398. }
  399. }
  400. func (oc *OrbitControl) pan(deltaX, deltaY float32, swidth, sheight int) {
  401. // Perspective camera
  402. if oc.camPersp != nil {
  403. position := oc.cam.Position()
  404. target := oc.cam.Target()
  405. offset := position.Clone().Sub(&target)
  406. targetDistance := offset.Length()
  407. // Half the FOV is center to top of screen
  408. targetDistance += math32.Tan((oc.camPersp.Fov() / 2.0) * math32.Pi / 180.0)
  409. // we actually don't use screenWidth, since perspective camera is fixed to screen height
  410. oc.panLeft(2 * deltaX * targetDistance / float32(sheight))
  411. oc.panUp(2 * deltaY * targetDistance / float32(sheight))
  412. return
  413. }
  414. // Orthographic camera
  415. left, right, top, bottom, _, _ := oc.camOrtho.Planes()
  416. oc.panLeft(deltaX * (right - left) / float32(swidth))
  417. oc.panUp(deltaY * (top - bottom) / float32(sheight))
  418. }
  419. func (oc *OrbitControl) panLeft(distance float32) {
  420. oc.panOffset.X += distance
  421. }
  422. func (oc *OrbitControl) panUp(distance float32) {
  423. oc.panOffset.Y += distance
  424. }