sprite.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 graphic
  5. import (
  6. "github.com/g3n/engine/core"
  7. "github.com/g3n/engine/geometry"
  8. "github.com/g3n/engine/gls"
  9. "github.com/g3n/engine/material"
  10. "github.com/g3n/engine/math32"
  11. )
  12. // Sprite is a potentially animated image positioned in space that always faces the camera.
  13. type Sprite struct {
  14. Graphic // Embedded graphic
  15. uniMVPM gls.Uniform // Model view projection matrix uniform location cache
  16. }
  17. // NewSprite creates and returns a pointer to a sprite with the specified dimensions and material
  18. func NewSprite(width, height float32, imat material.IMaterial) *Sprite {
  19. s := new(Sprite)
  20. // Creates geometry
  21. geom := geometry.NewGeometry()
  22. w := width / 2
  23. h := height / 2
  24. // Builds array with vertex positions and texture coordinates
  25. positions := math32.NewArrayF32(0, 12)
  26. positions.Append(
  27. -w, -h, 0, 0, 0,
  28. w, -h, 0, 1, 0,
  29. w, h, 0, 1, 1,
  30. -w, h, 0, 0, 1,
  31. )
  32. // Builds array of indices
  33. indices := math32.NewArrayU32(0, 6)
  34. indices.Append(0, 1, 2, 0, 2, 3)
  35. // Set geometry buffers
  36. geom.SetIndices(indices)
  37. geom.AddVBO(
  38. gls.NewVBO(positions).
  39. AddAttrib(gls.VertexPosition).
  40. AddAttrib(gls.VertexTexcoord),
  41. )
  42. s.Graphic.Init(s, geom, gls.TRIANGLES)
  43. s.AddMaterial(s, imat, 0, 0)
  44. s.uniMVPM.Init("MVP")
  45. return s
  46. }
  47. // RenderSetup sets up the rendering of the sprite.
  48. func (s *Sprite) RenderSetup(gs *gls.GLS, rinfo *core.RenderInfo) {
  49. // Calculates model view matrix
  50. mw := s.MatrixWorld()
  51. var mvm math32.Matrix4
  52. mvm.MultiplyMatrices(&rinfo.ViewMatrix, &mw)
  53. // Decomposes model view matrix
  54. var position math32.Vector3
  55. var quaternion math32.Quaternion
  56. var scale math32.Vector3
  57. mvm.Decompose(&position, &quaternion, &scale)
  58. // Removes any rotation in X and Y axes and compose new model view matrix
  59. rotation := s.Rotation()
  60. rotation.X = 0
  61. rotation.Y = 0
  62. quaternion.SetFromEuler(&rotation)
  63. var mvmNew math32.Matrix4
  64. mvmNew.Compose(&position, &quaternion, &scale)
  65. // Calculates final MVP and updates uniform
  66. var mvpm math32.Matrix4
  67. mvpm.MultiplyMatrices(&rinfo.ProjMatrix, &mvmNew)
  68. location := s.uniMVPM.Location(gs)
  69. gs.UniformMatrix4fv(location, 1, false, &mvpm[0])
  70. }