gls.go 19 KB

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