listener-desktop.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. // +build !wasm
  5. package audio
  6. import (
  7. "github.com/g3n/engine/audio/al"
  8. "github.com/g3n/engine/core"
  9. "github.com/g3n/engine/gls"
  10. "github.com/g3n/engine/math32"
  11. )
  12. // Listener is an audio listener positioned in space.
  13. type Listener struct {
  14. core.Node
  15. }
  16. // NewListener creates a Listener object.
  17. func NewListener() *Listener {
  18. l := new(Listener)
  19. l.Node.Init(l)
  20. return l
  21. }
  22. // SetVelocity sets the velocity of the listener with x, y, z components.
  23. func (l *Listener) SetVelocity(vx, vy, vz float32) {
  24. al.Listener3f(al.Velocity, vx, vy, vz)
  25. }
  26. // SetVelocityVec sets the velocity of the listener with a vector.
  27. func (l *Listener) SetVelocityVec(v *math32.Vector3) {
  28. al.Listener3f(al.Velocity, v.X, v.Y, v.Z)
  29. }
  30. // Velocity returns the velocity of the listener as x, y, z components.
  31. func (l *Listener) Velocity() (float32, float32, float32) {
  32. return al.GetListener3f(al.Velocity)
  33. }
  34. // VelocityVec returns the velocity of the listener as a vector.
  35. func (l *Listener) VelocityVec() math32.Vector3 {
  36. vx, vy, vz := al.GetListener3f(al.Velocity)
  37. return math32.Vector3{vx, vy, vz}
  38. }
  39. // SetGain sets the gain of the listener.
  40. func (l *Listener) SetGain(gain float32) {
  41. al.Listenerf(al.Gain, gain)
  42. }
  43. // Gain returns the gain of the listener.
  44. func (l *Listener) Gain() float32 {
  45. return al.GetListenerf(al.Gain)
  46. }
  47. // Render is called by the renderer at each frame.
  48. // Updates the position and orientation of the listener.
  49. func (l *Listener) Render(gl *gls.GLS) {
  50. // Sets the listener source world position
  51. var wpos math32.Vector3
  52. l.WorldPosition(&wpos)
  53. al.Listener3f(al.Position, wpos.X, wpos.Y, wpos.Z)
  54. // Get listener current world direction
  55. var vdir math32.Vector3
  56. l.WorldDirection(&vdir)
  57. // Assumes initial UP vector and recalculates current up vector
  58. vup := math32.Vector3{0, 1, 0}
  59. var vright math32.Vector3
  60. vright.CrossVectors(&vdir, &vup)
  61. vup.CrossVectors(&vright, &vdir)
  62. // Sets the listener orientation
  63. orientation := []float32{vdir.X, vdir.Y, vdir.Z, vup.X, vup.Y, vup.Z}
  64. al.Listenerfv(al.Orientation, orientation)
  65. }