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 }
func (camera *cameraInfo) doArchitectFocusRegion(g *Game, sys system.System) { if camera.limit.mid.X == 0 && camera.limit.mid.Y == 0 { // On the very first frame the limit midpoint will be (0,0), which should // never happen after the game begins. We use this as an opportunity to // init the data now that we know the region we're working with. rdx := float64(g.Levels[GidInvadersStart].Room.Dx) rdy := float64(g.Levels[GidInvadersStart].Room.Dy) if camera.regionDims.X/camera.regionDims.Y > rdx/rdy { camera.limit.dims.Y = rdy camera.limit.dims.X = rdy * camera.regionDims.X / camera.regionDims.Y } else { camera.limit.dims.X = rdx camera.limit.dims.Y = rdx * camera.regionDims.Y / camera.regionDims.X } camera.limit.mid.X = rdx / 2 camera.limit.mid.Y = rdy / 2 camera.current = camera.limit camera.zoom = 0 base.Log().Printf("Region Dims: %2.2v", camera.regionDims) base.Log().Printf("Room Dims: %2.2v %2.2v", rdx, rdy) base.Log().Printf("Limit Dims: %2.2v", camera.limit.dims) } wheel := gin.In().GetKeyFlat(gin.MouseWheelVertical, gin.DeviceTypeAny, gin.DeviceIndexAny) camera.zoom += wheel.FramePressAmt() / 500 if camera.zoom < 0 { camera.zoom = 0 } if camera.zoom > 2 { camera.zoom = 2 } zoom := 1 / math.Exp(camera.zoom) camera.current.dims = camera.limit.dims.Scale(zoom) if gin.In().GetKey(gin.AnySpace).CurPressAmt() > 0 { if !camera.cursorHidden { sys.HideCursor(true) camera.cursorHidden = true } x := gin.In().GetKey(gin.AnyMouseXAxis).FramePressAmt() y := gin.In().GetKey(gin.AnyMouseYAxis).FramePressAmt() camera.current.mid.X -= float64(x) * 2 camera.current.mid.Y -= float64(y) * 2 } else { if camera.cursorHidden { sys.HideCursor(false) camera.cursorHidden = false } } }
func (l *LocalData) activateAbility(abs *personalAbilities, gid Gid, n int, keyPress bool) { if len(abs.abilities) <= n { return } activeAbility := abs.activeAbility abs.activeAbility = nil events, active := abs.abilities[n].Activate(gid, keyPress) for _, event := range events { l.engine.ApplyEvent(event) } if active && activeAbility != nil && activeAbility != abs.abilities[n] { base.Log().Printf("Deactivate on keypress") events := activeAbility.Deactivate(gid) for _, event := range events { l.engine.ApplyEvent(event) } if activeAbility == abs.abilities[n] { return } } if active { abs.activeAbility = abs.abilities[n] } if abs.activeAbility == nil { abs.activeAbility = activeAbility } }
func (l *LocalData) thinkAbility(g *Game, abs *personalAbilities, gid Gid) { if abs.activeAbility == nil { return } var mouse linear.Vec2 if l.mode == LocalModeArchitect { mx, my := l.sys.GetCursorPos() mouse.X = float64(mx) mouse.Y = float64(my) mouse = mouse.Sub(l.architect.camera.regionPos) mouse.X /= l.architect.camera.regionDims.X mouse.Y /= l.architect.camera.regionDims.Y mouse.X *= l.architect.camera.current.dims.X mouse.Y *= l.architect.camera.current.dims.Y mouse = mouse.Sub(l.architect.camera.current.dims.Scale(0.5)) mouse = mouse.Add(l.architect.camera.current.mid) } events, die := abs.activeAbility.Think(gid, g, mouse) for _, event := range events { l.engine.ApplyEvent(event) } if die { base.Log().Printf("Deactivate on die") more_events := abs.activeAbility.Deactivate(gid) abs.activeAbility = nil for _, event := range more_events { l.engine.ApplyEvent(event) } } }
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 }
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 = 1024 wdy = 768 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) }
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) } }) }
func (p *pullProcess) Draw(player_id int, g *game.Game) { gl.Color4d(1, 1, 1, 1) gl.Disable(gl.TEXTURE_2D) player := g.GetEnt(player_id).(*game.Player) v1 := player.Pos() v2 := v1.Add(linear.Vec2{1000, 0}) v3 := v2.RotateAround(v1, player.Angle-p.Angle/2) v4 := v2.RotateAround(v1, player.Angle+p.Angle/2) gl.Begin(gl.LINES) vs := []linear.Vec2{v3, v4, linear.Vec2{player.X, player.Y}} for i := range vs { gl.Vertex2d(gl.Double(vs[i].X), gl.Double(vs[i].Y)) gl.Vertex2d(gl.Double(vs[(i+1)%len(vs)].X), gl.Double(vs[(i+1)%len(vs)].Y)) } gl.End() s := fmt.Sprintf("%.2f", p.supplied) base.Log().Printf("'%s'", s) if true { base.GetDictionary("luxisr").RenderString(s, 10, 10, 0, 50, gin.Left) } }
func (g *Game) AddPest(pos linear.Vec2) Ent { var p Pest err := json.NewDecoder(bytes.NewBuffer([]byte(` { "Base": { "Mass": 100, "Health": 100 }, "Dynamic": { "Health": 100 } } `))).Decode(&p.BaseEnt.StatsInst) if err != nil { base.Log().Fatalf("%v", err) } p.Position = pos p.Gid = g.NextGid() p.Processes = make(map[int]Process) g.Ents[p.Gid] = &p return &p }
func mainLoop(engine *cgf.Engine, local *game.LocalData, 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, Local: local, Dims: g2.Dims{wdx, wdy}}, g2.AnchorDeadCenter) ui.AddChild(g2.MakeConsole(wdx, wdy), 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 } if mode == "moba" { if side0Key.FramePressCount() > 0 { local.DebugCyclePlayers() } // if side0Key.FramePressCount() > 0 { // local.DebugSetSide(0) // } // if side1Key.FramePressCount() > 0 { // local.DebugSetSide(1) // } } if mode == "standard" { if side0Key.FramePressCount() > 0 { local.DebugChangeMode(game.LocalModeInvaders) } if side1Key.FramePressCount() > 0 { local.DebugChangeMode(game.LocalModeArchitect) } if side2Key.FramePressCount() > 0 { local.DebugChangeMode(game.LocalModeEditor) } } sys.Think() render.Queue(func() { ui.Draw() }) render.Queue(func() { sys.SwapBuffers() }) render.Purge() // 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++ } } }
func debugHookup(version string) (*cgf.Engine, *game.LocalData) { // if version != "standard" && version != "moba" && version != "host" && version != "client" { // base.Log().Fatalf("Unable to handle Version() == '%s'", Version()) // } for false && len(sys.GetActiveDevices()[gin.DeviceTypeController]) < 2 { time.Sleep(time.Millisecond * 100) sys.Think() } var engine *cgf.Engine var room game.Room generated := generator.GenerateRoom(1024, 1024, 100, 64, 64522029961391019) data, err := json.Marshal(generated) if err != nil { base.Error().Fatalf("%v", err) } err = json.Unmarshal(data, &room) // err = base.LoadJson(filepath.Join(base.GetDataDir(), "rooms/basic.json"), &room) if err != nil { base.Error().Fatalf("%v", err) } var players []game.Gid var localData *game.LocalData var g *game.Game if version != "host" { res, err := cgf.SearchLANForHosts(20007, 20002, 500) if err != nil || len(res) == 0 { base.Log().Printf("Unable to connect: %v", err) base.Error().Fatalf("%v", err.Error()) } engine, err = cgf.NewClientEngine(17, res[0].Ip, 20007, base.EmailCrashReport, base.Log()) if err != nil { base.Log().Printf("Unable to connect: %v", err) base.Error().Fatalf("%v", err.Error()) } localData = game.NewLocalDataArchitect(engine, sys) g = engine.GetState().(*game.Game) for _, ent := range g.Ents { if _, ok := ent.(*game.PlayerEnt); ok { players = append(players, ent.Id()) } } } 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()) } } localData = game.NewLocalDataMoba(engine, gin.DeviceIndexAny, sys) // localData = game.NewLocalDataInvaders(engine, sys) // Hook the players up regardless of in we're architect or not, since we can // switch between the two in debug mode. // d := sys.GetActiveDevices() // n := 0 // for _, index := range d[gin.DeviceTypeController] { // localData.SetLocalPlayer(g.Ents[players[n]], index) // n++ // if n > len(players) { // break // } // } // if len(d[gin.DeviceTypeController]) == 0 { // localData.SetLocalPlayer(g.Ents[players[0]], 0) // } base.Log().Printf("Engine Id: %v", engine.Id()) base.Log().Printf("All Ids: %v", engine.Ids()) return engine, localData }
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 } }
func (mc *massCondition) ModifyBase(b stats.Base) stats.Base { b.Mass *= 1.5 base.Log().Printf("Returning mass %v", b.Mass) return b }
func (u SetupComplete) Apply(_g interface{}) { g := _g.(*Game) if g.Setup == nil { return } g.Engines = make(map[int64]*PlayerData) for _, id := range g.Setup.EngineIds { g.Engines[id] = &PlayerData{ PlayerGid: Gid(fmt.Sprintf("Engine:%d", id)), Side: g.Setup.Sides[id].Side, } } // Add a single Ai player to side 0 g.Engines[123123] = &PlayerData{ PlayerGid: Gid(fmt.Sprintf("Engine:%d", 123123)), Side: 0, Ai: &AiPlayerData{}, } g.Setup.Sides[123123] = &SetupSideData{ Champ: 0, Side: 0, } var room Room dx, dy := 1024, 1024 generated := generator.GenerateRoom(float64(dx), float64(dy), 100, 64, u.Seed) data, err := json.Marshal(generated) if err != nil { base.Error().Fatalf("%v", err) } err = json.Unmarshal(data, &room) // err = base.LoadJson(filepath.Join(base.GetDataDir(), "rooms/basic.json"), &room) if err != nil { base.Error().Fatalf("%v", err) } g.Levels = make(map[Gid]*Level) g.Levels[GidInvadersStart] = &Level{} g.Levels[GidInvadersStart].Room = room g.Rng = cmwc.MakeGoodCmwc() g.Rng.Seed(12313131) g.Ents = make(map[Gid]Ent) g.Friction = 0.97 // g.Standard = &GameModeStandard{} g.Moba = &GameModeMoba{ Sides: make(map[int]*GameModeMobaSideData), } sides := make(map[int][]int64) for id, data := range g.Engines { sides[data.Side] = append(sides[data.Side], id) } for _, players := range sides { var ids []int64 for _, id := range players { ids = append(ids, id) } side := g.Setup.Sides[ids[0]].Side gids := g.AddPlayers(ids, side) g.Moba.Sides[side] = &GameModeMobaSideData{} for i := range ids { player := g.Ents[gids[i]].(*PlayerEnt) player.Champ = g.Setup.Sides[ids[i]].Champ } } g.Moba.losCache = makeLosCache(dx, dy) g.MakeControlPoints() g.Init() base.Log().Printf("Nillifying g.Setup()") g.Setup = nil }
func (g *Game) Think() { g.GameThinks++ if g.Setup != nil { return } defer base.StackCatcher() // cache wall data if g.temp.AllWalls == nil || g.temp.AllWallsDirty { g.temp.AllWalls = make(map[Gid][]linear.Seg2) g.temp.WallCache = make(map[Gid]*wallCache) g.temp.VisibleWallCache = make(map[Gid]*wallCache) for gid := range g.Levels { var allWalls []linear.Seg2 base.DoOrdered(g.Levels[gid].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.DoForEnts(func(entGid Gid, ent Ent) { // if ent.Level() == gid { // for _, walls := range ent.Walls() { // for i := range walls { // allWalls = append(allWalls, walls.Seg(i)) // } // } // } // }) g.temp.AllWalls[gid] = allWalls g.temp.WallCache[gid] = &wallCache{} g.temp.WallCache[gid].SetWalls(g.Levels[gid].Room.Dx, g.Levels[gid].Room.Dy, allWalls, 100) g.temp.VisibleWallCache[gid] = &wallCache{} g.temp.VisibleWallCache[gid].SetWalls(g.Levels[gid].Room.Dx, g.Levels[gid].Room.Dy, allWalls, stats.LosPlayerHorizon) base.Log().Printf("WallCache: %v", g.temp.WallCache) } g.Moba.losCache.SetWallCache(g.temp.VisibleWallCache[GidInvadersStart]) } // cache ent data for _, ent := range g.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 { 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 } } } } ent.OnDeath(g) g.RemoveEnt(ent.Id()) } } // Death countdown for engineId, engineData := range g.Engines { if engineData.CountdownFrames > 0 { engineData.CountdownFrames-- if engineData.CountdownFrames == 0 { // TODO: It's a bit janky to do it like this, right? g.AddPlayers([]int64{engineId}, engineData.Side) } } } if g.temp.AllEnts == nil || g.temp.AllEntsDirty { g.temp.AllEnts = g.temp.AllEnts[0:0] g.DoForEnts(func(gid Gid, ent Ent) { g.temp.AllEnts = append(g.temp.AllEnts, ent) }) g.temp.AllEntsDirty = false } for _, proc := range g.Processes { proc.Think(g) } algorithm.Choose(&g.Processes, func(proc Process) bool { return proc.Phase() != PhaseComplete }) // Advance players, check for collisions, add segments for _, ent := range g.temp.AllEnts { ent.Think(g) pos := ent.Pos() eps := 1.0e-3 pos.X = clamp(pos.X, eps, float64(g.Levels[ent.Level()].Room.Dx)-eps) pos.Y = clamp(pos.Y, eps, float64(g.Levels[ent.Level()].Room.Dy)-eps) ent.SetPos(pos) } for i := 0; i < len(g.temp.AllEnts); i++ { for j := i + 1; j < len(g.temp.AllEnts); j++ { outerEnt := g.temp.AllEnts[i] innerEnt := g.temp.AllEnts[j] distSq := outerEnt.Pos().Sub(innerEnt.Pos()).Mag2() colDist := outerEnt.Stats().Size() + innerEnt.Stats().Size() if distSq > colDist*colDist { continue } if distSq < 0.0001 { continue } if distSq <= 0.25 { distSq = 0.25 } dist := math.Sqrt(distSq) force := 50.0 * (colDist - dist) outerEnt.ApplyForce(outerEnt.Pos().Sub(innerEnt.Pos()).Scale(force / dist)) innerEnt.ApplyForce(innerEnt.Pos().Sub(outerEnt.Pos()).Scale(force / dist)) } } switch { case g.Moba != nil: g.ThinkMoba() case g.Standard != nil: panic("Thinkgs aren't implemented, like thinking on mana sources") // Do standard thinking default: panic("Game mode not set") } }
func (s *Sludge) Terminated() bool { base.Log().Printf("Checking terminated") return *s <= 0 }
func GenerateRoom(dx, dy, radius float64, grid int, seed int64) Room { var room Room room.Walls = make(map[string]linear.Poly) nextIdInt = 0 room.Dx = int(dx) room.Dy = int(dy) c := cmwc.MakeGoodCmwc() if seed == 0 { c.SeedWithDevRand() n := c.Int63() c = cmwc.MakeGoodCmwc() base.Log().Printf("SEED: %v", n) c.Seed(n) } else { c.Seed(seed) } sanity := int(math.Sqrt(dx * dy)) r := rand.New(c) var poss []linear.Vec2 for sanity > 0 { pos := linear.Vec2{r.Float64() * (dx - radius + 1), r.Float64() * (dy - radius + 1)} good := true for _, p := range poss { if p.Sub(pos).Mag() < 2*(2*radius) { good = false break } } if !good { sanity-- continue } poss = append(poss, pos) } // Find the pair of points that maximizes distance maxDist := 0.0 for i := range poss { for j := range poss { dist := poss[i].Sub(poss[j]).Mag() if dist > maxDist { maxDist = dist } } } var a, b int minDist := maxDist * 3 / 4 hits := 1.0 for i := range poss { for j := range poss { if i == j { continue } dist := poss[i].Sub(poss[j]).Mag() if dist > minDist && r.Float64() < 1.0/hits { a, b = i, j hits = hits + 1 } } } room.Starts = []linear.Vec2{poss[a], poss[b]} for _, start := range room.Starts { var data mobaRoomSideData data.Base = start room.Moba.SideData = append(room.Moba.SideData, data) } var data mobaRoomSideData for i, pos := range poss { if i == a || i == b { continue } data.Towers = append(data.Towers, pos) } room.Moba.SideData = append(room.Moba.SideData, data) sanity = int(math.Pow(dx*dy, 0.20)) var segs []linear.Seg2 for sanity > 0 { a := linear.Vec2{r.Float64() * (dx), r.Float64() * (dy)} length := gridify(r.Float64()*radius+(radius), grid) angle := float64(r.Intn(4)) * 3.1415926535 / 2 ray := (linear.Vec2{1, 0}).Rotate(angle) seg := linear.Seg2{a, a.Add(ray.Scale(length))} seg.P.X = gridify(seg.P.X, grid) seg.P.Y = gridify(seg.P.Y, grid) seg.Q.X = gridify(seg.Q.X, grid) seg.Q.Y = gridify(seg.Q.Y, grid) good := true if seg.P.X <= 0 || seg.P.X >= dx || seg.P.Y <= 0 || seg.P.Y >= dy { good = false } if seg.Q.X <= 0 || seg.Q.X >= dx || seg.Q.Y <= 0 || seg.Q.Y >= dy { good = false } if seg.P.X == seg.Q.X && seg.P.Y == seg.Q.Y { good = false } // Can't get too close to a circle for _, p := range poss { if distFromPointToSeg(p, seg) < radius/2 { good = false break } } // Check to make sure this segment isn't coincident with any othe segment. // To avoid annoying degeneracies we'll rotate the segment slightly. rot := linear.Seg2{seg.P, seg.Ray().Rotate(0.01).Add(seg.P)} for _, cur := range segs { if rot.DoesIsect(cur) { good = false break } } if !good { sanity-- continue } segs = append(segs, seg) } for _, s := range segs { right := s.Ray().Cross().Norm().Scale(-float64(grid)) s2 := linear.Seg2{s.Q.Add(right), s.P.Add(right)} room.Walls[nextId()] = linear.Poly{s.P, s.Q, s2.P, s2.Q} } room.Walls[nextId()] = linear.Poly{ linear.Vec2{0, 0}, linear.Vec2{dx, 0}, linear.Vec2{dx, dy}, linear.Vec2{0, dy}, } room.NextId = nextIdInt return room }
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 }
func (s *Sludge) CauseDamage() stats.Damage { base.Log().Printf("Sludge at %v", *s) (*s)-- return stats.Damage{} }