gls.go 19 KB

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