plane.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. // NewPlane creates a plane geometry with the specified width and height.
  10. // The plane is generated centered in the XY plane with Z=0.
  11. func NewPlane(width, height float32) *Geometry {
  12. return NewSegmentedPlane(width, height, 1, 1)
  13. }
  14. // NewSegmentedPlane creates a segmented plane geometry with the specified width, height, and number of
  15. // segments in each dimension (minimum 1 in each). The plane is generated centered in the XY plane with Z=0.
  16. func NewSegmentedPlane(width, height float32, widthSegments, heightSegments int) *Geometry {
  17. plane := NewGeometry()
  18. widthHalf := width / 2
  19. heightHalf := height / 2
  20. gridX := widthSegments
  21. gridY := heightSegments
  22. gridX1 := gridX + 1
  23. gridY1 := gridY + 1
  24. segmentWidth := width / float32(gridX)
  25. segmentHeight := height / float32(gridY)
  26. // Create buffers
  27. positions := math32.NewArrayF32(0, 16)
  28. normals := math32.NewArrayF32(0, 16)
  29. uvs := math32.NewArrayF32(0, 16)
  30. indices := math32.NewArrayU32(0, 16)
  31. // Generate plane vertices, vertices normals and vertices texture mappings.
  32. for iy := 0; iy < gridY1; iy++ {
  33. y := float32(iy)*segmentHeight - heightHalf
  34. for ix := 0; ix < gridX1; ix++ {
  35. x := float32(ix)*segmentWidth - widthHalf
  36. positions.Append(float32(x), float32(-y), 0)
  37. normals.Append(0, 0, 1)
  38. uvs.Append(float32(float64(ix)/float64(gridX)), float32(float64(1)-(float64(iy)/float64(gridY))))
  39. }
  40. }
  41. // Generate plane vertices indices for the faces
  42. for iy := 0; iy < gridY; iy++ {
  43. for ix := 0; ix < gridX; ix++ {
  44. a := ix + gridX1*iy
  45. b := ix + gridX1*(iy+1)
  46. c := (ix + 1) + gridX1*(iy+1)
  47. d := (ix + 1) + gridX1*iy
  48. indices.Append(uint32(a), uint32(b), uint32(d))
  49. indices.Append(uint32(b), uint32(c), uint32(d))
  50. }
  51. }
  52. plane.SetIndices(indices)
  53. plane.AddVBO(gls.NewVBO(positions).AddAttrib(gls.VertexPosition))
  54. plane.AddVBO(gls.NewVBO(normals).AddAttrib(gls.VertexNormal))
  55. plane.AddVBO(gls.NewVBO(uvs).AddAttrib(gls.VertexTexcoord))
  56. // Update area
  57. plane.area = width * height
  58. plane.areaValid = true
  59. // Update volume
  60. plane.volume = 0
  61. plane.volumeValid = true
  62. return plane
  63. }