Beispiel #1
0
func main() {
	if sdl.Init(sdl.INIT_VIDEO) != 0 {
		panic(sdl.GetError())
	}

	defer sdl.Quit()

	screen := sdl.SetVideoMode(400, 300, 32, 0)
	if screen == nil {
		panic(sdl.GetError())
	}

	sdl.WM_SetCaption("Template", "")

	ticker := time.NewTicker(1e9 / 2 /*2 Hz*/)

loop:
	for {
		select {
		case <-ticker.C:
			// Note: For better efficiency, use UpdateRects instead of Flip
			screen.FillRect(nil /*color*/, rand.Uint32())
			//screen.Blit(&sdl.Rect{x,y, 0, 0}, image, nil)
			screen.Flip()

		case event := <-sdl.Events:
			fmt.Printf("%#v\n", event)

			switch event.(type) {
			case sdl.QuitEvent:
				break loop
			}
		}
	}
}
Beispiel #2
0
func main() {
	log.SetFlags(0)

	var resourcePath string
	{
		GOPATH := os.Getenv("GOPATH")
		if GOPATH == "" {
			log.Fatal("No such environment variable: GOPATH")
		}
		for _, gopath := range strings.Split(GOPATH, ":") {
			a := gopath + "/src/github.com/neagix/Go-SDL/examples/completeTest"
			_, err := os.Stat(a)
			if err == nil {
				resourcePath = a
				break
			}
		}
		if resourcePath == "" {
			log.Fatal("Failed to find resource directory")
		}
	}

	if sdl.Init(sdl.INIT_EVERYTHING) != 0 {
		log.Fatal(sdl.GetError())
	}

	sound.Init()

	desiredSpec := audio.AudioSpec{Freq: 44100, Format: audio.AUDIO_S16SYS, Channels: 1, Samples: 4096}
	var obtainedSpec audio.AudioSpec

	if audio.OpenAudio(&desiredSpec, &obtainedSpec) != 0 {
		log.Fatal(sdl.GetError())
	}

	fmt := sound.AudioInfo{obtainedSpec.Format, obtainedSpec.Channels, uint32(obtainedSpec.Freq)}
	/* note: on my machine i always get 2 channels, despite only requesting one */

	sdl.EnableUNICODE(1)

	sample := sound.NewSampleFromFile(resourcePath+"/test.ogg", &fmt, 1048756)

	sample.DecodeAll()
	buf := sample.Buffer_int16()
	/* this decodes the entire file at once and loads it into memory. sample.Decode()
	will decode in chunks of ~1mb, since that's the buffer size I requested above. */

	audio.PauseAudio(false)

	audio.SendAudio_int16(buf)
	/* note: this sends the entire buffer to the audio system at once, which
	is a stupid thing to do in practice because the audio callback will block while
	it copies the samples to its internal tail buffer, and won't be able to fill the
	current audio frame in a timely manner. this will cause many underruns.
	A better approach is to call SendAudio in a loop with small chunks of the
	buffer at a time. */

	time.Sleep(time.Second * 45)
	/* we better stick around or we'll exit before making any noise! */
}
Beispiel #3
0
func (gfx *Graphics) setup() error {
	var errno = sdl.Init(sdl.INIT_EVERYTHING)
	if errno != 0 {
		return fmt.Errorf("Init failed: %s", sdl.GetError())
	}

	gfx.display = sdl.SetVideoMode(int(gfx.cfg.ScreenX), int(gfx.cfg.ScreenY), 32, sdl.HWSURFACE|sdl.DOUBLEBUF|sdl.FULLSCREEN)
	if gfx.display == nil {
		return fmt.Errorf("No surface created: %s", sdl.GetError())
	}

	return nil
}
Beispiel #4
0
func loadTexture(texture_file string) (*sdl.Surface, error) {

	surface := sdl.Load(texture_file)
	if surface == nil {
		return nil, fmt.Errorf("Failed to load texture: %s", sdl.GetError())
	}

	surface = surface.DisplayFormat()
	if surface == nil {
		return nil, fmt.Errorf("Failed to convert texture: %s", sdl.GetError())
	}

	return surface, nil
}
Beispiel #5
0
func (g *guiLayer) Render(target *sdl.Surface) {
	if g.child != nil {
		g.child.Render(target)
	}

	target.FillRect(
		&sdl.Rect{
			X: 20,
			Y: 300,
			H: uint16(30 + (30 * g.game.NumPlayers)),
			W: 200,
		},
		0xffffff,
	)

	for i := 0; i < g.game.NumPlayers; i++ {
		p := g.game.GetPlayer(i)
		str := fmt.Sprintf("Player %d: %d - %d - %d", i, p.Money.Get(), p.Money.GetIncome(), p.GetLives())

		txt_surface := ttf.RenderText_Solid(g.font, str, sdl.Color{})
		if txt_surface == nil {
			fmt.Printf("RenderText Solid failed: %s", sdl.GetError())
		}

		target.Blit(
			&sdl.Rect{
				X: 50,
				Y: int16(320 + (i * 30)),
			},
			txt_surface,
			nil,
		)
	}
}
Beispiel #6
0
func (g *stageLayer) Setup() (err error) {
	g.surface, err = util.CreateSurface(true, true, g.size_x, g.size_y)
	if err != nil {
		return err
	}

	var row uint16
	var col uint16
	var y_tile uint16
	var x_tile uint16
	var y_tiles uint16
	var x_tiles uint16

	stage := g.game.GetStage()
	for row = 0; row < uint16(len(stage.Tiles[0])); row++ {
		for col = 0; col < uint16(len(stage.Tiles)); col++ {
			texture := g.terrain_textures[stage.Tiles[col][row]]

			x_tiles = g.square_size / texture.Width
			y_tiles = g.square_size / texture.Height

			if x_tiles == 0 || y_tiles == 0 {
				panic(fmt.Errorf("terrain (%s) texture is larger than square_size (%d, %d) > %d", texture.Name, texture.Width, texture.Height, g.square_size))
			}

			for y_tile = 0; y_tile < y_tiles; y_tile++ {
				for x_tile = 0; x_tile < x_tiles; x_tile++ {
					errno := g.surface.Blit(
						&sdl.Rect{
							X: int16(col*g.square_size + x_tile*texture.Width),
							Y: int16(row*g.square_size + y_tile*texture.Height),
							W: texture.Width,
							H: texture.Height,
						},
						texture.Surface,
						&sdl.Rect{
							X: 0,
							Y: 0,
							W: texture.Width,
							H: texture.Height,
						},
					)

					if errno != 0 {
						return fmt.Errorf("Blit failed: %s", sdl.GetError())
					}
				}
			}
		}
	}

	if g.child != nil {
		return g.child.Setup()
	}

	return nil
}
Beispiel #7
0
func (g *guiLayer) Setup() (err error) {
	errno := ttf.Init()
	if errno != 0 {
		return fmt.Errorf("ttf.Init failed: %s", sdl.GetError())
	}

	// TODO: fix this
	g.font = ttf.OpenFont(g.fontFile, g.fontSize)
	if g.font == nil {
		return fmt.Errorf("OpenFont failed: %s", sdl.GetError())
	}

	if g.child != nil {
		return g.child.Setup()
	}

	return nil
}
Beispiel #8
0
func loadImage(name string) *sdl.Surface {
	image := sdl.Load(name)

	if image == nil {
		panic(sdl.GetError())
	}

	return image

}
Beispiel #9
0
func main() {
	res.WriteResources(ResPath)
	fonts.SetFontsPath(ResPath)

	if sdl.Init(sdl.INIT_VIDEO) != 0 {
		panic(sdl.GetError())
	}
	defer sdl.Quit()
	if ttf.Init() != 0 {
		panic("Error initializing SDL TTF")
	}
	defer ttf.Quit()

	screen := sdl.SetVideoMode(ScreenWidth, ScreenHeight, 32, 0)
	if screen == nil {
		panic(sdl.GetError())
	}
	sdl.WM_SetCaption("Drones", "")

	newLayers := make(chan ui.Layer, 100)
	layerStack := ui.LayerStack{mainmenu.New(newLayers)}
	frameTime := time.Second / time.Duration(FPS)
	tickTimer := time.NewTicker(frameTime)

	for len(layerStack) != 0 {
		select {
		case newLayer := <-newLayers:
			layerStack = append(layerStack, newLayer)
		case <-tickTimer.C:
			if toRemove := layerStack.Tick(frameTime); len(toRemove) != 0 {
				layerStack.RemoveLayers(toRemove)
			}
			layerStack.Draw(screen)
		case event := <-sdl.Events:
			layerStack.HandleEvent(event)
			switch event.(type) {
			case sdl.QuitEvent:
				layerStack = nil
			}
		}
	}
}
Beispiel #10
0
func CreateSurface(hw bool, display_format bool, x, y uint16) (*sdl.Surface, error) {
	var flags uint32 = 0
	if hw {
		flags = sdl.HWSURFACE
	} else {
		flags = sdl.SWSURFACE
	}

	surface := sdl.CreateRGBSurface(flags, int(x), int(y), 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000)
	if surface == nil {
		return nil, fmt.Errorf("Failed to load texture: %s", sdl.GetError())
	}

	if display_format {
		surface = surface.DisplayFormat()
		if surface == nil {
			return nil, fmt.Errorf("Failed to convert texture: %s", sdl.GetError())
		}
	}

	return surface, nil
}
Beispiel #11
0
func main() {

	var screen = sdl.SetVideoMode(640, 480, 32, sdl.RESIZABLE)

	if screen == nil {
		log.Fatal(sdl.GetError())
	}

	var n int32
	for n = 0; n < 1000000; n++ {

		var y int32 = rand.Int31() % 480
		var x int32 = rand.Int31() % 640
		var value uint32 = rand.Uint32()
		draw_point(x, y, value, screen)

		screen.Flip()
	}
}
Beispiel #12
0
/**
 * The main loop for the pygame interface. The pygame window will be 4
 * times wider and 4 times taller than the width and height of the liquid
 * simulation. It uses a standard double buffered sdl window. With pygame the
 * simulation speed and the framerate are locked together. You can use the
 * mouse to click and drag around the particles.
 */
func SdlMain(l *Liquid) {
	if sdl.Init(sdl.INIT_EVERYTHING) != 0 {
		panic(sdl.GetError())
	}

	defer sdl.Quit()

	canvas := sdl.SetVideoMode(int(l.width)*4, int(l.height)*4, 32, 0)

	if canvas == nil {
		panic(sdl.GetError())
	}

	surf := MakeSurface(canvas)
	mouse := MouseState{false, 0.0, 0.0}
	//mch := make(chan MouseState)
	eventtime := int64(0)
	simulatetime := int64(0)
	drawtime := int64(0)
	start := time.Now()
	t1 := time.Now()
	for frames := 0; ; frames++ {
		t1 = time.Now()
		select {
		case event := <-sdl.Events:
			switch e := event.(type) {
			case sdl.QuitEvent:
				fmt.Printf("%v frames\n", frames)
				fmt.Printf("%v frames/s\n", float64(frames)/time.Since(start).Seconds())
				fmt.Printf("%v time polling events\n", time.Duration(eventtime))
				fmt.Printf("%v time simulating\n", time.Duration(simulatetime))
				fmt.Printf("%v time drawing\n", time.Duration(drawtime))
				return
			case sdl.MouseButtonEvent:
				if e.State == sdl.PRESSED {
					mouse.pressed = true
				}
				if e.State == sdl.RELEASED {
					mouse.pressed = false
				}
			case sdl.MouseMotionEvent:
				mouse.x = float64(e.X / 4)
				mouse.y = float64(e.Y / 4)
			}
		default:
			mouse.pressed = mouse.pressed
		}
		eventtime += time.Since(t1).Nanoseconds()

		t1 = time.Now()
		l.simulate(mouse)
		simulatetime += time.Since(t1).Nanoseconds()

		t1 = time.Now()
		canvas.FillRect(nil, 0x000000)
		//draw simulation state
		surf.surface.Lock()
		for _, p := range l.particles {
			DrawLinePrelocked(
				surf,
				p.color,
				4*p.x, 4*p.y,
				4*(p.x-p.u), 4*(p.y-p.v),
			)
		}
		surf.surface.Unlock()
		canvas.Flip()
		drawtime += time.Since(t1).Nanoseconds()
	}
}
Beispiel #13
0
func main() {
	log.SetFlags(0)

	var resourcePath string
	{
		GOPATH := os.Getenv("GOPATH")
		if GOPATH == "" {
			log.Fatal("No such environment variable: GOPATH")
		}
		for _, gopath := range strings.Split(GOPATH, ":") {
			a := gopath + "/src/github.com/neagix/Go-SDL/examples/completeTest"
			_, err := os.Stat(a)
			if err == nil {
				resourcePath = a
				break
			}
		}
		if resourcePath == "" {
			log.Fatal("Failed to find resource directory")
		}
	}

	var joy *sdl.Joystick
	if sdl.Init(sdl.INIT_EVERYTHING) != 0 {
		log.Fatal(sdl.GetError())
	}

	if ttf.Init() != 0 {
		log.Fatal(sdl.GetError())
	}

	if sdl.NumJoysticks() > 0 {
		// Open joystick
		joy = sdl.JoystickOpen(0)

		if joy != nil {
			println("Opened Joystick 0")
			println("Name: ", sdl.JoystickName(0))
			println("Number of Axes: ", joy.NumAxes())
			println("Number of Buttons: ", joy.NumButtons())
			println("Number of Balls: ", joy.NumBalls())
		} else {
			println("Couldn't open Joystick!")
		}
	}

	if mixer.OpenAudio(mixer.DEFAULT_FREQUENCY, mixer.DEFAULT_FORMAT,
		mixer.DEFAULT_CHANNELS, 4096) != 0 {
		log.Fatal(sdl.GetError())
	}

	var screen = sdl.SetVideoMode(640, 480, 32, sdl.RESIZABLE)

	if screen == nil {
		log.Fatal(sdl.GetError())
	}

	var video_info = sdl.GetVideoInfo()

	println("HW_available = ", video_info.HW_available)
	println("WM_available = ", video_info.WM_available)
	println("Video_mem = ", video_info.Video_mem, "kb")

	sdl.EnableUNICODE(1)

	sdl.WM_SetCaption("Go-SDL SDL Test", "")

	image := sdl.Load(resourcePath + "/test.png")

	if image == nil {
		log.Fatal(sdl.GetError())
	}

	sdl.WM_SetIcon(image, nil)

	running := true

	font := ttf.OpenFont(resourcePath+"/Fontin Sans.otf", 72)

	if font == nil {
		log.Fatal(sdl.GetError())
	}

	font.SetStyle(ttf.STYLE_UNDERLINE)
	white := sdl.Color{255, 255, 255, 0}
	text := ttf.RenderText_Blended(font, "Test (with music)", white)
	music := mixer.LoadMUS(resourcePath + "/test.ogg")

	if music == nil {
		log.Fatal(sdl.GetError())
	}

	music.PlayMusic(-1)

	if sdl.GetKeyName(270) != "[+]" {
		log.Fatal("GetKeyName broken")
	}

	worm_in := make(chan Point)
	draw := make(chan Point, 64)

	var out chan Point
	var in chan Point

	out = worm_in

	in = out
	out = make(chan Point)
	go worm(in, out, draw)

	ticker := time.NewTicker(time.Second / 50) // 50 Hz

	// Note: The following SDL code is highly ineffective.
	//       It is eating too much CPU. If you intend to use Go-SDL,
	//       you should to do better than this.

	for running {
		select {
		case <-ticker.C:
			screen.FillRect(nil, 0x302019)
			screen.Blit(&sdl.Rect{0, 0, 0, 0}, text, nil)

		loop:
			for {
				select {
				case p := <-draw:
					screen.Blit(&sdl.Rect{int16(p.x), int16(p.y), 0, 0}, image, nil)

				case <-out:
				default:
					break loop
				}
			}

			var p Point
			sdl.GetMouseState(&p.x, &p.y)
			worm_in <- p

			screen.Flip()

		case _event := <-sdl.Events:
			switch e := _event.(type) {
			case sdl.QuitEvent:
				running = false

			case sdl.KeyboardEvent:
				println("")
				println(e.Keysym.Sym, ": ", sdl.GetKeyName(sdl.Key(e.Keysym.Sym)))

				if e.Keysym.Sym == sdl.K_ESCAPE {
					running = false
				}

				fmt.Printf("%04x ", e.Type)

				for i := 0; i < len(e.Pad0); i++ {
					fmt.Printf("%02x ", e.Pad0[i])
				}
				println()

				fmt.Printf("Type: %02x Which: %02x State: %02x Pad: %02x\n", e.Type, e.Which, e.State, e.Pad0[0])
				fmt.Printf("Scancode: %02x Sym: %08x Mod: %04x Unicode: %04x\n", e.Keysym.Scancode, e.Keysym.Sym, e.Keysym.Mod, e.Keysym.Unicode)

			case sdl.MouseButtonEvent:
				if e.Type == sdl.MOUSEBUTTONDOWN {
					println("Click:", e.X, e.Y)
					in = out
					out = make(chan Point)
					go worm(in, out, draw)
				}

			case sdl.JoyAxisEvent:
				println("Joystick Axis Event ->", "Type", e.Type, "Axis:", e.Axis, " Value:", e.Value, "Which:", e.Which)

			case sdl.JoyButtonEvent:
				println("Joystick Button Event ->", e.Button)
				println("State of button", e.Button, "->", joy.GetButton(int(e.Button)))

			case sdl.ResizeEvent:
				println("resize screen ", e.W, e.H)

				screen = sdl.SetVideoMode(int(e.W), int(e.H), 32, sdl.RESIZABLE)

				if screen == nil {
					log.Fatal(sdl.GetError())
				}
			}
		}
	}

	// Close if opened
	if sdl.JoystickOpened(0) > 0 {
		joy.Close()
	}

	image.Free()
	music.Free()
	font.Close()

	ttf.Quit()
	sdl.Quit()
}
Beispiel #14
0
func sdlError() error {
	return errors.New(sdl.GetError())
}