gls.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  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 gls
  5. // #include <stdlib.h>
  6. // #include "glcorearb.h"
  7. // #include "glapi.h"
  8. import "C"
  9. import (
  10. "fmt"
  11. "math"
  12. "reflect"
  13. "unsafe"
  14. )
  15. // GLS encapsulates the state of an OpenGL context and contains
  16. // methods to call OpenGL functions.
  17. type GLS struct {
  18. stats Stats // statistics
  19. prog *Program // current active shader program
  20. programs map[*Program]bool // shader programs cache
  21. checkErrors bool // check openGL API errors flag
  22. viewportX int32 // cached last set viewport x
  23. viewportY int32 // cached last set viewport y
  24. viewportWidth int32 // cached last set viewport width
  25. viewportHeight int32 // cached last set viewport height
  26. lineWidth float32 // cached last set line width
  27. sideView int // cached last set triangle side view mode
  28. frontFace uint32 // cached last set glFrontFace value
  29. depthFunc uint32 // cached last set depth function
  30. depthMask int // cached last set depth mask
  31. capabilities map[int]int // cached capabilities (Enable/Disable)
  32. blendEquation uint32 // cached last set blend equation value
  33. blendSrc uint32 // cached last set blend src value
  34. blendDst uint32 // cached last set blend equation destination value
  35. blendEquationRGB uint32 // cached last set blend equation rgb value
  36. blendEquationAlpha uint32 // cached last set blend equation alpha value
  37. blendSrcRGB uint32 // cached last set blend src rgb
  38. blendSrcAlpha uint32 // cached last set blend src alpha value
  39. blendDstRGB uint32 // cached last set blend destination rgb value
  40. blendDstAlpha uint32 // cached last set blend destination alpha value
  41. polygonModeFace uint32 // cached last set polygon mode face
  42. polygonModeMode uint32 // cached last set polygon mode mode
  43. polygonOffsetFactor float32 // cached last set polygon offset factor
  44. polygonOffsetUnits float32 // cached last set polygon offset units
  45. gobuf []byte // conversion buffer with GO memory
  46. cbuf []byte // conversion buffer with C memory
  47. }
  48. // Stats contains counters of OpenGL resources being used as well
  49. // the cummulative numbers of some OpenGL calls for performance evaluation.
  50. type Stats struct {
  51. Shaders int // Current number of shader programs
  52. Vaos int // Number of Vertex Array Objects
  53. Buffers int // Number of Buffer Objects
  54. Textures int // Number of Textures
  55. Caphits uint64 // Cummulative number of hits for Enable/Disable
  56. UnilocHits uint64 // Cummulative number of uniform location cache hits
  57. UnilocMiss uint64 // Cummulative number of uniform location cache misses
  58. Unisets uint64 // Cummulative number of uniform sets
  59. Drawcalls uint64 // Cummulative number of draw calls
  60. }
  61. // Polygon side view.
  62. const (
  63. FrontSide = iota + 1
  64. BackSide
  65. DoubleSide
  66. )
  67. const (
  68. capUndef = 0
  69. capDisabled = 1
  70. capEnabled = 2
  71. uintUndef = math.MaxUint32
  72. intFalse = 0
  73. intTrue = 1
  74. )
  75. // New creates and returns a new instance of an GLS object
  76. // which encapsulates the state of an OpenGL context
  77. // This should be called only after an active OpenGL context
  78. // was established, such as by creating a new window.
  79. func New() (*GLS, error) {
  80. gs := new(GLS)
  81. gs.reset()
  82. // Load OpenGL functions
  83. err := C.glapiLoad()
  84. if err != 0 {
  85. return nil, fmt.Errorf("Error loading OpenGL")
  86. }
  87. gs.setDefaultState()
  88. gs.checkErrors = true
  89. // Preallocates conversion buffers
  90. size := 1 * 1024
  91. gs.gobuf = make([]byte, size)
  92. p := C.malloc(C.size_t(size))
  93. gs.cbuf = (*[1 << 30]byte)(unsafe.Pointer(p))[:size:size]
  94. return gs, nil
  95. }
  96. // SetCheckErrors enables/disables checking for errors after the
  97. // call of any OpenGL function. It is enabled by default but
  98. // could be disabled after an application is stable to improve the performance.
  99. func (gs *GLS) SetCheckErrors(enable bool) {
  100. if enable {
  101. C.glapiCheckError(1)
  102. } else {
  103. C.glapiCheckError(1)
  104. }
  105. gs.checkErrors = enable
  106. }
  107. // ChecksErrors returns if error checking is enabled or not.
  108. func (gs *GLS) CheckErrors() bool {
  109. return gs.checkErrors
  110. }
  111. // reset resets the internal state kept of the OpenGL
  112. func (gs *GLS) reset() {
  113. gs.lineWidth = 0.0
  114. gs.sideView = uintUndef
  115. gs.frontFace = 0
  116. gs.depthFunc = 0
  117. gs.depthMask = uintUndef
  118. gs.capabilities = make(map[int]int)
  119. gs.programs = make(map[*Program]bool)
  120. gs.prog = nil
  121. gs.blendEquation = uintUndef
  122. gs.blendSrc = uintUndef
  123. gs.blendDst = uintUndef
  124. gs.blendEquationRGB = 0
  125. gs.blendEquationAlpha = 0
  126. gs.blendSrcRGB = uintUndef
  127. gs.blendSrcAlpha = uintUndef
  128. gs.blendDstRGB = uintUndef
  129. gs.blendDstAlpha = uintUndef
  130. gs.polygonModeFace = 0
  131. gs.polygonModeMode = 0
  132. gs.polygonOffsetFactor = -1
  133. gs.polygonOffsetUnits = -1
  134. }
  135. // setDefaultState is used internally to set the initial state of OpenGL
  136. // for this context.
  137. func (gs *GLS) setDefaultState() {
  138. C.glClearColor(0, 0, 0, 1)
  139. C.glClearDepth(1)
  140. C.glClearStencil(0)
  141. gs.Enable(DEPTH_TEST)
  142. gs.DepthFunc(LEQUAL)
  143. gs.FrontFace(CCW)
  144. gs.CullFace(BACK)
  145. gs.Enable(CULL_FACE)
  146. gs.Enable(BLEND)
  147. gs.BlendEquation(FUNC_ADD)
  148. gs.BlendFunc(SRC_ALPHA, ONE_MINUS_SRC_ALPHA)
  149. gs.Enable(VERTEX_PROGRAM_POINT_SIZE)
  150. gs.Enable(PROGRAM_POINT_SIZE)
  151. gs.Enable(MULTISAMPLE)
  152. gs.Enable(POLYGON_OFFSET_FILL)
  153. gs.Enable(POLYGON_OFFSET_LINE)
  154. gs.Enable(POLYGON_OFFSET_POINT)
  155. }
  156. // Stats copy the current values of the internal statistics structure
  157. // to the specified pointer.
  158. func (gs *GLS) Stats(s *Stats) {
  159. *s = gs.stats
  160. s.Shaders = len(gs.programs)
  161. }
  162. func (gs *GLS) ActiveTexture(texture uint32) {
  163. C.glActiveTexture(C.GLenum(texture))
  164. }
  165. func (gs *GLS) AttachShader(program, shader uint32) {
  166. C.glAttachShader(C.GLuint(program), C.GLuint(shader))
  167. }
  168. func (gs *GLS) BindBuffer(target int, vbo uint32) {
  169. C.glBindBuffer(C.GLenum(target), C.GLuint(vbo))
  170. }
  171. func (gs *GLS) BindTexture(target int, tex uint32) {
  172. C.glBindTexture(C.GLenum(target), C.GLuint(tex))
  173. }
  174. func (gs *GLS) BindVertexArray(vao uint32) {
  175. C.glBindVertexArray(C.GLuint(vao))
  176. }
  177. func (gs *GLS) BlendEquation(mode uint32) {
  178. if gs.blendEquation == mode {
  179. return
  180. }
  181. C.glBlendEquation(C.GLenum(mode))
  182. gs.blendEquation = mode
  183. }
  184. func (gs *GLS) BlendEquationSeparate(modeRGB uint32, modeAlpha uint32) {
  185. if gs.blendEquationRGB == modeRGB && gs.blendEquationAlpha == modeAlpha {
  186. return
  187. }
  188. C.glBlendEquationSeparate(C.GLenum(modeRGB), C.GLenum(modeAlpha))
  189. gs.blendEquationRGB = modeRGB
  190. gs.blendEquationAlpha = modeAlpha
  191. }
  192. func (gs *GLS) BlendFunc(sfactor, dfactor uint32) {
  193. if gs.blendSrc == sfactor && gs.blendDst == dfactor {
  194. return
  195. }
  196. C.glBlendFunc(C.GLenum(sfactor), C.GLenum(dfactor))
  197. gs.blendSrc = sfactor
  198. gs.blendDst = dfactor
  199. }
  200. func (gs *GLS) BlendFuncSeparate(srcRGB uint32, dstRGB uint32, srcAlpha uint32, dstAlpha uint32) {
  201. if gs.blendSrcRGB == srcRGB && gs.blendDstRGB == dstRGB &&
  202. gs.blendSrcAlpha == srcAlpha && gs.blendDstAlpha == dstAlpha {
  203. return
  204. }
  205. C.glBlendFuncSeparate(C.GLenum(srcRGB), C.GLenum(dstRGB), C.GLenum(srcAlpha), C.GLenum(dstAlpha))
  206. gs.blendSrcRGB = srcRGB
  207. gs.blendDstRGB = dstRGB
  208. gs.blendSrcAlpha = srcAlpha
  209. gs.blendDstAlpha = dstAlpha
  210. }
  211. func (gs *GLS) BufferData(target uint32, size int, data interface{}, usage uint32) {
  212. C.glBufferData(C.GLenum(target), C.GLsizeiptr(size), ptr(data), C.GLenum(usage))
  213. }
  214. func (gs *GLS) ClearColor(r, g, b, a float32) {
  215. C.glClearColor(C.GLfloat(r), C.GLfloat(g), C.GLfloat(b), C.GLfloat(a))
  216. }
  217. func (gs *GLS) Clear(mask uint) {
  218. C.glClear(C.GLbitfield(mask))
  219. }
  220. func (gs *GLS) CompileShader(shader uint32) {
  221. C.glCompileShader(C.GLuint(shader))
  222. }
  223. func (gs *GLS) CreateProgram() uint32 {
  224. p := C.glCreateProgram()
  225. return uint32(p)
  226. }
  227. func (gs *GLS) CreateShader(stype uint32) uint32 {
  228. h := C.glCreateShader(C.GLenum(stype))
  229. return uint32(h)
  230. }
  231. func (gs *GLS) DeleteBuffers(bufs ...uint32) {
  232. C.glDeleteBuffers(C.GLsizei(len(bufs)), (*C.GLuint)(&bufs[0]))
  233. gs.stats.Buffers -= len(bufs)
  234. }
  235. func (gs *GLS) DeleteShader(shader uint32) {
  236. C.glDeleteShader(C.GLuint(shader))
  237. }
  238. func (gs *GLS) DeleteProgram(program uint32) {
  239. C.glDeleteProgram(C.GLuint(program))
  240. }
  241. func (gs *GLS) DeleteTextures(tex ...uint32) {
  242. C.glDeleteTextures(C.GLsizei(len(tex)), (*C.GLuint)(&tex[0]))
  243. gs.stats.Textures -= len(tex)
  244. }
  245. func (gs *GLS) DeleteVertexArrays(vaos ...uint32) {
  246. C.glDeleteVertexArrays(C.GLsizei(len(vaos)), (*C.GLuint)(&vaos[0]))
  247. gs.stats.Vaos -= len(vaos)
  248. }
  249. func (gs *GLS) DepthFunc(mode uint32) {
  250. if gs.depthFunc == mode {
  251. return
  252. }
  253. C.glDepthFunc(C.GLenum(mode))
  254. gs.depthFunc = mode
  255. }
  256. func (gs *GLS) DepthMask(flag bool) {
  257. if gs.depthMask == intTrue && flag {
  258. return
  259. }
  260. if gs.depthMask == intFalse && !flag {
  261. return
  262. }
  263. C.glDepthMask(bool2c(flag))
  264. if flag {
  265. gs.depthMask = intTrue
  266. } else {
  267. gs.depthMask = intFalse
  268. }
  269. }
  270. func (gs *GLS) DrawArrays(mode uint32, first int32, count int32) {
  271. C.glDrawArrays(C.GLenum(mode), C.GLint(first), C.GLsizei(count))
  272. gs.stats.Drawcalls++
  273. }
  274. func (gs *GLS) DrawElements(mode uint32, count int32, itype uint32, start uint32) {
  275. C.glDrawElements(C.GLenum(mode), C.GLsizei(count), C.GLenum(itype), unsafe.Pointer(uintptr(start)))
  276. gs.stats.Drawcalls++
  277. }
  278. func (gs *GLS) Enable(cap int) {
  279. if gs.capabilities[cap] == capEnabled {
  280. gs.stats.Caphits++
  281. return
  282. }
  283. C.glEnable(C.GLenum(cap))
  284. gs.capabilities[cap] = capEnabled
  285. }
  286. func (gs *GLS) EnableVertexAttribArray(index uint32) {
  287. C.glEnableVertexAttribArray(C.GLuint(index))
  288. }
  289. func (gs *GLS) Disable(cap int) {
  290. if gs.capabilities[cap] == capDisabled {
  291. gs.stats.Caphits++
  292. return
  293. }
  294. C.glDisable(C.GLenum(cap))
  295. gs.capabilities[cap] = capDisabled
  296. }
  297. func (gs *GLS) CullFace(mode uint32) {
  298. C.glCullFace(C.GLenum(mode))
  299. }
  300. func (gs *GLS) FrontFace(mode uint32) {
  301. if gs.frontFace == mode {
  302. return
  303. }
  304. C.glFrontFace(C.GLenum(mode))
  305. gs.frontFace = mode
  306. }
  307. func (gs *GLS) GenBuffer() uint32 {
  308. var buf uint32
  309. C.glGenBuffers(1, (*C.GLuint)(&buf))
  310. gs.stats.Buffers++
  311. return buf
  312. }
  313. func (gs *GLS) GenerateMipmap(target uint32) {
  314. C.glGenerateMipmap(C.GLenum(target))
  315. }
  316. func (gs *GLS) GenTexture() uint32 {
  317. var tex uint32
  318. C.glGenTextures(1, (*C.GLuint)(&tex))
  319. gs.stats.Textures++
  320. return tex
  321. }
  322. func (gs *GLS) GenVertexArray() uint32 {
  323. var vao uint32
  324. C.glGenVertexArrays(1, (*C.GLuint)(&vao))
  325. gs.stats.Vaos++
  326. return vao
  327. }
  328. func (gs *GLS) GetAttribLocation(program uint32, name string) int32 {
  329. loc := C.glGetAttribLocation(C.GLuint(program), gs.gobufStr(name))
  330. return int32(loc)
  331. }
  332. func (gs *GLS) GetProgramiv(program, pname uint32, params *int32) {
  333. C.glGetProgramiv(C.GLuint(program), C.GLenum(pname), (*C.GLint)(params))
  334. }
  335. // GetProgramInfoLog returns the information log for the specified program object.
  336. func (gs *GLS) GetProgramInfoLog(program uint32) string {
  337. var length int32
  338. gs.GetProgramiv(program, INFO_LOG_LENGTH, &length)
  339. if length == 0 {
  340. return ""
  341. }
  342. C.glGetProgramInfoLog(C.GLuint(program), C.GLsizei(length), nil, gs.gobufSize(uint32(length)))
  343. return string(gs.gobuf[:length])
  344. }
  345. // GetShaderInfoLog returns the information log for the specified shader object.
  346. func (gs *GLS) GetShaderInfoLog(shader uint32) string {
  347. var length int32
  348. gs.GetShaderiv(shader, INFO_LOG_LENGTH, &length)
  349. if length == 0 {
  350. return ""
  351. }
  352. C.glGetShaderInfoLog(C.GLuint(shader), C.GLsizei(length), nil, gs.gobufSize(uint32(length)))
  353. return string(gs.gobuf[:length])
  354. }
  355. func (gs *GLS) GetString(name uint32) string {
  356. cs := C.glGetString(C.GLenum(name))
  357. return C.GoString((*C.char)(unsafe.Pointer(cs)))
  358. }
  359. // GetUniformLocation returns the location of a uniform variable for the specified program.
  360. func (gs *GLS) GetUniformLocation(program uint32, name string) int32 {
  361. loc := C.glGetUniformLocation(C.GLuint(program), gs.gobufStr(name))
  362. return int32(loc)
  363. }
  364. func (gs *GLS) GetViewport() (x, y, width, height int32) {
  365. return gs.viewportX, gs.viewportY, gs.viewportWidth, gs.viewportHeight
  366. }
  367. func (gs *GLS) LineWidth(width float32) {
  368. if gs.lineWidth == width {
  369. return
  370. }
  371. C.glLineWidth(C.GLfloat(width))
  372. gs.lineWidth = width
  373. }
  374. func (gs *GLS) LinkProgram(program uint32) {
  375. C.glLinkProgram(C.GLuint(program))
  376. }
  377. func (gs *GLS) GetShaderiv(shader, pname uint32, params *int32) {
  378. C.glGetShaderiv(C.GLuint(shader), C.GLenum(pname), (*C.GLint)(params))
  379. }
  380. func (gs *GLS) ShaderSource(shader uint32, src string) {
  381. csource := gs.cbufStr(src)
  382. C.glShaderSource(C.GLuint(shader), 1, (**C.GLchar)(unsafe.Pointer(&csource)), nil)
  383. }
  384. func (gs *GLS) TexImage2D(target uint32, level int32, iformat int32, width int32, height int32, border int32, format uint32, itype uint32, data interface{}) {
  385. C.glTexImage2D(C.GLenum(target),
  386. C.GLint(level),
  387. C.GLint(iformat),
  388. C.GLsizei(width),
  389. C.GLsizei(height),
  390. C.GLint(border),
  391. C.GLenum(format),
  392. C.GLenum(itype),
  393. ptr(data))
  394. }
  395. func (gs *GLS) TexParameteri(target uint32, pname uint32, param int32) {
  396. C.glTexParameteri(C.GLenum(target), C.GLenum(pname), C.GLint(param))
  397. }
  398. func (gs *GLS) PolygonMode(face, mode uint32) {
  399. if gs.polygonModeFace == face && gs.polygonModeMode == mode {
  400. return
  401. }
  402. C.glPolygonMode(C.GLenum(face), C.GLenum(mode))
  403. gs.polygonModeFace = face
  404. gs.polygonModeMode = mode
  405. }
  406. func (gs *GLS) PolygonOffset(factor float32, units float32) {
  407. if gs.polygonOffsetFactor == factor && gs.polygonOffsetUnits == units {
  408. return
  409. }
  410. C.glPolygonOffset(C.GLfloat(factor), C.GLfloat(units))
  411. gs.polygonOffsetFactor = factor
  412. gs.polygonOffsetUnits = units
  413. }
  414. func (gs *GLS) Uniform1i(location int32, v0 int32) {
  415. C.glUniform1i(C.GLint(location), C.GLint(v0))
  416. gs.stats.Unisets++
  417. }
  418. func (gs *GLS) Uniform1f(location int32, v0 float32) {
  419. C.glUniform1f(C.GLint(location), C.GLfloat(v0))
  420. gs.stats.Unisets++
  421. }
  422. func (gs *GLS) Uniform2f(location int32, v0, v1 float32) {
  423. C.glUniform2f(C.GLint(location), C.GLfloat(v0), C.GLfloat(v1))
  424. gs.stats.Unisets++
  425. }
  426. func (gs *GLS) Uniform3f(location int32, v0, v1, v2 float32) {
  427. C.glUniform3f(C.GLint(location), C.GLfloat(v0), C.GLfloat(v1), C.GLfloat(v2))
  428. gs.stats.Unisets++
  429. }
  430. func (gs *GLS) Uniform4f(location int32, v0, v1, v2, v3 float32) {
  431. C.glUniform4f(C.GLint(location), C.GLfloat(v0), C.GLfloat(v1), C.GLfloat(v2), C.GLfloat(v3))
  432. gs.stats.Unisets++
  433. }
  434. func (gs *GLS) UniformMatrix3fv(location int32, count int32, transpose bool, pm *float32) {
  435. C.glUniformMatrix3fv(C.GLint(location), C.GLsizei(count), bool2c(transpose), (*C.GLfloat)(pm))
  436. gs.stats.Unisets++
  437. }
  438. func (gs *GLS) UniformMatrix4fv(location int32, count int32, transpose bool, pm *float32) {
  439. C.glUniformMatrix4fv(C.GLint(location), C.GLsizei(count), bool2c(transpose), (*C.GLfloat)(pm))
  440. gs.stats.Unisets++
  441. }
  442. func (gs *GLS) Uniform1fv(location int32, count int32, v []float32) {
  443. C.glUniform1fv(C.GLint(location), C.GLsizei(count), (*C.GLfloat)(&v[0]))
  444. gs.stats.Unisets++
  445. }
  446. func (gs *GLS) Uniform2fv(location int32, count int32, v []float32) {
  447. C.glUniform2fv(C.GLint(location), C.GLsizei(count), (*C.GLfloat)(&v[0]))
  448. gs.stats.Unisets++
  449. }
  450. func (gs *GLS) Uniform3fv(location int32, count int32, v []float32) {
  451. C.glUniform3fv(C.GLint(location), C.GLsizei(count), (*C.GLfloat)(&v[0]))
  452. gs.stats.Unisets++
  453. }
  454. func (gs *GLS) Uniform4fv(location int32, count int32, v []float32) {
  455. C.glUniform4fv(C.GLint(location), C.GLsizei(count), (*C.GLfloat)(&v[0]))
  456. gs.stats.Unisets++
  457. }
  458. func (gs *GLS) VertexAttribPointer(index uint32, size int32, xtype uint32, normalized bool, stride int32, offset uint32) {
  459. C.glVertexAttribPointer(C.GLuint(index), C.GLint(size), C.GLenum(xtype), bool2c(normalized), C.GLsizei(stride), unsafe.Pointer(uintptr(offset)))
  460. }
  461. func (gs *GLS) Viewport(x, y, width, height int32) {
  462. C.glViewport(C.GLint(x), C.GLint(y), C.GLsizei(width), C.GLsizei(height))
  463. gs.viewportX = x
  464. gs.viewportY = y
  465. gs.viewportWidth = width
  466. gs.viewportHeight = height
  467. }
  468. // Use set this program as the current program.
  469. func (gs *GLS) UseProgram(prog *Program) {
  470. if prog.handle == 0 {
  471. panic("Invalid program")
  472. }
  473. C.glUseProgram(C.GLuint(prog.handle))
  474. gs.prog = prog
  475. // Inserts program in cache if not already there.
  476. if !gs.programs[prog] {
  477. gs.programs[prog] = true
  478. log.Debug("New Program activated. Total: %d", len(gs.programs))
  479. }
  480. }
  481. // Ptr takes a slice or pointer (to a singular scalar value or the first
  482. // element of an array or slice) and returns its GL-compatible address.
  483. //
  484. // For example:
  485. //
  486. // var data []uint8
  487. // ...
  488. // gl.TexImage2D(gl.TEXTURE_2D, ..., gl.UNSIGNED_BYTE, gl.Ptr(&data[0]))
  489. func ptr(data interface{}) unsafe.Pointer {
  490. if data == nil {
  491. return unsafe.Pointer(nil)
  492. }
  493. var addr unsafe.Pointer
  494. v := reflect.ValueOf(data)
  495. switch v.Type().Kind() {
  496. case reflect.Ptr:
  497. e := v.Elem()
  498. switch e.Kind() {
  499. case
  500. reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
  501. reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
  502. reflect.Float32, reflect.Float64:
  503. addr = unsafe.Pointer(e.UnsafeAddr())
  504. default:
  505. panic(fmt.Errorf("unsupported pointer to type %s; must be a slice or pointer to a singular scalar value or the first element of an array or slice", e.Kind()))
  506. }
  507. case reflect.Uintptr:
  508. addr = unsafe.Pointer(v.Pointer())
  509. case reflect.Slice:
  510. addr = unsafe.Pointer(v.Index(0).UnsafeAddr())
  511. default:
  512. panic(fmt.Errorf("unsupported type %s; must be a slice or pointer to a singular scalar value or the first element of an array or slice", v.Type()))
  513. }
  514. return addr
  515. }
  516. // bool2c convert a Go bool to C.GLboolean
  517. func bool2c(b bool) C.GLboolean {
  518. if b {
  519. return C.GLboolean(1)
  520. }
  521. return C.GLboolean(0)
  522. }
  523. // gobufSize returns a pointer to static buffer with the specified size not including the terminator.
  524. // If there is available space, there is no memory allocation.
  525. func (gs *GLS) gobufSize(size uint32) *C.GLchar {
  526. if size+1 > uint32(len(gs.gobuf)) {
  527. gs.gobuf = make([]byte, size+1)
  528. }
  529. return (*C.GLchar)(unsafe.Pointer(&gs.gobuf[0]))
  530. }
  531. // gobufStr converts a Go String to a C string by copying it to a static buffer
  532. // and returning a pointer to the start of the buffer.
  533. // If there is available space, there is no memory allocation.
  534. func (gs *GLS) gobufStr(s string) *C.GLchar {
  535. p := gs.gobufSize(uint32(len(s) + 1))
  536. copy(gs.gobuf, s)
  537. gs.gobuf[len(s)] = 0
  538. return p
  539. }
  540. // cbufSize returns a pointer to static buffer with C memory
  541. // If there is available space, there is no memory allocation.
  542. func (gs *GLS) cbufSize(size uint32) *C.GLchar {
  543. if size > uint32(len(gs.cbuf)) {
  544. if len(gs.cbuf) > 0 {
  545. C.free(unsafe.Pointer(&gs.cbuf[0]))
  546. }
  547. p := C.malloc(C.size_t(size))
  548. gs.cbuf = (*[1 << 30]byte)(unsafe.Pointer(p))[:size:size]
  549. }
  550. return (*C.GLchar)(unsafe.Pointer(&gs.cbuf[0]))
  551. }
  552. // cbufStr converts a Go String to a C string by copying it to a single pre-allocated buffer
  553. // using C memory and returning a pointer to the start of the buffer.
  554. // If there is available space, there is no memory allocation.
  555. func (gs *GLS) cbufStr(s string) *C.GLchar {
  556. p := gs.cbufSize(uint32(len(s) + 1))
  557. copy(gs.cbuf, s)
  558. gs.cbuf[len(s)] = 0
  559. return p
  560. }