renderer.go 14 KB

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