program.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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. import (
  6. "bytes"
  7. "errors"
  8. "fmt"
  9. "github.com/g3n/engine/math32"
  10. "io"
  11. "strconv"
  12. "strings"
  13. )
  14. // Shader Program Object
  15. type Program struct {
  16. // Shows source code in error messages
  17. ShowSource bool
  18. gs *GLS
  19. handle uint32
  20. shaders []shaderInfo
  21. uniforms map[string]int32
  22. Specs interface{}
  23. }
  24. type shaderInfo struct {
  25. stype uint32
  26. source string
  27. defines map[string]interface{}
  28. handle uint32
  29. }
  30. // Map shader types to names
  31. var shaderNames = map[uint32]string{
  32. VERTEX_SHADER: "Vertex Shader",
  33. FRAGMENT_SHADER: "Fragment Shader",
  34. }
  35. // NewProgram creates a new empty shader program object.
  36. // Use this type methods to add shaders and build the final program.
  37. func (gs *GLS) NewProgram() *Program {
  38. prog := new(Program)
  39. prog.gs = gs
  40. prog.shaders = make([]shaderInfo, 0)
  41. prog.uniforms = make(map[string]int32)
  42. prog.ShowSource = true
  43. return prog
  44. }
  45. // AddShaders adds a shader to this program.
  46. // This must be done before the program is built.
  47. func (prog *Program) AddShader(stype uint32, source string, defines map[string]interface{}) {
  48. if prog.handle != 0 {
  49. log.Fatal("Program already built")
  50. }
  51. prog.shaders = append(prog.shaders, shaderInfo{stype, source, defines, 0})
  52. }
  53. // Build builds the program compiling and linking the previously supplied shaders.
  54. func (prog *Program) Build() error {
  55. if prog.handle != 0 {
  56. return fmt.Errorf("Program already built")
  57. }
  58. // Checks if shaders were provided
  59. if len(prog.shaders) == 0 {
  60. return fmt.Errorf("No shaders supplied")
  61. }
  62. // Create program
  63. prog.handle = prog.gs.CreateProgram()
  64. if prog.handle == 0 {
  65. return fmt.Errorf("Error creating program")
  66. }
  67. // Clean unused GL allocated resources
  68. defer func() {
  69. for _, sinfo := range prog.shaders {
  70. if sinfo.handle != 0 {
  71. prog.gs.DeleteShader(sinfo.handle)
  72. sinfo.handle = 0
  73. }
  74. }
  75. }()
  76. // Compiles and attach each shader
  77. for _, sinfo := range prog.shaders {
  78. // Creates string with defines from specified parameters
  79. deflines := make([]string, 0)
  80. if sinfo.defines != nil {
  81. for pname, pval := range sinfo.defines {
  82. line := "#define " + pname + " "
  83. switch val := pval.(type) {
  84. case bool:
  85. if val {
  86. deflines = append(deflines, line)
  87. }
  88. case float32:
  89. line += strconv.FormatFloat(float64(val), 'f', -1, 32)
  90. deflines = append(deflines, line)
  91. default:
  92. panic("Parameter type not supported")
  93. }
  94. }
  95. }
  96. deftext := strings.Join(deflines, "\n")
  97. // Compile shader
  98. shader, err := prog.CompileShader(sinfo.stype, sinfo.source+deftext)
  99. if err != nil {
  100. prog.gs.DeleteProgram(prog.handle)
  101. prog.handle = 0
  102. msg := fmt.Sprintf("Error compiling %s: %s", shaderNames[sinfo.stype], err)
  103. if prog.ShowSource {
  104. source := FormatSource(sinfo.source + deftext)
  105. msg += source
  106. }
  107. return errors.New(msg)
  108. }
  109. sinfo.handle = shader
  110. prog.gs.AttachShader(prog.handle, shader)
  111. }
  112. // Link program and checks for errors
  113. prog.gs.LinkProgram(prog.handle)
  114. var status int32
  115. prog.gs.GetProgramiv(prog.handle, LINK_STATUS, &status)
  116. if status == FALSE {
  117. log := prog.gs.GetProgramInfoLog(prog.handle)
  118. prog.handle = 0
  119. return fmt.Errorf("Error linking program: %v", log)
  120. }
  121. return nil
  122. }
  123. // Handle returns the handle of this program
  124. func (prog *Program) Handle() uint32 {
  125. return prog.handle
  126. }
  127. // GetAttributeLocation returns the location of the specified attribute
  128. // in this program. This location is internally cached.
  129. func (prog *Program) GetAttribLocation(name string) int32 {
  130. return prog.gs.GetAttribLocation(prog.handle, name)
  131. }
  132. // GetUniformLocation returns the location of the specified uniform in this program.
  133. // This location is internally cached.
  134. func (prog *Program) GetUniformLocation(name string) int32 {
  135. // Try to get from the cache
  136. loc, ok := prog.uniforms[name]
  137. if ok {
  138. return loc
  139. }
  140. // Get location from GL
  141. loc = prog.gs.GetUniformLocation(prog.handle, name)
  142. // Cache result
  143. prog.uniforms[name] = loc
  144. if loc < 0 {
  145. log.Warn("GetUniformLocation(%s) NOT FOUND", name)
  146. }
  147. return loc
  148. }
  149. // SetUniformInt sets this program uniform variable specified by
  150. // its location to the the value of the specified int
  151. func (prog *Program) SetUniformInt(loc int32, v int) {
  152. prog.gs.Uniform1i(loc, int32(v))
  153. }
  154. // SetUniformFloat sets this program uniform variable specified by
  155. // its location to the the value of the specified float
  156. func (prog *Program) SetUniformFloat(loc int32, v float32) {
  157. prog.gs.Uniform1f(loc, v)
  158. }
  159. // SetUniformVector2 sets this program uniform variable specified by
  160. // its location to the the value of the specified Vector2
  161. func (prog *Program) SetUniformVector2(loc int32, v *math32.Vector2) {
  162. prog.gs.Uniform2f(loc, v.X, v.Y)
  163. }
  164. // SetUniformVector3 sets this program uniform variable specified by
  165. // its location to the the value of the specified Vector3
  166. func (prog *Program) SetUniformVector3(loc int32, v *math32.Vector3) {
  167. prog.gs.Uniform3f(loc, v.X, v.Y, v.Z)
  168. }
  169. // SetUniformVector4 sets this program uniform variable specified by
  170. // its location to the the value of the specified Vector4
  171. func (prog *Program) SetUniformVector4(loc int32, v *math32.Vector4) {
  172. prog.gs.Uniform4f(loc, v.X, v.Y, v.Z, v.W)
  173. }
  174. // SetUniformMatrix3 sets this program uniform variable specified by
  175. // its location with the values from the specified Matrix3.
  176. func (prog *Program) SetUniformMatrix3(loc int32, m *math32.Matrix3) {
  177. prog.gs.UniformMatrix3fv(loc, 1, false, &m[0])
  178. }
  179. // SetUniformMatrix4 sets this program uniform variable specified by
  180. // its location with the values from the specified Matrix4.
  181. func (prog *Program) SetUniformMatrix4(loc int32, m *math32.Matrix4) {
  182. prog.gs.UniformMatrix4fv(loc, 1, false, &m[0])
  183. }
  184. // SetUniformIntByName sets this program uniform variable specified by
  185. // its name to the value of the specified int.
  186. // The specified name location is cached internally.
  187. func (prog *Program) SetUniformIntByName(name string, v int) {
  188. prog.gs.Uniform1i(prog.GetUniformLocation(name), int32(v))
  189. }
  190. // SetUniformFloatByName sets this program uniform variable specified by
  191. // its name to the value of the specified float32.
  192. // The specified name location is cached internally.
  193. func (prog *Program) SetUniformFloatByName(name string, v float32) {
  194. prog.gs.Uniform1f(prog.GetUniformLocation(name), v)
  195. }
  196. // SetUniformVector2ByName sets this program uniform variable specified by
  197. // its name to the values from the specified Vector2.
  198. // The specified name location is cached internally.
  199. func (prog *Program) SetUniformVector2ByName(name string, v *math32.Vector2) {
  200. prog.gs.Uniform2f(prog.GetUniformLocation(name), v.X, v.Y)
  201. }
  202. // SetUniformVector3ByName sets this program uniform variable specified by
  203. // its name to the values from the specified Vector3.
  204. // The specified name location is cached internally.
  205. func (prog *Program) SetUniformVector3ByName(name string, v *math32.Vector3) {
  206. prog.gs.Uniform3f(prog.GetUniformLocation(name), v.X, v.Y, v.Z)
  207. }
  208. // SetUniformVector4ByName sets this program uniform variable specified by
  209. // its name to the values from the specified Vector4.
  210. // The specified name location is cached internally.
  211. func (prog *Program) SetUniformVector4ByName(name string, v *math32.Vector4) {
  212. prog.gs.Uniform4f(prog.GetUniformLocation(name), v.X, v.Y, v.Z, v.W)
  213. }
  214. // SetUniformMatrix3ByName sets this program uniform variable specified by
  215. // its name with the values from the specified Matrix3.
  216. // The specified name location is cached internally.
  217. func (prog *Program) SetUniformMatrix3ByName(name string, m *math32.Matrix3) {
  218. prog.gs.UniformMatrix3fv(prog.GetUniformLocation(name), 1, false, &m[0])
  219. }
  220. // SetUniformMatrix4ByName sets this program uniform variable specified by
  221. // its name with the values from the specified Matrix4.
  222. // The location of the name is cached internally.
  223. func (prog *Program) SetUniformMatrix4ByName(name string, m *math32.Matrix4) {
  224. prog.gs.UniformMatrix4fv(prog.GetUniformLocation(name), 1, false, &m[0])
  225. }
  226. // SetUniformColorByName set this program uniform variable specified by
  227. // its name to the values from the specified Color
  228. // The specified name location is cached internally.
  229. func (prog *Program) SetUniformColorByName(name string, c *math32.Color) {
  230. prog.gs.Uniform3f(prog.GetUniformLocation(name), c.R, c.G, c.B)
  231. }
  232. // SetUniformColor4ByName set this program uniform variable specified by
  233. // its name to the values from the specified Color4
  234. // The specified name location is cached internally.
  235. func (prog *Program) SetUniformColor4ByName(name string, c *math32.Color4) {
  236. prog.gs.Uniform4f(prog.GetUniformLocation(name), c.R, c.G, c.B, c.A)
  237. }
  238. // CompileShader creates and compiles a shader of the specified type and with
  239. // the specified source code and returns a non-zero value by which
  240. // it can be referenced.
  241. func (prog *Program) CompileShader(stype uint32, source string) (uint32, error) {
  242. // Creates shader object
  243. shader := prog.gs.CreateShader(stype)
  244. if shader == 0 {
  245. return 0, fmt.Errorf("Error creating shader")
  246. }
  247. // Set shader source and compile it
  248. prog.gs.ShaderSource(shader, source)
  249. prog.gs.CompileShader(shader)
  250. // Get the shader compiler log
  251. slog := prog.gs.GetShaderInfoLog(shader)
  252. // Get the shader compile status
  253. var status int32
  254. prog.gs.GetShaderiv(shader, COMPILE_STATUS, &status)
  255. if status == FALSE {
  256. return shader, fmt.Errorf("%s", slog)
  257. }
  258. // If the shader compiled OK but the log has data,
  259. // logs this data instead of returning error
  260. if len(slog) > 2 {
  261. log.Warn("%s", slog)
  262. }
  263. return shader, nil
  264. }
  265. // FormatSource returns the supplied program source code with
  266. // line numbers prepended.
  267. func FormatSource(source string) string {
  268. // Reads all lines from the source string
  269. lines := make([]string, 0)
  270. buf := bytes.NewBuffer([]byte(source))
  271. for {
  272. line, err := buf.ReadBytes('\n')
  273. if err != nil {
  274. if err == io.EOF {
  275. break
  276. }
  277. panic(err)
  278. }
  279. lines = append(lines, string(line[:len(line)-1]))
  280. }
  281. // Adds a final line terminator
  282. lines = append(lines, "\n")
  283. // Prepends the line number for each line
  284. ndigits := len(strconv.Itoa(len(lines)))
  285. format := "%0" + strconv.Itoa(ndigits) + "d:%s"
  286. formatted := make([]string, 0)
  287. for pos, l := range lines {
  288. fline := fmt.Sprintf(format, pos+1, l)
  289. formatted = append(formatted, fline)
  290. }
  291. return strings.Join(formatted, "\n")
  292. }