listener-desktop.go 2.2 KB

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