directional.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 light
  5. import (
  6. "unsafe"
  7. "github.com/g3n/engine/core"
  8. "github.com/g3n/engine/gls"
  9. "github.com/g3n/engine/math32"
  10. )
  11. // Directional represents a directional, positionless light
  12. type Directional struct {
  13. core.Node // Embedded node
  14. color math32.Color // Light color
  15. intensity float32 // Light intensity
  16. uni gls.Uniform // Uniform location cache
  17. udata struct { // Combined uniform data in 2 vec3:
  18. color math32.Color // Light color
  19. position math32.Vector3 // Light position
  20. }
  21. }
  22. // NewDirectional creates and returns a pointer of a new directional light
  23. // the specified color and intensity.
  24. func NewDirectional(color *math32.Color, intensity float32) *Directional {
  25. ld := new(Directional)
  26. ld.Node.Init()
  27. ld.color = *color
  28. ld.intensity = intensity
  29. ld.uni.Init("DirLight")
  30. ld.SetColor(color)
  31. return ld
  32. }
  33. // SetColor sets the color of this light
  34. func (ld *Directional) SetColor(color *math32.Color) {
  35. ld.color = *color
  36. ld.udata.color = ld.color
  37. ld.udata.color.MultiplyScalar(ld.intensity)
  38. }
  39. // Color returns the current color of this light
  40. func (ld *Directional) Color() math32.Color {
  41. return ld.color
  42. }
  43. // SetIntensity sets the intensity of this light
  44. func (ld *Directional) SetIntensity(intensity float32) {
  45. ld.intensity = intensity
  46. ld.udata.color = ld.color
  47. ld.udata.color.MultiplyScalar(ld.intensity)
  48. }
  49. // Intensity returns the current intensity of this light
  50. func (ld *Directional) Intensity() float32 {
  51. return ld.intensity
  52. }
  53. // RenderSetup is called by the engine before rendering the scene
  54. func (ld *Directional) RenderSetup(gs *gls.GLS, rinfo *core.RenderInfo, idx int) {
  55. // Calculates light position in camera coordinates and updates uniform
  56. var pos math32.Vector3
  57. ld.WorldPosition(&pos)
  58. pos4 := math32.Vector4{pos.X, pos.Y, pos.Z, 0.0}
  59. pos4.ApplyMatrix4(&rinfo.ViewMatrix)
  60. ld.udata.position.X = pos4.X
  61. ld.udata.position.Y = pos4.Y
  62. ld.udata.position.Z = pos4.Z
  63. // Transfer uniform data
  64. const vec3count = 2
  65. location := ld.uni.LocationIdx(gs, vec3count*int32(idx))
  66. gs.Uniform3fvUP(location, vec3count, unsafe.Pointer(&ld.udata))
  67. }