camera.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 camera contains common camera types used for rendering 3D scenes.
  5. package camera
  6. import (
  7. "github.com/g3n/engine/core"
  8. "github.com/g3n/engine/math32"
  9. )
  10. // ICamera is interface for all camera types.
  11. type ICamera interface {
  12. GetCamera() *Camera
  13. ViewMatrix(*math32.Matrix4)
  14. ProjMatrix(*math32.Matrix4)
  15. Project(*math32.Vector3) (*math32.Vector3, error)
  16. Unproject(*math32.Vector3) (*math32.Vector3, error)
  17. SetRaycaster(rc *core.Raycaster, x, y float32) error
  18. }
  19. // Camera is the base camera which is normally embedded in other camera types.
  20. type Camera struct {
  21. core.Node // Embedded Node
  22. target math32.Vector3 // Camera target in world coordinates
  23. up math32.Vector3 // Camera Up vector
  24. viewMatrix math32.Matrix4 // Last calculated view matrix
  25. }
  26. // Initialize initializes the base camera.
  27. // Normally used by other camera types which embed this base camera.
  28. func (cam *Camera) Initialize() {
  29. cam.Node.Init()
  30. cam.target.Set(0, 0, 0)
  31. cam.up.Set(0, 1, 0)
  32. cam.SetDirection(0, 0, -1)
  33. }
  34. // LookAt rotates the camera to look at the specified target position.
  35. // This method does not support objects with rotated and/or translated parent(s).
  36. // TODO: maybe move method to Node, or create similar in Node.
  37. func (cam *Camera) LookAt(target *math32.Vector3) {
  38. cam.target = *target
  39. var rotMat math32.Matrix4
  40. pos := cam.Position()
  41. rotMat.LookAt(&pos, &cam.target, &cam.up)
  42. var q math32.Quaternion
  43. q.SetFromRotationMatrix(&rotMat)
  44. cam.SetQuaternionQuat(&q)
  45. }
  46. // GetCamera satisfies the ICamera interface.
  47. func (cam *Camera) GetCamera() *Camera {
  48. return cam
  49. }
  50. // Target get the current target position.
  51. func (cam *Camera) Target() math32.Vector3 {
  52. return cam.target
  53. }
  54. // Up get the current camera up vector.
  55. func (cam *Camera) Up() math32.Vector3 {
  56. return cam.up
  57. }
  58. // SetUp sets the camera up vector.
  59. func (cam *Camera) SetUp(up *math32.Vector3) {
  60. cam.up = *up
  61. cam.LookAt(&cam.target) // TODO Maybe remove and let user call LookAt explicitly
  62. }
  63. // ViewMatrix returns the current view matrix of this camera.
  64. func (cam *Camera) ViewMatrix(m *math32.Matrix4) {
  65. cam.UpdateMatrixWorld()
  66. matrixWorld := cam.MatrixWorld()
  67. err := m.GetInverse(&matrixWorld)
  68. if err != nil {
  69. panic("Camera.ViewMatrix: Couldn't invert matrix")
  70. }
  71. }