renderer.go 14 KB

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