application.go 14 KB

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