application.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. package application
  2. import (
  3. "flag"
  4. "fmt"
  5. "os"
  6. "runtime"
  7. "runtime/pprof"
  8. "runtime/trace"
  9. "time"
  10. "github.com/g3n/engine/audio/al"
  11. "github.com/g3n/engine/audio/ov"
  12. "github.com/g3n/engine/audio/vorbis"
  13. "github.com/g3n/engine/camera"
  14. "github.com/g3n/engine/camera/control"
  15. "github.com/g3n/engine/core"
  16. "github.com/g3n/engine/gls"
  17. "github.com/g3n/engine/gui"
  18. "github.com/g3n/engine/math32"
  19. "github.com/g3n/engine/renderer"
  20. "github.com/g3n/engine/util/logger"
  21. "github.com/g3n/engine/window"
  22. )
  23. // Application is a standard application object which can be used as a base for G3N applications.
  24. // It creates a Window, OpenGL state, default cameras, default scene and Gui and has a method to run the render loop.
  25. type Application struct {
  26. core.Dispatcher // Embedded event dispatcher
  27. core.TimerManager // Embedded timer manager
  28. wmgr window.IWindowManager // Window manager
  29. win window.IWindow // Application window
  30. gl *gls.GLS // OpenGL state
  31. log *logger.Logger // Default application logger
  32. renderer *renderer.Renderer // Renderer object
  33. camPersp *camera.Perspective // Perspective camera
  34. camOrtho *camera.Orthographic // Orthographic camera
  35. camera camera.ICamera // Current camera
  36. orbit *control.OrbitControl // Camera orbit controller
  37. audio bool // Audio available
  38. vorbis bool // Vorbis decoder available
  39. audioEFX bool // Audio effect extension support available
  40. audioDev *al.Device // Audio player device
  41. captureDev *al.Device // Audio capture device
  42. frameRater *FrameRater // Render loop frame rater
  43. scene *core.Node // Node container for 3D tests
  44. guiroot *gui.Root // Gui root panel
  45. frameCount uint64 // Frame counter
  46. frameTime time.Time // Time at the start of the frame
  47. frameDelta time.Duration // Time delta from previous frame
  48. startTime time.Time // Time at the start of the render loop
  49. fullScreen *bool // Full screen option
  50. swapInterval *int // Swap interval option
  51. targetFPS *uint // Target FPS option
  52. noglErrors *bool // No OpenGL check errors options
  53. cpuProfile *string // File to write cpu profile to
  54. execTrace *string // File to write execution trace data to
  55. }
  56. // Options defines initial options passed to the application creation function
  57. type Options struct {
  58. Height int // Initial window height (default is screen width)
  59. Width int // Initial window width (default is screen height)
  60. Fullscreen bool // Window full screen flag (default = false)
  61. LogLevel int // Initial log level (default = DEBUG)
  62. EnableFlags bool // Enable command line flags (default = false)
  63. TargetFPS uint // Desired frames per second rate (default = 60)
  64. }
  65. // OnBeforeRender is the event generated by Application just before rendering the scene/gui
  66. const OnBeforeRender = "util.application.OnBeforeRender"
  67. // OnAfterRender is the event generated by Application just after rendering the scene/gui
  68. const OnAfterRender = "util.application.OnAfterRender"
  69. // appInstance contains the pointer to the single Application instance
  70. var appInstance *Application
  71. // Create creates and returns the application object using the specified name for
  72. // the window title and log messages
  73. // This function must be called only once.
  74. func Create(name string, ops Options) (*Application, error) {
  75. if appInstance != nil {
  76. return nil, fmt.Errorf("Application already created")
  77. }
  78. app := new(Application)
  79. appInstance = app
  80. app.Dispatcher.Initialize()
  81. app.TimerManager.Initialize()
  82. // Initialize options defaults
  83. app.fullScreen = new(bool)
  84. app.cpuProfile = new(string)
  85. app.swapInterval = new(int)
  86. *app.swapInterval = -1
  87. app.targetFPS = new(uint)
  88. *app.targetFPS = 60
  89. app.noglErrors = new(bool)
  90. // Options parameter overrides some options
  91. if ops.TargetFPS != 0 {
  92. *app.fullScreen = ops.Fullscreen
  93. *app.targetFPS = ops.TargetFPS
  94. }
  95. // Creates flags if requested (override options defaults)
  96. if ops.EnableFlags {
  97. app.fullScreen = flag.Bool("fullscreen", false, "Stars application with full screen")
  98. app.swapInterval = flag.Int("swapinterval", -1, "Sets the swap buffers interval to this value")
  99. app.targetFPS = flag.Uint("targetfps", 60, "Sets the frame rate in frames per second")
  100. app.noglErrors = flag.Bool("noglerrors", false, "Do not check OpenGL errors at each call (may increase FPS)")
  101. app.cpuProfile = flag.String("cpuprofile", "", "Activate cpu profiling writing profile to the specified file")
  102. app.execTrace = flag.String("exectrace", "", "Activate execution tracer writing data to the specified file")
  103. }
  104. flag.Parse()
  105. // Creates application logger
  106. app.log = logger.New(name, nil)
  107. app.log.AddWriter(logger.NewConsole(false))
  108. app.log.SetFormat(logger.FTIME | logger.FMICROS)
  109. app.log.SetLevel(ops.LogLevel)
  110. // Window event handling must run on the main OS thread
  111. runtime.LockOSThread()
  112. // Get the window manager
  113. wmgr, err := window.Manager("glfw")
  114. if err != nil {
  115. return nil, err
  116. }
  117. app.wmgr = wmgr
  118. // Get the screen resolution
  119. swidth, sheight := app.wmgr.ScreenResolution(nil)
  120. var posx, posy int
  121. // If not full screen, sets the window size
  122. if !*app.fullScreen {
  123. if ops.Width != 0 {
  124. posx = (swidth - ops.Width) / 2
  125. if posx < 0 {
  126. posx = 0
  127. }
  128. swidth = ops.Width
  129. }
  130. if ops.Height != 0 {
  131. posy = (sheight - ops.Height) / 2
  132. if posy < 0 {
  133. posy = 0
  134. }
  135. sheight = ops.Height
  136. }
  137. }
  138. // Creates window
  139. win, err := app.wmgr.CreateWindow(swidth, sheight, name, *app.fullScreen)
  140. if err != nil {
  141. return nil, err
  142. }
  143. win.SetPos(posx, posy)
  144. app.win = win
  145. // Create OpenGL state
  146. gl, err := gls.New()
  147. if err != nil {
  148. return nil, err
  149. }
  150. app.gl = gl
  151. // Checks OpenGL errors
  152. app.gl.SetCheckErrors(!*app.noglErrors)
  153. cc := math32.NewColor("gray")
  154. app.gl.ClearColor(cc.R, cc.G, cc.B, 1)
  155. app.gl.Clear(gls.DEPTH_BUFFER_BIT | gls.STENCIL_BUFFER_BIT | gls.COLOR_BUFFER_BIT)
  156. // Creates perspective camera
  157. width, height := app.win.Size()
  158. aspect := float32(width) / float32(height)
  159. app.camPersp = camera.NewPerspective(65, aspect, 0.01, 1000)
  160. // Creates orthographic camera
  161. app.camOrtho = camera.NewOrthographic(-2, 2, 2, -2, 0.01, 100)
  162. app.camOrtho.SetPosition(0, 0, 3)
  163. app.camOrtho.LookAt(&math32.Vector3{0, 0, 0})
  164. app.camOrtho.SetZoom(1.0)
  165. // Default camera is perspective
  166. app.camera = app.camPersp
  167. // Creates orbit camera control
  168. // It is important to do this after the root panel subscription
  169. // to avoid GUI events being propagated to the orbit control.
  170. app.orbit = control.NewOrbitControl(app.camera, app.win)
  171. // Creates scene for 3D objects
  172. app.scene = core.NewNode()
  173. // Creates gui root panel
  174. app.guiroot = gui.NewRoot(app.gl, app.win)
  175. app.guiroot.SetColor(math32.NewColor("silver"))
  176. // Creates renderer
  177. app.renderer = renderer.NewRenderer(gl)
  178. err = app.renderer.AddDefaultShaders()
  179. if err != nil {
  180. return nil, fmt.Errorf("Error from AddDefaulShaders:%v", err)
  181. }
  182. app.renderer.SetScene(app.scene)
  183. app.renderer.SetGui(app.guiroot)
  184. // Create frame rater
  185. app.frameRater = NewFrameRater(*app.targetFPS)
  186. // Sets the default window resize event handler
  187. app.win.SubscribeID(window.OnWindowSize, app, func(evname string, ev interface{}) {
  188. app.OnWindowResize()
  189. })
  190. app.OnWindowResize()
  191. return app, nil
  192. }
  193. // Get returns the application single instance or nil
  194. // if the application was not created yet
  195. func Get() *Application {
  196. return appInstance
  197. }
  198. // Log returns the application logger
  199. func (app *Application) Log() *logger.Logger {
  200. return app.log
  201. }
  202. // Window returns the application window
  203. func (app *Application) Window() window.IWindow {
  204. return app.win
  205. }
  206. // Gl returns the OpenGL state
  207. func (app *Application) Gl() *gls.GLS {
  208. return app.gl
  209. }
  210. // Gui returns the current application Gui root panel
  211. func (app *Application) Gui() *gui.Root {
  212. return app.guiroot
  213. }
  214. // Scene returns the current application 3D scene
  215. func (app *Application) Scene() *core.Node {
  216. return app.scene
  217. }
  218. // SetScene sets the 3D scene to be rendered
  219. func (app *Application) SetScene(scene *core.Node) {
  220. app.renderer.SetScene(scene)
  221. }
  222. // SetGui sets the root panel of the gui to be rendered
  223. func (app *Application) SetGui(root *gui.Root) {
  224. app.guiroot = root
  225. app.renderer.SetGui(app.guiroot)
  226. }
  227. // SetPanel3D sets the gui panel inside which the 3D scene is shown.
  228. func (app *Application) SetPanel3D(panel3D gui.IPanel) {
  229. app.renderer.SetGuiPanel3D(panel3D)
  230. }
  231. // Panel3D returns the current gui panel where the 3D scene is shown.
  232. func (app *Application) Panel3D() gui.IPanel {
  233. return app.renderer.Panel3D()
  234. }
  235. // CameraPersp returns the application perspective camera
  236. func (app *Application) CameraPersp() *camera.Perspective {
  237. return app.camPersp
  238. }
  239. // CameraOrtho returns the application orthographic camera
  240. func (app *Application) CameraOrtho() *camera.Orthographic {
  241. return app.camOrtho
  242. }
  243. // Camera returns the current application camera
  244. func (app *Application) Camera() camera.ICamera {
  245. return app.camera
  246. }
  247. // SetCamera sets the current application camera
  248. func (app *Application) SetCamera(cam camera.ICamera) {
  249. app.camera = cam
  250. }
  251. // Orbit returns the current camera orbit control
  252. func (app *Application) Orbit() *control.OrbitControl {
  253. return app.orbit
  254. }
  255. // SetOrbit sets the camera orbit control
  256. func (app *Application) SetOrbit(oc *control.OrbitControl) {
  257. app.orbit = oc
  258. }
  259. // FrameRater returns the FrameRater object
  260. func (app *Application) FrameRater() *FrameRater {
  261. return app.frameRater
  262. }
  263. // FrameCount returns the total number of frames since the call to Run()
  264. func (app *Application) FrameCount() uint64 {
  265. return app.frameCount
  266. }
  267. // FrameDelta returns the duration of the previous frame
  268. func (app *Application) FrameDelta() time.Duration {
  269. return app.frameDelta
  270. }
  271. // FrameDeltaSeconds returns the duration of the previous frame
  272. // in float32 seconds
  273. func (app *Application) FrameDeltaSeconds() float32 {
  274. return float32(app.frameDelta.Seconds())
  275. }
  276. // RunTime returns the duration since the call to Run()
  277. func (app *Application) RunTime() time.Duration {
  278. return time.Now().Sub(app.startTime)
  279. }
  280. // RunSeconds returns the elapsed time in seconds since the call to Run()
  281. func (app *Application) RunSeconds() float32 {
  282. return float32(time.Now().Sub(app.startTime).Seconds())
  283. }
  284. // Renderer returns the application renderer
  285. func (app *Application) Renderer() *renderer.Renderer {
  286. return app.renderer
  287. }
  288. // AudioSupport returns if the audio library was loaded OK
  289. func (app *Application) AudioSupport() bool {
  290. return app.audio
  291. }
  292. // VorbisSupport returns if the Ogg Vorbis decoder library was loaded OK
  293. func (app *Application) VorbisSupport() bool {
  294. return app.vorbis
  295. }
  296. // SetCPUProfile must be called before Run() and sets the file name for cpu profiling.
  297. // If set the cpu profiling starts before running the render loop and continues
  298. // till the end of the application.
  299. func (app *Application) SetCPUProfile(fname string) {
  300. *app.cpuProfile = fname
  301. }
  302. // SetOnWindowResize replaces the default window resize handler with the specified one
  303. func (app *Application) SetOnWindowResize(f func(evname string, ev interface{})) {
  304. app.win.UnsubscribeID(window.OnWindowSize, app)
  305. app.win.SubscribeID(window.OnWindowSize, app, f)
  306. }
  307. // Run runs the application render loop
  308. func (app *Application) Run() error {
  309. // Set swap interval
  310. if *app.swapInterval >= 0 {
  311. app.wmgr.SetSwapInterval(*app.swapInterval)
  312. app.log.Debug("Swap interval set to: %v", *app.swapInterval)
  313. }
  314. // Start profiling if requested
  315. if *app.cpuProfile != "" {
  316. f, err := os.Create(*app.cpuProfile)
  317. if err != nil {
  318. return err
  319. }
  320. defer f.Close()
  321. err = pprof.StartCPUProfile(f)
  322. if err != nil {
  323. return err
  324. }
  325. defer pprof.StopCPUProfile()
  326. app.log.Info("Started writing CPU profile to: %s", *app.cpuProfile)
  327. }
  328. // Start execution trace if requested
  329. if *app.execTrace != "" {
  330. f, err := os.Create(*app.execTrace)
  331. if err != nil {
  332. return err
  333. }
  334. defer f.Close()
  335. err = trace.Start(f)
  336. if err != nil {
  337. return err
  338. }
  339. defer trace.Stop()
  340. app.log.Info("Started writing execution trace to: %s", *app.execTrace)
  341. }
  342. app.startTime = time.Now()
  343. app.frameTime = time.Now()
  344. // Render loop
  345. for !app.win.ShouldClose() {
  346. // Starts measuring this frame
  347. app.frameRater.Start()
  348. // Updates frame start and time delta in context
  349. now := time.Now()
  350. app.frameDelta = now.Sub(app.frameTime)
  351. app.frameTime = now
  352. // Process root panel timers
  353. if app.Gui() != nil {
  354. app.Gui().TimerManager.ProcessTimers()
  355. }
  356. // Process application timers
  357. app.ProcessTimers()
  358. // Dispatch before render event
  359. app.Dispatch(OnBeforeRender, nil)
  360. // Renders the current scene and/or gui
  361. rendered, err := app.renderer.Render(app.camera)
  362. if err != nil {
  363. return err
  364. }
  365. // Poll input events and process them
  366. app.wmgr.PollEvents()
  367. if rendered {
  368. app.win.SwapBuffers()
  369. }
  370. // Dispatch after render event
  371. app.Dispatch(OnAfterRender, nil)
  372. // Controls the frame rate
  373. app.frameRater.Wait()
  374. app.frameCount++
  375. }
  376. // Close default audio device
  377. if app.audioDev != nil {
  378. err := al.CloseDevice(app.audioDev)
  379. if err != nil {
  380. app.log.Error("Error closing audio device: %v", err)
  381. }
  382. }
  383. // Dispose GL resources
  384. if app.scene != nil {
  385. app.scene.DisposeChildren(true)
  386. }
  387. if app.guiroot != nil {
  388. app.guiroot.DisposeChildren(true)
  389. }
  390. // Terminates window manager
  391. app.wmgr.Terminate()
  392. return nil
  393. }
  394. // Quit ends the application
  395. func (app *Application) Quit() {
  396. app.win.SetShouldClose(true)
  397. }
  398. // OnWindowResize is default handler for window resize events.
  399. func (app *Application) OnWindowResize() {
  400. // Get window size and sets the viewport to the same size
  401. width, height := app.win.Size()
  402. app.gl.Viewport(0, 0, int32(width), int32(height))
  403. // Sets perspective camera aspect ratio
  404. aspect := float32(width) / float32(height)
  405. app.camPersp.SetAspect(aspect)
  406. // Sets the GUI root panel size to the size of the screen
  407. if app.guiroot != nil {
  408. app.guiroot.SetSize(float32(width), float32(height))
  409. }
  410. }
  411. // LoadAudioLibs try to load audio libraries
  412. func (app *Application) LoadAudioLibs() error {
  413. // Try to load OpenAL
  414. err := al.Load()
  415. if err != nil {
  416. return err
  417. }
  418. // Opens default audio device
  419. app.audioDev, err = al.OpenDevice("")
  420. if app.audioDev == nil {
  421. return fmt.Errorf("Error: %s opening OpenAL default device", err)
  422. }
  423. // Checks for OpenAL effects extension support
  424. if al.IsExtensionPresent("ALC_EXT_EFX") {
  425. app.audioEFX = true
  426. }
  427. // Creates audio context with auxiliary sends
  428. var attribs []int
  429. if app.audioEFX {
  430. attribs = []int{al.MAX_AUXILIARY_SENDS, 4}
  431. }
  432. acx, err := al.CreateContext(app.audioDev, attribs)
  433. if err != nil {
  434. return fmt.Errorf("Error creating audio context:%s", err)
  435. }
  436. // Makes the context the current one
  437. err = al.MakeContextCurrent(acx)
  438. if err != nil {
  439. return fmt.Errorf("Error setting audio context current:%s", err)
  440. }
  441. app.audio = true
  442. app.log.Info("%s version: %s", al.GetString(al.Vendor), al.GetString(al.Version))
  443. // Ogg Vorbis support
  444. err = ov.Load()
  445. if err == nil {
  446. app.vorbis = true
  447. vorbis.Load()
  448. app.log.Info("%s", vorbis.VersionString())
  449. }
  450. return nil
  451. }