Example #1
0
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
		}
	}
}
Example #2
0
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
		}
	}
}
Example #3
0
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()
}
Example #4
0
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
}
Example #5
0
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()
	}
}
Example #6
0
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
}
Example #7
0
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
	}
}
Example #8
0
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
		}
	}
}
Example #9
0
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()
	}
}
Example #10
0
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++
		}
	}
}
Example #11
0
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
	}
}
Example #12
0
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
}