shaman.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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 renderer
  5. import (
  6. "fmt"
  7. "regexp"
  8. "strconv"
  9. "strings"
  10. "github.com/g3n/engine/gls"
  11. "github.com/g3n/engine/material"
  12. "github.com/g3n/engine/renderer/shaders"
  13. )
  14. // Regular expression to parse #include <name> directive
  15. var rexInclude *regexp.Regexp
  16. func init() {
  17. rexInclude = regexp.MustCompile(`#include\s+<(.*)>`)
  18. }
  19. // ShaderSpecs describes the specification of a compiled shader program
  20. type ShaderSpecs struct {
  21. Name string // Shader name
  22. Version string // GLSL version
  23. ShaderUnique bool // indicates if shader is independent of lights and textures
  24. UseLights material.UseLights // Bitmask indicating which lights to consider
  25. AmbientLightsMax int // Current number of ambient lights
  26. DirLightsMax int // Current Number of directional lights
  27. PointLightsMax int // Current Number of point lights
  28. SpotLightsMax int // Current Number of spot lights
  29. MatTexturesMax int // Current Number of material textures
  30. Defines map[string]string // Additional shader defines
  31. }
  32. // ProgSpecs represents a compiled shader program along with its specs
  33. type ProgSpecs struct {
  34. program *gls.Program // program object
  35. specs ShaderSpecs // associated specs
  36. }
  37. // Shaman is the shader manager
  38. type Shaman struct {
  39. gs *gls.GLS
  40. includes map[string]string // include files sources
  41. shadersm map[string]string // maps shader name to its template
  42. proginfo map[string]shaders.ProgramInfo // maps name of the program to ProgramInfo
  43. programs []ProgSpecs // list of compiled programs with specs
  44. specs ShaderSpecs // Current shader specs
  45. }
  46. // NewShaman creates and returns a pointer to a new shader manager
  47. func NewShaman(gs *gls.GLS) *Shaman {
  48. sm := new(Shaman)
  49. sm.Init(gs)
  50. return sm
  51. }
  52. // Init initializes the shader manager
  53. func (sm *Shaman) Init(gs *gls.GLS) {
  54. sm.gs = gs
  55. sm.includes = make(map[string]string)
  56. sm.shadersm = make(map[string]string)
  57. sm.proginfo = make(map[string]shaders.ProgramInfo)
  58. }
  59. // AddDefaultShaders adds to this shader manager all default
  60. // include chunks, shaders and programs statically registered.
  61. func (sm *Shaman) AddDefaultShaders() error {
  62. for _, name := range shaders.Includes() {
  63. sm.AddChunk(name, shaders.IncludeSource(name))
  64. }
  65. for _, name := range shaders.Shaders() {
  66. sm.AddShader(name, shaders.ShaderSource(name))
  67. }
  68. for _, name := range shaders.Programs() {
  69. sm.proginfo[name] = shaders.GetProgramInfo(name)
  70. }
  71. return nil
  72. }
  73. // AddChunk adds a shader chunk with the specified name and source code
  74. func (sm *Shaman) AddChunk(name, source string) {
  75. sm.includes[name] = source
  76. }
  77. // AddShader adds a shader program with the specified name and source code
  78. func (sm *Shaman) AddShader(name, source string) {
  79. sm.shadersm[name] = source
  80. }
  81. // AddProgram adds a program with the specified name and associated vertex
  82. // and fragment shaders names (previously registered)
  83. func (sm *Shaman) AddProgram(name, vertexName, fragName string, others ...string) {
  84. geomName := ""
  85. if len(others) > 0 {
  86. geomName = others[0]
  87. }
  88. sm.proginfo[name] = shaders.ProgramInfo{
  89. Vertex: vertexName,
  90. Fragment: fragName,
  91. Geometry: geomName,
  92. }
  93. }
  94. // SetProgram set the shader program to satisfy the specified specs.
  95. // Returns an indication if the current shader has changed and a possible error
  96. // when creating a new shader program.
  97. // Receives a copy of the specs because it changes the fields which specify the
  98. // number of lights depending on the UseLights flags.
  99. func (sm *Shaman) SetProgram(s *ShaderSpecs) (bool, error) {
  100. // Checks material use lights bit mask
  101. var specs ShaderSpecs
  102. specs.copy(s)
  103. if (specs.UseLights & material.UseLightAmbient) == 0 {
  104. specs.AmbientLightsMax = 0
  105. }
  106. if (specs.UseLights & material.UseLightDirectional) == 0 {
  107. specs.DirLightsMax = 0
  108. }
  109. if (specs.UseLights & material.UseLightPoint) == 0 {
  110. specs.PointLightsMax = 0
  111. }
  112. if (specs.UseLights & material.UseLightSpot) == 0 {
  113. specs.SpotLightsMax = 0
  114. }
  115. // If current shader specs are the same as the specified specs, nothing to do.
  116. if sm.specs.compare(&specs) {
  117. return false, nil
  118. }
  119. // Search for compiled program with the specified specs
  120. for _, pinfo := range sm.programs {
  121. if pinfo.specs.compare(&specs) {
  122. sm.gs.UseProgram(pinfo.program)
  123. sm.specs = specs
  124. return true, nil
  125. }
  126. }
  127. // Generates new program with the specified specs
  128. prog, err := sm.GenProgram(&specs)
  129. if err != nil {
  130. return false, err
  131. }
  132. log.Debug("Created new shader:%v", specs.Name)
  133. // Save specs as current specs, adds new program to the list and activates the program
  134. sm.specs = specs
  135. sm.programs = append(sm.programs, ProgSpecs{prog, specs})
  136. sm.gs.UseProgram(prog)
  137. return true, nil
  138. }
  139. // GenProgram generates shader program from the specified specs
  140. func (sm *Shaman) GenProgram(specs *ShaderSpecs) (*gls.Program, error) {
  141. // Get info for the specified shader program
  142. progInfo, ok := sm.proginfo[specs.Name]
  143. if !ok {
  144. return nil, fmt.Errorf("Program:%s not found", specs.Name)
  145. }
  146. // Sets the defines map
  147. defines := map[string]string{}
  148. defines["GLSL_VERSION"] = "330 core"
  149. defines["AMB_LIGHTS"] = strconv.FormatUint(uint64(specs.AmbientLightsMax), 10)
  150. defines["DIR_LIGHTS"] = strconv.FormatUint(uint64(specs.DirLightsMax), 10)
  151. defines["POINT_LIGHTS"] = strconv.FormatUint(uint64(specs.PointLightsMax), 10)
  152. defines["SPOT_LIGHTS"] = strconv.FormatUint(uint64(specs.SpotLightsMax), 10)
  153. defines["MAT_TEXTURES"] = strconv.FormatUint(uint64(specs.MatTexturesMax), 10)
  154. // Adds additional material defines from the specs parameter
  155. for name, value := range specs.Defines {
  156. defines[name] = value
  157. }
  158. // Get vertex shader source
  159. vertexSource, ok := sm.shadersm[progInfo.Vertex]
  160. if !ok {
  161. return nil, fmt.Errorf("Vertex shader:%s not found", progInfo.Vertex)
  162. }
  163. // Preprocess vertex shader source
  164. vertexSource, err := sm.preprocess(vertexSource, defines)
  165. if err != nil {
  166. return nil, err
  167. }
  168. //fmt.Printf("vertexSource:%s\n", vertexSource)
  169. // Get fragment shader source
  170. fragSource, ok := sm.shadersm[progInfo.Fragment]
  171. if err != nil {
  172. return nil, fmt.Errorf("Fragment shader:%s not found", progInfo.Fragment)
  173. }
  174. // Preprocess fragment shader source
  175. fragSource, err = sm.preprocess(fragSource, defines)
  176. if err != nil {
  177. return nil, err
  178. }
  179. //fmt.Printf("fragSource:%s\n", fragSource)
  180. // Checks for optional geometry shader compiled template
  181. var geomSource = ""
  182. if progInfo.Geometry != "" {
  183. // Get geometry shader source
  184. geomSource, ok = sm.shadersm[progInfo.Geometry]
  185. if !ok {
  186. return nil, fmt.Errorf("Geometry shader:%s not found", progInfo.Geometry)
  187. }
  188. // Preprocess geometry shader source
  189. geomSource, err = sm.preprocess(geomSource, defines)
  190. if err != nil {
  191. return nil, err
  192. }
  193. }
  194. // Creates shader program
  195. prog := sm.gs.NewProgram()
  196. prog.AddShader(gls.VERTEX_SHADER, vertexSource, nil)
  197. prog.AddShader(gls.FRAGMENT_SHADER, fragSource, nil)
  198. if progInfo.Geometry != "" {
  199. prog.AddShader(gls.GEOMETRY_SHADER, geomSource, nil)
  200. }
  201. err = prog.Build()
  202. if err != nil {
  203. return nil, err
  204. }
  205. return prog, nil
  206. }
  207. // preprocess preprocesses the specified source prefixing it with optional defines directives
  208. // contained in "defines" parameter and replaces '#include <name>' directives
  209. // by the respective source code of include chunk of the specified name.
  210. // The included "files" are also processed recursively.
  211. func (sm *Shaman) preprocess(source string, defines map[string]string) (string, error) {
  212. // If defines map supplied, generates prefix with glsl version directive first,
  213. // followed by "#define directives"
  214. var prefix = ""
  215. if defines != nil {
  216. prefix = fmt.Sprintf("#version %s\n", defines["GLSL_VERSION"])
  217. for name, value := range defines {
  218. if name == "GLSL_VERSION" {
  219. continue
  220. }
  221. prefix = prefix + fmt.Sprintf("#define %s %s\n", name, value)
  222. }
  223. }
  224. // Find all string submatches for the "#include <name>" directive
  225. matches := rexInclude.FindAllStringSubmatch(source, 100)
  226. if len(matches) == 0 {
  227. return prefix + source, nil
  228. }
  229. // For each directive found, replace the name by the respective include chunk source code
  230. var newSource = source
  231. for _, m := range matches {
  232. // Get the source of the include chunk with the match <name>
  233. incSource := sm.includes[m[1]]
  234. if len(incSource) == 0 {
  235. return "", fmt.Errorf("Include:[%s] not found", m[1])
  236. }
  237. // Preprocess the include chunk source code
  238. incSource, err := sm.preprocess(incSource, nil)
  239. if err != nil {
  240. return "", err
  241. }
  242. // Replace all occurrences of the include directive with its processed source code
  243. newSource = strings.Replace(newSource, m[0], incSource, -1)
  244. }
  245. return prefix + newSource, nil
  246. }
  247. // copy copies other spec into this
  248. func (ss *ShaderSpecs) copy(other *ShaderSpecs) {
  249. *ss = *other
  250. if other.Defines != nil {
  251. ss.Defines = make(map[string]string)
  252. for k, v := range other.Defines {
  253. ss.Defines[k] = v
  254. }
  255. }
  256. }
  257. // Compare compares two shaders specifications structures
  258. func (ss *ShaderSpecs) compare(other *ShaderSpecs) bool {
  259. if ss.Name != other.Name {
  260. return false
  261. }
  262. if other.ShaderUnique {
  263. return true
  264. }
  265. if ss.AmbientLightsMax == other.AmbientLightsMax &&
  266. ss.DirLightsMax == other.DirLightsMax &&
  267. ss.PointLightsMax == other.PointLightsMax &&
  268. ss.SpotLightsMax == other.SpotLightsMax &&
  269. ss.MatTexturesMax == other.MatTexturesMax &&
  270. ss.compareDefines(other) {
  271. return true
  272. }
  273. return false
  274. }
  275. // compareDefines compares two shaders specification define maps.
  276. func (ss *ShaderSpecs) compareDefines(other *ShaderSpecs) bool {
  277. if ss.Defines == nil && other.Defines == nil {
  278. return true
  279. }
  280. if ss.Defines != nil && other.Defines != nil {
  281. if len(ss.Defines) != len(other.Defines) {
  282. return false
  283. }
  284. for k, _ := range ss.Defines {
  285. v1, ok1 := ss.Defines[k]
  286. v2, ok2 := other.Defines[k]
  287. if v1 != v2 || ok1 != ok2 {
  288. return false
  289. }
  290. }
  291. return true
  292. }
  293. // One is nil and the other is not nil
  294. return false
  295. }