コード例 #1
0
ファイル: main.go プロジェクト: runningwild/glomple
func main() {
	sys := system.Make(gos.GetSystemInterface())
	sys.Startup()

	render.Init()
	render.Queue(func() {
		initWindow(sys, 800, 600)
	})

	font := loadDictionary("skia.dict")
	fmt.Fprintf(log, "Font: %v", font)
	for true {
		sys.Think()
		render.Queue(func() {
			// gl.Color4ub(0, 255, 255, 255)
			// gl.Begin(gl.QUADS)
			// gl.Vertex2d(100, 100)
			// gl.Vertex2d(500, 100)
			// gl.Vertex2d(500, 150)
			// gl.Vertex2d(100, 150)
			// gl.End()
			font.SetFontColor(1, 1, 1)
			font.RenderString("TEST", 100, 100, 100)
			sys.SwapBuffers()
		})
		render.Purge()
		if gin.In().GetKey(gin.AnyEscape).FramePressCount() > 0 {
			break
		}
	}
}
コード例 #2
0
ファイル: main.go プロジェクト: runningwild/jbot
func main() {
	sys.Startup()
	err := gl.Init()
	if err != nil {
		base.Error().Fatalf("%v", err)
	}

	render.Init()
	render.Queue(func() {
		sys.CreateWindow(10, 10, wdx, wdy)
		sys.EnableVSync(true)
	})
	base.InitShaders()
	runtime.GOMAXPROCS(10)
	sys.Think()

	console := base.MakeConsole(wdx, wdy)
	controllers := getPlayers(console)
	base.Log().Printf("%v\n", controllers)
	go server.Main()

	base.LoadAllDictionaries()

	client, err := game.MakeClient("127.0.0.1", 1231)
	if err != nil {
		base.Error().Printf("Unable to connect to server: %v\n", err)
		return
	}
	mainLoop(client, controllers, console)
}
コード例 #3
0
ファイル: manager.go プロジェクト: runningwild/jbot
// Launch this in its own go-routine if you want to occassionally
// delete textures that haven't been used in a while.
func (m *Manager) Scavenger() {
	var unused []string
	for {
		time.Sleep(time.Minute)
		unused = unused[0:0]
		m.mutex.RLock()
		for s, d := range m.registry {
			if generation-d.accessed >= 2 {
				unused = append(unused, s)
			}
		}
		m.mutex.RUnlock()

		m.mutex.Lock()
		generation++
		if len(unused) == 0 {
			m.mutex.Unlock()
			continue
		}

		var unused_data []*Data
		for _, s := range unused {
			unused_data = append(unused_data, m.registry[s])
			m.deleted[s] = m.registry[s]
			delete(m.registry, s)
		}
		render.Queue(func() {
			for _, d := range unused_data {
				gl.DeleteTextures(1, (*gl.Uint)(&d.texture))
				d.texture = 0
			}
		})
		m.mutex.Unlock()
	}
}
コード例 #4
0
ファイル: main.go プロジェクト: runningwild/arkanoid
func main() {
	runtime.GOMAXPROCS(2)
	sys := system.Make(gos.GetSystemInterface())
	sys.Startup()

	game := Game{}
	var lb LevelBlueprint
	loadJson(filepath.Join(base.DataDir(), "1p_basic_level.json"), &lb)
	if len(lb.Players) == 0 || len(lb.Walls) == 0 {
		panic(fmt.Sprintf("Invalid level config: %d players and %d walls.",
			len(lb.Players), len(lb.Walls)))
	}
	engine, _ := cgf.NewLocalEngine(&game, int(Config.FrameTime*1000), nil)
	engine.ApplyEvent(&NewLevelEvent{&lb})

	render.Init()
	render.Queue(func() {
		initWindow(sys, Config.WindowWidth, Config.WindowHeight)
	})
	render.Purge()

	ticker := time.Tick(time.Millisecond * time.Duration(Config.FrameTime*1000))
	for true {
		<-ticker
		LocalThink(sys, engine, &game)
		if gin.In().GetKey(gin.AnyEscape).FramePressCount() > 0 {
			break
		}
	}
}
コード例 #5
0
ファイル: main.go プロジェクト: runningwild/jota
func main() {
	defer base.StackCatcher()
	sys.Startup()
	err := gl.Init()
	if err != nil {
		base.Error().Fatalf("%v", err)
	}

	render.Init()
	render.Queue(func() {
		sys.CreateWindow(10, 10, wdx, wdy)
		sys.EnableVSync(true)
	})
	base.InitShaders()
	runtime.GOMAXPROCS(10)
	sys.Think()

	base.LoadAllDictionaries()

	if Version() != "standard" {
		engine := debugHookup(Version())
		mainLoop(engine, "standard")
	} else {
		// TODO: Reimplement standard hookup
	}
}
コード例 #6
0
ファイル: main.go プロジェクト: runningwild/jbot
func getPlayers(console *base.Console) []gin.DeviceId {
	var ct controllerTracker
	gin.In().RegisterEventListener(&ct)
	defer gin.In().UnregisterEventListener(&ct)
	ticker := time.Tick(time.Millisecond * 17)
	start := time.Time{}
	readyDuration := time.Second * 2
	for start.IsZero() || time.Now().Sub(start) < readyDuration {
		<-ticker
		sys.Think()
		if ct.Ready() && start.IsZero() {
			start = time.Now()
		}
		if !ct.Ready() {
			start = time.Time{}
		}
		render.Queue(func() {
			defer console.Draw(0, 0, wdx, wdy)
			gl.Clear(gl.COLOR_BUFFER_BIT)
			gl.Disable(gl.DEPTH_TEST)
			gui.SetFontColor(1, 1, 1, 1)
			gl.Disable(gl.TEXTURE_2D)
			gl.MatrixMode(gl.PROJECTION)
			gl.LoadIdentity()
			gl.Ortho(gl.Double(0), gl.Double(wdx), gl.Double(wdy), gl.Double(0), 1000, -1000)
			gl.ClearColor(0, 0, 0, 1)
			gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
			gl.MatrixMode(gl.MODELVIEW)
			gl.LoadIdentity()
			base.GetDictionary("crackin").RenderString(fmt.Sprintf("Num players: %d", len(ct.ids)), float64(wdx)/2, 300, 0, 100, gui.Center)
			base.GetDictionary("crackin").RenderString(fmt.Sprintf("Num ready: %d", ct.NumReady()), float64(wdx)/2, 400, 0, 100, gui.Center)
			if !start.IsZero() {
				base.GetDictionary("crackin").RenderString(fmt.Sprintf("Starting in %2.2f", (readyDuration-time.Now().Sub(start)).Seconds()), float64(wdx)/2, 500, 0, 100, gui.Center)
			}
		})
		render.Queue(func() {
			sys.SwapBuffers()
		})
		render.Purge()
	}
	var devices []gin.DeviceId
	for id := range ct.ids {
		devices = append(devices, id)
	}
	return devices
}
コード例 #7
0
ファイル: main.go プロジェクト: runningwild/jbot
func mainLoop(client sgf.ClientEngine, controllers []gin.DeviceId, console *base.Console) {
	client.MakeRequest(game.Join{Rebels: make([]*game.RebelPlayer, 2)})
	ticker := time.Tick(time.Millisecond * 17)
	render.Queue(func() {
		gl.Enable(gl.BLEND)
		gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)
	})
	for {
		<-ticker
		if gin.In().GetKey(gin.AnyEscape).FramePressCount() != 0 {
			return
		}
		sys.Think()
		render.Queue(func() {
			gl.Clear(gl.COLOR_BUFFER_BIT)
			gl.Disable(gl.DEPTH_TEST)
			gui.SetFontColor(1, 1, 1, 1)
			gl.Disable(gl.TEXTURE_2D)
			gl.MatrixMode(gl.PROJECTION)
			gl.LoadIdentity()
			gl.Ortho(gl.Double(0), gl.Double(wdx), gl.Double(wdy), gl.Double(0), 1000, -1000)
			gl.ClearColor(0, 0, 0, 1)
			gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
			gl.MatrixMode(gl.MODELVIEW)
			gl.LoadIdentity()
			base.GetDictionary("crackin").RenderString("Waiting on some nubs", float64(wdx)/2, 300, 0, 100, gui.Center)
		})

		client.RLock()
		g := client.Game().(*game.Game)
		mode := g.Mode
		client.RUnlock()
		if mode == game.ModeWaiting {
		} else if mode == game.ModeProgram {
			programLoop(client, controllers, console)
		} else if mode == game.ModeRun {

		}

		render.Queue(func() {
			sys.SwapBuffers()
		})
		render.Purge()
	}
}
コード例 #8
0
ファイル: text.go プロジェクト: jctaylor1/haunts
// Sets up anything that wouldn't have been loaded from disk, including
// all opengl data, and sets up finalizers for that data.
func (d *Dictionary) setupGlStuff() {
	d.dlists = make(map[string]uint32)
	d.strs = make(map[string]strBuffer)
	d.pars = make(map[string]strBuffer)

	// TODO: This finalizer is untested
	runtime.SetFinalizer(d, func(d *Dictionary) {
		render.Queue(func() {
			for _, v := range d.dlists {
				gl.DeleteLists(gl.Uint(v), 1)
			}
		})
	})

	render.Queue(func() {
		gl.Enable(gl.TEXTURE_2D)
		gl.GenTextures(1, (*gl.Uint)(&d.texture))
		gl.BindTexture(gl.TEXTURE_2D, gl.Uint(d.texture))
		gl.PixelStorei(gl.UNPACK_ALIGNMENT, 1)
		gl.TexEnvf(gl.TEXTURE_ENV, gl.TEXTURE_ENV_MODE, gl.MODULATE)
		gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
		gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
		gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT)
		gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT)

		gl.TexImage2D(
			gl.TEXTURE_2D,
			0,
			gl.ALPHA,
			gl.Sizei(d.data.Dx),
			gl.Sizei(d.data.Dy),
			0,
			gl.ALPHA,
			gl.UNSIGNED_BYTE,
			gl.Pointer(&d.data.Pix[0]))

		gl.Disable(gl.TEXTURE_2D)
	})
}
コード例 #9
0
ファイル: sheet.go プロジェクト: runningwild/glop
func (s *sheet) loadRoutine() {
	ready := make(chan bool, 1)
	pixer := make(chan []byte)
	for load := range s.load_chan {
		if load {
			go s.compose(pixer)
			go func() {
				render.Queue(func() {
					s.makeTexture(pixer)
					ready <- true
				})
			}()
		} else {
			go func() {
				<-ready
				render.Queue(func() {
					gl.DeleteTextures(1, &s.texture)
					s.texture = 0
				})
			}()
		}
	}
}
コード例 #10
0
ファイル: game.go プロジェクト: runningwild/arkanoid
func LocalThink(sys system.System, engine *cgf.Engine, game *Game) {
	sys.Think()
	engine.Pause()

	// We might have no level if the event has not gone through yet.
	if game.Level != nil {
		render.Queue(func() {
			game.Render()
			sys.SwapBuffers()
		})
		game.Level.LocalThink(sys, engine)
	}

	render.Purge()
	engine.Unpause()
}
コード例 #11
0
ファイル: text.go プロジェクト: jctaylor1/haunts
func LoadDictionary(r io.Reader) (*Dictionary, error) {
	init_once.Do(func() {
		render.Queue(func() {
			err := render.RegisterShader("glop.font", []byte(font_vertex_shader), []byte(font_fragment_shader))
			if err != nil {
				panic(err)
			}
		})
		render.Purge()
	})

	var d Dictionary
	err := gob.NewDecoder(r).Decode(&d.data)
	if err != nil {
		return nil, err
	}
	d.setupGlStuff()
	return &d, nil
}
コード例 #12
0
ファイル: sprite.go プロジェクト: runningwild/glop
func (m *Manager) LoadSprite(path string) (*Sprite, error) {
	// We can't run this during an init() function because it will get queued to
	// run before the opengl context is created, so we just check here and run
	// it if we haven't run it before.
	gen_tex_once.Do(func() {
		render.Queue(func() {
			gl.Enable(gl.TEXTURE_2D)
			gl.GenTextures(1, &error_texture)
			gl.BindTexture(gl.TEXTURE_2D, error_texture)
			gl.TexEnvf(gl.TEXTURE_ENV, gl.TEXTURE_ENV_MODE, gl.MODULATE)
			gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR)
			gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
			gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT)
			gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT)
			pink := []byte{255, 0, 255, 255}
			gl.TexImage2D(
				gl.TEXTURE_2D,
				0,
				gl.RGBA,
				1,
				1,
				0,
				gl.RGBA,
				gl.UNSIGNED_INT,
				gl.Pointer(&pink[0]))
		})
	})

	path = filepath.Clean(path)
	err := m.loadSharedSprite(path)
	if err != nil {
		return nil, err
	}
	var s Sprite
	m.mutex.Lock()
	s.shared = m.shared[path]
	m.mutex.Unlock()
	s.anim_node = s.shared.anim_start
	s.state_node = s.shared.state_start
	return &s, nil
}
コード例 #13
0
ファイル: manager.go プロジェクト: runningwild/jbot
func setupTextureList() {
	textureListSync.Do(func() {
		render.Queue(func() {
			textureList = gl.GenLists(1)
			gl.NewList(textureList, gl.COMPILE)
			gl.Begin(gl.QUADS)
			gl.TexCoord2d(0, -1)
			gl.Vertex2i(0, 0)

			gl.TexCoord2d(0, 0)
			gl.Vertex2i(0, 1)

			gl.TexCoord2d(1, 0)
			gl.Vertex2i(1, 1)

			gl.TexCoord2d(1, -1)
			gl.Vertex2i(1, 0)
			gl.End()
			gl.EndList()
		})
	})
}
コード例 #14
0
ファイル: main.go プロジェクト: runningwild/magnus
func main() {
	defer base.StackCatcher()
	fmt.Printf("sys.Startup()...")
	sys.Startup()
	fmt.Printf("successful.\n")
	fmt.Printf("gl.Init()...")
	err := gl.Init()
	fmt.Printf("successful.\n")
	if err != nil {
		base.Error().Fatalf("%v", err)
	}

	fmt.Printf("render.Init()...")
	render.Init()
	fmt.Printf("successful.\n")
	render.Queue(func() {
		fmt.Printf("sys.CreateWindow()...")
		sys.CreateWindow(10, 10, wdx, wdy)
		fmt.Printf("successful.\n")
		sys.EnableVSync(true)
	})
	base.InitShaders()
	runtime.GOMAXPROCS(10)
	fmt.Printf("sys.Think()...")
	sys.Think()
	fmt.Printf("successful.\n")

	base.LoadAllDictionaries()

	if Version() != "standard" {
		engine, local := debugHookup(Version())
		mainLoop(engine, local, "standard")
	} else {
		standardHookup()
	}
}
コード例 #15
0
ファイル: main.go プロジェクト: dgthunder/magnus
func main() {
	fmt.Printf("%v\n", key_map)
	sys.Startup()
	err := gl.Init()
	if err != nil {
		panic(err)
	}

	render.Init()
	render.Queue(func() {
		sys.CreateWindow(10, 10, wdx, wdy)
		sys.EnableVSync(true)
		err := gl.Init()
		if err != nil {
			panic(err)
		}
	})
	base.InitShaders()
	runtime.GOMAXPROCS(2)
	ui, err = gui.Make(gin.In(), gui.Dims{wdx, wdy}, filepath.Join(datadir, "fonts", "skia.ttf"))
	if err != nil {
		panic(err)
	}
	sys.Think()
	for false && len(sys.GetActiveDevices()[gin.DeviceTypeController]) < 2 {
		time.Sleep(time.Millisecond * 100)
		sys.Think()
	}

	var ids []int
	var engine *cgf.Engine
	var room game.Room
	err = base.LoadJson(filepath.Join(base.GetDataDir(), "rooms/basic.json"), &room)
	if err != nil {
		panic(err)
	}
	if IsHost() {
		sys.Think()
		var g game.Game
		g.Rng = cmwc.MakeGoodCmwc()
		g.Rng.SeedWithDevRand()
		g.Dx = 900
		g.Dy = 600
		g.Friction = 0.97
		g.Friction_lava = 0.85
		g.Room = room
		var p game.Player
		p.Color.R = 255
		err := json.NewDecoder(bytes.NewBuffer([]byte(`
      {
        "Base": {
          "Max_turn": 0.07,
          "Max_acc": 0.2,
          "Mass": 750,
          "Max_rate": 10,
          "Influence": 75,
          "Health": 1000
        },
        "Dynamic": {
          "Health": 1000
        }
      }
    `))).Decode(&p.Stats)
		if err != nil {
			panic(err)
		}
		Nx := 2
		Ny := 1
		p.X = float64(g.Dx-Nx)/2 - 200
		p.Y = float64(g.Dy-Ny)/2 - 200
		for x := 0; x < Nx; x++ {
			for y := 0; y < Ny; y++ {
				p.X += float64(x * 25)
				p.Y += float64(y * 25)
				p.Gid++
				// p.Mass += float64(x+y) * 150
				p.Processes = make(map[int]game.Process)
				temp := p
				ids = append(ids, g.AddEnt(&temp))

				// p.Mass -= float64(x+y) * 150
				p.X -= float64(x * 25)
				p.Y -= float64(y * 25)
			}
		}
		g.Ents[0].(*game.Player).X = 500
		g.Ents[0].(*game.Player).Y = 300
		g.Ents[1].(*game.Player).X = 550
		g.Ents[1].(*game.Player).Y = 300
		g.SetLocalData()
		d := sys.GetActiveDevices()
		base.Log().Printf("%v\n", d)
		n := 0
		base.Log().Printf("%v\n", d[gin.DeviceTypeController])
		for _, index := range d[gin.DeviceTypeController] {
			// panic("ASD")
			g.SetLocalPlayer(g.Ents[n].(*game.Player), index)
			n++
			if n > 2 {
				break
			}
		}
		if len(d[gin.DeviceTypeController]) == 0 {
			g.SetLocalPlayer(g.Ents[0].(*game.Player), 0)
		}
		// g.Ents[0], g.Ents[(N*N)/2+(1-N%2)*N/2] = g.Ents[(N*N)/2+(1-N%2)*N/2], g.Ents[0]
		g.Init()
		// engine, err = cgf.NewLocalEngine(&g, 17, base.Log())
		engine, err = cgf.NewHostEngine(&g, 17, "", 1231, base.Log())
		if err != nil {
			panic(err.Error())
		}
		g.SetEngine(engine)
	} else {
		engine, err = cgf.NewClientEngine(17, "", 1231, base.Log())
		if err != nil {
			panic(err.Error())
		}
		engine.CopyState().(*game.Game).SetEngine(engine)
	}

	anchor := gui.MakeAnchorBox(gui.Dims{wdx, wdy})
	ui.AddChild(anchor)
	anchor.AddChild(&game.GameWindow{Engine: engine}, gui.Anchor{0.5, 0.5, 0.5, 0.5})
	var v float64
	var profile_output *os.File
	var num_mem_profiles int
	// ui.AddChild(base.MakeConsole())

	base.LoadAllDictionaries()

	for gin.In().GetKey(gin.AnyEscape).FramePressCount() == 0 {
		sys.Think()
		render.Queue(func() {
			ui.Draw()
		})
		render.Queue(func() {
			sys.SwapBuffers()
		})
		render.Purge()
		game.LocalThink()

		if IsHost() {
			for i := 0; i <= 0; i++ {
				// down_axis := gin.In().GetKeyFlat(gin.ControllerAxis0Positive+1, gin.DeviceTypeController, gin.DeviceIndexAny)
				// up_axis := gin.In().GetKeyFlat(gin.ControllerAxis0Negative+1, gin.DeviceTypeController, gin.DeviceIndexAny)
				// right_axis := gin.In().GetKeyFlat(gin.ControllerAxis0Positive, gin.DeviceTypeController, gin.DeviceIndexAny)
				// left_axis := gin.In().GetKeyFlat(gin.ControllerAxis0Negative, gin.DeviceTypeController, gin.DeviceIndexAny)
				// up := key_map[fmt.Sprintf("%dup", i)].FramePressAvg()
				// down := key_map[fmt.Sprintf("%ddown", i)].FramePressAvg()
				// left := key_map[fmt.Sprintf("%dleft", i)].FramePressAvg()
				// right := key_map[fmt.Sprintf("%dright", i)].FramePressAvg()
				// up = axisControl(up_axis.FramePressAmt())
				// down = axisControl(down_axis.FramePressAmt())
				// left = axisControl(left_axis.FramePressAmt())
				// right = axisControl(right_axis.FramePressAmt())
				// if up-down != 0 {
				// 	engine.ApplyEvent(game.Accelerate{ids[i], 2 * (up - down)})
				// }
				// if left-right != 0 {
				// 	engine.ApplyEvent(game.Turn{ids[i], (left - right)})
				// }

				// if key_map[fmt.Sprintf("%d-1", i)].FramePressCount() > 0 {
				// 	engine.ApplyEvent(game.Pull{ids[i], 0, 20000})
				// }
				// if key_map[fmt.Sprintf("%d-2", i)].FramePressCount() > 0 {
				// 	engine.ApplyEvent(game.MoonFire{ids[i], 1, 50, 50})
				// }
				// if gin.In().GetKeyFlat(gin.ControllerButton0, gin.DeviceTypeController, gin.DeviceTypeAny).FramePressCount() > 0 {
				// if key_map[fmt.Sprintf("%d-3", i)].FramePressCount() > 0 {
				// engine.ApplyEvent(game.Burst{ids[i], 2, 3, 100000})
				// }
			}
		}

		// TODO: Replace the 'P' key with an appropriate keybind
		if gin.In().GetKey(gin.AnyKeyP).FramePressCount() > 0 {
			if profile_output == nil {
				profile_output, err = os.Create(filepath.Join(datadir, "cpu.prof"))
				if err == nil {
					err = pprof.StartCPUProfile(profile_output)
					if err != nil {
						fmt.Printf("Unable to start CPU profile: %v\n", err)
						profile_output.Close()
						profile_output = nil
					}
					fmt.Printf("profout: %v\n", profile_output)
				} else {
					fmt.Printf("Unable to start CPU profile: %v\n", err)
				}
			} else {
				pprof.StopCPUProfile()
				profile_output.Close()
				profile_output = nil
			}
		}

		// TODO: Replace the 'M' key with an appropriate keybind
		if gin.In().GetKey(gin.AnyKeyM).FramePressCount() > 0 {
			f, err := os.Create(filepath.Join(datadir, fmt.Sprintf("mem.%d.prof", num_mem_profiles)))
			if err != nil {
				base.Error().Printf("Unable to write mem profile: %v", err)
			}
			pprof.WriteHeapProfile(f)
			f.Close()
			num_mem_profiles++
		}

		v += 0.01
	}
}
コード例 #16
0
ファイル: main.go プロジェクト: runningwild/tester
func main() {
	sys = system.Make(gos.GetSystemInterface())
	sys.Startup()
	wdx := 1000
	wdy := 500
	render.Init()
	var ui *gui.Gui
	render.Queue(func() {
		sys.CreateWindow(50, 150, wdx, wdy)
		sys.EnableVSync(true)
		err := gl.Init()
		if err != nil {
			f, err2 := os.Create(filepath.Join(datadir, "gl_log.txt"))
			if err2 != nil {
				fmt.Printf("Unable to write log to a file:%v\n%v\v", err, err2)
			} else {
				fmt.Fprintf(f, "%v\n", err)
				f.Close()
			}
		}
		ui, _ = gui.Make(gin.In(), gui.Dims{wdx, wdy}, filepath.Join(datadir, "fonts", "luxisr.ttf"))
		font, err := loadFont()
		if err != nil {
			panic(err.Error())
		}
		dict = gui.MakeDictionary(font, 15)
	})
	render.Purge()

	anchor := gui.MakeAnchorBox(gui.Dims{wdx, wdy})
	ui.AddChild(anchor)
	var event_handler handler
	gin.In().RegisterEventListener(&event_handler)
	actions_list := gui.MakeVerticalTable()
	keyname_list := gui.MakeVerticalTable()
	both_lists := gui.MakeHorizontalTable()
	both_lists.AddChild(actions_list)
	both_lists.AddChild(keyname_list)
	anchor.AddChild(both_lists, gui.Anchor{1, 0.5, 1, 0.5})
	var actions []string
	for action := range action_map {
		actions = append(actions, action)
	}
	sort.Strings(actions)
	for _, action := range actions {
		actions_list.AddChild(gui.MakeTextLine("standard", action, 150, 1, 1, 1, 1))
		keyname_list.AddChild(gui.MakeTextLine("standard", commands[action].Cmd, 100, 1, 1, 1, 1))
	}

	current_anim := gui.MakeTextLine("standard", "", 300, 1, 1, 1, 1)
	current_state := gui.MakeTextLine("standard", "", 300, 1, 1, 1, 1)
	frame_data := gui.MakeVerticalTable()
	frame_data.AddChild(current_anim)
	frame_data.AddChild(current_state)
	anchor.AddChild(frame_data, gui.Anchor{0, 1, 0, 1})

	speed := 100
	speed_text := gui.MakeTextLine("standard", "Speed: 100%", 150, 1, 1, 1, 1)
	anchor.AddChild(speed_text, gui.Anchor{0, 0, 0, 0})

	var box1, box2 boxdata

	box1.name = "box1"
	box1.sb = makeSpriteBox(nil)
	anchor.AddChild(box1.sb, gui.Anchor{0.5, 0.5, 0.25, 0.5})
	box1.load(GetStoreVal("box1"))
	box := box1

	box2.name = "box2"
	box2.sb = makeSpriteBox(nil)
	anchor.AddChild(box2.sb, gui.Anchor{0.5, 0.5, 0.45, 0.5})
	box2.load(GetStoreVal("box2"))
	box2.sb.top = true
	box_other := box2

	box2.sb.r, box2.sb.g, box2.sb.b = 0.2, 0.1, 0.4
	box1.sb.r, box1.sb.g, box1.sb.b = 0.4, 0.2, 0.8

	error_msg = gui.MakeTextLine("standard", "", wdx, 1, 0.5, 0.5, 1)
	anchor.AddChild(error_msg, gui.Anchor{0, 0, 0, 0.1})

	var chooser gui.Widget
	// curdir := GetStoreVal("curdir")
	// if curdir == "" {
	//   curdir = "."
	// } else {
	//   _,err := os.Stat(filepath.Join(datadir, curdir))
	//   if err == nil {
	//     go func() {
	//       anim, err := sprite.LoadSprite(filepath.Join(datadir, curdir))
	//       loaded <- loadResult{ anim, err }
	//     } ()
	//   } else {
	//     curdir = "."
	//   }
	// }
	// var profile_output *os.File
	then := time.Now()
	sys.Think()
	for key_map["quit"].FramePressCount() == 0 {
		event_handler.box1 = &box
		event_handler.box2 = &box_other
		now := time.Now()
		dt := (now.Nanosecond() - then.Nanosecond()) / 1000000
		then = now
		render.Queue(func() {
			sys.Think()
			if box1.sb.s != nil {
				box1.sb.s.Think(int64(float64(dt) * float64(speed) / 100))
			}
			if box2.sb.s != nil {
				box2.sb.s.Think(int64(float64(dt) * float64(speed) / 100))
			}
			gl.ClearColor(1, 0, 0, 1)
			gl.Clear(gl.COLOR_BUFFER_BIT)
			ui.Draw()
			sys.SwapBuffers()
		})
		render.Purge()
		select {
		case load := <-loaded:
			if load.err != nil {
				error_msg.SetText(load.err.Error())
				current_anim.SetText("")
			} else {
				box.sb.s = load.anim
				error_msg.SetText("")
			}
		default:
		}
		// if box.sb.s != nil {
		//   box.sb.s.Think()
		//   current_anim.SetText(fmt.Sprintf("%d: %s", box.sb.s.Facing(), box.sb.s.Anim()))
		//   current_state.SetText(box.sb.s.AnimState())
		// }

		if box.sb.s != nil {
			if key_map["reset"].FramePressCount() > 0 {
				box.load(box.dir)
				box_other.load(box_other.dir)
			}
		}

		// if key_map["profile"].FramePressCount() > 0 {
		//   if profile_output == nil {
		//     var err error
		//     profile_output, err = os.Create(filepath.Join(datadir, "cpu.prof"))
		//     if err == nil {
		//       err = pprof.StartCPUProfile(profile_output)
		//       if err != nil {
		//         fmt.Printf("Unable to start CPU profile: %v\n", err)
		//         profile_output.Close()
		//         profile_output = nil
		//       }
		//       fmt.Printf("profout: %v\n", profile_output)
		//     } else {
		//       fmt.Printf("Unable to open CPU profile: %v\n", err)
		//     }
		//   } else {
		//     pprof.StopCPUProfile()
		//     profile_output.Close()
		//     profile_output = nil
		//   }
		// }

		if key_map["load"].FramePressCount() > 0 && chooser == nil {
			anch := gui.MakeAnchorBox(gui.Dims{wdx, wdy})
			file_chooser := gui.MakeFileChooser(filepath.Join(datadir, box.dir),
				func(path string, err error) {
					if err == nil && len(path) > 0 {
						curpath, _ := filepath.Split(path)
						box.load(curpath)
					}
					ui.RemoveChild(chooser)
					chooser = nil
				},
				func(path string, is_dir bool) bool {
					return true
				})
			anch.AddChild(file_chooser, gui.Anchor{0.5, 0.5, 0.5, 0.5})
			chooser = anch
			ui.AddChild(chooser)
		}
		delta := key_map["speed up"].FramePressAmt() - key_map["slow down"].FramePressAmt()
		if delta != 0 {
			speed += int(delta)
			if speed < 1 {
				speed = 1
			}
			if speed > 100 {
				speed = 100
			}
			speed_text.SetText(fmt.Sprintf("Speed: %d%%", speed))
		}

		if key_map["select1"].FramePressCount() > 0 {
			box2.sb.r, box2.sb.g, box2.sb.b = 0.2, 0.1, 0.4
			box1.sb.r, box1.sb.g, box1.sb.b = 0.4, 0.2, 0.8
			box = box1
			box_other = box2
		}
		if key_map["select2"].FramePressCount() > 0 {
			box2.sb.r, box2.sb.g, box2.sb.b = 0.4, 0.2, 0.8
			box1.sb.r, box1.sb.g, box1.sb.b = 0.2, 0.1, 0.4
			box = box2
			box_other = box1
		}
	}
}
コード例 #17
0
ファイル: shaders.go プロジェクト: RickDakan/haunts
func InitShaders() {
	render.Queue(func() {
		vertex_shaders = make(map[string]uint32)
		fragment_shaders = make(map[string]uint32)
		shader_progs = make(map[string]uint32)
		warned_names = make(map[string]bool)
		RemoveRegistry("shaders")
		RegisterRegistry("shaders", make(map[string]*shaderDef))
		RegisterAllObjectsInDir("shaders", filepath.Join(GetDataDir(), "shaders"), ".json", "json")
		names := GetAllNamesInRegistry("shaders")
		for _, name := range names {
			// Load the shader files
			shader := Shader{Defname: name}
			GetObject("shaders", &shader)
			vdata, err := ioutil.ReadFile(filepath.Join(GetDataDir(), shader.Vertex_path))
			if err != nil {
				Error().Printf("Unable to load vertex shader '%s': %v", shader.Vertex_path, err)
				continue
			}
			fdata, err := ioutil.ReadFile(filepath.Join(GetDataDir(), shader.Fragment_path))
			if err != nil {
				Error().Printf("Unable to load fragment shader '%s': %v", shader.Fragment_path, err)
				continue
			}

			// Create the vertex shader
			vertex_id, ok := vertex_shaders[shader.Vertex_path]
			if !ok {
				vertex_id = gl.CreateShader(gl.VERTEX_SHADER)
				pointer := &vdata[0]
				length := int32(len(vdata))
				gl.ShaderSource(vertex_id, 1, (**gl.Char)(unsafe.Pointer(&pointer)), &length)
				gl.CompileShader(vertex_id)
				var param int32
				gl.GetShaderiv(vertex_id, gl.COMPILE_STATUS, &param)
				if param == 0 {
					Error().Printf("Failed to compile vertex shader '%s': %v", shader.Vertex_path, param)
					continue
				}
			}

			// Create the fragment shader
			fragment_id, ok := fragment_shaders[shader.Fragment_path]
			if !ok {
				fragment_id = gl.CreateShader(gl.FRAGMENT_SHADER)
				pointer := &fdata[0]
				length := int32(len(fdata))
				gl.ShaderSource(fragment_id, 1, (**gl.Char)(unsafe.Pointer(&pointer)), &length)
				gl.CompileShader(fragment_id)
				var param int32
				gl.GetShaderiv(fragment_id, gl.COMPILE_STATUS, &param)
				if param == 0 {
					Error().Printf("Failed to compile fragment shader '%s': %v", shader.Fragment_path, param)
					continue
				}
			}

			// shader successfully compiled - now link
			program_id := gl.CreateProgram()
			gl.AttachShader(program_id, vertex_id)
			gl.AttachShader(program_id, fragment_id)
			gl.LinkProgram(program_id)
			var param int32
			gl.GetProgramiv(program_id, gl.LINK_STATUS, &param)
			if param == 0 {
				Error().Printf("Failed to link shader '%s': %v", shader.Name, param)
				continue
			}

			vertex_shaders[shader.Vertex_path] = vertex_id
			fragment_shaders[shader.Fragment_path] = fragment_id
			shader_progs[shader.Name] = program_id
		}
	})
}
コード例 #18
0
ファイル: manager.go プロジェクト: runningwild/jbot
func handleLoadRequest(req loadRequest) {
	f, _ := os.Open(req.path)
	im, _, err := image.Decode(f)
	f.Close()
	if err != nil {
		return
	}
	gray := true
	dx := im.Bounds().Dx()
	dy := im.Bounds().Dy()
	for i := 0; i < dx; i++ {
		for j := 0; j < dy; j++ {
			r, g, b, _ := im.At(i, j).RGBA()
			if r != g || g != b {
				gray = false
				break
			}
		}
		if !gray {
			break
		}
	}
	var canvas draw.Image
	var pix []byte
	if gray {
		ga := NewGrayAlpha(im.Bounds())
		pix = ga.Pix
		canvas = ga
	} else {
		pix = memory.GetBlock(4 * req.data.dx * req.data.dy)
		canvas = &image.RGBA{pix, 4 * req.data.dx, im.Bounds()}
	}
	draw.Draw(canvas, im.Bounds(), im, image.Point{}, draw.Src)
	load_mutex.Lock()
	load_count += len(pix)
	manual_unlock := false
	// This prevents us from trying to send too much to opengl in a single
	// frame.  If we go over the threshold then we hold the lock until we're
	// done sending data to opengl, then other requests will be free to
	// queue up and they will run on the next frame.
	if load_count < load_threshold {
		load_mutex.Unlock()
	} else {
		manual_unlock = true
	}
	render.Queue(func() {
		{
			gl.Enable(gl.TEXTURE_2D)
			gl.GenTextures(1, (*gl.Uint)(&req.data.texture))
			gl.BindTexture(gl.TEXTURE_2D, req.data.texture)
			gl.PixelStorei(gl.UNPACK_ALIGNMENT, 1)
			gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
			gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
			gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT)
			gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT)
		}
		if gray {
			gl.TexImage2D(
				gl.TEXTURE_2D,
				0,
				gl.LUMINANCE_ALPHA,
				gl.Sizei(req.data.dx),
				gl.Sizei(req.data.dy),
				0,
				gl.LUMINANCE_ALPHA,
				gl.BYTE,
				gl.Pointer(&pix[0]))
		} else {
			gl.TexImage2D(
				gl.TEXTURE_2D,
				0,
				gl.RGBA,
				gl.Sizei(req.data.dx),
				gl.Sizei(req.data.dy),
				0,
				gl.RGBA,
				gl.UNSIGNED_BYTE,
				gl.Pointer(&pix[0]))
			// gl.TexImage2D(target, level, internalformat, width, height, border, format, type_, pixels)
			// glu.Build2DMipmaps(gl.TEXTURE_2D, gl.RGBA, req.data.dx, req.data.dy, gl.RGBA, pix)
		}
		memory.FreeBlock(pix)
		if manual_unlock {
			load_count = 0
			load_mutex.Unlock()
		}
	})
}
コード例 #19
0
ファイル: main.go プロジェクト: runningwild/shadertest
func main() {
	{
		f, err := os.Create("/Users/jwills/code/src/github.com/runningwild/shadertest/log.err")
		if err != nil {
			panic("shoot")
		}
		os.Stderr = f
		f, err = os.Create("/Users/jwills/code/src/github.com/runningwild/shadertest/log.out")
		if err != nil {
			panic("shoot")
		}
		os.Stdout = f
	}
	sys.Startup()
	err := gl.Init()
	if err != nil {
		panic(err)
	}
	fmt.Printf("RAWR!!!\n")
	render.Init()
	render.Queue(func() {
		sys.CreateWindow(10, 10, wdx, wdy)
		sys.EnableVSync(true)
		err := gl.Init()
		if err != nil {
			panic(err)
		}
	})
	base.InitShaders()
	runtime.GOMAXPROCS(2)
	ui, err = gui.Make(gin.In(), gui.Dims{wdx, wdy}, filepath.Join(datadir, "fonts", "skia.ttf"))
	if err != nil {
		panic(err)
	}

	anchor := gui.MakeAnchorBox(gui.Dims{wdx, wdy})
	ui.AddChild(anchor)
	var v float64
	// var profile_output *os.File
	// var num_mem_profiles int
	// ui.AddChild(base.MakeConsole())
	size := 19.0
	base.InitShaders()
	x := gl.Double(0.0)
	// y := 0.0
	// tex := texture.LoadFromPath(filepath.Join(base.GetDataDir(), "test/out.dff.small.png"))
	fmt.Printf("RAWR!\n")
	listener := Listener{}
	gin.In().RegisterEventListener(&listener)
	button := gin.In().GetKeyFlat(gin.ControllerButton0+6, gin.DeviceTypeController, gin.DeviceIndexAny)
	fmt.Printf("RAWR!\n")
	for button.FramePressCount() == 0 {
		sys.Think()
		// dsize := gin.In().GetKey(gin.MouseWheelVertical).FramePressAmt()
		// size += dsize
		// x -= float64(tex.Dx()) * dsize / 2
		// y -= float64(tex.Dy()) * dsize / 2
		// if gin.In().GetKey(gin.Down).FramePressAmt() > 0 {
		// 	y += 10
		// }
		// if gin.In().GetKey(gin.Up).FramePressAmt() > 0 {
		// 	y -= 10
		// }
		// if gin.In().GetKey(gin.Left).FramePressAmt() > 0 {
		// 	x += 10
		// }
		// if gin.In().GetKey(gin.Right).FramePressAmt() > 0 {
		// 	x -= 10
		// }
		render.Queue(func() {
			ui.Draw()
			gl.Enable(gl.BLEND)
			gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)
			gl.Disable(gl.TEXTURE_2D)
			gl.Color4ub(255, 0, 0, 255)
			gl.Begin(gl.QUADS)
			gl.Vertex2d(100+x, 20)
			gl.Vertex2d(100+x, gl.Double(size+20))
			gl.Vertex2d(200+x, gl.Double(size+20))
			gl.Vertex2d(200+x, 20)
			x += 1
			gl.End()
			gl.Enable(gl.TEXTURE_2D)
			gl.Color4ub(255, 255, 255, 255)
			// // str := "!@#$%^&*"
			// diff := 5.0 / (math.Log(size) + math.Pow(size, 0.7))

			// // Works for 1200
			// diff = 50 * math.Pow(base.GetDictionary("skia").Scale(), 2) / math.Pow(size, 1.0)

			// // Works for 3000
			// diff = 50 * math.Pow(base.GetDictionary("skia").Scale(), 1.5) / math.Pow(size, 0.8)
			// //0.340637
			// //0.159241
			// diff = 75 * math.Pow(base.GetDictionary("skia").Scale(), 1.0) / math.Pow(size, 1.0)
			// diff = 10 / math.Pow(size, 1.0)
			// diff = 20/math.Pow(size, 1.0) + 5*math.Pow(base.GetDictionary("skia").Scale(), 1.0)/math.Pow(size, 1.0)
			// if diff > 0.45 {
			//   diff = 0.45
			// }
			// base.EnableShader("distance_field")
			// base.SetUniformF("distance_field", "dist_min", float32(0.5-diff))
			// base.SetUniformF("distance_field", "dist_max", float32(0.5+diff))
			// base.GetDictionary("skia").RenderString(str, 100, 20, 0, dy, gui.Left)
			// base.GetDictionary("skia").RenderString(str, 100, 20+2*dy, 0, dy/4, gui.Left)
			// base.GetDictionary("skia").RenderString(str, 100, 20, 0, size, gui.Left)
			lorem := "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum"
			kk := gin.In().GetKeyFlat(gin.ControllerAxis0Positive+1, gin.DeviceTypeController, device_index)
			kl := gin.In().GetKeyFlat(gin.ControllerAxis0Positive+1, gin.DeviceTypeController, gin.DeviceIndexAny)
			s := fmt.Sprintf("%1.2f %1.2f - %1.2f %1.2f", kk.FramePressAvg(), kk.FramePressAmt(), kl.FramePressAvg(), kl.FramePressAmt())
			devices := sys.GetActiveDevices()
			y := 500.0
			for _, t := range []gin.DeviceType{gin.DeviceTypeController, gin.DeviceTypeKeyboard, gin.DeviceTypeMouse} {
				for _, d := range devices[t] {
					var s string
					switch t {
					case gin.DeviceTypeController:
						s = "controller"
					case gin.DeviceTypeKeyboard:
						s = "keyboard"
					case gin.DeviceTypeMouse:
						s = "mouse"
					}
					base.GetDictionary("skia").RenderString(fmt.Sprintf("%s: %d", s, d), 100, y, 0, 45, gui.Left)
					y -= 50
				}
			}
			base.GetDictionary("luxisr").RenderString(s, 50, 50, 0, size, gui.Left)
			// base.GetDictionary("luxisr").RenderString(lorem, 50, 50+size, 0, size, gui.Left)
			base.GetDictionary("skia").RenderString(lorem, 50, 50+2*size, 0, size, gui.Left)
			base.Log().Printf("Foo")
			//      base.EnableShader("")
			// gl.Enable(gl.ALPHA_TEST)
			// gl.AlphaFunc(gl.GREATER, 0.5)
			// tex := texture.LoadFromPath(filepath.Join(base.GetDataDir(), "ships/ship.png"))
			// tex.Bind()
			// tex.RenderAdvanced(x, y, float64(tex.Dx())*size, float64(tex.Dy())*size, 0, true)
			// tex.RenderNatural(300, 100)
			// gl.Disable(gl.ALPHA_TEST)
		})
		render.Queue(func() {
			sys.SwapBuffers()
		})
		render.Purge()

		// if key_map["cpu profile"].FramePressCount() > 0 {
		// 	if profile_output == nil {
		// 		profile_output, err = os.Create(filepath.Join(datadir, "cpu.prof"))
		// 		if err == nil {
		// 			err = pprof.StartCPUProfile(profile_output)
		// 			if err != nil {
		// 				fmt.Printf("Unable to start CPU profile: %v\n", err)
		// 				profile_output.Close()
		// 				profile_output = nil
		// 			}
		// 			fmt.Printf("profout: %v\n", profile_output)
		// 		} else {
		// 			fmt.Printf("Unable to start CPU profile: %v\n", err)
		// 		}
		// 	} else {
		// 		pprof.StopCPUProfile()
		// 		profile_output.Close()
		// 		profile_output = nil
		// 	}
		// }

		// if key_map["mem profile"].FramePressCount() > 0 {
		// 	f, err := os.Create(filepath.Join(datadir, fmt.Sprintf("mem.%d.prof", num_mem_profiles)))
		// 	if err != nil {
		// 		base.Error().Printf("Unable to write mem profile: %v", err)
		// 	}
		// 	pprof.WriteHeapProfile(f)
		// 	f.Close()
		// 	num_mem_profiles++
		// }

		v += 0.01
	}
}
コード例 #20
0
ファイル: manager.go プロジェクト: RickDakan/haunts
func handleLoadRequest(req loadRequest) {
	f, _ := os.Open(req.path)
	im, _, err := image.Decode(f)
	f.Close()
	if err != nil {
		return
	}
	gray := true
	dx := im.Bounds().Dx()
	dy := im.Bounds().Dy()
	for i := 0; i < dx; i++ {
		for j := 0; j < dy; j++ {
			r, g, b, _ := im.At(i, j).RGBA()
			if r != g || g != b {
				gray = false
				break
			}
		}
		if !gray {
			break
		}
	}
	var canvas draw.Image
	var pix []byte
	if gray {
		ga := NewGrayAlpha(im.Bounds())
		pix = ga.Pix
		canvas = ga
	} else {
		pix = memory.GetBlock(4 * req.data.dx * req.data.dy)
		canvas = &image.RGBA{pix, 4 * req.data.dx, im.Bounds()}
	}
	draw.Draw(canvas, im.Bounds(), im, image.Point{}, draw.Src)
	load_mutex.Lock()
	load_count += len(pix)
	manual_unlock := false
	// This prevents us from trying to send too much to opengl in a single
	// frame.  If we go over the threshold then we hold the lock until we're
	// done sending data to opengl, then other requests will be free to
	// queue up and they will run on the next frame.
	if load_count < load_threshold {
		load_mutex.Unlock()
	} else {
		manual_unlock = true
	}
	render.Queue(func() {
		{
			gl.Enable(gl.TEXTURE_2D)
			req.data.texture = gl.GenTexture()
			req.data.texture.Bind(gl.TEXTURE_2D)
			gl.TexEnvf(gl.TEXTURE_ENV, gl.TEXTURE_ENV_MODE, gl.MODULATE)
			gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR)
			gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
			gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT)
			gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT)
		}
		if gray {
			glu.Build2DMipmaps(gl.TEXTURE_2D, gl.LUMINANCE_ALPHA, req.data.dx, req.data.dy, gl.LUMINANCE_ALPHA, pix)
		} else {
			glu.Build2DMipmaps(gl.TEXTURE_2D, gl.RGBA, req.data.dx, req.data.dy, gl.RGBA, pix)
		}
		memory.FreeBlock(pix)
		if manual_unlock {
			load_count = 0
			load_mutex.Unlock()
		}
	})
}
コード例 #21
0
func (sys *sysObj) Think() {
	render.Queue(func() {
		sys.thinkInternal()
	})
}
コード例 #22
0
ファイル: main.go プロジェクト: runningwild/jbot
func programLoop(client sgf.ClientEngine, controllers []gin.DeviceId, console *base.Console) {
	ticker := time.Tick(time.Millisecond * 17)
	var selections cardSelections
	selections.cols = 7
	selections.players = make([]cardSelection, len(controllers))
	client.RLock()
	g := client.Game().(*game.Game)
	for _, card := range g.Cards {
		selections.cards = append(selections.cards, card)
		selections.used = append(selections.used, -1)
	}
	client.RUnlock()
	for {
		<-ticker
		if gin.In().GetKey(gin.AnyEscape).FramePressCount() != 0 {
			return
		}
		for i, device := range controllers {
			up := gin.In().GetKeyFlat(gin.ControllerHatSwitchUp, device.Type, device.Index).FramePressCount()
			down := gin.In().GetKeyFlat(gin.ControllerHatSwitchDown, device.Type, device.Index).FramePressCount()
			left := gin.In().GetKeyFlat(gin.ControllerHatSwitchLeft, device.Type, device.Index).FramePressCount()
			right := gin.In().GetKeyFlat(gin.ControllerHatSwitchRight, device.Type, device.Index).FramePressCount()
			selections.HandleMove(i, right-left, down-up)
			drop := gin.In().GetKeyFlat(gin.ControllerButton0+1, device.Type, device.Index).FramePressCount() > 0
			choose := gin.In().GetKeyFlat(gin.ControllerButton0+2, device.Type, device.Index).FramePressCount() > 0
			if choose {
				selections.HandleChoose(i)
			}
			if drop {
				selections.HandleDrop(i)
			}
		}
		sys.Think()
		render.Queue(func() {
			defer console.Draw(0, 0, wdx, wdy)
			gl.Clear(gl.COLOR_BUFFER_BIT)
			gl.Disable(gl.DEPTH_TEST)
			gui.SetFontColor(1, 1, 1, 1)
			gl.Disable(gl.TEXTURE_2D)
			gl.MatrixMode(gl.PROJECTION)
			gl.LoadIdentity()
			gl.Ortho(gl.Double(0), gl.Double(wdx), gl.Double(wdy), gl.Double(0), 1000, -1000)
			gl.ClearColor(0, 0, 0, 1)
			gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
			gl.MatrixMode(gl.MODELVIEW)
			gl.LoadIdentity()
			client.RLock()
			g := client.Game().(*game.Game)
			renderBoard(g, 10, 10, 400, 400)
			client.RUnlock()
			renderCards(selections.cards, 64, 400, 400, selections.cols, &selections)
			for i, player := range selections.players {
				setColorForIndex(i)
				renderCardReticle(false, 64, player.sx, player.sy, 400, 400)
				renderCards(player.cards, 64, 400, 300-100*i, selections.cols, nil)
			}
		})
		render.Queue(func() {
			sys.SwapBuffers()
		})
		render.Purge()
	}
}
コード例 #23
0
ファイル: main.go プロジェクト: runningwild/magnus
func standardHookup() {
	g := g2.Make(0, 0, wdx, wdy)
	var tm g2.ThunderMenu
	tm.Subs = make(map[string]*g2.ThunderSubMenu)
	triggers := map[gin.KeyId]struct{}{
		gin.AnyReturn: struct{}{},
		gin.In().GetKeyFlat(gin.ControllerButton0+2, gin.DeviceTypeController, gin.DeviceIndexAny).Id(): struct{}{},
	}
	action := ""
	tm.Subs[""] = g2.MakeThunderSubMenu(
		[]g2.Widget{
			&g2.Button{Size: 50, Triggers: triggers, Name: "Debug", Callback: func() { tm.Push("debug") }},
			&g2.Button{Size: 50, Triggers: triggers, Name: "Host LAN game", Callback: func() { base.Log().Printf("HOST"); print("HOST\n") }},
			&g2.Button{Size: 50, Triggers: triggers, Name: "Join LAN game", Callback: func() { base.Log().Printf("JOIN"); print("JOIN\n") }},
			&g2.Button{Size: 50, Triggers: triggers, Name: "Quit", Callback: func() { action = "Quit" }},
		})

	tm.Subs["debug"] = g2.MakeThunderSubMenu(
		[]g2.Widget{
			&g2.Button{Size: 50, Triggers: triggers, Name: "Standard", Callback: func() { action = "standard" }},
			&g2.Button{Size: 50, Triggers: triggers, Name: "Moba", Callback: func() { action = "moba" }},
			&g2.Button{Size: 50, Triggers: triggers, Name: "Back", Callback: func() { tm.Pop() }},
		})

	tm.Start(500)
	g.AddChild(&tm, g2.AnchorDeadCenter)
	g.AddChild(g2.MakeConsole(wdx, wdy), g2.AnchorDeadCenter)

	t := texture.LoadFromPath(filepath.Join(base.GetDataDir(), "background/buttons1.jpg"))
	for {
		sys.Think()
		if action == "Quit" {
			return
		}
		if action == "standard" || action == "moba" {
			g.StopEventListening()
			engine, local := debugHookup(action)
			mainLoop(engine, local, action)
			g.RestartEventListening()
			action = ""
		}
		render.Queue(func() {
			gl.ClearColor(0, 0, 0, 1)
			gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
			if true {
				ratio := float64(wdx) / float64(wdy)
				t.RenderAdvanced(-1+(1-1/ratio), -1, 2/ratio, 2, 0, false)
			}
			gl.Disable(gl.TEXTURE_2D)
			base.GetDictionary("luxisr").RenderString("INvASioN!!!", 0, 0.5, 0, 0.03, gui.Center)
		})
		render.Queue(func() {
			g.Draw()
			sys.SwapBuffers()
		})
		render.Purge()
	}
	// 1 Start with a title screen
	// 2 Option to host or join
	// 3a If host then wait for a connection
	// 3b If join then ping and connect
	// 4 Once joined up the 'game' will handle choosing sides and whatnot
}
コード例 #24
0
ファイル: main.go プロジェクト: runningwild/jota
func mainLoop(engine *cgf.Engine, mode string) {
	defer engine.Kill()
	var profile_output *os.File
	var contention_output *os.File
	var num_mem_profiles int
	// ui.AddChild(base.MakeConsole())

	ticker := time.Tick(time.Millisecond * 17)
	ui := g2.Make(0, 0, wdx, wdy)
	ui.AddChild(&game.GameWindow{Engine: engine, Dims: g2.Dims{wdx - 50, wdy - 50}}, g2.AnchorDeadCenter)
	ui.AddChild(g2.MakeConsole(wdx-50, wdy-50), g2.AnchorDeadCenter)
	// side0Index := gin.In().BindDerivedKeyFamily("Side0", gin.In().MakeBindingFamily(gin.Key1, []gin.KeyIndex{gin.EitherControl}, []bool{true}))
	// side1Index := gin.In().BindDerivedKeyFamily("Side1", gin.In().MakeBindingFamily(gin.Key2, []gin.KeyIndex{gin.EitherControl}, []bool{true}))
	// side2Index := gin.In().BindDerivedKeyFamily("Side2", gin.In().MakeBindingFamily(gin.Key3, []gin.KeyIndex{gin.EitherControl}, []bool{true}))
	// side0Key := gin.In().GetKeyFlat(side0Index, gin.DeviceTypeAny, gin.DeviceIndexAny)
	// side1Key := gin.In().GetKeyFlat(side1Index, gin.DeviceTypeAny, gin.DeviceIndexAny)
	// side2Key := gin.In().GetKeyFlat(side2Index, gin.DeviceTypeAny, gin.DeviceIndexAny)
	defer ui.StopEventListening()
	for {
		<-ticker
		if gin.In().GetKey(gin.AnyEscape).FramePressCount() != 0 {
			return
		}
		start := time.Now()
		sys.Think()
		start = time.Now()
		render.Queue(func() {
			ui.Draw()
		})
		render.Queue(func() {
			start = time.Now()
			sys.SwapBuffers()
		})
		render.Purge()
		start = time.Now()
		// TODO: Replace the 'P' key with an appropriate keybind
		var err error
		if gin.In().GetKey(gin.AnyKeyP).FramePressCount() > 0 {
			if profile_output == nil {
				profile_output, err = os.Create(filepath.Join(datadir, "cpu.prof"))
				if err == nil {
					err = pprof.StartCPUProfile(profile_output)
					if err != nil {
						base.Log().Printf("Unable to start CPU profile: %v\n", err)
						profile_output.Close()
						profile_output = nil
					}
					base.Log().Printf("cpu prof: %v\n", profile_output)
				} else {
					base.Log().Printf("Unable to start CPU profile: %v\n", err)
				}
			} else {
				pprof.StopCPUProfile()
				profile_output.Close()
				profile_output = nil
			}
		}

		if gin.In().GetKey(gin.AnyKeyL).FramePressCount() > 0 {
			if contention_output == nil {
				contention_output, err = os.Create(filepath.Join(datadir, "contention.prof"))
				if err == nil {
					runtime.SetBlockProfileRate(1)
					base.Log().Printf("contention prof: %v\n", contention_output)
				} else {
					base.Log().Printf("Unable to start contention profile: %v\n", err)
				}
			} else {
				pprof.Lookup("block").WriteTo(contention_output, 0)
				contention_output.Close()
				contention_output = nil
			}
		}

		// TODO: Replace the 'M' key with an appropriate keybind
		if gin.In().GetKey(gin.AnyKeyM).FramePressCount() > 0 {
			f, err := os.Create(filepath.Join(datadir, fmt.Sprintf("mem.%d.prof", num_mem_profiles)))
			if err != nil {
				base.Error().Printf("Unable to write mem profile: %v", err)
			}
			pprof.WriteHeapProfile(f)
			f.Close()
			num_mem_profiles++
		}
	}
}
コード例 #25
0
ファイル: text.go プロジェクト: runningwild/glop
// LoadDictionary reads a gobbed Dictionary object from r, registers its atlas texture with opengl,
// and returns a Dictionary that is ready to render text.
func LoadDictionary(r io.Reader) (*Dictionary, error) {
	errChan := make(chan error)
	initOnce.Do(func() {
		render.Queue(func() {
			// errChan <- render.RegisterShader("glop.font", []byte(font_vertex_shader), []byte(font_fragment_shader))
			errChan <- render.RegisterShader("glop.font", []byte(font_vshader), []byte(font_fshader))
		})
	})
	err := <-errChan
	if err != nil {
		return nil, err
	}

	var dict Dictionary
	dec := gob.NewDecoder(r)
	err = dec.Decode(&dict)
	if err != nil {
		return nil, err
	}

	render.Queue(func() {
		// Create the gl texture for the atlas
		gl.GenTextures(1, &dict.atlas.texture)
		glerr := gl.GetError()
		if glerr != 0 {
			errChan <- fmt.Errorf("Gl Error on gl.GenTextures: %v", glerr)
			return
		}

		// Send the atlas to opengl
		gl.BindTexture(gl.TEXTURE_2D, dict.atlas.texture)
		gl.PixelStorei(gl.UNPACK_ALIGNMENT, 1)
		gl.TexImage2D(
			gl.TEXTURE_2D,
			0,
			gl.RED,
			dict.Dx,
			dict.Dy,
			0,
			gl.RED,
			gl.UNSIGNED_BYTE,
			gl.Ptr(&dict.Pix[0]))
		glerr = gl.GetError()
		if glerr != 0 {
			errChan <- fmt.Errorf("Gl Error on creating texture: %v", glerr)
			return
		}

		// Create the atlas sampler and set the parameters we want for it
		gl.GenSamplers(1, &dict.atlas.sampler)
		gl.SamplerParameteri(dict.atlas.sampler, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
		gl.SamplerParameteri(dict.atlas.sampler, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
		gl.SamplerParameteri(dict.atlas.sampler, gl.TEXTURE_WRAP_S, gl.REPEAT)
		gl.SamplerParameteri(dict.atlas.sampler, gl.TEXTURE_WRAP_T, gl.REPEAT)
		glerr = gl.GetError()
		if glerr != 0 {
			errChan <- fmt.Errorf("Gl Error on creating sampler: %v", glerr)
			return
		}
		errChan <- nil
	})

	err = <-errChan
	if err != nil {
		return nil, err
	}

	return &dict, nil
}