geometry.go 15 KB

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