geometry.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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. // IGeometry is the interface for all geometries.
  10. type IGeometry interface {
  11. GetGeometry() *Geometry
  12. RenderSetup(gs *gls.GLS)
  13. Dispose()
  14. }
  15. // Geometry encapsulates a three-dimensional vertex-based geometry.
  16. type Geometry struct {
  17. refcount int // Current number of references
  18. vbos []*gls.VBO // Array of VBOs
  19. groups []Group // Array geometry groups
  20. indices math32.ArrayU32 // Buffer with indices
  21. gs *gls.GLS // Pointer to gl context. Valid after first render setup
  22. handleVAO uint32 // Handle to OpenGL VAO
  23. handleIndices uint32 // Handle to OpenGL buffer for indices
  24. updateIndices bool // Flag to indicate that indices must be transferred
  25. // Geometric properties
  26. boundingBox math32.Box3 // Last calculated bounding box
  27. boundingSphere math32.Sphere // Last calculated bounding sphere
  28. area float32 // Last calculated area
  29. volume float32 // Last calculated volume
  30. rotInertia math32.Matrix3 // Last calculated rotational inertia matrix
  31. // Flags indicating whether geometric properties are valid
  32. boundingBoxValid bool // Indicates if last calculated bounding box is valid
  33. boundingSphereValid bool // Indicates if last calculated bounding sphere is valid
  34. areaValid bool // Indicates if last calculated area is valid
  35. volumeValid bool // Indicates if last calculated volume is valid
  36. rotInertiaValid bool // Indicates if last calculated rotational inertia matrix is valid
  37. }
  38. // Group is a geometry group object.
  39. type Group struct {
  40. Start int // Index of first element of the group
  41. Count int // Number of elements in the group
  42. Matindex int // Material index for this group
  43. Matid string // Material id used when loading external models
  44. }
  45. // NewGeometry creates and returns a pointer to a new Geometry.
  46. func NewGeometry() *Geometry {
  47. g := new(Geometry)
  48. g.Init()
  49. return g
  50. }
  51. // Init initializes the geometry.
  52. func (g *Geometry) Init() {
  53. g.refcount = 1
  54. g.vbos = make([]*gls.VBO, 0)
  55. g.groups = make([]Group, 0)
  56. g.gs = nil
  57. g.handleVAO = 0
  58. g.handleIndices = 0
  59. g.updateIndices = true
  60. }
  61. // Incref increments the reference count for this geometry
  62. // and returns a pointer to the geometry.
  63. // It should be used when this geometry is shared by another
  64. // Graphic object.
  65. func (g *Geometry) Incref() *Geometry {
  66. g.refcount++
  67. return g
  68. }
  69. // Dispose decrements this geometry reference count and
  70. // if necessary releases OpenGL resources, C memory
  71. // and VBOs associated with this geometry.
  72. func (g *Geometry) Dispose() {
  73. if g.refcount > 1 {
  74. g.refcount--
  75. return
  76. }
  77. // Delete VAO and indices buffer
  78. if g.gs != nil {
  79. g.gs.DeleteVertexArrays(g.handleVAO)
  80. g.gs.DeleteBuffers(g.handleIndices)
  81. }
  82. // Delete this geometry VBO buffers
  83. for i := 0; i < len(g.vbos); i++ {
  84. g.vbos[i].Dispose()
  85. }
  86. g.Init()
  87. }
  88. // GetGeometry satisfies the IGeometry interface.
  89. func (g *Geometry) GetGeometry() *Geometry {
  90. return g
  91. }
  92. // AddGroup adds a geometry group (for multimaterial).
  93. func (g *Geometry) AddGroup(start, count, matIndex int) *Group {
  94. g.groups = append(g.groups, Group{start, count, matIndex, ""})
  95. return &g.groups[len(g.groups)-1]
  96. }
  97. // AddGroupList adds the specified list of groups to this geometry.
  98. func (g *Geometry) AddGroupList(groups []Group) {
  99. for _, group := range groups {
  100. g.groups = append(g.groups, group)
  101. }
  102. }
  103. // GroupCount returns the number of geometry groups (for multimaterial).
  104. func (g *Geometry) GroupCount() int {
  105. return len(g.groups)
  106. }
  107. // GroupAt returns pointer to geometry group at the specified index.
  108. func (g *Geometry) GroupAt(idx int) *Group {
  109. return &g.groups[idx]
  110. }
  111. // SetIndices sets the indices array for this geometry.
  112. func (g *Geometry) SetIndices(indices math32.ArrayU32) {
  113. g.indices = indices
  114. g.updateIndices = true
  115. g.boundingBoxValid = false
  116. g.boundingSphereValid = false
  117. }
  118. // Indices returns this geometry indices array.
  119. func (g *Geometry) Indices() math32.ArrayU32 {
  120. return g.indices
  121. }
  122. // AddVBO adds a Vertex Buffer Object for this geometry.
  123. func (g *Geometry) AddVBO(vbo *gls.VBO) {
  124. // Check that the provided VBO doesn't have conflicting attributes with existing VBOs
  125. for _, existingVbo := range g.vbos {
  126. for _, attrib := range vbo.Attributes() {
  127. if existingVbo.Attrib(attrib.Name) != nil {
  128. panic("Geometry.AddVBO: geometry already has a VBO with attribute " + attrib.Name)
  129. }
  130. }
  131. }
  132. g.vbos = append(g.vbos, vbo)
  133. }
  134. // VBO returns a pointer to this geometry's VBO which contain the specified attribute.
  135. // Returns nil if the VBO is not found.
  136. func (g *Geometry) VBO(attrib string) *gls.VBO {
  137. for _, vbo := range g.vbos {
  138. if vbo.Attrib(attrib) != nil {
  139. return vbo
  140. }
  141. }
  142. return nil
  143. }
  144. // Items returns the number of items in the first VBO.
  145. // (The number of items should be same for all VBOs)
  146. // An item is a complete group of attributes in the VBO buffer.
  147. func (g *Geometry) Items() int {
  148. if len(g.vbos) == 0 {
  149. return 0
  150. }
  151. vbo := g.vbos[0]
  152. if vbo.AttribCount() == 0 {
  153. return 0
  154. }
  155. return vbo.Buffer().Bytes() / vbo.StrideSize()
  156. }
  157. // OperateOnVertices iterates over all the vertices and calls
  158. // the specified callback function with a pointer to each vertex.
  159. // The vertex pointers can be modified inside the callback and
  160. // the modifications will be applied to the buffer at each iteration.
  161. // The callback function returns false to continue or true to break.
  162. func (g *Geometry) OperateOnVertices(cb func(vertex *math32.Vector3) bool) {
  163. // Get buffer with position vertices
  164. vbo := g.VBO("VertexPosition")
  165. if vbo == nil {
  166. return
  167. }
  168. vbo.OperateOnVectors3("VertexPosition", cb)
  169. }
  170. // ReadVertices iterates over all the vertices and calls
  171. // the specified callback function with the value of each vertex.
  172. // The callback function returns false to continue or true to break.
  173. func (g *Geometry) ReadVertices(cb func(vertex math32.Vector3) bool) {
  174. // Get buffer with position vertices
  175. vbo := g.VBO("VertexPosition")
  176. if vbo == nil {
  177. return
  178. }
  179. vbo.ReadVectors3("VertexPosition", cb)
  180. }
  181. // OperateOnVertexNormals iterates over all the vertex normals
  182. // and calls the specified callback function with a pointer to each normal.
  183. // The vertex pointers can be modified inside the callback and
  184. // the modifications will be applied to the buffer at each iteration.
  185. // The callback function returns false to continue or true to break.
  186. func (g *Geometry) OperateOnVertexNormals(cb func(normal *math32.Vector3) bool) {
  187. // Get buffer with position vertices
  188. vbo := g.VBO("VertexNormal")
  189. if vbo == nil {
  190. return
  191. }
  192. vbo.OperateOnVectors3("VertexNormal", cb)
  193. }
  194. // ReadVertexNormals iterates over all the vertex normals and calls
  195. // the specified callback function with the value of each normal.
  196. // The callback function returns false to continue or true to break.
  197. func (g *Geometry) ReadVertexNormals(cb func(vertex math32.Vector3) bool) {
  198. // Get buffer with position vertices
  199. vbo := g.VBO("VertexNormal")
  200. if vbo == nil {
  201. return
  202. }
  203. vbo.ReadVectors3("VertexNormal", cb)
  204. }
  205. // ReadFaces iterates over all the vertices and calls
  206. // the specified callback function with face-forming vertex triples.
  207. // The callback function returns false to continue or true to break.
  208. func (g *Geometry) ReadFaces(cb func(vA, vB, vC math32.Vector3) bool) {
  209. // Get buffer with position vertices
  210. vbo := g.VBO("VertexPosition")
  211. if vbo == nil {
  212. return
  213. }
  214. // If geometry has indexed vertices need to loop over indexes
  215. if g.Indexed() {
  216. var vA, vB, vC math32.Vector3
  217. positions := vbo.Buffer()
  218. for i := 0; i < g.indices.Size(); i += 3 {
  219. // Get face vertices
  220. positions.GetVector3(int(3*g.indices[i]), &vA)
  221. positions.GetVector3(int(3*g.indices[i+1]), &vB)
  222. positions.GetVector3(int(3*g.indices[i+2]), &vC)
  223. // Call callback with face vertices
  224. brk := cb(vA, vB, vC)
  225. if brk {
  226. break
  227. }
  228. }
  229. } else {
  230. // Geometry does NOT have indexed vertices - can read vertices in sequence
  231. vbo.ReadTripleVectors3("VertexPosition", cb)
  232. }
  233. }
  234. // TODO Read and Operate on Texcoords, Faces, Edges, FaceNormals, etc...
  235. // Indexed returns whether the geometry is indexed or not.
  236. func (g *Geometry) Indexed() bool {
  237. return g.indices.Size() > 0
  238. }
  239. // BoundingBox computes the bounding box of the geometry if necessary
  240. // and returns is value.
  241. func (g *Geometry) BoundingBox() math32.Box3 {
  242. // If valid, return its value
  243. if g.boundingBoxValid {
  244. return g.boundingBox
  245. }
  246. // Reset bounding box
  247. g.boundingBox.Min.Set(0, 0, 0)
  248. g.boundingBox.Max.Set(0, 0, 0)
  249. // Expand bounding box by each vertex
  250. g.ReadVertices(func(vertex math32.Vector3) bool {
  251. g.boundingBox.ExpandByPoint(&vertex)
  252. return false
  253. })
  254. g.boundingBoxValid = true
  255. return g.boundingBox
  256. }
  257. // BoundingSphere computes the bounding sphere of this geometry
  258. // if necessary and returns its value.
  259. func (g *Geometry) BoundingSphere() math32.Sphere {
  260. // If valid, return its value
  261. if g.boundingSphereValid {
  262. return g.boundingSphere
  263. }
  264. // Reset radius, calculate bounding box and copy center
  265. g.boundingSphere.Radius = float32(0)
  266. box := g.BoundingBox()
  267. box.Center(&g.boundingSphere.Center)
  268. // Find the radius of the bounding sphere
  269. maxRadiusSq := float32(0)
  270. g.ReadVertices(func(vertex math32.Vector3) bool {
  271. maxRadiusSq = math32.Max(maxRadiusSq, g.boundingSphere.Center.DistanceToSquared(&vertex))
  272. return false
  273. })
  274. g.boundingSphere.Radius = float32(math32.Sqrt(maxRadiusSq))
  275. g.boundingSphereValid = true
  276. return g.boundingSphere
  277. }
  278. // Area returns the surface area.
  279. // NOTE: This only works for triangle-based meshes.
  280. func (g *Geometry) Area() float32 {
  281. // If valid, return its value
  282. if g.areaValid {
  283. return g.area
  284. }
  285. // Reset area
  286. g.area = 0
  287. // Sum area of all triangles
  288. g.ReadFaces(func(vA, vB, vC math32.Vector3) bool {
  289. vA.Sub(&vC)
  290. vB.Sub(&vC)
  291. vC.CrossVectors(&vA, &vB)
  292. g.area += vC.Length() / 2.0
  293. return false
  294. })
  295. g.areaValid = true
  296. return g.area
  297. }
  298. // Volume returns the volume.
  299. // NOTE: This only works for closed triangle-based meshes.
  300. func (g *Geometry) Volume() float32 {
  301. // If valid, return its value
  302. if g.volumeValid {
  303. return g.volume
  304. }
  305. // Reset volume
  306. g.volume = 0
  307. // Calculate volume of all tetrahedrons
  308. g.ReadFaces(func(vA, vB, vC math32.Vector3) bool {
  309. vA.Sub(&vC)
  310. vB.Sub(&vC)
  311. g.volume += vC.Dot(vA.Cross(&vB)) / 6.0
  312. return false
  313. })
  314. g.volumeValid = true
  315. return g.volume
  316. }
  317. // RotationalInertia returns the rotational inertia tensor, also known as the moment of inertia.
  318. // This assumes constant density of 1 (kg/m^2).
  319. // To adjust for a different constant density simply scale the returning matrix by the density.
  320. func (g *Geometry) RotationalInertia(mass float32) math32.Matrix3 {
  321. // If valid, return its value
  322. if g.rotInertiaValid {
  323. return g.rotInertia
  324. }
  325. // Reset rotational inertia
  326. g.rotInertia.Zero()
  327. // For now approximate result based on bounding box
  328. b := math32.NewVec3()
  329. box := g.BoundingBox()
  330. box.Size(b)
  331. multiplier := mass / 12.0
  332. x := (b.Y*b.Y + b.Z*b.Z) * multiplier
  333. y := (b.X*b.X + b.Z*b.Z) * multiplier
  334. z := (b.Y*b.Y + b.X*b.X) * multiplier
  335. g.rotInertia.Set(
  336. x, 0, 0,
  337. 0, y, 0,
  338. 0, 0, z,
  339. )
  340. return g.rotInertia
  341. }
  342. // ProjectOntoAxis projects the geometry onto the specified axis,
  343. // effectively squashing it into a line passing through the local origin.
  344. // Returns the maximum and the minimum values on that line (i.e. signed distances from the local origin).
  345. func (g *Geometry) ProjectOntoAxis(localAxis *math32.Vector3) (float32, float32) {
  346. var max, min float32
  347. g.ReadVertices(func(vertex math32.Vector3) bool {
  348. val := vertex.Dot(localAxis)
  349. if val > max {
  350. max = val
  351. }
  352. if val < min {
  353. min = val
  354. }
  355. return false
  356. })
  357. return max, min
  358. }
  359. // TODO:
  360. // https://stackoverflow.com/questions/21640545/how-to-check-for-convexity-of-a-3d-mesh
  361. // func (g *Geometry) IsConvex() bool {
  362. //
  363. // {
  364. // ApplyMatrix multiplies each of the geometry position vertices
  365. // by the specified matrix and apply the correspondent normal
  366. // transform matrix to the geometry normal vectors.
  367. // The geometry's bounding box and sphere are recomputed if needed.
  368. func (g *Geometry) ApplyMatrix(m *math32.Matrix4) {
  369. // Apply matrix to all vertices
  370. g.OperateOnVertices(func(vertex *math32.Vector3) bool {
  371. vertex.ApplyMatrix4(m)
  372. return false
  373. })
  374. // Apply normal matrix to all normal vectors
  375. var normalMatrix math32.Matrix3
  376. normalMatrix.GetNormalMatrix(m)
  377. g.OperateOnVertexNormals(func(normal *math32.Vector3) bool {
  378. normal.ApplyMatrix3(&normalMatrix).Normalize()
  379. return false
  380. })
  381. }
  382. // RenderSetup is called by the renderer before drawing the geometry.
  383. func (g *Geometry) RenderSetup(gs *gls.GLS) {
  384. // First time initialization
  385. if g.gs == nil {
  386. // Generates VAO and binds it
  387. g.handleVAO = gs.GenVertexArray()
  388. gs.BindVertexArray(g.handleVAO)
  389. // Generates VBO for indices
  390. g.handleIndices = gs.GenBuffer()
  391. // Saves pointer to gl indicating initialization was done.
  392. g.gs = gs
  393. }
  394. // Update VBOs
  395. gs.BindVertexArray(g.handleVAO)
  396. for _, vbo := range g.vbos {
  397. vbo.Transfer(gs)
  398. }
  399. // Updates Indices buffer if necessary
  400. if g.indices.Size() > 0 && g.updateIndices {
  401. gs.BindBuffer(gls.ELEMENT_ARRAY_BUFFER, g.handleIndices)
  402. gs.BufferData(gls.ELEMENT_ARRAY_BUFFER, g.indices.Bytes(), g.indices, gls.STATIC_DRAW)
  403. g.updateIndices = false
  404. }
  405. }