plane.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 geometry
  5. import (
  6. "github.com/g3n/engine/gls"
  7. "github.com/g3n/engine/math32"
  8. )
  9. type Plane struct {
  10. Geometry
  11. Width float32
  12. Height float32
  13. WidthSegments int
  14. HeightSegments int
  15. }
  16. // NewPlane creates and returns a pointer to a Plane Geometry.
  17. // The plane is defined by its width, height and the number of width and height segments.
  18. // The minimum number of segments for the width and/or the height is 1.
  19. // The plane is generated centered in the XY plane with Z=0.
  20. func NewPlane(width, height float32, widthSegments, heightSegments int) *Plane {
  21. plane := new(Plane)
  22. plane.Geometry.Init()
  23. plane.Width = width
  24. plane.Height = height
  25. plane.WidthSegments = widthSegments
  26. plane.HeightSegments = heightSegments
  27. width_half := width / 2
  28. height_half := height / 2
  29. gridX := widthSegments
  30. gridY := heightSegments
  31. gridX1 := gridX + 1
  32. gridY1 := gridY + 1
  33. segment_width := width / float32(gridX)
  34. segment_height := height / float32(gridY)
  35. // Create buffers
  36. positions := math32.NewArrayF32(0, 16)
  37. normals := math32.NewArrayF32(0, 16)
  38. uvs := math32.NewArrayF32(0, 16)
  39. indices := math32.NewArrayU32(0, 16)
  40. // Generate plane vertices, vertices normals and vertices texture mappings.
  41. for iy := 0; iy < gridY1; iy++ {
  42. y := float32(iy)*segment_height - height_half
  43. for ix := 0; ix < gridX1; ix++ {
  44. x := float32(ix)*segment_width - width_half
  45. positions.Append(float32(x), float32(-y), 0)
  46. normals.Append(0, 0, 1)
  47. uvs.Append(float32(float64(ix)/float64(gridX)), float32(float64(1)-(float64(iy)/float64(gridY))))
  48. }
  49. }
  50. // Generate plane vertices indices for the faces
  51. for iy := 0; iy < gridY; iy++ {
  52. for ix := 0; ix < gridX; ix++ {
  53. a := ix + gridX1*iy
  54. b := ix + gridX1*(iy+1)
  55. c := (ix + 1) + gridX1*(iy+1)
  56. d := (ix + 1) + gridX1*iy
  57. indices.Append(uint32(a), uint32(b), uint32(d))
  58. indices.Append(uint32(b), uint32(c), uint32(d))
  59. }
  60. }
  61. plane.SetIndices(indices)
  62. plane.AddVBO(gls.NewVBO().AddAttrib("VertexPosition", 3).SetBuffer(positions))
  63. plane.AddVBO(gls.NewVBO().AddAttrib("VertexNormal", 3).SetBuffer(normals))
  64. plane.AddVBO(gls.NewVBO().AddAttrib("VertexTexcoord", 2).SetBuffer(uvs))
  65. return plane
  66. }