directional.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. "github.com/g3n/engine/core"
  7. "github.com/g3n/engine/gls"
  8. "github.com/g3n/engine/math32"
  9. )
  10. type Directional struct {
  11. core.Node // Embedded node
  12. color math32.Color // Light color
  13. intensity float32 // Light intensity
  14. uni *gls.Uniform3fv // uniform with light color and direction
  15. }
  16. const (
  17. dirColor = 0 // index of color triplet in uniform
  18. dirPosition = 1 // index of position vector in uniform
  19. dirUniSize = 2 // uniform count of 3 float32
  20. )
  21. // NewDirectional creates and returns a pointer of a new directional light
  22. // the specified color and intensity.
  23. func NewDirectional(color *math32.Color, intensity float32) *Directional {
  24. ld := new(Directional)
  25. ld.Node.Init()
  26. ld.color = *color
  27. ld.intensity = intensity
  28. ld.uni = gls.NewUniform3fv("DirLight", dirUniSize)
  29. ld.SetColor(color)
  30. return ld
  31. }
  32. // SetColor sets the color of this light
  33. func (ld *Directional) SetColor(color *math32.Color) {
  34. ld.color = *color
  35. tmpColor := ld.color
  36. tmpColor.MultiplyScalar(ld.intensity)
  37. ld.uni.SetColor(dirColor, &tmpColor)
  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. tmpColor := ld.color
  47. tmpColor.MultiplyScalar(ld.intensity)
  48. ld.uni.SetColor(dirColor, &tmpColor)
  49. }
  50. // Intensity returns the current intensity of this light
  51. func (ld *Directional) Intensity() float32 {
  52. return ld.intensity
  53. }
  54. // RenderSetup is called by the engine before rendering the scene
  55. func (ld *Directional) RenderSetup(gs *gls.GLS, rinfo *core.RenderInfo, idx int) {
  56. // Calculates and updates light direction uniform in camera coordinates
  57. var pos math32.Vector3
  58. ld.WorldPosition(&pos)
  59. pos4 := math32.Vector4{pos.X, pos.Y, pos.Z, 0.0}
  60. pos4.ApplyMatrix4(&rinfo.ViewMatrix)
  61. ld.uni.SetVector3(dirPosition, &math32.Vector3{pos4.X, pos4.Y, pos4.Z})
  62. // Transfer color and position uniform
  63. ld.uni.TransferIdx(gs, idx*dirUniSize)
  64. }