示例#1
0
func (ms *ManaSource) GobDecode(data []byte) error {
	base.Log().Printf("GobDecode")
	dec := gob.NewDecoder(bytes.NewBuffer(data))
	err := dec.Decode(&ms.options)
	var d1, d2 int
	if err == nil {
		var d uint32
		err = dec.Decode(&d)
		ms.thinks = int(d)
		base.Log().Printf("Decoded %d", d)
	}
	if err == nil {
		var d uint32
		err = dec.Decode(&d)
		d1 = int(d)
		base.Log().Printf("Decoded %d", d1)
	}
	if err == nil {
		var d uint32
		err = dec.Decode(&d)
		d2 = int(d)
		base.Log().Printf("Decoded %d", d2)
	}
	if err == nil {
		err = dec.Decode(&ms.rawNodes)
	}
	if err == nil {
		ms.nodes = make([][]node, d1)
		for i := range ms.nodes {
			ms.nodes[i] = ms.rawNodes[i*d2 : (i+1)*d2]
		}
	}
	return err
}
示例#2
0
func makePathingData(room *Room) *PathingData {
	start := time.Now()
	defer func() {
		base.Log().Printf("Pathing: %v", time.Now().Sub(start))
	}()
	var pd PathingData
	dx := (room.Dx + pathingDataGrid - 1) / pathingDataGrid
	dy := (room.Dy + pathingDataGrid - 1) / pathingDataGrid
	pd.finishDirectPaths.Add(dx * dy)
	go func() {
		pd.dirs = make([][][][]pathingDataCell, dx)
		pd.conns = make([][][]pathingConnection, dx)
		pd.dstData = make([][]pathingDstData, dx)
		for i := range pd.dirs {
			pd.dirs[i] = make([][][]pathingDataCell, dy)
			pd.conns[i] = make([][]pathingConnection, dy)
			pd.dstData[i] = make([]pathingDstData, dy)
			for j := range pd.dirs[i] {
				pd.dirs[i][j] = make([][]pathingDataCell, dx)
				for k := range pd.dirs[i][j] {
					pd.dirs[i][j][k] = make([]pathingDataCell, dy)
				}
				go pd.findAllDirectPaths(i, j, room)
			}
		}
	}()
	return &pd
}
示例#3
0
func (pd *PathingData) Dir(src, dst linear.Vec2) linear.Vec2 {
	x := int(src.X / pathingDataGrid)
	y := int(src.Y / pathingDataGrid)
	x2 := int(dst.X / pathingDataGrid)
	y2 := int(dst.Y / pathingDataGrid)
	if x < 0 || y < 0 || x >= len(pd.dstData) || y >= len(pd.dstData[x]) {
		return linear.Vec2{0, 0}
	}
	if x2 < 0 || y2 < 0 || x2 >= len(pd.dstData) || y2 >= len(pd.dstData[x2]) {
		return linear.Vec2{0, 0}
	}
	dstData := &pd.dstData[x2][y2]
	dstData.RLock()
	defer dstData.RUnlock()
	if !dstData.complete {
		dstData.once.Do(func() {
			base.Log().Printf("Eval: %2.2v %2.2v", src, dst)
			go func() {
				pd.finishDirectPaths.Wait()
				dstData.Lock()
				defer dstData.Unlock()
				pd.findAllPaths(x2, y2)
				dstData.complete = true
			}()
		})
		return dst.Sub(src).Norm()
	}
	cell := pd.dirs[x2][y2][x][y]
	if !cell.direct {
		return (linear.Vec2{1, 0}).Rotate(cell.angle)
	}
	return dst.Sub(src).Norm()
}
示例#4
0
func (lm *LogModule) Printf(vs ...runtime.Val) runtime.Val {
	var args []interface{}
	for _, v := range vs[1:] {
		args = append(args, v.Native())
	}
	base.Log().Printf(vs[0].String(), args...)
	return runtime.Nil
}
示例#5
0
文件: main.go 项目: runningwild/jota
func debugHookup(version string) *cgf.Engine {
	var err error
	for false && len(sys.GetActiveDevices()[gin.DeviceTypeController]) < 2 {
		time.Sleep(time.Millisecond * 100)
		sys.Think()
	}

	var engine *cgf.Engine
	if version != "host" {
		engine, err = cgf.NewClientEngine(17, "thunderingvictory.dyndns.org", 20007, base.EmailCrashReport, base.Log())
		if err != nil {
			base.Log().Printf("Unable to connect: %v", err)
			base.Error().Fatalf("%v", err.Error())
		}
	} else {
		sys.Think()
		g := game.MakeGame()
		if version == "host" {
			engine, err = cgf.NewHostEngine(g, 17, "", 20007, base.EmailCrashReport, base.Log())
			if err != nil {
				panic(err)
			}
			err = cgf.Host(20007, "thunderball")
			if err != nil {
				panic(err)
			}
		} else {
			engine, err = cgf.NewLocalEngine(g, 17, base.EmailCrashReport, base.Log())
		}
		if err != nil {
			base.Error().Fatalf("%v", err.Error())
		}
	}
	engine.Pause()
	engine.GetState().(*game.Game).SetSystem(sys)
	engine.Unpause()

	base.Log().Printf("Engine Id: %v", engine.Id())
	base.Log().Printf("All Ids: %v", engine.Ids())
	return engine
}
示例#6
0
func (ms *ManaSource) GobEncode() ([]byte, error) {
	base.Log().Printf("GobEncode")
	buf := bytes.NewBuffer(nil)
	enc := gob.NewEncoder(buf)
	err := enc.Encode(ms.options)
	if err == nil {
		err = enc.Encode(uint32(ms.thinks))
		base.Log().Printf("Encode thinks: %d", ms.thinks)
	}
	if err == nil {
		err = enc.Encode(uint32(len(ms.nodes)))
		base.Log().Printf("Encode dx: %d", len(ms.nodes))
	}
	if err == nil {
		err = enc.Encode(uint32(len(ms.nodes[0])))
		base.Log().Printf("Encode dy: %d", len(ms.nodes[0]))
	}
	if err == nil {
		err = enc.Encode(ms.rawNodes)
	}
	return buf.Bytes(), err
}
示例#7
0
func (jr jotaResolver) Resolve(id string) (io.Reader, error) {
	jr.cacheMutex.Lock()
	defer jr.cacheMutex.Unlock()
	if data, ok := jr.cache[id]; ok {
		return bytes.NewReader(data), nil
	}
	base.Log().Printf("Opening: %s", jr.root)
	data, err := ioutil.ReadFile(filepath.Join(jr.root, id+".agora"))
	if err != nil {
		return nil, err
	}
	jr.cache[id] = data
	return bytes.NewReader(data), nil
}
示例#8
0
文件: main.go 项目: runningwild/jota
func init() {
	runtime.LockOSThread()
	sys = system.Make(gos.GetSystemInterface())

	datadir = filepath.Join(os.Args[0], "..", "..")
	base.SetDatadir(datadir)
	base.Log().Printf("Setting datadir: %s", datadir)
	wdx = 1000
	wdy = 800
	var key_binds base.KeyBinds
	base.LoadJson(filepath.Join(datadir, "key_binds.json"), &key_binds)
	fmt.Printf("Prething: %v\n", key_binds)
	key_map = key_binds.MakeKeyMap()
	base.SetDefaultKeyMap(key_map)
}
示例#9
0
文件: gui.go 项目: runningwild/jota
func (p *PosWidget) Draw(region Region, style StyleStack) {
	gl.Disable(gl.TEXTURE_2D)
	gl.Color4ub(0, 255, 0, 255)
	gl.Begin(gl.QUADS)
	x := gl.Int(region.X)
	y := gl.Int(region.Y)
	dx := gl.Int(base.GetDictionary("luxisr").StringWidth(p.text, float64(p.Size)))
	dy := gl.Int(p.Size)
	gl.Vertex2i(x, y)
	gl.Vertex2i(x, y+dy)
	gl.Vertex2i(x+dx, y+dy)
	gl.Vertex2i(x+dx, y)
	gl.End()
	base.Log().Printf("%v %v %v %v", x, y, dx, dy)
	gl.Color4ub(255, 0, 255, 255)
	base.GetDictionary("luxisr").RenderString(p.text, float64(region.X), float64(region.Y), 0, float64(p.Size), gui.Left)
}
示例#10
0
func setupSound() {
	soundInit.Do(func() {
		var err error
		// fmodSys, err = fmod.CreateSystem()
		if err != nil {
			// base.Error().Fatalf("Unable to initialize fmod: %v", err)
		}
		// err = fmodSys.Init(2, 0, nil)
		if err != nil {
			// base.Error().Fatalf("Unable to initialize fmod: %v", err)
		}
		target := filepath.Join(base.GetDataDir(), "sound/ping.wav")
		base.Log().Printf("Trying to load ", target)
		// sound, err = fmodSys.CreateSound_FromFilename(target, fmod.MODE_DEFAULT)
		if err != nil {
			base.Error().Fatalf("Unable to load sound: %v", err)
		}
	})
}
示例#11
0
文件: game.go 项目: runningwild/jota
func MakeGame() *Game {
	var g Game
	g.Setup = &SetupData{}
	g.Setup.Players = make(map[int64]*SetupPlayerData)

	// NOTE: Obviously this isn't threadsafe, but I don't intend to be Init()ing
	// multiple game objects at the same time.
	base.RemoveRegistry("champs")
	base.RegisterRegistry("champs", make(map[string]*champ.ChampionDef))
	base.RegisterAllObjectsInDir("champs", filepath.Join(base.GetDataDir(), "champs"), ".json", "json")

	names := base.GetAllNamesInRegistry("champs")
	g.Champs = make([]champ.Champion, len(names))
	for i, name := range names {
		g.Champs[i].Defname = name
		base.GetObject("champs", &g.Champs[i])
		base.Log().Printf("Champ %v has %v", name, g.Champs[i].Abilities)
	}
	return &g
}
示例#12
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++
		}
	}
}
示例#13
0
文件: game.go 项目: runningwild/jota
func (g *Game) ThinkGame() {
	// cache wall data
	if g.local.temp.AllWalls == nil || g.local.temp.AllWallsDirty {
		g.local.temp.AllWallsDirty = false
		g.local.temp.AllWalls = nil
		g.local.temp.WallCache = nil
		g.local.temp.VisibleWallCache = nil

		// Can't use a nil slice, otherwise we'll run this block every Think for levels
		// with no walls.
		allWalls := make([]linear.Seg2, 0)
		base.DoOrdered(g.Level.Room.Walls, func(a, b string) bool { return a < b }, func(_ string, walls linear.Poly) {
			for i := range walls {
				allWalls = append(allWalls, walls.Seg(i))
			}
		})
		g.local.temp.AllWalls = allWalls
		g.local.temp.WallCache = &wallCache{}
		g.local.temp.WallCache.SetWalls(g.Level.Room.Dx, g.Level.Room.Dy, allWalls, 100)
		g.local.temp.VisibleWallCache = &wallCache{}
		g.local.temp.VisibleWallCache.SetWalls(g.Level.Room.Dx, g.Level.Room.Dy, allWalls, stats.LosPlayerHorizon)
		g.local.pathingData = makePathingData(&g.Level.Room)
	}

	// cache ent data
	for _, ent := range g.local.temp.AllEnts {
		if ent.Dead() {
			if _, ok := ent.(*PlayerEnt); ok {
				var id int64
				_, err := fmt.Sscanf(string(ent.Id()), "Engine:%d", &id)
				if err != nil {
					_, err = fmt.Sscanf(string(ent.Id()), "Ai:%d", &id)
					id = -id // Ai's engine ids are negative
				}
				if err != nil {
					base.Error().Printf("Unable to parse player id '%v'", ent.Id())
				} else {
					if engineData, ok := g.Engines[id]; ok {
						if !ok {
							base.Error().Printf("Unable to find engine %d for player %v", id, ent.Id())
						} else {
							engineData.CountdownFrames = 60 * 10
							base.Log().Printf("%v died, counting down....", *engineData)
						}
					}
				}
			}
			ent.OnDeath(g)
			g.RemoveEnt(ent.Id())
		}
	}

	// Death countdown
	base.DoOrdered(g.Engines, func(a, b int64) bool { return a < b }, func(_ int64, engineData *PlayerData) {
		if engineData.CountdownFrames > 0 {
			engineData.CountdownFrames--
			if engineData.CountdownFrames == 0 {
				g.AddPlayers([]*PlayerData{engineData})
			}
		}
	})

	if g.local.temp.AllEnts == nil || g.local.temp.AllEntsDirty {
		g.local.temp.AllEnts = g.local.temp.AllEnts[0:0]
		g.DoForEnts(func(gid Gid, ent Ent) {
			g.local.temp.AllEnts = append(g.local.temp.AllEnts, ent)
		})
		g.local.temp.AllEntsDirty = false
	}
	if g.local.temp.EntGrid == nil {
		g.local.temp.EntGrid = MakeEntCache(g.Level.Room.Dx, g.Level.Room.Dy)
	}
	g.local.temp.EntGrid.SetEnts(g.local.temp.AllEnts)

	for _, proc := range g.Processes {
		proc.Think(g)
	}
	algorithm.Choose(&g.Processes, func(proc Process) bool { return !proc.Dead() })

	// Advance players, check for collisions, add segments
	eps := 1.0e-3
	for _, ent := range g.local.temp.AllEnts {
		ent.Think(g)
		for _, ab := range ent.Abilities() {
			ab.Think(ent, g)
		}
		pos := ent.Pos()
		pos.X = clamp(pos.X, eps, float64(g.Level.Room.Dx)-eps)
		pos.Y = clamp(pos.Y, eps, float64(g.Level.Room.Dy)-eps)
		ent.SetPos(pos)
	}

	var nearby []Ent
	for i := 0; i < len(g.local.temp.AllEnts); i++ {
		outerEnt := g.local.temp.AllEnts[i]
		outerSize := outerEnt.Stats().Size()
		if outerSize == 0 {
			continue
		}
		g.local.temp.EntGrid.EntsInRange(outerEnt.Pos(), 100, &nearby)
		for _, innerEnt := range nearby {
			innerSize := innerEnt.Stats().Size()
			if innerSize == 0 {
				continue
			}
			distSq := outerEnt.Pos().Sub(innerEnt.Pos()).Mag2()
			colDist := innerSize + outerSize
			if distSq > colDist*colDist {
				continue
			}
			if distSq < 0.015625 { // this means that dist < 0.125
				continue
			}
			dist := math.Sqrt(distSq)
			force := 50.0 * (colDist - dist)
			innerEnt.ApplyForce(innerEnt.Pos().Sub(outerEnt.Pos()).Scale(force / dist))
		}
	}

	g.Level.ManaSource.Think(g.Ents)
}
示例#14
0
文件: game.go 项目: runningwild/jota
func (u SetupComplete) Apply(_g interface{}) {
	g := _g.(*Game)
	if g.Setup == nil {
		return
	}
	sideCount := make(map[int]int)
	// Must have at least two sides
	sideCount[0] = 0
	sideCount[1] = 0
	for _, spd := range g.Setup.Players {
		sideCount[spd.Side]++
	}
	g.Engines = make(map[int64]*PlayerData)
	for id, player := range g.Setup.Players {
		var gid Gid
		if id < 0 {
			gid = Gid(fmt.Sprintf("Ai:%d", -id))
		} else {
			gid = Gid(fmt.Sprintf("Engine:%d", id))
		}
		g.Engines[id] = &PlayerData{
			PlayerGid:  Gid(gid),
			Side:       player.Side,
			ChampIndex: player.ChampIndex,
		}
	}

	// Now that we have the information we can set up a lot of the local data for
	// this engine's player.

	if g.IsPlaying() {
		g.local.Side = g.Engines[g.local.Engine.Id()].Side
		g.local.Gid = g.Engines[g.local.Engine.Id()].PlayerGid
		g.local.Data = g.Engines[g.local.Engine.Id()]
	}

	var room Room
	err := base.LoadJson(filepath.Join(base.GetDataDir(), "rooms/basic.json"), &room)
	if err != nil {
		base.Error().Fatalf("%v", err)
	}
	errs := room.Validate()
	for _, err := range errs {
		base.Error().Printf("%v", err)
	}
	if len(errs) > 0 {
		base.Error().Fatalf("Errors with the level, bailing...")
	}
	g.Level = &Level{}
	g.Level.Room = room
	g.Rng = cmwc.MakeGoodCmwc()
	g.Rng.Seed(u.Seed)
	g.Ents = make(map[Gid]Ent)
	g.Friction = 0.97
	g.losCache = makeLosCache(g.Level.Room.Dx, g.Level.Room.Dy)
	sides := make(map[int][]int64)
	var playerDatas []*PlayerData
	base.DoOrdered(g.Engines, func(a, b int64) bool { return a < b }, func(id int64, data *PlayerData) {
		sides[data.Side] = append(sides[data.Side], id)
		playerDatas = append(playerDatas, data)
	})
	for id, ed := range g.Engines {
		base.Log().Printf("%v -> %v", id, *ed)
	}
	g.AddPlayers(playerDatas)

	g.MakeControlPoints()
	g.Init()
	base.Log().Printf("Nillifying g.Setup()")
	g.Setup = nil
}