gls-desktop.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  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. // +build !wasm
  5. package gls
  6. // #include <stdlib.h>
  7. // #include "glcorearb.h"
  8. // #include "glapi.h"
  9. import "C"
  10. import (
  11. "fmt"
  12. "math"
  13. "reflect"
  14. "unsafe"
  15. )
  16. // GLS encapsulates the state of an OpenGL context and contains
  17. // methods to call OpenGL functions.
  18. type GLS struct {
  19. stats Stats // statistics
  20. prog *Program // current active shader program
  21. programs map[*Program]bool // shader programs cache
  22. checkErrors bool // check openGL API errors flag
  23. // Cache OpenGL state to avoid making unnecessary API calls
  24. activeTexture uint32 // cached last set active texture unit
  25. viewportX int32 // cached last set viewport x
  26. viewportY int32 // cached last set viewport y
  27. viewportWidth int32 // cached last set viewport width
  28. viewportHeight int32 // cached last set viewport height
  29. lineWidth float32 // cached last set line width
  30. sideView int // cached last set triangle side view mode
  31. frontFace uint32 // cached last set glFrontFace value
  32. depthFunc uint32 // cached last set depth function
  33. depthMask int // cached last set depth mask
  34. capabilities map[int]int // cached capabilities (Enable/Disable)
  35. blendEquation uint32 // cached last set blend equation value
  36. blendSrc uint32 // cached last set blend src value
  37. blendDst uint32 // cached last set blend equation destination value
  38. blendEquationRGB uint32 // cached last set blend equation rgb value
  39. blendEquationAlpha uint32 // cached last set blend equation alpha value
  40. blendSrcRGB uint32 // cached last set blend src rgb
  41. blendSrcAlpha uint32 // cached last set blend src alpha value
  42. blendDstRGB uint32 // cached last set blend destination rgb value
  43. blendDstAlpha uint32 // cached last set blend destination alpha value
  44. polygonModeFace uint32 // cached last set polygon mode face
  45. polygonModeMode uint32 // cached last set polygon mode mode
  46. polygonOffsetFactor float32 // cached last set polygon offset factor
  47. polygonOffsetUnits float32 // cached last set polygon offset units
  48. gobuf []byte // conversion buffer with GO memory
  49. cbuf []byte // conversion buffer with C memory
  50. }
  51. // Stats contains counters of OpenGL resources being used as well
  52. // the cumulative numbers of some OpenGL calls for performance evaluation.
  53. type Stats struct {
  54. Shaders int // Current number of shader programs
  55. Vaos int // Number of Vertex Array Objects
  56. Buffers int // Number of Buffer Objects
  57. Textures int // Number of Textures
  58. Caphits uint64 // Cumulative number of hits for Enable/Disable
  59. UnilocHits uint64 // Cumulative number of uniform location cache hits
  60. UnilocMiss uint64 // Cumulative number of uniform location cache misses
  61. Unisets uint64 // Cumulative number of uniform sets
  62. Drawcalls uint64 // Cumulative number of draw calls
  63. }
  64. const (
  65. capUndef = 0
  66. capDisabled = 1
  67. capEnabled = 2
  68. uintUndef = math.MaxUint32
  69. intFalse = 0
  70. intTrue = 1
  71. )
  72. const (
  73. FloatSize = int32(unsafe.Sizeof(float32(0)))
  74. )
  75. // New creates and returns a new instance of a GLS object,
  76. // which encapsulates the state of an OpenGL context.
  77. // This should be called only after an active OpenGL context
  78. // is 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. // Preallocate 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(0)
  104. }
  105. gs.checkErrors = enable
  106. }
  107. // CheckErrors 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.activeTexture = uintUndef
  122. gs.blendEquation = uintUndef
  123. gs.blendSrc = uintUndef
  124. gs.blendDst = uintUndef
  125. gs.blendEquationRGB = 0
  126. gs.blendEquationAlpha = 0
  127. gs.blendSrcRGB = uintUndef
  128. gs.blendSrcAlpha = uintUndef
  129. gs.blendDstRGB = uintUndef
  130. gs.blendDstAlpha = uintUndef
  131. gs.polygonModeFace = 0
  132. gs.polygonModeMode = 0
  133. gs.polygonOffsetFactor = -1
  134. gs.polygonOffsetUnits = -1
  135. }
  136. // setDefaultState is used internally to set the initial state of OpenGL
  137. // for this context.
  138. func (gs *GLS) setDefaultState() {
  139. gs.ClearColor(0, 0, 0, 1)
  140. gs.ClearDepth(1)
  141. gs.ClearStencil(0)
  142. gs.Enable(DEPTH_TEST)
  143. gs.DepthFunc(LEQUAL)
  144. gs.FrontFace(CCW)
  145. gs.CullFace(BACK)
  146. gs.Enable(CULL_FACE)
  147. gs.Enable(BLEND)
  148. gs.BlendEquation(FUNC_ADD)
  149. gs.BlendFunc(SRC_ALPHA, ONE_MINUS_SRC_ALPHA)
  150. gs.Enable(VERTEX_PROGRAM_POINT_SIZE)
  151. gs.Enable(PROGRAM_POINT_SIZE)
  152. gs.Enable(MULTISAMPLE)
  153. gs.Enable(POLYGON_OFFSET_FILL)
  154. gs.Enable(POLYGON_OFFSET_LINE)
  155. gs.Enable(POLYGON_OFFSET_POINT)
  156. }
  157. // Stats copy the current values of the internal statistics structure
  158. // to the specified pointer.
  159. func (gs *GLS) Stats(s *Stats) {
  160. *s = gs.stats
  161. s.Shaders = len(gs.programs)
  162. }
  163. // ActiveTexture selects which texture unit subsequent texture state calls
  164. // will affect. The number of texture units an implementation supports is
  165. // implementation dependent, but must be at least 48 in GL 3.3.
  166. func (gs *GLS) ActiveTexture(texture uint32) {
  167. if gs.activeTexture == texture {
  168. return
  169. }
  170. C.glActiveTexture(C.GLenum(texture))
  171. gs.activeTexture = texture
  172. }
  173. // AttachShader attaches the specified shader object to the specified program object.
  174. func (gs *GLS) AttachShader(program, shader uint32) {
  175. C.glAttachShader(C.GLuint(program), C.GLuint(shader))
  176. }
  177. // BindBuffer binds a buffer object to the specified buffer binding point.
  178. func (gs *GLS) BindBuffer(target int, vbo uint32) {
  179. C.glBindBuffer(C.GLenum(target), C.GLuint(vbo))
  180. }
  181. // BindTexture lets you create or use a named texture.
  182. func (gs *GLS) BindTexture(target int, tex uint32) {
  183. C.glBindTexture(C.GLenum(target), C.GLuint(tex))
  184. }
  185. // BindVertexArray binds the vertex array object.
  186. func (gs *GLS) BindVertexArray(vao uint32) {
  187. C.glBindVertexArray(C.GLuint(vao))
  188. }
  189. // BlendEquation sets the blend equations for all draw buffers.
  190. func (gs *GLS) BlendEquation(mode uint32) {
  191. if gs.blendEquation == mode {
  192. return
  193. }
  194. C.glBlendEquation(C.GLenum(mode))
  195. gs.blendEquation = mode
  196. }
  197. // BlendEquationSeparate sets the blend equations for all draw buffers
  198. // allowing different equations for the RGB and alpha components.
  199. func (gs *GLS) BlendEquationSeparate(modeRGB uint32, modeAlpha uint32) {
  200. if gs.blendEquationRGB == modeRGB && gs.blendEquationAlpha == modeAlpha {
  201. return
  202. }
  203. C.glBlendEquationSeparate(C.GLenum(modeRGB), C.GLenum(modeAlpha))
  204. gs.blendEquationRGB = modeRGB
  205. gs.blendEquationAlpha = modeAlpha
  206. }
  207. // BlendFunc defines the operation of blending for
  208. // all draw buffers when blending is enabled.
  209. func (gs *GLS) BlendFunc(sfactor, dfactor uint32) {
  210. if gs.blendSrc == sfactor && gs.blendDst == dfactor {
  211. return
  212. }
  213. C.glBlendFunc(C.GLenum(sfactor), C.GLenum(dfactor))
  214. gs.blendSrc = sfactor
  215. gs.blendDst = dfactor
  216. }
  217. // BlendFuncSeparate defines the operation of blending for all draw buffers when blending
  218. // is enabled, allowing different operations for the RGB and alpha components.
  219. func (gs *GLS) BlendFuncSeparate(srcRGB uint32, dstRGB uint32, srcAlpha uint32, dstAlpha uint32) {
  220. if gs.blendSrcRGB == srcRGB && gs.blendDstRGB == dstRGB &&
  221. gs.blendSrcAlpha == srcAlpha && gs.blendDstAlpha == dstAlpha {
  222. return
  223. }
  224. C.glBlendFuncSeparate(C.GLenum(srcRGB), C.GLenum(dstRGB), C.GLenum(srcAlpha), C.GLenum(dstAlpha))
  225. gs.blendSrcRGB = srcRGB
  226. gs.blendDstRGB = dstRGB
  227. gs.blendSrcAlpha = srcAlpha
  228. gs.blendDstAlpha = dstAlpha
  229. }
  230. // BufferData creates a new data store for the buffer object currently
  231. // bound to target, deleting any pre-existing data store.
  232. func (gs *GLS) BufferData(target uint32, size int, data interface{}, usage uint32) {
  233. C.glBufferData(C.GLenum(target), C.GLsizeiptr(size), ptr(data), C.GLenum(usage))
  234. }
  235. // ClearColor specifies the red, green, blue, and alpha values
  236. // used by glClear to clear the color buffers.
  237. func (gs *GLS) ClearColor(r, g, b, a float32) {
  238. C.glClearColor(C.GLfloat(r), C.GLfloat(g), C.GLfloat(b), C.GLfloat(a))
  239. }
  240. // ClearDepth specifies the depth value used by Clear to clear the depth buffer.
  241. func (gs *GLS) ClearDepth(v float32) {
  242. C.glClearDepth(C.GLclampd(v))
  243. }
  244. // ClearStencil specifies the index used by Clear to clear the stencil buffer.
  245. func (gs *GLS) ClearStencil(v int32) {
  246. C.glClearStencil(C.GLint(v))
  247. }
  248. // Clear sets the bitplane area of the window to values previously
  249. // selected by ClearColor, ClearDepth, and ClearStencil.
  250. func (gs *GLS) Clear(mask uint) {
  251. C.glClear(C.GLbitfield(mask))
  252. }
  253. // CompileShader compiles the source code strings that
  254. // have been stored in the specified shader object.
  255. func (gs *GLS) CompileShader(shader uint32) {
  256. C.glCompileShader(C.GLuint(shader))
  257. }
  258. // CreateProgram creates an empty program object and returns
  259. // a non-zero value by which it can be referenced.
  260. func (gs *GLS) CreateProgram() uint32 {
  261. p := C.glCreateProgram()
  262. return uint32(p)
  263. }
  264. // CreateShader creates an empty shader object and returns
  265. // a non-zero value by which it can be referenced.
  266. func (gs *GLS) CreateShader(stype uint32) uint32 {
  267. h := C.glCreateShader(C.GLenum(stype))
  268. return uint32(h)
  269. }
  270. // DeleteBuffers deletes n​buffer objects named
  271. // by the elements of the provided array.
  272. func (gs *GLS) DeleteBuffers(bufs ...uint32) {
  273. C.glDeleteBuffers(C.GLsizei(len(bufs)), (*C.GLuint)(&bufs[0]))
  274. gs.stats.Buffers -= len(bufs)
  275. }
  276. // DeleteShader frees the memory and invalidates the name
  277. // associated with the specified shader object.
  278. func (gs *GLS) DeleteShader(shader uint32) {
  279. C.glDeleteShader(C.GLuint(shader))
  280. }
  281. // DeleteProgram frees the memory and invalidates the name
  282. // associated with the specified program object.
  283. func (gs *GLS) DeleteProgram(program uint32) {
  284. C.glDeleteProgram(C.GLuint(program))
  285. }
  286. // DeleteTextures deletes n​textures named
  287. // by the elements of the provided array.
  288. func (gs *GLS) DeleteTextures(tex ...uint32) {
  289. C.glDeleteTextures(C.GLsizei(len(tex)), (*C.GLuint)(&tex[0]))
  290. gs.stats.Textures -= len(tex)
  291. }
  292. // DeleteVertexArrays deletes n​vertex array objects named
  293. // by the elements of the provided array.
  294. func (gs *GLS) DeleteVertexArrays(vaos ...uint32) {
  295. C.glDeleteVertexArrays(C.GLsizei(len(vaos)), (*C.GLuint)(&vaos[0]))
  296. gs.stats.Vaos -= len(vaos)
  297. }
  298. // DepthFunc specifies the function used to compare each incoming pixel
  299. // depth value with the depth value present in the depth buffer.
  300. func (gs *GLS) DepthFunc(mode uint32) {
  301. if gs.depthFunc == mode {
  302. return
  303. }
  304. C.glDepthFunc(C.GLenum(mode))
  305. gs.depthFunc = mode
  306. }
  307. // DepthMask enables or disables writing into the depth buffer.
  308. func (gs *GLS) DepthMask(flag bool) {
  309. if gs.depthMask == intTrue && flag {
  310. return
  311. }
  312. if gs.depthMask == intFalse && !flag {
  313. return
  314. }
  315. C.glDepthMask(bool2c(flag))
  316. if flag {
  317. gs.depthMask = intTrue
  318. } else {
  319. gs.depthMask = intFalse
  320. }
  321. }
  322. // DrawArrays renders primitives from array data.
  323. func (gs *GLS) DrawArrays(mode uint32, first int32, count int32) {
  324. C.glDrawArrays(C.GLenum(mode), C.GLint(first), C.GLsizei(count))
  325. gs.stats.Drawcalls++
  326. }
  327. // DrawElements renders primitives from array data.
  328. func (gs *GLS) DrawElements(mode uint32, count int32, itype uint32, start uint32) {
  329. C.glDrawElements(C.GLenum(mode), C.GLsizei(count), C.GLenum(itype), unsafe.Pointer(uintptr(start)))
  330. gs.stats.Drawcalls++
  331. }
  332. // Enable enables the specified capability.
  333. func (gs *GLS) Enable(cap int) {
  334. if gs.capabilities[cap] == capEnabled {
  335. gs.stats.Caphits++
  336. return
  337. }
  338. C.glEnable(C.GLenum(cap))
  339. gs.capabilities[cap] = capEnabled
  340. }
  341. // Disable disables the specified capability.
  342. func (gs *GLS) Disable(cap int) {
  343. if gs.capabilities[cap] == capDisabled {
  344. gs.stats.Caphits++
  345. return
  346. }
  347. C.glDisable(C.GLenum(cap))
  348. gs.capabilities[cap] = capDisabled
  349. }
  350. // EnableVertexAttribArray enables a generic vertex attribute array.
  351. func (gs *GLS) EnableVertexAttribArray(index uint32) {
  352. C.glEnableVertexAttribArray(C.GLuint(index))
  353. }
  354. // CullFace specifies whether front- or back-facing facets can be culled.
  355. func (gs *GLS) CullFace(mode uint32) {
  356. C.glCullFace(C.GLenum(mode))
  357. }
  358. // FrontFace defines front- and back-facing polygons.
  359. func (gs *GLS) FrontFace(mode uint32) {
  360. if gs.frontFace == mode {
  361. return
  362. }
  363. C.glFrontFace(C.GLenum(mode))
  364. gs.frontFace = mode
  365. }
  366. // GenBuffer generates a ​buffer object name.
  367. func (gs *GLS) GenBuffer() uint32 {
  368. var buf uint32
  369. C.glGenBuffers(1, (*C.GLuint)(&buf))
  370. gs.stats.Buffers++
  371. return buf
  372. }
  373. // GenerateMipmap generates mipmaps for the specified texture target.
  374. func (gs *GLS) GenerateMipmap(target uint32) {
  375. C.glGenerateMipmap(C.GLenum(target))
  376. }
  377. // GenTexture generates a texture object name.
  378. func (gs *GLS) GenTexture() uint32 {
  379. var tex uint32
  380. C.glGenTextures(1, (*C.GLuint)(&tex))
  381. gs.stats.Textures++
  382. return tex
  383. }
  384. // GenVertexArray generates a vertex array object name.
  385. func (gs *GLS) GenVertexArray() uint32 {
  386. var vao uint32
  387. C.glGenVertexArrays(1, (*C.GLuint)(&vao))
  388. gs.stats.Vaos++
  389. return vao
  390. }
  391. // GetAttribLocation returns the location of the specified attribute variable.
  392. func (gs *GLS) GetAttribLocation(program uint32, name string) int32 {
  393. loc := C.glGetAttribLocation(C.GLuint(program), gs.gobufStr(name))
  394. return int32(loc)
  395. }
  396. // GetProgramiv returns the specified parameter from the specified program object.
  397. func (gs *GLS) GetProgramiv(program, pname uint32, params *int32) {
  398. C.glGetProgramiv(C.GLuint(program), C.GLenum(pname), (*C.GLint)(params))
  399. }
  400. // GetProgramInfoLog returns the information log for the specified program object.
  401. func (gs *GLS) GetProgramInfoLog(program uint32) string {
  402. var length int32
  403. gs.GetProgramiv(program, INFO_LOG_LENGTH, &length)
  404. if length == 0 {
  405. return ""
  406. }
  407. C.glGetProgramInfoLog(C.GLuint(program), C.GLsizei(length), nil, gs.gobufSize(uint32(length)))
  408. return string(gs.gobuf[:length])
  409. }
  410. // GetShaderInfoLog returns the information log for the specified shader object.
  411. func (gs *GLS) GetShaderInfoLog(shader uint32) string {
  412. var length int32
  413. gs.GetShaderiv(shader, INFO_LOG_LENGTH, &length)
  414. if length == 0 {
  415. return ""
  416. }
  417. C.glGetShaderInfoLog(C.GLuint(shader), C.GLsizei(length), nil, gs.gobufSize(uint32(length)))
  418. return string(gs.gobuf[:length])
  419. }
  420. // GetString returns a string describing the specified aspect of the current GL connection.
  421. func (gs *GLS) GetString(name uint32) string {
  422. cs := C.glGetString(C.GLenum(name))
  423. return C.GoString((*C.char)(unsafe.Pointer(cs)))
  424. }
  425. // GetUniformLocation returns the location of a uniform variable for the specified program.
  426. func (gs *GLS) GetUniformLocation(program uint32, name string) int32 {
  427. loc := C.glGetUniformLocation(C.GLuint(program), gs.gobufStr(name))
  428. return int32(loc)
  429. }
  430. // GetViewport returns the current viewport information.
  431. func (gs *GLS) GetViewport() (x, y, width, height int32) {
  432. return gs.viewportX, gs.viewportY, gs.viewportWidth, gs.viewportHeight
  433. }
  434. // LineWidth specifies the rasterized width of both aliased and antialiased lines.
  435. func (gs *GLS) LineWidth(width float32) {
  436. if gs.lineWidth == width {
  437. return
  438. }
  439. C.glLineWidth(C.GLfloat(width))
  440. gs.lineWidth = width
  441. }
  442. // LinkProgram links the specified program object.
  443. func (gs *GLS) LinkProgram(program uint32) {
  444. C.glLinkProgram(C.GLuint(program))
  445. }
  446. // GetShaderiv returns the specified parameter from the specified shader object.
  447. func (gs *GLS) GetShaderiv(shader, pname uint32, params *int32) {
  448. C.glGetShaderiv(C.GLuint(shader), C.GLenum(pname), (*C.GLint)(params))
  449. }
  450. // Scissor defines the scissor box rectangle in window coordinates.
  451. func (gs *GLS) Scissor(x, y int32, width, height uint32) {
  452. C.glScissor(C.GLint(x), C.GLint(y), C.GLsizei(width), C.GLsizei(height))
  453. }
  454. // ShaderSource sets the source code for the specified shader object.
  455. func (gs *GLS) ShaderSource(shader uint32, src string) {
  456. csource := gs.cbufStr(src)
  457. C.glShaderSource(C.GLuint(shader), 1, (**C.GLchar)(unsafe.Pointer(&csource)), nil)
  458. }
  459. // TexImage2D specifies a two-dimensional texture image.
  460. func (gs *GLS) TexImage2D(target uint32, level int32, iformat int32, width int32, height int32, format uint32, itype uint32, data interface{}) {
  461. C.glTexImage2D(C.GLenum(target),
  462. C.GLint(level),
  463. C.GLint(iformat),
  464. C.GLsizei(width),
  465. C.GLsizei(height),
  466. C.GLint(0),
  467. C.GLenum(format),
  468. C.GLenum(itype),
  469. ptr(data))
  470. }
  471. // TexParameteri sets the specified texture parameter on the specified texture.
  472. func (gs *GLS) TexParameteri(target uint32, pname uint32, param int32) {
  473. C.glTexParameteri(C.GLenum(target), C.GLenum(pname), C.GLint(param))
  474. }
  475. // PolygonMode controls the interpretation of polygons for rasterization.
  476. func (gs *GLS) PolygonMode(face, mode uint32) {
  477. if gs.polygonModeFace == face && gs.polygonModeMode == mode {
  478. return
  479. }
  480. C.glPolygonMode(C.GLenum(face), C.GLenum(mode))
  481. gs.polygonModeFace = face
  482. gs.polygonModeMode = mode
  483. }
  484. // PolygonOffset sets the scale and units used to calculate depth values.
  485. func (gs *GLS) PolygonOffset(factor float32, units float32) {
  486. if gs.polygonOffsetFactor == factor && gs.polygonOffsetUnits == units {
  487. return
  488. }
  489. C.glPolygonOffset(C.GLfloat(factor), C.GLfloat(units))
  490. gs.polygonOffsetFactor = factor
  491. gs.polygonOffsetUnits = units
  492. }
  493. // Uniform1i sets the value of an int uniform variable for the current program object.
  494. func (gs *GLS) Uniform1i(location int32, v0 int32) {
  495. C.glUniform1i(C.GLint(location), C.GLint(v0))
  496. gs.stats.Unisets++
  497. }
  498. // Uniform1f sets the value of a float uniform variable for the current program object.
  499. func (gs *GLS) Uniform1f(location int32, v0 float32) {
  500. C.glUniform1f(C.GLint(location), C.GLfloat(v0))
  501. gs.stats.Unisets++
  502. }
  503. // Uniform2f sets the value of a vec2 uniform variable for the current program object.
  504. func (gs *GLS) Uniform2f(location int32, v0, v1 float32) {
  505. C.glUniform2f(C.GLint(location), C.GLfloat(v0), C.GLfloat(v1))
  506. gs.stats.Unisets++
  507. }
  508. // Uniform3f sets the value of a vec3 uniform variable for the current program object.
  509. func (gs *GLS) Uniform3f(location int32, v0, v1, v2 float32) {
  510. C.glUniform3f(C.GLint(location), C.GLfloat(v0), C.GLfloat(v1), C.GLfloat(v2))
  511. gs.stats.Unisets++
  512. }
  513. // Uniform4f sets the value of a vec4 uniform variable for the current program object.
  514. func (gs *GLS) Uniform4f(location int32, v0, v1, v2, v3 float32) {
  515. C.glUniform4f(C.GLint(location), C.GLfloat(v0), C.GLfloat(v1), C.GLfloat(v2), C.GLfloat(v3))
  516. gs.stats.Unisets++
  517. }
  518. // UniformMatrix3fv sets the value of one or many 3x3 float matrices for the current program object.
  519. func (gs *GLS) UniformMatrix3fv(location int32, count int32, transpose bool, pm *float32) {
  520. C.glUniformMatrix3fv(C.GLint(location), C.GLsizei(count), bool2c(transpose), (*C.GLfloat)(pm))
  521. gs.stats.Unisets++
  522. }
  523. // UniformMatrix4fv sets the value of one or many 4x4 float matrices for the current program object.
  524. func (gs *GLS) UniformMatrix4fv(location int32, count int32, transpose bool, pm *float32) {
  525. C.glUniformMatrix4fv(C.GLint(location), C.GLsizei(count), bool2c(transpose), (*C.GLfloat)(pm))
  526. gs.stats.Unisets++
  527. }
  528. // Uniform1fv sets the value of one or many float uniform variables for the current program object.
  529. func (gs *GLS) Uniform1fv(location int32, count int32, v *float32) {
  530. C.glUniform1fv(C.GLint(location), C.GLsizei(count), (*C.GLfloat)(v))
  531. gs.stats.Unisets++
  532. }
  533. // Uniform2fv sets the value of one or many vec2 uniform variables for the current program object.
  534. func (gs *GLS) Uniform2fv(location int32, count int32, v *float32) {
  535. C.glUniform2fv(C.GLint(location), C.GLsizei(count), (*C.GLfloat)(v))
  536. gs.stats.Unisets++
  537. }
  538. // Uniform3fv sets the value of one or many vec3 uniform variables for the current program object.
  539. func (gs *GLS) Uniform3fv(location int32, count int32, v *float32) {
  540. C.glUniform3fv(C.GLint(location), C.GLsizei(count), (*C.GLfloat)(v))
  541. gs.stats.Unisets++
  542. }
  543. // Uniform4fv sets the value of one or many vec4 uniform variables for the current program object.
  544. func (gs *GLS) Uniform4fv(location int32, count int32, v *float32) {
  545. C.glUniform4fv(C.GLint(location), C.GLsizei(count), (*C.GLfloat)(v))
  546. gs.stats.Unisets++
  547. }
  548. // VertexAttribPointer defines an array of generic vertex attribute data.
  549. func (gs *GLS) VertexAttribPointer(index uint32, size int32, xtype uint32, normalized bool, stride int32, offset uint32) {
  550. C.glVertexAttribPointer(C.GLuint(index), C.GLint(size), C.GLenum(xtype), bool2c(normalized), C.GLsizei(stride), unsafe.Pointer(uintptr(offset)))
  551. }
  552. // Viewport sets the viewport.
  553. func (gs *GLS) Viewport(x, y, width, height int32) {
  554. C.glViewport(C.GLint(x), C.GLint(y), C.GLsizei(width), C.GLsizei(height))
  555. gs.viewportX = x
  556. gs.viewportY = y
  557. gs.viewportWidth = width
  558. gs.viewportHeight = height
  559. }
  560. // UseProgram sets the specified program as the current program.
  561. func (gs *GLS) UseProgram(prog *Program) {
  562. if prog.handle == 0 {
  563. panic("Invalid program")
  564. }
  565. C.glUseProgram(C.GLuint(prog.handle))
  566. gs.prog = prog
  567. // Inserts program in cache if not already there.
  568. if !gs.programs[prog] {
  569. gs.programs[prog] = true
  570. log.Debug("New Program activated. Total: %d", len(gs.programs))
  571. }
  572. }
  573. // Ptr takes a slice or pointer (to a singular scalar value or the first
  574. // element of an array or slice) and returns its GL-compatible address.
  575. //
  576. // For example:
  577. //
  578. // var data []uint8
  579. // ...
  580. // gl.TexImage2D(gl.TEXTURE_2D, ..., gl.UNSIGNED_BYTE, gl.Ptr(&data[0]))
  581. func ptr(data interface{}) unsafe.Pointer {
  582. if data == nil {
  583. return unsafe.Pointer(nil)
  584. }
  585. var addr unsafe.Pointer
  586. v := reflect.ValueOf(data)
  587. switch v.Type().Kind() {
  588. case reflect.Ptr:
  589. e := v.Elem()
  590. switch e.Kind() {
  591. case
  592. reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
  593. reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
  594. reflect.Float32, reflect.Float64:
  595. addr = unsafe.Pointer(e.UnsafeAddr())
  596. default:
  597. 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()))
  598. }
  599. case reflect.Uintptr:
  600. addr = unsafe.Pointer(v.Pointer())
  601. case reflect.Slice:
  602. addr = unsafe.Pointer(v.Index(0).UnsafeAddr())
  603. default:
  604. 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()))
  605. }
  606. return addr
  607. }
  608. // bool2c convert a Go bool to C.GLboolean
  609. func bool2c(b bool) C.GLboolean {
  610. if b {
  611. return C.GLboolean(1)
  612. }
  613. return C.GLboolean(0)
  614. }
  615. // gobufSize returns a pointer to static buffer with the specified size not including the terminator.
  616. // If there is available space, there is no memory allocation.
  617. func (gs *GLS) gobufSize(size uint32) *C.GLchar {
  618. if size+1 > uint32(len(gs.gobuf)) {
  619. gs.gobuf = make([]byte, size+1)
  620. }
  621. return (*C.GLchar)(unsafe.Pointer(&gs.gobuf[0]))
  622. }
  623. // gobufStr converts a Go String to a C string by copying it to a static buffer
  624. // and returning a pointer to the start of the buffer.
  625. // If there is available space, there is no memory allocation.
  626. func (gs *GLS) gobufStr(s string) *C.GLchar {
  627. p := gs.gobufSize(uint32(len(s) + 1))
  628. copy(gs.gobuf, s)
  629. gs.gobuf[len(s)] = 0
  630. return p
  631. }
  632. // cbufSize returns a pointer to static buffer with C memory
  633. // If there is available space, there is no memory allocation.
  634. func (gs *GLS) cbufSize(size uint32) *C.GLchar {
  635. if size > uint32(len(gs.cbuf)) {
  636. if len(gs.cbuf) > 0 {
  637. C.free(unsafe.Pointer(&gs.cbuf[0]))
  638. }
  639. p := C.malloc(C.size_t(size))
  640. gs.cbuf = (*[1 << 30]byte)(unsafe.Pointer(p))[:size:size]
  641. }
  642. return (*C.GLchar)(unsafe.Pointer(&gs.cbuf[0]))
  643. }
  644. // cbufStr converts a Go String to a C string by copying it to a single pre-allocated buffer
  645. // using C memory and returning a pointer to the start of the buffer.
  646. // If there is available space, there is no memory allocation.
  647. func (gs *GLS) cbufStr(s string) *C.GLchar {
  648. p := gs.cbufSize(uint32(len(s) + 1))
  649. copy(gs.cbuf, s)
  650. gs.cbuf[len(s)] = 0
  651. return p
  652. }