application.go 15 KB

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