gls.go 19 KB

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