geometry.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. // Interface for all geometries
  10. type IGeometry interface {
  11. GetGeometry() *Geometry
  12. RenderSetup(gs *gls.GLS)
  13. Dispose()
  14. }
  15. type Geometry struct {
  16. refcount int // Current number of references
  17. vbos []*gls.VBO // Array of VBOs
  18. groups []Group // Array geometry groups
  19. indices math32.ArrayU32 // Buffer with indices
  20. gs *gls.GLS // Pointer to gl context. Valid after first render setup
  21. handleVAO uint32 // Handle to OpenGL VAO
  22. handleIndices uint32 // Handle to OpenGL buffer for indices
  23. updateIndices bool // Flag to indicate that indices must be transferred
  24. boundingBox math32.Box3 // Last calculated bounding box
  25. boundingBoxValid bool // Indicates if last calculated bounding box is valid
  26. boundingSphere math32.Sphere // Last calculated bounding sphere
  27. boundingSphereValid bool // Indicates if last calculated bounding sphere is valid
  28. }
  29. // Geometry group object
  30. type Group struct {
  31. Start int // Index of first element of the group
  32. Count int // Number of elements in the group
  33. Matindex int // Material index for this group
  34. Matid string // Material id used when loading external models
  35. }
  36. func NewGeometry() *Geometry {
  37. g := new(Geometry)
  38. g.Init()
  39. return g
  40. }
  41. // Init initializes the geometry
  42. func (g *Geometry) Init() {
  43. g.refcount = 1
  44. g.vbos = make([]*gls.VBO, 0)
  45. g.groups = make([]Group, 0)
  46. g.gs = nil
  47. g.handleVAO = 0
  48. g.handleIndices = 0
  49. g.updateIndices = true
  50. }
  51. // Incref increments the reference count for this geometry
  52. // and returns a pointer to the geometry.
  53. // It should be used when this geometry is shared by another
  54. // Graphic object.
  55. func (g *Geometry) Incref() *Geometry {
  56. g.refcount++
  57. return g
  58. }
  59. // Dispose decrements this geometry reference count and
  60. // if necessary releases OpenGL resources, C memory
  61. // and VBOs associated with this geometry.
  62. func (g *Geometry) Dispose() {
  63. if g.refcount > 1 {
  64. g.refcount--
  65. return
  66. }
  67. if g.gs != nil {
  68. g.gs.DeleteVertexArrays(g.handleVAO)
  69. g.gs.DeleteBuffers(g.handleIndices)
  70. }
  71. g.Init()
  72. }
  73. func (g *Geometry) GetGeometry() *Geometry {
  74. return g
  75. }
  76. // AddGroup adds a geometry group (for multimaterial)
  77. func (g *Geometry) AddGroup(start, count, matIndex int) *Group {
  78. g.groups = append(g.groups, Group{start, count, matIndex, ""})
  79. return &g.groups[len(g.groups)-1]
  80. }
  81. // AddGroupList adds the specified list of groups to this geometry
  82. func (g *Geometry) AddGroupList(groups []Group) {
  83. for _, group := range groups {
  84. g.groups = append(g.groups, group)
  85. }
  86. }
  87. // GroupCount returns the number of geometry groups (for multimaterial)
  88. func (g *Geometry) GroupCount() int {
  89. return len(g.groups)
  90. }
  91. // GroupAt returns pointer to geometry group at the specified index
  92. func (g *Geometry) GroupAt(idx int) *Group {
  93. return &g.groups[idx]
  94. }
  95. // SetIndices sets the indices array for this geometry
  96. func (g *Geometry) SetIndices(indices math32.ArrayU32) {
  97. g.indices = indices
  98. g.boundingBoxValid = false
  99. g.boundingSphereValid = false
  100. }
  101. // Indices returns this geometry indices array
  102. func (g *Geometry) Indices() math32.ArrayU32 {
  103. return g.indices
  104. }
  105. // AddVBO adds a Vertex Buffer Object for this geometry
  106. func (g *Geometry) AddVBO(vbo *gls.VBO) {
  107. g.vbos = append(g.vbos, vbo)
  108. }
  109. // VBO returns a pointer to this geometry VBO for the specified attribute.
  110. // Returns nil if the VBO is not found.
  111. func (g *Geometry) VBO(attrib string) *gls.VBO {
  112. for _, vbo := range g.vbos {
  113. if vbo.Attrib(attrib) != nil {
  114. return vbo
  115. }
  116. }
  117. return nil
  118. }
  119. // Returns the number of items in the first VBO
  120. // (The number of items should be same for all VBOs)
  121. // An item is a complete vertex position (3 floats) for example
  122. func (g *Geometry) Items() int {
  123. if len(g.vbos) == 0 {
  124. return 0
  125. }
  126. vbo := g.vbos[0]
  127. if vbo.AttribCount() == 0 {
  128. return 0
  129. }
  130. attrib := vbo.AttribAt(0)
  131. return vbo.Buffer().Size() / int(attrib.ItemSize)
  132. }
  133. // BoundingBox computes the bounding box of the geometry if necessary
  134. // and returns is value
  135. func (g *Geometry) BoundingBox() math32.Box3 {
  136. // If valid, returns its value
  137. if g.boundingBoxValid {
  138. return g.boundingBox
  139. }
  140. // Get buffer with position vertices
  141. vbPos := g.VBO("VertexPosition")
  142. if vbPos == nil {
  143. return g.boundingBox
  144. }
  145. positions := vbPos.Buffer()
  146. // Calculates bounding box
  147. var vertex math32.Vector3
  148. g.boundingBox.Min.Set(0, 0, 0)
  149. g.boundingBox.Max.Set(0, 0, 0)
  150. for i := 0; i < positions.Size(); i += 3 {
  151. positions.GetVector3(i, &vertex)
  152. g.boundingBox.ExpandByPoint(&vertex)
  153. }
  154. g.boundingBoxValid = true
  155. return g.boundingBox
  156. }
  157. // BoundingSphere computes the bounding sphere of this geometry
  158. // if necessary and returns its value.
  159. func (g *Geometry) BoundingSphere() math32.Sphere {
  160. // if valid, returns its value
  161. if g.boundingSphereValid {
  162. return g.boundingSphere
  163. }
  164. // Get buffer with position vertices
  165. vbPos := g.VBO("VertexPosition")
  166. if vbPos == nil {
  167. return g.boundingSphere
  168. }
  169. positions := vbPos.Buffer()
  170. // Get/calculates the bounding box
  171. box := g.BoundingBox()
  172. // Sets the center of the bounding sphere the same as the center of the bounding box.
  173. box.Center(&g.boundingSphere.Center)
  174. center := g.boundingSphere.Center
  175. // Find the radius of the bounding sphere
  176. maxRadiusSq := float32(0.0)
  177. for i := 0; i < positions.Size(); i += 3 {
  178. var vertex math32.Vector3
  179. positions.GetVector3(i, &vertex)
  180. maxRadiusSq = math32.Max(maxRadiusSq, center.DistanceToSquared(&vertex))
  181. }
  182. radius := math32.Sqrt(maxRadiusSq)
  183. if math32.IsNaN(radius) {
  184. panic("geometry.BoundingSphere: computed radius is NaN")
  185. }
  186. g.boundingSphere.Radius = float32(radius)
  187. g.boundingSphereValid = true
  188. return g.boundingSphere
  189. }
  190. // ApplyMatrix multiplies each of the geometry position vertices
  191. // by the specified matrix and apply the correspondent normal
  192. // transform matrix to the geometry normal vectors.
  193. // The geometry's bounding box and sphere are recomputed if needed.
  194. func (g *Geometry) ApplyMatrix(m *math32.Matrix4) {
  195. // Get positions buffer
  196. vboPos := g.VBO("VertexPosition")
  197. if vboPos == nil {
  198. return
  199. }
  200. positions := vboPos.Buffer()
  201. // Apply matrix to all position vertices
  202. for i := 0; i < positions.Size(); i += 3 {
  203. var vertex math32.Vector3
  204. positions.GetVector3(i, &vertex)
  205. vertex.ApplyMatrix4(m)
  206. positions.SetVector3(i, &vertex)
  207. }
  208. vboPos.Update()
  209. // Get normals buffer
  210. vboNormals := g.VBO("VertexNormal")
  211. if vboNormals == nil {
  212. return
  213. }
  214. normals := vboNormals.Buffer()
  215. // Apply normal matrix to all normal vectors
  216. var normalMatrix math32.Matrix3
  217. normalMatrix.GetNormalMatrix(m)
  218. for i := 0; i < normals.Size(); i += 3 {
  219. var vertex math32.Vector3
  220. normals.GetVector3(i, &vertex)
  221. vertex.ApplyMatrix3(&normalMatrix).Normalize()
  222. normals.SetVector3(i, &vertex)
  223. }
  224. vboNormals.Update()
  225. }
  226. // RenderSetup is called by the renderer before drawing the geometry
  227. func (g *Geometry) RenderSetup(gs *gls.GLS) {
  228. // First time initialization
  229. if g.gs == nil {
  230. // Generates VAO and binds it
  231. g.handleVAO = gs.GenVertexArray()
  232. gs.BindVertexArray(g.handleVAO)
  233. // Generates VBO for indices
  234. g.handleIndices = gs.GenBuffer()
  235. // Saves pointer to gl indicating initialization was done.
  236. g.gs = gs
  237. }
  238. // Update VBOs
  239. gs.BindVertexArray(g.handleVAO)
  240. for _, vbo := range g.vbos {
  241. vbo.Transfer(gs)
  242. }
  243. // Updates Indices buffer if necessary
  244. if g.indices.Size() > 0 && g.updateIndices {
  245. gs.BindBuffer(gls.ELEMENT_ARRAY_BUFFER, g.handleIndices)
  246. gs.BufferData(gls.ELEMENT_ARRAY_BUFFER, g.indices.Bytes(), g.indices, gls.STATIC_DRAW)
  247. g.updateIndices = false
  248. }
  249. }