func (self *OpenGLWindow) Open() { var err error if !glfw.Init() { panic(errors.New("Unable to initialize GLFW")) } glfw.SetErrorCallback(func(code glfw.ErrorCode, desc string) { log.Printf("[GLFW Error] (%d) %s", code, desc) }) var monitor *glfw.Monitor if self.config.Fullscreen { monitor, err = glfw.GetPrimaryMonitor() if err != nil { panic(err) } } glfw.WindowHint(glfw.ContextVersionMajor, 4) glfw.WindowHint(glfw.ContextVersionMinor, 1) glfw.WindowHint(glfw.OpenglProfile, glfw.OpenglCoreProfile) glfw.WindowHint(glfw.OpenglForwardCompatible, glfw.True) // Default buffer sizes glfw.WindowHint(glfw.DepthBits, 32) glfw.WindowHint(glfw.StencilBits, 0) // Toggle VSync. Turning VSync off aparently doesn't work via glfw through // some ATI cards and drivers if self.config.VSync { glfw.SwapInterval(1) } else { glfw.SwapInterval(0) } self.window, err = glfw.CreateWindow( int(self.config.Width), int(self.config.Height), "Project Slartibartfast", monitor, nil) if err != nil { panic(err) } self.window.MakeContextCurrent() if glewError := gl.Init(); glewError != 0 { panic(errors.New("Unable to initialize OpenGL")) } }
func main() { glfw.SetErrorCallback(errorCallback) if !glfw.Init() { panic("Can't init glfw!") } defer glfw.Terminate() window, err := glfw.CreateWindow(800, 640, "MyGui", nil, nil) if err != nil { panic(err) } window.MakeContextCurrent() glfw.SwapInterval(1) gl.Init() mvp := prepareModelViewProjection(800, 640) prepareScene() dt := float64(0) glfw.SetTime(dt) for !window.ShouldClose() { dt = glfw.GetTime() glfw.SetTime(0) updateScene(dt) drawScene(mvp, dt) window.SwapBuffers() glfw.PollEvents() } }
func main() { if !glfw.Init() { log.Fatal("glfw failed to initialize") } defer glfw.Terminate() window, err := glfw.CreateWindow(640, 480, "Deformable", nil, nil) if err != nil { log.Fatal(err.Error()) } window.MakeContextCurrent() glfw.SwapInterval(1) window.SetMouseButtonCallback(handleMouseButton) window.SetKeyCallback(handleKeyDown) window.SetInputMode(glfw.Cursor, glfw.CursorHidden) gl.Init() initGL() i := 16 m = GenerateMap(1600/i, 1200/i, i) for running && !window.ShouldClose() { x, y := window.GetCursorPosition() if drawing != 0 { m.Add(int(x)+int(camera[0]), int(y)+int(camera[1]), drawing, brushSizes[currentBrushSize]) } gl.Clear(gl.COLOR_BUFFER_BIT) gl.LoadIdentity() gl.PushMatrix() gl.PushAttrib(gl.CURRENT_BIT | gl.ENABLE_BIT | gl.LIGHTING_BIT | gl.POLYGON_BIT | gl.LINE_BIT) gl.Translatef(-camera[0], -camera[1], 0) m.Draw() gl.PopAttrib() gl.PopMatrix() gl.PushAttrib(gl.COLOR_BUFFER_BIT) gl.LineWidth(2) gl.Enable(gl.BLEND) gl.BlendFunc(gl.ONE_MINUS_DST_COLOR, gl.ZERO) // gl.Enable(gl.LINE_SMOOTH) // gl.Hint(gl.LINE_SMOOTH_HINT, gl.NICEST) gl.Translatef(float32(x), float32(y), 0) gl.EnableClientState(gl.VERTEX_ARRAY) gl.VertexPointer(2, gl.DOUBLE, 0, cursorVerts) gl.DrawArrays(gl.LINE_LOOP, 0, 24) gl.PopAttrib() window.SwapBuffers() glfw.PollEvents() } }
func main() { runtime.LockOSThread() defer runtime.UnlockOSThread() defer glfw.Terminate() mandala.Verbose = true if !glfw.Init() { panic("Can't init glfw!") } // Enable OpenGL ES 2.0. glfw.WindowHint(glfw.ClientApi, glfw.OpenglEsApi) glfw.WindowHint(glfw.ContextVersionMajor, 2) window, err := glfw.CreateWindow(Width, Height, "gltext black-box testing", nil, nil) if err != nil { panic(err) } glfw.SwapInterval(0) mandala.Init(window) go prettytest.Run(new(testing.T), testlib.NewTestSuite(outputPath)) for !window.ShouldClose() { glfw.WaitEvents() } }
func main() { glfw.SetErrorCallback(errorCallback) if !glfw.Init() { panic("Can't init glfw!") } defer glfw.Terminate() window, err := glfw.CreateWindow(Width, Height, Title, nil, nil) if err != nil { panic(err) } window.MakeContextCurrent() glfw.SwapInterval(1) gl.Init() if err := initScene(); err != nil { fmt.Fprintf(os.Stderr, "init: %s\n", err) return } defer destroyScene() for !window.ShouldClose() { drawScene() window.SwapBuffers() glfw.PollEvents() } }
func main() { glfw.SetErrorCallback(glfwError) if !glfw.Init() { log.Printf("Unable to initializer glfw") return } defer glfw.Terminate() window, err := glfw.CreateWindow(Width, Height, Title, nil, nil) if err != nil { panic(err) } window.MakeContextCurrent() window.SetSizeCallback(fixProjection) err = initGL() if err != nil { log.Printf("Error initializing OpenGL. %v", err) panic(err) } glfw.SwapInterval(1) fixProjection(window, Width, Height) meshBuff := createMeshBuffer() for !window.ShouldClose() { timeDelta.Tick() log.Printf("Time: %v", timeDelta.Delta) window.SwapBuffers() glfw.PollEvents() } }
func NewTestbed(title string) *Testbed { t := new(Testbed) t.window = OpenWindow(500, 500, title) glfw.SwapInterval(1) t.image = LoadPNG("testimage.png").(*image.NRGBA) return t }
func main() { runtime.LockOSThread() glfw.SetErrorCallback(errorCallback) if !glfw.Init() { panic("Can't init glfw!") } defer glfw.Terminate() // must be done in main thread or we get a nasty stderr message from glfw, // although it does seem to 'work' window, err := glfw.CreateWindow(Width, Height, Title, nil, nil) if err != nil { panic(err) } // separate thread for drawing so that we don't block on the event thread. // most obvious benefit is that we continue to render during window // resizes. go func() { runtime.LockOSThread() window.MakeContextCurrent() glfw.SwapInterval(1) gl.Init() if err := initScene(); err != nil { fmt.Fprintf(os.Stderr, "init: %s\n", err) return } for !window.ShouldClose() { drawScene() window.SwapBuffers() } os.Exit(0) }() for { glfw.WaitEvents() } }
func main() { if !glfw.Init() { f.Println("Failed to init glfw") panic("Cannot initialize glfw library") } defer glfw.Terminate() //glfw.WindowHint(glfw.DepthBits, 16) window, err := glfw.CreateWindow(300, 300, "Wander", nil, nil) if err != nil { panic(err) } window.SetFramebufferSizeCallback(reshape) window.SetKeyCallback(key) window.MakeContextCurrent() glfw.SwapInterval(1) width, height := window.GetFramebufferSize() reshape(window, width, height) if gl.Init() != 0 { panic("Failed to init GL") } prog := setupProgram() defer prog.Delete() prog.Use() attr = prog.GetAttribLocation("offset") setup() for !window.ShouldClose() { if shouldRender() { draw() } animate() window.SwapBuffers() glfw.PollEvents() } }
func main() { // initialize glfw if !glfw.Init() { panic("Failed to initialize GLFW") } defer glfw.Terminate() // create window window, err := glfw.CreateWindow(600, 600, os.Args[0], nil, nil) if err != nil { panic(err) } window.SetFramebufferSizeCallback(onResize) window.MakeContextCurrent() // set up opengl context onResize(window, 600, 600) // set up physics createBodies() runtime.LockOSThread() glfw.SwapInterval(1) ticksToNextBall := 10 ticker := time.NewTicker(time.Second / 60) for !window.ShouldClose() { ticksToNextBall-- if ticksToNextBall == 0 { ticksToNextBall = rand.Intn(100) + 1 addBall() } draw() step(1.0 / 60.0) window.SwapBuffers() glfw.PollEvents() <-ticker.C // wait up to 1/60th of a second } }
func main() { if !glfw.Init() { panic("Failed to initialize GLFW") } defer glfw.Terminate() glfw.WindowHint(glfw.DepthBits, 16) window, err := glfw.CreateWindow(300, 300, "Gears", nil, nil) if err != nil { panic(err) } // Set callback functions window.SetFramebufferSizeCallback(reshape) window.SetKeyCallback(key) window.MakeContextCurrent() glfw.SwapInterval(1) width, height := window.GetFramebufferSize() reshape(window, width, height) // Parse command-line options Init() // Main loop for !window.ShouldClose() { // Draw gears draw() // Update animation animate() // Swap buffers window.SwapBuffers() glfw.PollEvents() } }
func main() { flag.Parse() glfw.SetErrorCallback(errorCallback) if !glfw.Init() { println("glfw init failure") } defer glfw.Terminate() glfw.WindowHint(glfw.ClientApi, glfw.OpenglEsApi) glfw.WindowHint(glfw.ContextVersionMajor, 2) glfw.WindowHint(glfw.ContextVersionMinor, 0) window, err := glfw.CreateWindow(Width, Height, Title, nil, nil) if err != nil { panic(err) } defer window.Destroy() window.MakeContextCurrent() glfw.SwapInterval(1) window.SetSizeCallback(reshape) window.SetKeyCallback(keyEvent) gl.Viewport(0, 0, Width, Height) initScene() if *debug { go func() { tick := time.Tick(1 * time.Second) for { <-tick fmt.Printf("FPS:%v\tGOROUTINE:%v\r", atomic.LoadUint64(fps), runtime.NumGoroutine()) atomic.StoreUint64(fps, 0) } }() } for !window.ShouldClose() { drawScene() window.SwapBuffers() glfw.PollEvents() atomic.AddUint64(fps, 1) } }
func main() { glfw.SetErrorCallback(errorCallback) if !glfw.Init() { panic("Can't init glfw!") } defer glfw.Terminate() glfw.WindowHint(glfw.DepthBits, 16) window, err := glfw.CreateWindow(Width, Height, Title, nil, nil) if err != nil { panic(err) } window.SetFramebufferSizeCallback(reshape) window.SetKeyCallback(key) window.MakeContextCurrent() glfw.SwapInterval(1000 / 60) width, height := window.GetFramebufferSize() reshape(window, width, height) if err := initGL(); err != nil { fmt.Fprintf(os.Stderr, "init: %s\n", err) return } defer destroyGL() for !window.ShouldClose() { drawScene() window.SwapBuffers() glfw.PollEvents() } }
func main() { f, err := os.Create("Go.pprof") // Create file for profiling if err != nil { panic(err) } glfw.SetErrorCallback(errorCallback) if !glfw.Init() { panic("Can't init glfw!") } defer glfw.Terminate() glfw.WindowHint(glfw.Samples, 2) glfw.WindowHint(glfw.ContextVersionMajor, 2) glfw.WindowHint(glfw.ContextVersionMinor, 1) window, err := glfw.CreateWindow(Width, Height, Title, nil, nil) if err != nil { panic(err) } window.MakeContextCurrent() glfw.SwapInterval(0) // No limit on FPS gl.Init() initScene() loadCubeToGPU() for !window.ShouldClose() { frameInitT = time.Now() movPts(frameDur) doWind() if spwnTmr >= SpawnInterval { spwnPts(SpawnInterval) spwnTmr -= SpawnInterval } if cleanupTmr >= float64(MaxLife)/1000 { cleanupPtPool() cleanupTmr = 0 } checkColls() gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) gpuInitT = time.Now() renderPts() window.SwapBuffers() gpuEndT = time.Now() glfw.PollEvents() frameEndT = time.Now() frameDur = frameEndT.Sub(frameInitT).Seconds() // Calculate the length of the previous frame spwnTmr += frameDur cleanupTmr += frameDur runTmr += frameDur if runTmr > MaxLife/1000 { // Start collecting framerate data and profiling after a full MaxLife worth of particles have been spawned frames[curFrame] = frameDur gpuTimes[curFrame] = gpuEndT.Sub(gpuInitT).Seconds() curFrame += 1 pprof.StartCPUProfile(f) } if runTmr >= RunningTime { // Animation complete; calculate framerate mean and standard deviation pprof.StopCPUProfile() var sum float64 var i uint64 for i = 0; i < curFrame; i++ { sum += frames[i] } frameTimeMean := sum / float64(curFrame) fmt.Println("Average framerate was:", 1/frameTimeMean, "frames per second.") sum = 0 for i = 0; i < curFrame; i++ { sum += gpuTimes[i] } gpuTimeMean := sum / float64(curFrame) fmt.Println("Average cpu time was-", frameTimeMean-gpuTimeMean, "seconds per frame.") sumDiffs := 0.0 for i = 0; i < curFrame; i++ { sumDiffs += math.Pow(1/frames[i]-1/frameTimeMean, 2) } variance := sumDiffs / float64(curFrame) sd := math.Sqrt(variance) fmt.Println("The standard deviation was:", sd, "frames per second.") if PrintFrames == true { fmt.Print("--:") for i = 0; i < curFrame; i++ { fmt.Print(1 / frames[i]) fmt.Print(",") } fmt.Print(".--") } break } } gl.DisableClientState(gl.NORMAL_ARRAY) gl.DisableClientState(gl.VERTEX_ARRAY) }
// NewWindow creates a new window for the given dimensions and title. // The window is created via GLFW. func NewWindow(settings WindowSettings) (*Window, error) { // Error callback glfw.SetErrorCallback(errorCallback) // Init glfw logger.Debug("Initializing GLFW") if !glfw.Init() { return nil, errors.New("Could not initialise GLFW.") } glfw.WindowHint(glfw.Samples, 4) glfw.WindowHint(glfw.ContextVersionMajor, 3) glfw.WindowHint(glfw.ContextVersionMinor, 3) glfw.WindowHint(glfw.OpenglForwardCompatible, glfw.True) glfw.WindowHint(glfw.OpenglProfile, glfw.OpenglCoreProfile) glfw.WindowHint(glfw.OpenglDebugContext, 1) var monitor *glfw.Monitor var err error if settings.Fullscreen { logger.Debug("Get primary monitor to create fullscreen window.") monitor, err = glfw.GetPrimaryMonitor() if err != nil { return nil, err } logger.Debug("Checking available video modes:") videoModes, err := monitor.GetVideoModes() if err != nil { return nil, err } for _, videoMode := range videoModes { logger.Debug(fmt.Sprintf("-- %+v", videoMode)) } idealVideoMode := videoModes[len(videoModes)-1] settings.Width = idealVideoMode.Width settings.Height = idealVideoMode.Height } // Create window logger.Info("Creating new window") window, err := glfw.CreateWindow(settings.Width, settings.Height, settings.Title, monitor, nil) if err != nil { return nil, err } window.SetKeyCallback(keyCallback) window.MakeContextCurrent() window.SetInputMode(glfw.StickyKeys, 1) // Use vsync glfw.SwapInterval(1) w := &Window{ window: window, Settings: settings, } currentWindow = w return w, nil }
func (me *context) SetSwapInterval(interval int) { glfw.SwapInterval(interval) }
// Starts a game loop. // If error == nil everything went well, otherwise a fatal error occured func Gameloop(g Game, width, height, tickrate int, glfwHints map[glfw.Hint]int) (err error) { // Disable GC debug.SetGCPercent(-1) // Make sure this function/goroutine keeps running on the current OS thread runtime.LockOSThread() // Calculate tick delay nanosPerTick := int64(NANOS_PER_SECOND / tickrate) // Variables for statistics ticks := 0 frames := 0 // Initialize game g.Init() defer g.Cleanup() // Setup window glfw.SetErrorCallback(g.HandleGlfwError) if !glfw.Init() { err = errors.New("gogame: glfw failed to initialize") return } defer glfw.Terminate() for target, hint := range glfwHints { glfw.WindowHint(target, hint) } window, err := glfw.CreateWindow(width, height, "GoGame", nil, nil) if err != nil { // Just to be verbose err = err return } // Set callbacks window.SetFramebufferSizeCallback(g.HandleReshape) window.SetKeyCallback(g.HandleKey) window.MakeContextCurrent() // TODO: Investigate double buffering/vsync glfw.SwapInterval(1) if gl.Init() != 0 { // GLEW_OK err = errors.New("gogame: error initializing opengl/glew") return } // Manually reshape window width, height = window.GetFramebufferSize() g.HandleReshape(window, width, height) // Let the game initialize its graphics g.InitGL() defer g.CleanupGL() last_out := time.Now().UnixNano() previous := time.Now().UnixNano() unprocessed := int64(0) for !window.ShouldClose() { current := time.Now().UnixNano() elapsed := current - previous previous = current unprocessed += elapsed for unprocessed >= nanosPerTick { if g.OnUpdate() { window.SetShouldClose(true) } ticks++ unprocessed -= nanosPerTick } if true { substep := float32(unprocessed) / float32(nanosPerTick) g.OnRender(substep) frames++ } if current-last_out >= NANOS_PER_SECOND { // TODO: Pass tps and fps to game instead of logging here log.Printf("%d TPS, %d FPS", ticks, frames) ticks = 0 frames = 0 last_out += NANOS_PER_SECOND } // Manually call GC runtime.GC() // Swap buffers window.SwapBuffers() glfw.PollEvents() // TODO: Look into handling sleeping between frames /*elapsed_time := time.Duration(time.Now().UnixNano()) - previous sleep_time := NANOS_PER_FRAME - elapsed_time // TODO: Decrease sleep time? if sleep_time >= SLEEP_THRESHOLD { time.Sleep(sleep_time) }*/ } err = nil return }
func CreateWindow(width, height int, name string, fullscreen bool, delegate WindowDelegate, legacy bool) error { if !glfw.Init() { return errors.New("Failed to initialize GLFW") } defer glfw.Terminate() glfw.WindowHint(glfw.DepthBits, 16) if !legacy { glfw.WindowHint(glfw.ContextVersionMajor, 3) glfw.WindowHint(glfw.ContextVersionMinor, 2) glfw.WindowHint(glfw.OpenglProfile, glfw.OpenglCoreProfile) glfw.WindowHint(glfw.OpenglForwardCompatible, 1) } var monitor *glfw.Monitor = nil var err error = nil if fullscreen { monitor, err = glfw.GetPrimaryMonitor() if err != nil { return err } vidModes, _ := monitor.GetVideoModes() maxResolution := vidModes[len(vidModes)-1] width = maxResolution.Width height = maxResolution.Height } window, err := glfw.CreateWindow(width, height, name, monitor, nil) if err != nil { return err } if fullscreen { window.SetInputMode(glfw.Cursor, glfw.CursorDisabled) } start := time.Now() last := start doSimulation := func() { now := time.Now() gameTime := GameTime{ now, now.Sub(start), now.Sub(last), } delegate.Simulate(gameTime) last = now } bindEvents(window, &IdleSimulatorWindowDelegator{ WindowDelegator{delegate}, doSimulation, }) window.MakeContextCurrent() glfw.SwapInterval(1) delegate.Init(window) frameWidth, frameHeight := window.GetFramebufferSize() delegate.Reshape(window, frameWidth, frameHeight) for !window.ShouldClose() { doSimulation() if delegate.NeedsRender() { delegate.Draw(window) } window.SwapBuffers() if delegate.IsIdle() { glfw.WaitEvents() } else { glfw.PollEvents() } } return nil }