Exemplo n.º 1
0
func Init() {

	runtime.LockOSThread()

	// Initialize GLFW

	var err error

	if err = glfw.Init(); err != nil {
		log.Fatalf("%v\n", err)
		return
	}

	err = glfw.OpenWindow(SCREEN_WIDTH, SCREEN_HEIGHT,
		0, 0, 0, 0, 0, 0, glfw.Windowed)

	if err != nil {
		log.Fatalf("%v\n", err)
		return
	}

	glfw.SetWindowTitle("Mandelbrot")
	glfw.SetSwapInterval(1)

	glfw.SetWindowSizeCallback(onResize)
	glfw.SetWindowCloseCallback(onClose)
	glfw.SetMouseButtonCallback(onMouseBtn)
	glfw.SetMouseWheelCallback(onMouseWheel)
	glfw.SetKeyCallback(onKey)
	glfw.SetCharCallback(onChar)

	// Initialize OpenGL
	gl.Disable(gl.DEPTH_TEST)
	gl.ClearColor(0, 0, 0, 0)
}
Exemplo n.º 2
0
func main() {
	var err error
	if err = glfw.Init(); err != nil {
		log.Fatalf("%v\n", err)
		return
	}

	defer glfw.Terminate()

	if err = glfw.OpenWindow(640, 480, 8, 8, 8, 8, 0, 0, glfw.Windowed); err != nil {
		log.Fatalf("%v\n", err)
		return
	}

	defer glfw.CloseWindow()

	glfw.SetWindowTitle("Draw")
	glfw.SetSwapInterval(1)
	glfw.SetKeyCallback(onKey)
	glfw.SetMouseButtonCallback(onMouseBtn)
	glfw.SetWindowSizeCallback(onResize)

	running = true
	for running && glfw.WindowParam(glfw.Opened) == 1 {
		if mouse[0] != 0 {
			pen.lineTo(glfw.MousePos())
		} else {
			pen.moveTo(glfw.MousePos())
		}

		glfw.SwapBuffers()
	}
}
Exemplo n.º 3
0
func MouseButtonChan() chan DigiState {
	out := make(chan DigiState)
	glfw.SetMouseButtonCallback(func(button, state int) {
		go func() { out <- DigiState{button, state} }()
	})
	return out
}
Exemplo n.º 4
0
func StartEngine() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	runtime.LockOSThread()
	fmt.Println("Enginge started!")
	var err error
	if err = glfw.Init(); err != nil {
		panic(err)
	}
	fmt.Println("GLFW Initialized!")

	glfw.OpenWindowHint(glfw.Accelerated, 1)

	if err = glfw.OpenWindow(Width, Height, 8, 8, 8, 8, 8, 8, glfw.Windowed); err != nil {
		panic(err)
	}

	glfw.SetSwapInterval(1) //0 to disable vsync, 1 to enable it
	glfw.SetWindowTitle(windowTitle)
	glfw.SetWindowSizeCallback(onResize)
	glfw.SetKeyCallback(input.OnKey)
	glfw.SetCharCallback(input.OnChar)
	glfw.SetMouseButtonCallback(input.ButtonPress)
	glfw.SetMouseWheel(0)
	glfw.SetMouseWheelCallback(input.MouseWheelCallback)

	input.MouseWheelPosition = glfw.MouseWheel
	input.MousePosition = glfw.MousePos

	if err = initGL(); err != nil {
		panic(err)
	}
	fmt.Println("Opengl Initialized!")

	TextureMaterial = NewBasicMaterial(spriteVertexShader, spriteFragmentShader)
	err = TextureMaterial.Load()
	if err != nil {
		fmt.Println(err)
	}

	SDFMaterial = NewBasicMaterial(sdfVertexShader, sdfFragmentShader)
	err = SDFMaterial.Load()
	if err != nil {
		fmt.Println(err)
	}

	internalMaterial = NewBasicMaterial(spriteVertexShader, spriteFragmentShader)
	err = internalMaterial.Load()
	if err != nil {
		fmt.Println(err)
	}

	initDefaultPlane()
	glfw.SwapBuffers()

	gameTime = time.Time{}
	lastTime = time.Now()
	dl = glfw.Time()
}
Exemplo n.º 5
0
func main() {
	var err error
	if err = glfw.Init(); err != nil {
		fmt.Fprintf(os.Stderr, "[e] %v\n", err)
		return
	}

	// Ensure glfw is cleanly terminated on exit.
	defer glfw.Terminate()

	if err = glfw.OpenWindow(256, 256, 8, 8, 8, 0, 0, 0, glfw.Windowed); err != nil {
		fmt.Fprintf(os.Stderr, "[e] %v\n", err)
		return
	}

	// Ensure window is cleanly closed on exit.
	defer glfw.CloseWindow()

	// Enable vertical sync on cards that support it.
	glfw.SetSwapInterval(1)

	// Set window title
	glfw.SetWindowTitle("Simple GLFW window")

	// Hook some events to demonstrate use of callbacks.
	// These are not necessary if you don't need them.
	glfw.SetWindowSizeCallback(onResize)
	glfw.SetWindowCloseCallback(onClose)
	glfw.SetMouseButtonCallback(onMouseBtn)
	glfw.SetMouseWheelCallback(onMouseWheel)
	glfw.SetKeyCallback(onKey)
	glfw.SetCharCallback(onChar)

	// Start loop
	running := true
	for running {
		// OpenGL rendering goes here.

		// Swap front and back rendering buffers. This also implicitly calls
		// glfw.PollEvents(), so we have valid key/mouse/joystick states after
		// this. This behavior can be disabled by calling glfw.Disable with the
		// argument glfw.AutoPollEvents. You must be sure to manually call
		// PollEvents() or WaitEvents() in this case.
		glfw.SwapBuffers()

		// Break out of loop when Escape key is pressed, or window is closed.
		running = glfw.Key(glfw.KeyEsc) == 0 && glfw.WindowParam(glfw.Opened) == 1
	}
}
Exemplo n.º 6
0
func main() {
	RunGame(Title, Width*Scale, Height*Scale, func() {
		gl.PointSize(1.0 * Scale)

		x := 0
		y := 0
		dcolor := WHITE
		glfw.SetMouseButtonCallback(func(button, state int) {
			dcolor += 1
			if dcolor > BLUE {
				dcolor = WHITE
			}
		})
		glfw.SetMousePosCallback(func(mx, my int) {
			mx /= Scale
			my /= Scale
			if mx >= Width || my >= Height || mx < 0 || my < 0 {
				return
			}
			x = mx
			y = my
			if matrix != nil && dcolor != WHITE {
				(*matrix)[x][y].Color = dcolor
				(*matrix)[x][y].Intensity = 10
			}
		})
		glfw.SetKeyCallback(func(key, state int) {
			matrix = makeMatrix(Width, Height)
		})
		matrix = makeMatrix(Width, Height)
	}, func() {
		matrix = NextMatrix(Width, Height, matrix)
		gl.Begin(gl.POINTS)
		drawMatrix(matrix, Scale, Scale)
		gl.End()
	})
}
Exemplo n.º 7
0
Arquivo: main.go Projeto: pwaller/mema
func main_loop(data *ProgramData) {
	start := time.Now()
	frames := 0
	lastblocks := 0

	// Frame counter
	go func() {
		for {
			time.Sleep(time.Second)
			if *verbose {
				memstats := new(runtime.MemStats)
				runtime.ReadMemStats(memstats)
				fps := float64(frames) / time.Since(start).Seconds()
				blocks := len(data.blocks)
				bps := float64(blocks-lastblocks) / time.Since(start).Seconds()
				lastblocks = blocks
				log.Printf("fps = %5.2f; blocks = %4d; bps = %5.2f sparemem = %6d MB; alloc'd = %6.6f; (+footprint = %6.6f)",
					fps, len(data.blocks), bps, SpareRAM(), float64(memstats.Alloc)/1024/1024,
					float64(memstats.Sys-memstats.Alloc)/1024/1024)

				PrintTimers(frames)
			}
			start = time.Now()
			frames = 0
		}
	}()

	// Necessary at the moment to prevent eventual OOM
	go func() {
		for {
			time.Sleep(5 * time.Second)
			if *verbose {
				log.Print("GC()")
			}
			runtime.GC()
			if *verbose {
				GCStats()
			}
		}
	}()

	var i int64 = -int64(*nback)

	// TODO(pwaller): Make this work again
	// text := glh.MakeText(data.filename, 32)

	// Location of mouse in record space
	var rec, rec_actual int64 = 0, 0

	var stacktext, dwarftext []*glh.Text
	var recordtext *glh.Text = nil

	var mousex, mousey, mousedownx, mousedowny int
	var mousepx, mousepy float64
	var lbutton bool
	escape_hit := false

	glfw.SetMouseWheelCallback(func(pos int) {
		nback_prev := *nback
		if pos < 0 {
			*nback = 40 * 1024 << uint(-pos)
		} else {
			*nback = 40 * 1024 >> uint(pos)
		}
		//log.Print("Mousewheel position: ", pos, " nback: ", *nback)

		if rec == 0 {
			return
		}

		// mouse cursor is at screen "rec_actual", and it should be after
		// the transformation

		// We need to adjust `i` to keep this value constant:
		// rec_actual == i + int64(constpart * float64(*nback))
		//   where constpart <- (-const + 2.) / 4.
		// (that way, the mouse is still pointing at the same place after scaling)

		constpart := float64(rec_actual-i) / float64(nback_prev)

		rec_actual_after := i + int64(constpart*float64(*nback))
		delta := rec_actual_after - rec_actual
		i -= delta

		// Ensure the mouse cursor position doesn't change when zooming
		rec = rec_actual - i
	})

	update_text := func() {
		if DoneThisFrame(RenderText) {
			return
		}

		if recordtext != nil {
			recordtext.Destroy()
			recordtext = nil
		}
		//r := 0 //data.GetRecord(rec_actual)
		//if r != nil {
		//log.Print(data.records[rec_actual])
		//recordtext = MakeText(r.String(), 32)
		//}

		for j := range stacktext {
			stacktext[j].Destroy()
		}
		// TODO: Load records on demand
		if false {
			stack := data.GetStackNames(rec_actual)
			stacktext = make([]*glh.Text, len(stack))
			for j := range stack {
				stacktext[j] = glh.MakeText(stack[j], 32)
			}
		}
	}

	glfw.SetMouseButtonCallback(func(button, action int) {
		switch button {
		case glfw.Mouse1:
			switch action {
			case glfw.KeyPress:
				mousedownx, mousedowny = mousex, mousey
				lbutton = true

				r := data.GetRecord(rec_actual)
				if r != nil {
					if r.Type == MEMA_ACCESS {
						log.Print(r)
						ma := r.MemAccess()
						dwarf := data.GetDwarf(ma.Pc)
						log.Print("Can has dwarf? ", len(dwarf))
						for i := range dwarf {
							log.Print("  ", dwarf[i])
							//recordtext = MakeText(data.records[rec_actual].String(), 32)

						}
						log.Print("")

						for j := range dwarftext {
							dwarftext[j].Destroy()
						}
						dwarftext = make([]*glh.Text, len(dwarf))
						for j := range dwarf {
							dwarftext[j] = glh.MakeText(fmt.Sprintf("%q", dwarf[j]), 32)
						}
					}

					//recordtext = MakeText(data.records[rec_actual].String(), 32)
				}

			case glfw.KeyRelease:
				lbutton = false
			}
		}
	})

	glfw.SetMousePosCallback(func(x, y int) {

		px, py := glh.WindowToProj(x, y)
		// Record index
		rec = int64((py+2)*float64(*nback)/4. + 0.5)
		rec_actual = rec + i

		dpy := py - mousepy
		di := int64(-dpy * float64(*nback) / 4.)

		if lbutton {
			i += di
		}

		mousepx, mousepy = px, py
		mousex, mousey = x, y

		//log.Printf("Mouse motion: (%3d, %3d), (%f, %f), (%d, %d) dpy=%f di=%d",
		//x, y, px, py, rec, rec_actual, dpy, di)

		update_text()
	})

	glfw.SetKeyCallback(func(key, state int) {
		switch key {
		case glfw.KeyEsc:
			escape_hit = true
		}
	})

	draw_mousepoint := func() {

		// Draw the mouse point
		glh.With(glh.Matrix{gl.MODELVIEW}, func() {
			gl.Translated(0, -2, 0)
			gl.Scaled(1, 4/float64(*nback), 1)
			gl.Translated(0, float64(rec), 0)

			gl.PointSize(10)
			glh.With(glh.Primitive{gl.POINTS}, func() {
				gl.Color4f(1, 1, 1, 1)
				gl.Vertex3d(mousepx, 0, 0)
			})
		})
	}

	draw_text := func() {
		// Draw any text
		glh.With(glh.WindowCoords{}, func() {
			w, h := glh.GetViewportWHD()

			glh.With(glh.Attrib{gl.ENABLE_BIT}, func() {
				gl.Enable(gl.TEXTURE_2D)
				// text.Draw(0, 0)
				for text_idx := range stacktext {
					stacktext[text_idx].Draw(int(w*0.55), int(h)-35-text_idx*16)
				}
				for text_idx := range dwarftext {
					dwarftext[text_idx].Draw(int(w*0.55), 35+text_idx*16)
				}
				if recordtext != nil {
					recordtext.Draw(int(w*0.55), 35)
				}
			})
		})
	}

	Draw = func() {

		gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

		// Draw the memory access/function data
		data.Draw(i, *nback)

		draw_mousepoint()
		draw_text()

		// Visible region quad
		// gl.Color4f(1, 1, 1, 0.25)
		// DrawQuadd(-2.1, -2.25, 4.4, 2.1 - -2.25)

		// StatsHUD()
	}

	interrupt := make(chan os.Signal)
	signal.Notify(interrupt, os.Interrupt)
	ctrlc_hit := false
	go func() {
		<-interrupt
		ctrlc_hit = true
	}()

	done := false
	for !done {
		done_this_frame = make(map[WorkType]bool)

		glh.With(&Timer{Name: "Draw"}, func() {
			Draw()
		})

		glfw.SwapBuffers()

		DoMainThreadWork()

		done = ctrlc_hit || escape_hit || glfw.WindowParam(glfw.Opened) == 0
		frames += 1
	}
}
Exemplo n.º 8
0
func New(width int, height int, title string) *Window {
	var err error
	window := &Window{width: width, height: height, title: title}
	// initialize logger
	logf, err := os.OpenFile("window.log", os.O_WRONLY|os.O_CREATE, 0640)
	logger := log.New(logf, "", log.Ldate|log.Ltime)

	if err = glfw.Init(); err != nil {
		fmt.Fprintf(os.Stderr, "[e] %v\n", err)
		return nil
	}

	// width, hieght, r,g,b,a (color depth bits), depth, stencil, mode
	if err = glfw.OpenWindow(window.width, window.height, 8, 8, 8, 0, 0, 0, glfw.Windowed); err != nil {
		fmt.Fprintf(os.Stderr, "[e] %v\n", err)
		return nil
	}

	onResize := func(w, h int) {
		logger.Printf("resized: %dx%d\n", w, h)
	}

	onClose := func() int {
		logger.Println("window closed\n")
		return 1 // return 0 to keep window open.
	}

	// list callback generators
	createBtnList := func(btnNext func() interface{}, device string) func(button, state int) {
		btnList := list.New()
		btnNext = func() interface{} { return btnList.Remove(btnList.Back()) }
		return func(button, state int) {
			btnList.PushFront(btnEvent{button: button, state: state})
			logger.Printf("%s button: %d, %d\n", device, button, state)
		}
	}

	createPosList := func(posNext func() interface{}, device string) func(x, y int) {
		posList := list.New()
		posNext = func() interface{} { return posList.Remove(posList.Back()) }
		return func(x, y int) {
			posList.PushFront(posEvent{x: x, y: y})
			logger.Printf("%s pos: %d, %d\n", device, x, y)
		}
	}

	createDeltaList := func(deltaNext func() interface{}, device string) func(delta int) {
		deltaList := list.New()
		deltaNext = func() interface{} { return deltaList.Remove(deltaList.Back()) }
		return func(delta int) {
			deltaList.PushFront(deltaEvent{delta: delta})
			logger.Printf("%s delta: %d\n", device, delta)
		}
	}

	glfw.SetSwapInterval(1)
	glfw.SetWindowTitle(title)

	glfw.SetWindowSizeCallback(onResize)
	glfw.SetWindowCloseCallback(onClose)
	glfw.SetMousePosCallback(createPosList(window.MousePos, "mouse pos"))
	glfw.SetMouseButtonCallback(createBtnList(window.MouseBtn, "mouse"))
	glfw.SetMouseWheelCallback(createDeltaList(window.MouseWheel, "mouse wheel"))
	glfw.SetKeyCallback(createBtnList(window.KeyEvt, "keyboard"))
	glfw.SetCharCallback(createBtnList(window.CharEvt, "char"))

	window.Start = func() {
		defer glfw.Terminate()
		defer glfw.CloseWindow()
		running := true
		for running {
			window.Render()
			glfw.SwapBuffers()
			// Break out of loop when Escape key is pressed, or window is closed.
			running = glfw.Key(glfw.KeyEsc) == 0 && glfw.WindowParam(glfw.Opened) == 1
		}
	}

	return window
}
Exemplo n.º 9
0
func main() {
	sys := Make()
	sys.Startup()
	defer sys.Shutdown()
	// InitQueue()

	sys.CreateWindow(1024, 768, "Gexic")
	gl.ClearColor(1, 1, 1, 0.)
	initGL()

	prevSelectPos = []int{0, 0, 0}

	// PurgeQueue()
	// genHexMap()
	hexMap2 = GenHexMap()
	// for matches := checkHexMap(); len(matches) > 0; matches = checkHexMap() {
	// 	removeHexAndGenNew(matches)
	// }
	glfw.SetMouseButtonCallback(MouseButtonCallback)
	glfw.SetCharCallback(charCallback)
	glfw.SetMousePosCallback(MousePosCallback)
	currExX = -1
	currExY = -1

	for sys.CheckExitMainLoop() {
		start := glfw.Time()
		wait := float64(1) / float64(30)
		gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
		gl.Enable(gl.TEXTURE_2D)
		gl.Enable(gl.BLEND)
		gl.Disable(gl.DEPTH_TEST)
		// renderHexMap()
		wallpaper.Bind(gl.TEXTURE_2D)
		gl.TexEnvf(gl.TEXTURE_ENV, gl.TEXTURE_ENV_MODE, gl.REPLACE)
		gl.Begin(gl.QUADS)
		gl.TexCoord2f(0, 0)
		gl.Vertex2i(0, 0)
		gl.TexCoord2f(0, 1)
		gl.Vertex2i(0, 768)
		gl.TexCoord2f(1, 1)
		gl.Vertex2i(1024, 768)
		gl.TexCoord2f(1, 0)
		gl.Vertex2i(1024, 0)
		gl.End()
		hexMap2.Render()
		hexRotate.AnimateAndExecute()
		hexShrink.AnimateAndExecute()
		hexFall.AnimateAndExecute()
		if !mouse.locked {
			x, y := mouse.GetXY()
			hexMap2.CalcClosestCenter(x, y)
		}
		gl.Flush()
		gl.Disable(gl.TEXTURE_2D)
		gl.Disable(gl.BLEND)
		sys.Refresh()
		diff := glfw.Time() - start
		if diff < wait {
			glfw.Sleep(wait - diff)
		}
	}
}
Exemplo n.º 10
0
func (w *glfwBackend) Open(width, height, zoom int, fs bool, font *FontData) {
	if err := glfw.Init(); err != nil {
		panic(err)
	}

	w.font = font
	w.zoom = zoom
	w.width = width
	w.height = height

	var fwidth = width * font.CellWidth * zoom
	var fheight = height * font.CellHeight * zoom
	var twidth = fwidth
	var theight = fheight

	flag := glfw.Windowed
	if fs {
		flag = glfw.Fullscreen
		dm := glfw.DesktopMode()
		twidth = dm.W
		theight = dm.H
	}

	glfw.OpenWindowHint(glfw.WindowNoResize, gl.TRUE)
	err := glfw.OpenWindow(twidth, theight, 8, 8, 8, 8, 0, 0, flag)
	if err != nil {
		panic(err)
	}

	w.key = NOKEY
	glfw.SetWindowCloseCallback(func() int { w.Close(); return 0 })
	glfw.SetKeyCallback(func(key, state int) { w.setKey(key, state) })
	glfw.SetCharCallback(func(key, state int) { w.setKey(key, state) })
	glfw.Enable(glfw.KeyRepeat)

	w.mouse = new(MouseData)
	glfw.Enable(glfw.MouseCursor)
	glfw.SetMousePosCallback(func(x, y int) { w.mouseMove(x, y) })
	glfw.SetMouseButtonCallback(func(but, state int) { w.mousePress(but, state) })
	glfw.Enable(glfw.MouseCursor)

	xoff := float32(twidth-fwidth) / 2.0
	yoff := float32(theight-fheight) / 2.0

	fc := float32(font.CellWidth * zoom)
	fch := float32(font.CellHeight * zoom)
	for y := 0; y < height; y++ {
		for x := 0; x < width; x++ {
			cx := xoff + float32(x)*fc
			cy := yoff + float32(y)*fch
			w.verts = append(w.verts, cx, cy, cx, cy+fch, cx+fc, cy+fch, cx+fc, cy)
		}
	}

	runtime.LockOSThread()
	glInit(twidth, theight)

	m := font.Image.(*image.RGBA)
	w.s = float32(font.CellWidth) / float32(m.Bounds().Max.X)
	w.t = float32(font.CellHeight) / float32(m.Bounds().Max.Y)
	textures = make([]gl.Uint, 2)
	gl.GenTextures(2, &textures[0])

	gl.BindTexture(gl.TEXTURE_2D, textures[0])
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
	gl.TexImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.Sizei(m.Bounds().Max.X), gl.Sizei(m.Bounds().Max.Y), 0, gl.RGBA, gl.UNSIGNED_BYTE, gl.Pointer(&m.Pix[0]))

	m = image.NewRGBA(image.Rect(0, 0, font.CellWidth, font.CellHeight))
	draw.Draw(m, m.Bounds(), &image.Uniform{White}, image.ZP, draw.Src)
	gl.BindTexture(gl.TEXTURE_2D, textures[1])
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
	gl.TexImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.Sizei(m.Bounds().Max.X), gl.Sizei(m.Bounds().Max.Y), 0, gl.RGBA, gl.UNSIGNED_BYTE, gl.Pointer(&m.Pix[0]))

	w.open = true
}
Exemplo n.º 11
0
func Init() {
	glfw.Disable(glfw.MouseCursor)
	glfw.SetMousePosCallback(OnMouseMove)
	glfw.SetMouseButtonCallback(OnMouseClick)
}