renderer.go 17 KB

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