geometry.go 14 KB

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