circle.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. "math"
  9. )
  10. // Circle represents a circle geometry
  11. type Circle struct {
  12. Geometry
  13. Radius float64
  14. Segments int
  15. ThetaStart float64
  16. ThetaLength float64
  17. }
  18. // NewCircle creates and returns a pointer to a new Circle geometry object.
  19. // The geometry is defined by its radius, the number of segments (triangles), minimum = 3,
  20. // the start angle in radians for the first segment (thetaStart) and
  21. // the central angle in radians (thetaLength) of the circular sector.
  22. func NewCircle(radius float64, segments int, thetaStart, thetaLength float64) *Circle {
  23. circ := new(Circle)
  24. circ.Geometry.Init()
  25. circ.Radius = radius
  26. circ.Segments = segments
  27. circ.ThetaStart = thetaStart
  28. circ.ThetaLength = thetaLength
  29. if segments < 3 {
  30. segments = 3
  31. }
  32. // Create buffers
  33. positions := math32.NewArrayF32(0, 16)
  34. normals := math32.NewArrayF32(0, 16)
  35. uvs := math32.NewArrayF32(0, 16)
  36. indices := math32.NewArrayU32(0, 16)
  37. // Append circle center position
  38. center := math32.NewVector3(0, 0, 0)
  39. positions.AppendVector3(center)
  40. // Append circle center normal
  41. var normal math32.Vector3
  42. normal.Z = 1
  43. normals.AppendVector3(&normal)
  44. // Append circle center uv coord
  45. centerUV := math32.NewVector2(0.5, 0.5)
  46. uvs.AppendVector2(centerUV)
  47. for i := 0; i <= segments; i++ {
  48. segment := thetaStart + float64(i)/float64(segments)*thetaLength
  49. vx := float32(radius * math.Cos(segment))
  50. vy := float32(radius * math.Sin(segment))
  51. // Appends vertex position, normal and uv coordinates
  52. positions.Append(vx, vy, 0)
  53. normals.AppendVector3(&normal)
  54. uvs.Append((vx/float32(radius)+1)/2, (vy/float32(radius)+1)/2)
  55. }
  56. for i := 1; i <= segments; i++ {
  57. indices.Append(uint32(i), uint32(i)+1, 0)
  58. }
  59. circ.SetIndices(indices)
  60. circ.AddVBO(gls.NewVBO().AddAttrib("VertexPosition", 3).SetBuffer(positions))
  61. circ.AddVBO(gls.NewVBO().AddAttrib("VertexNormal", 3).SetBuffer(normals))
  62. circ.AddVBO(gls.NewVBO().AddAttrib("VertexTexcoord", 2).SetBuffer(uvs))
  63. //circ.BoundingSphere = math32.NewSphere(math32.NewVector3(0,0,0), float32(radius))
  64. return circ
  65. }