renderer.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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. "github.com/g3n/engine/camera"
  7. "github.com/g3n/engine/core"
  8. "github.com/g3n/engine/gls"
  9. "github.com/g3n/engine/graphic"
  10. "github.com/g3n/engine/gui"
  11. "github.com/g3n/engine/light"
  12. )
  13. // Renderer renders a 3D scene and/or a 2D GUI on the current window.
  14. type Renderer struct {
  15. gs *gls.GLS
  16. shaman Shaman // Internal shader manager
  17. stats Stats // Renderer statistics
  18. scene core.INode // Node containing 3D scene to render
  19. panelGui gui.IPanel // Panel containing GUI to render
  20. panel3D gui.IPanel // Panel which contains the 3D scene
  21. ambLights []*light.Ambient // Array of ambient lights for last scene
  22. dirLights []*light.Directional // Array of directional lights for last scene
  23. pointLights []*light.Point // Array of point
  24. spotLights []*light.Spot // Array of spot lights for the scene
  25. others []core.INode // Other nodes (audio, players, etc)
  26. grmats []*graphic.GraphicMaterial // Array of all graphic materials for scene
  27. rinfo core.RenderInfo // Preallocated Render info
  28. specs ShaderSpecs // Preallocated Shader specs
  29. redrawGui bool // Flag indicating the gui must be redrawn completely
  30. rendered bool // Flag indicating if anything was rendered
  31. panList []gui.IPanel // list of panels to render
  32. frameBuffers int // Number of frame buffers
  33. frameCount int // Current number of frames to write
  34. }
  35. // Stats describes how many object types were rendered
  36. // It is cleared at the start of each render
  37. type Stats struct {
  38. Graphics int // Number of graphic objects rendered
  39. Lights int // Number of lights rendered
  40. Panels int // Number of Gui panels rendered
  41. Others int // Number of other objects rendered
  42. }
  43. // NewRenderer creates and returns a pointer to a new Renderer
  44. func NewRenderer(gs *gls.GLS) *Renderer {
  45. r := new(Renderer)
  46. r.gs = gs
  47. r.shaman.Init(gs)
  48. r.ambLights = make([]*light.Ambient, 0)
  49. r.dirLights = make([]*light.Directional, 0)
  50. r.pointLights = make([]*light.Point, 0)
  51. r.spotLights = make([]*light.Spot, 0)
  52. r.others = make([]core.INode, 0)
  53. r.grmats = make([]*graphic.GraphicMaterial, 0)
  54. r.panList = make([]gui.IPanel, 0)
  55. r.frameBuffers = 2
  56. return r
  57. }
  58. // AddDefaultShaders adds to this renderer's shader manager all default
  59. // include chunks, shaders and programs statically registered.
  60. func (r *Renderer) AddDefaultShaders() error {
  61. return r.shaman.AddDefaultShaders()
  62. }
  63. // AddChunk adds a shader chunk with the specified name and source code
  64. func (r *Renderer) AddChunk(name, source string) {
  65. r.shaman.AddChunk(name, source)
  66. }
  67. // AddShader adds a shader program with the specified name and source code
  68. func (r *Renderer) AddShader(name, source string) {
  69. r.shaman.AddShader(name, source)
  70. }
  71. // AddProgram adds a program with the specified name and associated vertex
  72. // and fragment shaders names (previously registered)
  73. func (r *Renderer) AddProgram(name, vertex, frag string, others ...string) {
  74. r.shaman.AddProgram(name, vertex, frag, others...)
  75. }
  76. // SetGui sets the gui panel which contains the Gui to render.
  77. // If set to nil, no Gui will be rendered
  78. func (r *Renderer) SetGui(gui gui.IPanel) {
  79. r.panelGui = gui
  80. }
  81. // SetGuiPanel3D sets the gui panel inside which the 3D scene is shown.
  82. // This informs the renderer that the Gui elements over this panel
  83. // must be redrawn even if they didn't change.
  84. // This panel panel must not be renderable, otherwise it will cover the 3D scene.
  85. func (r *Renderer) SetGuiPanel3D(panel3D gui.IPanel) {
  86. r.panel3D = panel3D
  87. }
  88. // Panel3D returns the current gui panel over the 3D scene
  89. func (r *Renderer) Panel3D() gui.IPanel {
  90. return r.panel3D
  91. }
  92. // SetScene sets the 3D scene to render
  93. // If set to nil, no 3D scene will be rendered
  94. func (r *Renderer) SetScene(scene core.INode) {
  95. r.scene = scene
  96. }
  97. // Returns statistics
  98. func (r *Renderer) Stats() Stats {
  99. return r.stats
  100. }
  101. // Render renders the previously set Scene and Gui using the specified camera
  102. // Returns an indication if anything was rendered and an error
  103. func (r *Renderer) Render(icam camera.ICamera) (bool, error) {
  104. r.redrawGui = false
  105. r.rendered = false
  106. r.stats = Stats{}
  107. // Renders the 3D scene
  108. if r.scene != nil {
  109. err := r.renderScene(r.scene, icam)
  110. if err != nil {
  111. return r.rendered, err
  112. }
  113. }
  114. // Renders the Gui over the 3D scene
  115. if r.panelGui != nil {
  116. err := r.renderGui()
  117. if err != nil {
  118. return r.rendered, err
  119. }
  120. }
  121. return r.rendered, nil
  122. }
  123. // renderScene renders the 3D scene using the specified camera
  124. func (r *Renderer) renderScene(iscene core.INode, icam camera.ICamera) error {
  125. // Updates world matrices of all scene nodes
  126. iscene.UpdateMatrixWorld()
  127. scene := iscene.GetNode()
  128. // Builds RenderInfo calls RenderSetup for all visible nodes
  129. icam.ViewMatrix(&r.rinfo.ViewMatrix)
  130. icam.ProjMatrix(&r.rinfo.ProjMatrix)
  131. // Clear scene arrays
  132. r.ambLights = r.ambLights[0:0]
  133. r.dirLights = r.dirLights[0:0]
  134. r.pointLights = r.pointLights[0:0]
  135. r.spotLights = r.spotLights[0:0]
  136. r.others = r.others[0:0]
  137. r.grmats = r.grmats[0:0]
  138. // Internal function to classify a node and its children
  139. var classifyNode func(inode core.INode)
  140. classifyNode = func(inode core.INode) {
  141. // If node not visible, ignore
  142. node := inode.GetNode()
  143. if !node.Visible() {
  144. return
  145. }
  146. // Checks if node is a Graphic
  147. igr, ok := inode.(graphic.IGraphic)
  148. if ok {
  149. if igr.Renderable() {
  150. // Appends to list each graphic material for this graphic
  151. gr := igr.GetGraphic()
  152. materials := gr.Materials()
  153. for i := 0; i < len(materials); i++ {
  154. r.grmats = append(r.grmats, &materials[i])
  155. }
  156. }
  157. // Node is not a Graphic
  158. } else {
  159. // Checks if node is a Light
  160. il, ok := inode.(light.ILight)
  161. if ok {
  162. switch l := il.(type) {
  163. case *light.Ambient:
  164. r.ambLights = append(r.ambLights, l)
  165. case *light.Directional:
  166. r.dirLights = append(r.dirLights, l)
  167. case *light.Point:
  168. r.pointLights = append(r.pointLights, l)
  169. case *light.Spot:
  170. r.spotLights = append(r.spotLights, l)
  171. default:
  172. panic("Invalid light type")
  173. }
  174. // Other nodes
  175. } else {
  176. r.others = append(r.others, inode)
  177. }
  178. }
  179. // Classify node children
  180. for _, ichild := range node.Children() {
  181. classifyNode(ichild)
  182. }
  183. }
  184. // Classify all scene nodes
  185. classifyNode(scene)
  186. // Sets lights count in shader specs
  187. r.specs.AmbientLightsMax = len(r.ambLights)
  188. r.specs.DirLightsMax = len(r.dirLights)
  189. r.specs.PointLightsMax = len(r.pointLights)
  190. r.specs.SpotLightsMax = len(r.spotLights)
  191. // Render other nodes (audio players, etc)
  192. for i := 0; i < len(r.others); i++ {
  193. inode := r.others[i]
  194. if !inode.GetNode().Visible() {
  195. continue
  196. }
  197. r.others[i].Render(r.gs)
  198. r.stats.Others++
  199. }
  200. // If there is graphic material to render
  201. if len(r.grmats) > 0 {
  202. // If the 3D scene to draw is to be confined to user specified panel
  203. // sets scissor to avoid erasing gui elements outside of this panel
  204. if r.panel3D != nil {
  205. pos := r.panel3D.GetPanel().Pospix()
  206. width, height := r.panel3D.GetPanel().Size()
  207. _, _, _, viewheight := r.gs.GetViewport()
  208. r.gs.Enable(gls.SCISSOR_TEST)
  209. r.gs.Scissor(int32(pos.X), viewheight-int32(pos.Y)-int32(height), uint32(width), uint32(height))
  210. } else {
  211. r.gs.Disable(gls.SCISSOR_TEST)
  212. r.redrawGui = true
  213. }
  214. // Clears the area inside the current scissor
  215. r.gs.Clear(gls.DEPTH_BUFFER_BIT | gls.STENCIL_BUFFER_BIT | gls.COLOR_BUFFER_BIT)
  216. r.rendered = true
  217. }
  218. // For each *GraphicMaterial
  219. for _, grmat := range r.grmats {
  220. mat := grmat.GetMaterial().GetMaterial()
  221. // Sets the shader specs for this material and sets shader program
  222. r.specs.Name = mat.Shader()
  223. r.specs.ShaderUnique = mat.ShaderUnique()
  224. r.specs.UseLights = mat.UseLights()
  225. r.specs.MatTexturesMax = mat.TextureCount()
  226. _, err := r.shaman.SetProgram(&r.specs)
  227. if err != nil {
  228. return err
  229. }
  230. // Setup lights (transfer lights uniforms)
  231. for idx, l := range r.ambLights {
  232. l.RenderSetup(r.gs, &r.rinfo, idx)
  233. r.stats.Lights++
  234. }
  235. for idx, l := range r.dirLights {
  236. l.RenderSetup(r.gs, &r.rinfo, idx)
  237. r.stats.Lights++
  238. }
  239. for idx, l := range r.pointLights {
  240. l.RenderSetup(r.gs, &r.rinfo, idx)
  241. r.stats.Lights++
  242. }
  243. for idx, l := range r.spotLights {
  244. l.RenderSetup(r.gs, &r.rinfo, idx)
  245. r.stats.Lights++
  246. }
  247. // Render this graphic material
  248. grmat.Render(r.gs, &r.rinfo)
  249. r.stats.Graphics++
  250. }
  251. return nil
  252. }
  253. // renderGui renders the Gui
  254. func (r *Renderer) renderGui() error {
  255. // If no 3D scene was rendered sets Gui panels as renderable for background
  256. // User must define the colors
  257. if len(r.grmats) == 0 {
  258. r.panelGui.SetRenderable(true)
  259. if r.panel3D != nil {
  260. r.panel3D.SetRenderable(true)
  261. }
  262. } else {
  263. r.panelGui.SetRenderable(false)
  264. if r.panel3D != nil {
  265. r.panel3D.SetRenderable(false)
  266. }
  267. }
  268. // Clears list of panels to render
  269. r.panList = r.panList[0:0]
  270. // Redraw all GUI elements elements (panel3D == nil and 3D scene drawn)
  271. if r.redrawGui {
  272. r.appendPanel(r.panelGui)
  273. // Redraw GUI elements only if changed
  274. // Set the number of frame buffers to draw these changes
  275. } else if r.checkChanged(r.panelGui) {
  276. r.appendPanel(r.panelGui)
  277. r.frameCount = r.frameBuffers
  278. // No change, but need to update frame buffers
  279. } else if r.frameCount > 0 {
  280. r.appendPanel(r.panelGui)
  281. // No change, draw only panels over 3D
  282. } else {
  283. r.getPanelsOver3D()
  284. }
  285. // If there are panels to render
  286. if len(r.panList) > 0 {
  287. // Updates panels bounds and relative positions
  288. r.panelGui.GetPanel().UpdateMatrixWorld()
  289. // Disable the scissor test which could have been set by the 3D scene renderer
  290. // and then clear the depth buffer, so the panels will be rendered over the 3D scene.
  291. r.gs.Disable(gls.SCISSOR_TEST)
  292. r.gs.Clear(gls.DEPTH_BUFFER_BIT)
  293. r.frameCount--
  294. r.rendered = true
  295. }
  296. // Render panels
  297. for i := 0; i < len(r.panList); i++ {
  298. err := r.renderPanel(r.panList[i])
  299. if err != nil {
  300. return err
  301. }
  302. }
  303. return nil
  304. }
  305. // getPanelsOver3D builds list of panels over 3D to be rendered
  306. func (r *Renderer) getPanelsOver3D() {
  307. // If panel3D not set or renderable, nothing to do
  308. if r.panel3D == nil || r.panel3D.Renderable() {
  309. return
  310. }
  311. // Internal recursive function to check if any child of the
  312. // specified panel is unbounded and over 3D.
  313. // If it is, it is inserted in the list of panels to render.
  314. var checkUnbounded func(pan *gui.Panel)
  315. checkUnbounded = func(pan *gui.Panel) {
  316. for i := 0; i < len(pan.Children()); i++ {
  317. child := pan.Children()[i].(gui.IPanel).GetPanel()
  318. if !child.Bounded() && r.checkPanelOver3D(child) {
  319. r.appendPanel(child)
  320. continue
  321. }
  322. checkUnbounded(child)
  323. }
  324. }
  325. // For all children of the Gui, checks if it is over the 3D panel
  326. children := r.panelGui.GetPanel().Children()
  327. for i := 0; i < len(children); i++ {
  328. pan := children[i].(gui.IPanel).GetPanel()
  329. if !pan.Visible() {
  330. continue
  331. }
  332. if r.checkPanelOver3D(pan) {
  333. r.appendPanel(pan)
  334. continue
  335. }
  336. // Current child is not over 3D but can have an unbounded child which is
  337. checkUnbounded(pan)
  338. }
  339. }
  340. // renderPanel renders the specified panel and all its children
  341. // and then sets the panel as not changed.
  342. func (r *Renderer) renderPanel(ipan gui.IPanel) error {
  343. // If panel not visible, ignore it and all its children
  344. pan := ipan.GetPanel()
  345. if !pan.Visible() {
  346. pan.SetChanged(false)
  347. return nil
  348. }
  349. // If panel is renderable, renders it
  350. if pan.Renderable() {
  351. // Sets shader program for the panel's material
  352. grmat := pan.GetGraphic().Materials()[0]
  353. mat := grmat.GetMaterial().GetMaterial()
  354. r.specs.Name = mat.Shader()
  355. r.specs.ShaderUnique = mat.ShaderUnique()
  356. _, err := r.shaman.SetProgram(&r.specs)
  357. if err != nil {
  358. return err
  359. }
  360. // Render this panel's graphic material
  361. grmat.Render(r.gs, &r.rinfo)
  362. r.stats.Panels++
  363. }
  364. pan.SetChanged(false)
  365. // Renders this panel children
  366. for i := 0; i < len(pan.Children()); i++ {
  367. err := r.renderPanel(pan.Children()[i].(gui.IPanel))
  368. if err != nil {
  369. return err
  370. }
  371. }
  372. return nil
  373. }
  374. // appendPanel appends the specified panel to the list of panels to render.
  375. // Currently there is no need to check for duplicates.
  376. func (r *Renderer) appendPanel(ipan gui.IPanel) {
  377. r.panList = append(r.panList, ipan)
  378. }
  379. // checkChanged checks if the specified panel or any of its children is changed
  380. func (r *Renderer) checkChanged(ipan gui.IPanel) bool {
  381. // Unbounded panels are checked even if not visible
  382. pan := ipan.GetPanel()
  383. if !pan.Bounded() && pan.Changed() {
  384. pan.SetChanged(false)
  385. return true
  386. }
  387. // Ignore invisible panel and its children
  388. if !pan.Visible() {
  389. return false
  390. }
  391. if pan.Changed() && pan.Renderable() {
  392. return true
  393. }
  394. for i := 0; i < len(pan.Children()); i++ {
  395. res := r.checkChanged(pan.Children()[i].(gui.IPanel))
  396. if res {
  397. return res
  398. }
  399. }
  400. return false
  401. }
  402. // checkPanelOver3D checks if the specified panel is over
  403. // the area where the 3D scene will be rendered.
  404. func (r *Renderer) checkPanelOver3D(ipan gui.IPanel) bool {
  405. pan := ipan.GetPanel()
  406. if !pan.Visible() {
  407. return false
  408. }
  409. if r.panel3D.GetPanel().Intersects(pan) {
  410. return true
  411. }
  412. return false
  413. }