renderer.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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. _, err := r.shaman.SetProgram(&r.specs)
  231. if err != nil {
  232. return err
  233. }
  234. // Setup lights (transfer lights uniforms)
  235. for idx, l := range r.ambLights {
  236. l.RenderSetup(r.gs, &r.rinfo, idx)
  237. r.stats.Lights++
  238. }
  239. for idx, l := range r.dirLights {
  240. l.RenderSetup(r.gs, &r.rinfo, idx)
  241. r.stats.Lights++
  242. }
  243. for idx, l := range r.pointLights {
  244. l.RenderSetup(r.gs, &r.rinfo, idx)
  245. r.stats.Lights++
  246. }
  247. for idx, l := range r.spotLights {
  248. l.RenderSetup(r.gs, &r.rinfo, idx)
  249. r.stats.Lights++
  250. }
  251. // Render this graphic material
  252. grmat.Render(r.gs, &r.rinfo)
  253. r.stats.Graphics++
  254. }
  255. return nil
  256. }
  257. // renderGui renders the Gui
  258. func (r *Renderer) renderGui() error {
  259. // If no 3D scene was rendered sets Gui panels as renderable for background
  260. // User must define the colors
  261. if len(r.grmats) == 0 {
  262. r.panelGui.SetRenderable(true)
  263. if r.panel3D != nil {
  264. r.panel3D.SetRenderable(true)
  265. }
  266. } else {
  267. r.panelGui.SetRenderable(false)
  268. if r.panel3D != nil {
  269. r.panel3D.SetRenderable(false)
  270. }
  271. }
  272. // Clears list of panels to render
  273. r.panList = r.panList[0:0]
  274. // Redraw all GUI elements elements (panel3D == nil and 3D scene drawn)
  275. if r.redrawGui {
  276. r.appendPanel(r.panelGui)
  277. // Redraw GUI elements only if changed
  278. // Set the number of frame buffers to draw these changes
  279. } else if r.checkChanged(r.panelGui) {
  280. r.appendPanel(r.panelGui)
  281. r.frameCount = r.frameBuffers
  282. // No change, but need to update frame buffers
  283. } else if r.frameCount > 0 {
  284. r.appendPanel(r.panelGui)
  285. // No change, draw only panels over 3D if any
  286. } else {
  287. r.getPanelsOver3D()
  288. }
  289. if len(r.panList) == 0 {
  290. return nil
  291. }
  292. // Updates panels bounds and relative positions
  293. r.panelGui.GetPanel().UpdateMatrixWorld()
  294. // Disable the scissor test which could have been set by the 3D scene renderer
  295. // and then clear the depth buffer, so the panels will be rendered over the 3D scene.
  296. r.gs.Disable(gls.SCISSOR_TEST)
  297. r.gs.Clear(gls.DEPTH_BUFFER_BIT)
  298. // Render panels
  299. for i := 0; i < len(r.panList); i++ {
  300. err := r.renderPanel(r.panList[i])
  301. if err != nil {
  302. return err
  303. }
  304. }
  305. r.frameCount--
  306. r.rendered = true
  307. return nil
  308. }
  309. // getPanelsOver3D builds list of panels over 3D to be rendered
  310. func (r *Renderer) getPanelsOver3D() {
  311. // If panel3D not set or renderable, nothing to do
  312. if r.panel3D == nil || r.panel3D.Renderable() {
  313. return
  314. }
  315. // Internal recursive function to check if any child of the
  316. // specified panel is unbounded and over 3D.
  317. // If it is, it is inserted in the list of panels to render.
  318. var checkUnbounded func(pan *gui.Panel)
  319. checkUnbounded = func(pan *gui.Panel) {
  320. for i := 0; i < len(pan.Children()); i++ {
  321. child := pan.Children()[i].(gui.IPanel).GetPanel()
  322. if !child.Bounded() && r.checkPanelOver3D(child) {
  323. r.appendPanel(child)
  324. continue
  325. }
  326. checkUnbounded(child)
  327. }
  328. }
  329. // For all children of the Gui, checks if it is over the 3D panel
  330. children := r.panelGui.GetPanel().Children()
  331. for i := 0; i < len(children); i++ {
  332. pan := children[i].(gui.IPanel).GetPanel()
  333. if !pan.Visible() {
  334. continue
  335. }
  336. if r.checkPanelOver3D(pan) {
  337. r.appendPanel(pan)
  338. continue
  339. }
  340. // Current child is not over 3D but can have an unbounded child which is
  341. checkUnbounded(pan)
  342. }
  343. }
  344. // renderPanel renders the specified panel and all its children
  345. // and then sets the panel as not changed.
  346. func (r *Renderer) renderPanel(ipan gui.IPanel) error {
  347. // If panel not visible, ignore it and all its children
  348. pan := ipan.GetPanel()
  349. if !pan.Visible() {
  350. pan.SetChanged(false)
  351. return nil
  352. }
  353. // If panel is renderable, renders it
  354. if pan.Renderable() {
  355. // Sets shader program for the panel's material
  356. grmat := pan.GetGraphic().Materials()[0]
  357. mat := grmat.GetMaterial().GetMaterial()
  358. r.specs.Name = mat.Shader()
  359. r.specs.ShaderUnique = mat.ShaderUnique()
  360. _, err := r.shaman.SetProgram(&r.specs)
  361. if err != nil {
  362. return err
  363. }
  364. // Render this panel's graphic material
  365. grmat.Render(r.gs, &r.rinfo)
  366. r.stats.Panels++
  367. }
  368. pan.SetChanged(false)
  369. // Renders this panel children
  370. for i := 0; i < len(pan.Children()); i++ {
  371. err := r.renderPanel(pan.Children()[i].(gui.IPanel))
  372. if err != nil {
  373. return err
  374. }
  375. }
  376. return nil
  377. }
  378. // appendPanel appends the specified panel to the list of panels to render.
  379. // Currently there is no need to check for duplicates.
  380. func (r *Renderer) appendPanel(ipan gui.IPanel) {
  381. r.panList = append(r.panList, ipan)
  382. }
  383. // checkChanged checks if the specified panel or any of its children is changed
  384. func (r *Renderer) checkChanged(ipan gui.IPanel) bool {
  385. // Unbounded panels are checked even if not visible
  386. pan := ipan.GetPanel()
  387. if !pan.Bounded() && pan.Changed() {
  388. pan.SetChanged(false)
  389. return true
  390. }
  391. // Ignore invisible panel and its children
  392. if !pan.Visible() {
  393. return false
  394. }
  395. if pan.Changed() && pan.Renderable() {
  396. return true
  397. }
  398. for i := 0; i < len(pan.Children()); i++ {
  399. res := r.checkChanged(pan.Children()[i].(gui.IPanel))
  400. if res {
  401. return res
  402. }
  403. }
  404. return false
  405. }
  406. // checkPanelOver3D checks if the specified panel is over
  407. // the area where the 3D scene will be rendered.
  408. func (r *Renderer) checkPanelOver3D(ipan gui.IPanel) bool {
  409. pan := ipan.GetPanel()
  410. if !pan.Visible() {
  411. return false
  412. }
  413. if r.panel3D.GetPanel().Intersects(pan) {
  414. return true
  415. }
  416. return false
  417. }