GithubHelp home page GithubHelp logo

veandco / go-sdl2 Goto Github PK

View Code? Open in Web Editor NEW
2.2K 49.0 219.0 59.54 MB

SDL2 binding for Go

Home Page: https://godoc.org/github.com/veandco/go-sdl2

License: BSD 3-Clause "New" or "Revised" License

Makefile 0.05% Go 20.72% C 78.72% Batchfile 0.02% Objective-C 0.33% C++ 0.16%
go binding sdl2 maintainer-wanted

go-sdl2's Introduction

SDL2 binding for Go Build Status Go Report Card Reviewed by Hound Financial Contributors on Open Collective

go-sdl2 is SDL2 wrapped for Go users. It enables interoperability between Go and the SDL2 library which is written in C. That means the original SDL2 installation is required for this to work. Note that the first build may take several minutes on machines that are not powerful such as Raspberry Pi.

NOTE: For the latest versions of SDL2, please use the master branch!

Table of Contents

Documentation

Getting Started

If you haven't created a Go module for your program, you can do it by making a directory called, for example, app and running the following command inside it:

go mod init app

After that you can start writing code that uses go-sdl2, for example, like the following:

// main.go
package main

import (
	"github.com/veandco/go-sdl2/sdl"
)

func main() {
	sdl.Init(sdl.INIT_EVERYTHING)
}

Then to tell Go to fetch dependencies, you can run:

go mod tidy

and then the program can be built using:

go build

After that, you can execute your program:

./app

Requirements

On Ubuntu 22.04 and above, type:
apt install libsdl2{,-image,-mixer,-ttf,-gfx}-dev

On Fedora 36 and above, type:
dnf install SDL2{,_image,_mixer,_ttf,_gfx}-devel

On Arch Linux, type:
pacman -S sdl2{,_image,_mixer,_ttf,_gfx}

On Gentoo, type:
emerge -av libsdl2 sdl2-{image,mixer,ttf,gfx}

On macOS, install SDL2 via Homebrew like so:
brew install sdl2{,_image,_mixer,_ttf,_gfx} pkg-config

On Windows,

  1. Install mingw-w64 from Mingw-builds. A 7z archive extractor software might be needed which can be downloaded here. In this example, we extract the content, which is mingw64, into C:\.
  2. Download and install SDL2-devel-[version]-mingw.zip files from https://github.com/libsdl-org/SDL/releases.
    • Extract the SDL2 folder from the archive using a tool like 7zip
    • Inside the extracted SDL2 folder, copy the i686-w64-mingw32 and/or x86_64-w64-mingw32 into mingw64 folder e.g. C:\mingw64
  3. Setup Path environment variable
    • Put mingw-w64 binaries location into system Path environment variable (e.g. C:\mingw64\bin)
  4. Close and open terminal again so the new Path environment variable takes effect. Now we should be able to run go build inside the project directory.
  5. Download and install SDL2 runtime libraries from https://github.com/libsdl-org/SDL/releases. Extract and copy the .dll file into the project directory. After that, the program should become runnable.
  6. (Optional) You can repeat Step 2 for SDL_image, SDL_mixer, SDL_ttf

Installation

To get the bindings, type:
go get -v github.com/veandco/go-sdl2/sdl
go get -v github.com/veandco/go-sdl2/img
go get -v github.com/veandco/go-sdl2/mix
go get -v github.com/veandco/go-sdl2/ttf
go get -v github.com/veandco/go-sdl2/gfx

or type this if you use Bash terminal:
go get -v github.com/veandco/go-sdl2/{sdl,img,mix,ttf}

Due to go-sdl2 being under active development, a lot of breaking changes are going to happen during v0.x. With versioning system coming to Go soon, we'll make use of semantic versioning to ensure stability in the future.

Static compilation

Since v0.3.0, it is possible to build statically against included libraries in .go-sdl2-libs. To build statically, run:

CGO_ENABLED=1 CC=gcc GOOS=linux GOARCH=amd64 go build -tags static -ldflags "-s -w"

You can also cross-compile to another OS. For example, to Windows:

CGO_ENABLED=1 CC=x86_64-w64-mingw32-gcc GOOS=windows GOARCH=amd64 go build -tags static -ldflags "-s -w"

On Windows, if you would like to hide the Command Prompt window when running the statically-compiled program, you could append -H windowsgui to the -ldflags value.

For the list of OS and architecture, you can see inside the .go-sdl2-libs directory.

NOTE: If you're using the new Go Module system, you will need to refer to the master branch for now by running:

go get -v github.com/veandco/go-sdl2/sdl@master

Before building the program.

Cross-compiling

Linux to Windows

  1. Install MinGW toolchain.
    • On Arch Linux, it's simply pacman -S mingw-w64.
  2. Download the SDL2 development package for MinGW here (and the others like SDL_image, SDL_mixer, etc.. here if you use them).
  3. Extract the SDL2 development package and copy the x86_64-w64-mingw32 folder inside recursively to the system's MinGW x86_64-w64-mingw32 folder. You may also do the same for the i686-w64-mingw32 folder.
    • On Arch Linux, it's cp -r x86_64-w64-mingw32 /usr.
  4. Now you can start cross-compiling your Go program by running env CGO_ENABLED="1" CC="/usr/bin/x86_64-w64-mingw32-gcc" GOOS="windows" CGO_LDFLAGS="-lmingw32 -lSDL2" CGO_CFLAGS="-D_REENTRANT" go build -x main.go. You can change some of the parameters if you'd like to. In this example, it should produce a main.exe executable file.
  5. Before running the program, you need to put SDL2.dll from the SDL2 runtime package (For others like SDL_image, SDL_mixer, etc.., look for them here) for Windows in the same folder as your executable.
  6. Now you should be able to run the program using Wine or Windows!

macOS to Windows

  1. Install Homebrew
  2. Install MinGW through Homebrew via brew install mingw-w64
  3. Download the SDL2 development package for MinGW here (and the others like SDL_image, SDL_mixer, etc.. here if you use them).
  4. Extract the SDL2 development package and copy the x86_64-w64-mingw folder inside recursively to the system's MinGW x86_64-w64-mingw32 folder. You may also do the same for the i686-w64-mingw32 folder. The path to MinGW may be slightly different but the command should look something like cp -r x86_64-w64-mingw32 /usr/local/Cellar/mingw-w64/5.0.3/toolchain-x86_64.
  5. Now you can start cross-compiling your Go program by running env CGO_ENABLED=1 CC=x86_64-w64-mingw32-gcc GOOS=windows CGO_LDFLAGS="-L/usr/local/Cellar/mingw-w64/5.0.3/toolchain-x86_64/x86_64-w64-mingw32/lib -lSDL2" CGO_CFLAGS="-I/usr/local/Cellar/mingw-w64/5.0.3/toolchain-x86_64/x86_64-w64-mingw32/include -D_REENTRANT" go build -x main.go. You can change some of the parameters if you'd like to. In this example, it should produce a main.exe executable file.
  6. Before running the program, you need to put SDL2.dll from the SDL2 runtime package (For others like SDL_image, SDL_mixer, etc.., look for them here) for Windows in the same folder as your executable.
  7. Now you should be able to run the program using Wine or Windows!

Linux to macOS

  1. Install macOS toolchain via osxcross
  2. Run the following build command (replace the values in parentheses):
CGO_ENABLED=1 CC=[path-to-osxcross]/target/bin/[arch]-apple-darwin[version]-clang GOOS=darwin GOARCH=[arch] go build -tags static -ldflags "-s -w" -a

Examples

NOTE: The following example is for the master branch. Please check the README of v0.4.x for the stable version.

package main

import "github.com/veandco/go-sdl2/sdl"

func main() {
	if err := sdl.Init(sdl.INIT_EVERYTHING); err != nil {
		panic(err)
	}
	defer sdl.Quit()

	window, err := sdl.CreateWindow("test", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, 800, 600, sdl.WINDOW_SHOWN)
	if err != nil {
		panic(err)
	}
	defer window.Destroy()

	surface, err := window.GetSurface()
	if err != nil {
		panic(err)
	}
	surface.FillRect(nil, 0)

	rect := sdl.Rect{0, 0, 200, 200}
	colour := sdl.Color{R: 255, G: 0, B: 255, A: 255} // purple
	pixel := sdl.MapRGBA(surface.Format, colour.R, colour.G, colour.B, colour.A)
	surface.FillRect(&rect, pixel)
	window.UpdateSurface()

	running := true
	for running {
		for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
			switch event.(type) {
			case sdl.QuitEvent: // NOTE: Please use `*sdl.QuitEvent` for `v0.4.x` (current version).
				println("Quit")
				running = false
				break
			}
		}

        sdl.Delay(33)
	}
}

There are two ways a game might be running: one that updates on user input using sdl.WaitEvent() and one that updates regardless of user input using sdl.PollEvent(). You can check the examples of those two loops here.

For more runnable examples, see https://github.com/veandco/go-sdl2-examples. You can run any of the .go files with go run.

FAQ

Why does the program not run on Windows? Try putting the runtime libraries (e.g. SDL2.dll and friends) in the same folder as your program.

Why does my program crash randomly or hang? Putting runtime.LockOSThread() at the start of your main() usually solves the problem (see SDL2 FAQ about multi-threading).

UPDATE: Recent update added a call queue system where you can put thread-sensitive code and have it called synchronously on the same OS thread. See the render_queue or render_goroutines examples from https://github.com/veandco/go-sdl2-examples to see how it works.

Why can't SDL_mixer seem to play MP3 audio file? Your installed SDL_mixer probably doesn't support MP3 file.

On macOS, this is easy to correct. First remove the faulty mixer: brew remove sdl2_mixer, then reinstall it with the MP3 option: brew install sdl2_mixer --with-flac --with-fluid-synth --with-libmikmod --with-libmodplug --with-smpeg2. If necessary, check which options you can enable with brew info sdl2_mixer. You could also try installing sdl2_mixer with mpg123 by running brew install sdl2_mixer --with-mpg123.

On Other Operating Systems, you will need to compile smpeg and SDL_mixer from source with the MP3 option enabled. You can find smpeg in the external directory of SDL_mixer. Refer to issue #148 for instructions.

Note that there seems to be a problem with SDL_mixer 2.0.2 so you can also try to revert back to 2.0.1 and see if it solves your problem

Does go-sdl2 support compiling on mobile platforms like Android and iOS? For Android, see https://github.com/veandco/go-sdl2-examples/tree/master/examples/android.

There is currently no support for iOS yet.

Why does my window not immediately render after creation? It appears the rendering subsystem needs some time to be able to present the drawn pixels. This can be workaround by adding delay using sdl.Delay() or put the rendering code inside a draw loop.

Contributors

Code Contributors

This project exists thanks to all the people who contribute. [Contribute].

Financial Contributors

Become a financial contributor and help us sustain our community. [Contribute]

Individuals

Organizations

Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]

License

Go-SDL2 is BSD 3-clause licensed.

go-sdl2's People

Contributors

akovaski avatar andreas-jonsson avatar baskerville avatar cdelorme avatar dusk125 avatar flga avatar flyx avatar gcatlin avatar gen2brain avatar gerow avatar gonutz avatar jalan avatar jclc avatar keithcat1 avatar kjx98 avatar krux02 avatar lundis avatar malashin avatar marcusva avatar nlordell avatar phicode avatar r41d avatar rasky avatar schobers avatar stantheman avatar tanema avatar thundergroove avatar veeableful avatar whyrusleeping avatar zeroxlr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

go-sdl2's Issues

Problems with Go Get under OSX

I've downloaded and installed the SDL development libraries found here:
https://www.libsdl.org/download-2.0.php
specifically:
https://www.libsdl.org/release/SDL2-2.0.3.dmg

I installed the framework by copying it to /Library/Frameworks/

However, when I run:
go get -v github.com/veandco/go-sdl2/sdl

I get the following output:

github.com/veandco/go-sdl2/sdl
../GoProjects/src/github.com/veandco/go-sdl2/sdl/audio.go:3:11: fatal error: 'SDL2/SDL.h' file not found
 #include <SDL2/SDL.h>
           ^
1 error generated.

Any pointers would be much appreciated!

Problems installing the package

Hi,

I have a problem installing the package; it looks like the compiler gets into an infinite loop while trying to look up the sdl.h header. I wonder whether it's caused by the #include <SDL.h> line in sdl/sdl.h, it may be trying to include itself and not the "global" one?

Error log:
http://pastebin.com/NKD45Mce

Environment:

  • OS X Yosemite
  • Homebrew: sdl2, sdl2_mixer

Compiling for windows

I am trying to compile a game for windows, it works great on linux.
I have installed all needed stuff such as 32 bit Golang, SDL2, MinGW and so on.
After trying to build it i get this error:

C:\Users\HaCk3D\Desktop\Game>go build main.go
github.com/veandco/go-sdl2/sdl
could not determine kind of name for C.free

I've googled it, found that I should add an include for stdio "// #include <stdlib.h"
But i dont know where to do it, added in almost any file but it does not help

WaitEvent() method broken

I couldn't manage to use the WaitEvent() method, and so I posted a question on golang-nuts [1] and it seems the method is not usable.

A gentleman posted a fix :

func WaitEvent(event *Event) int {
    var cevent CEvent
    ok := (int) (C.SDL_WaitEvent((*C.SDL_Event)(unsafe.Pointer(&cevent))))
    if ok == 0 {
        return ok
    }
    *event = goEvent(&cevent)
    return ok
}

[1] https://groups.google.com/forum/#!topic/golang-nuts/7yKTzmB-cgE

No such file "SDL.h" ??

Hi, I'm having issues setting this up on windows. When I run "go get -v github.com/veandco/go-sdl2/sdl" I get a error regarding "SDL.h", Which seems odd as not only is this line a comment, but is not even the correct c header for sdl (which would be "SDL2/SDL.h" ?). Here's what it gives me (using msys):

Alasdair@Alasdair-PC /C/Users/Alasdair/Documents/go
$ go get -v github.com/veandco/go-sdl2/sdl
github.com/veandco/go-sdl2 (download)
github.com/veandco/go-sdl2/sdl
# github.com/veandco/go-sdl2/sdl
C:\Users\Alasdair\Documents\Go\src\github.com\veandco\go-sdl2\sdl\audio.go:3:18:
 fatal error: SDL.h: No such file or directory
 // #include <SDL.h>
                  ^
compilation terminated.

Any thoughts?

'SDL_HasAVX' undeclared

Hi

I'm getting the following error when executing go get

$ go get -v github.com/jackyb/go-sdl2/sdl
github.com/jackyb/go-sdl2/sdl
# github.com/jackyb/go-sdl2/sdl
37: error: 'SDL_HasAVX' undeclared (first use in this function)

SDL.h: No such file or directory (Win7, no pkg-config installed)

Another unlucky Windows user here.
Is there a way to solve this without using pkg-config? I'm still getting the "fatal error: SDL.h: No such file or directory // #include <SDL.h>".

Do I have to put the SDL.h file in one of the go-sdl2 folders?
Do I need to put in on the path?
I've tried experimenting with putting SDL.h in various go-sdl2 folders and running make.bat, but no luck.

Using x86_64-w64-mingw32's GCC, Go 1.4.1, Win 7.

(I kind of don't even know why I bother... everything just works on Linux...)

Return error instead of nil checking

At the moment when calling CreateWindow or CreateRenderer, etc, you have to check if the return is nil, and then call sdl.GetError(). These functions should instead return an error (gotten by GetError) as a second return value.

This is more Go like, and lets someone using library know that they should check for an error. Someone who doesn't have an intimate knowledge of sdl might not know when they should check for nil, but if they see that the function returns an error then they know they must check it.

If you would be happy with this change I would gladly create a pull request.

Here is a probably incomplete list of functions I think should return an error:

  • sdl.CreateWindow
  • sdl.CreateRenderer
  • sdl.CreateWindowAndRenderer
  • img.Load
  • CreateTextureFromSurface

Exception 0xc0000005 0x1 0x333249 0x6c7bec77 PC=0x6c7bec77 signal arrived during cgo execution

I have this intermittent problem. Sometimes it crashes on launch.

package main

import (
    "fmt"
    "runtime"

    "github.com/veandco/go-sdl2/sdl"
    "github.com/veandco/go-sdl2/sdl_ttf"
)

func main() {
    runtime.LockOSThread()
    defer runtime.UnlockOSThread()

    ttf.Init()

    font, errOpen := ttf.OpenFont("Ubuntu-B.ttf", 300)
    if errOpen != nil {
        panic(errOpen)
    }
    defer font.Close()

    window, err := sdl.CreateWindow("test", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED,
        800, 600, sdl.WINDOW_SHOWN)
    if err != nil {
        panic(err)
    }
    defer window.Destroy()

    surface := window.GetSurface()

    fontSurface := font.RenderText_Shaded("123", sdl.Color{R: 255, G: 165, B: 0, A: 255}, sdl.Color{R: 0, G: 0, B: 0, A: 255})
    rect := sdl.Rect{surface.W/2 - fontSurface.W/2, surface.H/2 - fontSurface.H/2, 800, 800}
    fontSurface.Blit(nil, surface, &rect)
    fontSurface.Free()

    var event sdl.Event
    running := true

    for running {
        for event = sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
            switch t := event.(type) {
            case *sdl.QuitEvent:
                running = false
            case *sdl.MouseMotionEvent:
                fmt.Printf("[%d ms] MouseMotion\ttype:%d\tid:%d\tx:%d\ty:%d\txrel:%d\tyrel:%d\n",
                    t.Timestamp, t.Type, t.Which, t.X, t.Y, t.XRel, t.YRel)
            case *sdl.MouseButtonEvent:
                fmt.Printf("[%d ms] MouseButton\ttype:%d\tid:%d\tx:%d\ty:%d\tbutton:%d\tstate:%d\n",
                    t.Timestamp, t.Type, t.Which, t.X, t.Y, t.Button, t.State)
            case *sdl.MouseWheelEvent:
                fmt.Printf("[%d ms] MouseWheel\ttype:%d\tid:%d\tx:%d\ty:%d\n",
                    t.Timestamp, t.Type, t.Which, t.X, t.Y)
            case *sdl.KeyUpEvent:
                fmt.Printf("[%d ms] Keyboard\ttype:%d\tsym:%c\tmodifiers:%d\tstate:%d\trepeat:%d\n",
                    t.Timestamp, t.Type, t.Keysym.Sym, t.Keysym.Mod, t.State, t.Repeat)
            }
        }

        window.UpdateSurface()
        sdl.Delay(1000 / 30)
    }
}
Exception 0xc0000005 0x1 0x333249 0x6c7bec77
PC=0x6c7bec77
signal arrived during cgo execution

github.com/veandco/go-sdl2/sdl_ttf._Cfunc_SDL_free(0x8ce750)
        d:/dev/go/gopath/src/github.com/veandco/go-sdl2/sdl_ttf/:44 +0x4c
github.com/veandco/go-sdl2/sdl_ttf.(*Font).RenderText_Shaded(0xc082034018, 0x517010, 0x3, 0xff000000ff00a5ff, 0x2829a0)
        d:/dev/go/gopath/src/github.com/veandco/go-sdl2/sdl_ttf/sdl_ttf.go:110 +0x11c
main.main()
        D:/Dev/go/Tests/sdl2crash/sdl2.go:32 +0x24b

goroutine 17 [syscall, locked to thread]:
runtime.goexit()
        c:/go/src/runtime/asm_amd64.s:2232 +0x1
rax     0x8ce740
rbx     0x8
rcx     0x6c85fb60
rdx     0x333231
rdi     0xc082025d00
rsi     0x5bfa60
rbp     0x22feb0
rsp     0x22fdf0
r8      0x1c00bf0e2bb52254
r9      0x1c00bf0e2c420994
r10     0x8c0158
r11     0x280000
r12     0xff
r13     0x0
r14     0x0
r15     0x0
rip     0x6c7bec77
rflags  0x10293
cs      0x33
fs      0x53
gs      0x2b

SDL_BlitSurface

Hello,

I don't find the SDL_BlitSurface function in go-sdl2.
Is it not implemented ? Is it planned ?

Thank you for your work :)

SDL2 use golang image

How to make SDL2 use golang image package ?
My image decoder is implemented as an image decoder, I want to reuse this, is this possible ?

GameController GetBind

func (ctrl *GameController) GetBindForAxis(axis GameControllerAxis) GameControllerButtonBind

Will return a struct whose members are unexported (they are lowercase in gamecontroller.h) making this really hard to use.

controller := sdl.GameControllerOpen(0)
axisx := controller.GetBindForAxis(sdl.CONTROLLER_AXIS_LEFTX)
fmt.Printf("joy axis %+v", axisx.value)
axisx.value undefined (cannot refer to unexported field or method value)

Fixing the other Event funcions

Continuing on from the last issue...
PeepEvents, WaitEventTimeout, and PushEvent are still broken.

  • PeepEvents needs to use a slice instead of an Event pointer
  • PeepEvents and WaitEventTimeout suffer from the same problem that WaitEvent had
  • PushEvent probably suffers from the same problem

I'm posting this as an issue instead of a pull request because I'm about to raise another issue about refactoring.

Unusable header search path using pkg-config on Mac OS X

Attempting to run go get -v github.com/veandco/go-sdl2/sdl fails:

[snip]/src/github.com/veandco/go-sdl2/sdl/audio.go:3:11: fatal error: 'SDL2/SDL.h' file not found
 #include <SDL2/SDL.h>
          ^

sdl/sdl.go contains this:

// #cgo windows LDFLAGS: -lSDL2
// #cgo linux freebsd darwin pkg-config: sdl2
// #include <SDL2/SDL.h>

pkg-config returns an include path with the SDL2/ directory:

% pkg-config --cflags sdl2
-D_THREAD_SAFE -I/usr/local/include/SDL2

So, since the SDL2/ directory is already in the search path, the sdl/sdl.go comment should probably be changed to include SDL.h directly, rather than SDL2/SDL.h:

// #include <SDL.h>

I don’t know how this affects non-Mac OS X platforms though. I imagine that any platform that uses pkg-config is fine.

Can't install on Ubuntu 14.04 using standard instructions

EDIT: Instructions have been updated, but I will keep this open until the Ubuntu package is fixed.

I followed the instructions on readme.md, installed the SDL packages trough apt-get, the way it was suggested. So far no problems. Then, when trying to do

go get -v github.com/veandco/go-sdl2/sdl

I get the following error:

github.com/veandco/go-sdl2/sdl
# github.com/veandco/go-sdl2/sdl
In file included from Dev/Go/code/src/github.com/veandco/go-sdl2/sdl/sdl_syswm.go:4:0:
/usr/include/SDL2/SDL_syswm.h:97:44: fatal error: mir_toolkit/mir_client_library.h: No such file or directory
 #include <mir_toolkit/mir_client_library.h>

Any ideas what I did wrong? Again, running Ubuntu 14.04.

Implement GetDisplayBounds

Hi,

it would be very helpful if you could provide a Go version of the display information function SDL_GetDisplayBounds. Right now I have my own patch in sdl_video.go, but I'd prefer it to be in the official go-sdl2:

func GetDisplayBounds(displayIndex int, rect *Rect) int {
    return int(C.SDL_GetDisplayBounds(C.int(displayIndex), rect.cptr()))
}

The function is very helpful if one wants to open a borderless fullscreen window to avoid switching the display mode.

Or is there a reason why you left it out?

BR
Hagen

Godoc comments including link to original library call

I understand that this is library is in active development, but I think it would be helpful in the meantime to add some godoc comments to the library calls to at least link to the underlying SDL call. It would be incredibly convenient to be able to hit:

http://godoc.org/github.com/veandco/go-sdl2/sdl#Renderer.SetDrawColor

And (as a holdover before a stable release with documentation) have a link to the corresponding SDL documentation right there: https://wiki.libsdl.org/SDL_SetRenderDrawColor

Since the receiver name gets moved out of the function name, it would be especially nice to have the link. It looks pretty consistent -- it might even be straightforward to programmatically add the comments. If this is desirable, I'd be happy to try whipping up a little perl script to help make the PR.

Types mismatch using texture.Query()

I have simple code like

dst := sdl.Rect{X: x, Y:y, W:0, H:0}

_, _, dst.W, dst.H, _ = texture.Query()

according to docs interface sdl.Rect requires int32 values, while texture.Query() returns int values.
Thus i got this error

./sdl.go:63: cannot assign to int(dst.W)
./sdl.go:63: cannot assign to int(dst.H)

Is it ok, to allocate new temp variables, to later do like

_, _, w, h, _ = texture.Query()

dst.W = int32(w)
dst.H = int32(h)

Example of go-sdl2 using go routines

SDL2 has threading requirements. For instance, it would seem that the thread creating the main window needs also to be the same thread for manipulating the renderer and for pooling events.

Is it possible to use go routines with go-sdl2?

*mix.Chunk.setVolume() fails on Windows 7

So I finally got everything compiling and running under Windows (Win 7 32 bit using MSYS and MinGW). However, one function call causes a cgo exception with the following output:

Exception 0xc0000005 0x0 0xc 0x6788777b
PC=0x6788777b
signal arrived during cgo execution

github.com/veandco/go-sdl2/sdl_mixer._Cfunc_Mix_VolumeChunk(0x0, 0x63, 0x0)
    C:/dev/golang/src/github.com/veandco/go-sdl2/sdl_mixer/:443 +0x3f
github.com/veandco/go-sdl2/sdl_mixer.(*Chunk).SetVolume(0x0, 0x63, 0x115cff24)
    C:/dev/golang/src/github.com/veandco/go-sdl2/sdl_mixer/sdl_mixer.go:270 +0x30
main.initAudio()
    C:/dev/01_hello_SDL/revenge-of-the-gopher/src/audio.go:27 +0x162
main.main()
    C:/dev/01_hello_SDL/revenge-of-the-gopher/src/main.go:35 +0xf7

goroutine 17 [syscall, locked to thread]:
runtime.goexit()
    c:/go/src/runtime/asm_386.s:2287 +0x1
eax     0x0
ebx     0x0
ecx     0x5ab440
edx     0x63
edi     0x115d0000
esi     0x5a36c0
ebp     0x5a38e0
esp     0x12fe98
eip     0x6788777b
eflags  0x210206
cs      0x1b
fs      0x3b
gs      0x0
exit status 2

The offending function looks like this:

var gameAudio audio

type audio struct {
explode1, laser1, playerDeath *mix.Chunk
enemyHit, powerUp1Active      *mix.Chunk
intro, bgmusic                *mix.Music
}

func initAudio() {
mix.OpenAudio(22050, mix.DEFAULT_FORMAT, 2, 4096)

gameAudio = audio{
    explode1:       mix.LoadWAV("assets/SFX_Explosion_01.ogg"),
    laser1:         mix.LoadWAV("assets/Laser1.ogg"),
    playerDeath:    mix.LoadWAV("assets/player_death.ogg"),
    enemyHit:       mix.LoadWAV("assets/enemy_hit.ogg"),
    powerUp1Active: mix.LoadWAV("assets/powerup1_active.ogg"),

    bgmusic: mix.LoadMUS("assets/bgmusic1.ogg"),
    intro:   mix.LoadMUS("assets/bgmusic6.ogg"),
}

gameAudio.enemyHit.SetVolume(100)
gameAudio.laser1.SetVolume(20)
gameAudio.playerDeath.SetVolume(75)
}

Line 27 in audio.go refers to the line containing "gameAudio.enemyHit.SetVolume(100)".

The entire project is available here: https://github.com/Decker108/revenge-of-the-gopher/tree/060094c0d2140bf9dacd10a4485c97813b49134f

import sdl make program show testing args

write program import sdl like
package main

import (
"flag"
_ "github.com/veandco/go-sdl2/sdl"
)

func main() {
flag.Parse()
}

and run with -? argument show
-test.bench="": regular expression to select benchmarks to run
-test.benchmem=false: print memory allocations for benchmarks
-test.benchtime=1s: approximate run time for each benchmark
-test.blockprofile="": write a goroutine blocking profile to the named file after execution
-test.blockprofilerate=1: if >= 0, calls runtime.SetBlockProfileRate()
-test.coverprofile="": write a coverage profile to the named file after execution
-test.cpu="": comma-separated list of number of CPUs to use for each test
-test.cpuprofile="": write a cpu profile to the named file during execution
-test.memprofile="": write a memory profile to the named file after execution
-test.memprofilerate=0: if >=0, sets runtime.MemProfileRate
-test.outputdir="": directory in which to write profiles
-test.parallel=1: maximum test parallelism
-test.run="": regular expression to select tests and examples to run
-test.short=false: run smaller test suite to save time
-test.timeout=0: if positive, sets an aggregate time limit for all tests
-test.v=false: verbose: print additional output

Clipboard Update Event causes panic

Updating the clipboard, then focusing on the sdl window causes a panic under PollEvent under goEvent:

"panic: Unknown event type: 2304"
(The panic is at sdl/sdl_events.go:424)

2304 = 0x900 = sdl.CLIPBOARDUPDATE

To fix this, a case for CLIPBOARDUPDATE needs to be added to goEvent.

As far as I can tell, there is no data with CLIPBOARDUPDATE events, so an empty struct should probably suffice.

Readme Example

The small example provided by the readme needs "sdl.Init" before any SDL calls.

Intermittent SIGSEGV Issues

I'm getting segfault errors about 30-40% of the time when running my sdl2 compiled programs. Every other time works fine. In this example this is my code (An altered example):
https://dl.dropboxusercontent.com/u/22109038/Go/sdltest.go

Here's my gdb output

Starting program: C:\Users\Alasdair\Documents\Go\bin/sdltest.exe
[New Thread 8080.0xae4]
[New Thread 8080.0x2078]
[New Thread 8080.0xb04]
[New Thread 8080.0x15f0]
[New Thread 8080.0x1eac]
[New Thread 8080.0x1948]

Program received signal SIGSEGV, Segmentation fault.
0x6c79e3b8 in SDL_free () from C:\Users\Alasdair\Documents\Go\bin\SDL2.dll
(gdb) bt
#0  0x6c79e3b8 in SDL_free () from C:\Users\Alasdair\Documents\Go\bin\SDL2.dll
#1  0x00426d25 in runtime.asmcgocall () at c:/go/src/pkg/runtime/asm_386.s:624
#2  0x00713248 in ?? ()
#3  0x00000000 in ?? ()

events.go Compilation Error

Hi all. I'm trying to install the SDL2 bindings and followed the instructions. However the compilation terminates at the events.go file, which the following:

D:\gocode\src\github.com\veandco\go-sdl2\sdl\events.go:5:20: fatal error: events
.h: No such file or directory
#include "events.h"
^
compilation terminated.

Looking at the events.go source I'm missing the events.h header file. It's not included in the SDL distrubtion and not in the repo. Where can I find "events.h" and "events.c"?

I run Windows 7 64bit. SDL2 download was SDL2-devel-2.0.3-mingw and a working Mingw-64 compiler.

Thanks in advance folks!

Gusbin

'SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES' undeclared

37: error: 'SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES' undeclared (first use in this function)

This is the error I find when installing and building the library. I think this is a problem somewhere in the sdl package, but I'm puzzled because I do not find where the hint is called.

My machine is a 14.04 (already patched) ubuntu 64 bit.

EDIT:
Probably the hint is added in sdl 2.2.0.2. If it is required for this package, i suggest you to specify SDL2 library version somewhere.

Unknown event type: 8192

When creating a new window with sdl.WINDOW_RESIZABLE flag and later attempt at resizing the window or setting full screen through the window.FullScreen() method the program panics with "Unknown event type: 8192". Something similiar also happens when opening the task mananger with CTRL+ALT+DEL

Full error:
C:/Users/ADMINI~1/AppData/Local/Temp/2/makerelease250988475/go/src/pkg/runtime/panic.c:266 +0xc8
github.com/veandco/go-sdl2/sdl.goEvent(0xc08405a8c0, 0xc000000001, 0x100000000)
C:/Users/Kevin/Desktop/Go/src/github.com/veandco/go-sdl2/sdl/sdl_events.go:438 +0x15a
github.com/veandco/go-sdl2/sdl.PollEvent(0x69fbe8, 0x0)
C:/Users/Kevin/Desktop/Go/src/github.com/veandco/go-sdl2/sdl/sdl_events.go:383 +0x6a

OS: Window 8

go-sdl2 does not compile on macos x

I have the following error:

go get -v github.com/veandco/go-sdl2/sdl{,_mixer,_image,_ttf}
github.com/veandco/go-sdl2/sdl

github.com/veandco/go-sdl2/sdl

gotree/src/github.com/veandco/go-sdl2/sdl/syswm.go:5:10: fatal error: 'SDL2/SDL_syswm.h' file not found
#include <SDL2/SDL_syswm.h>
^

Maybe the following line is missing:

cgo pkg-config: sdl2

(from http://golang.org/cmd/cgo/)

sdl_mixer's PlayChannel error checking is wrong

The current implementation for sdl_mixer's PlayChannel function returns a bool specifying whether the call was successful or not:

func (chunk *Chunk) PlayChannel(channel, loops int) bool {
    _channel := (C.int)(channel)
    _chunk := (*C.Mix_Chunk)(unsafe.Pointer(chunk))
    _loops := (C.int)(loops)
    return int(C.Mix_PlayChannelTimed(_channel, _chunk, _loops, -1)) == 0
}

However, the original docs for sdl_mixer states that the return value is "the channel the sample is played on. On any errors, -1 is returned." (http://www.libsdl.org/projects/SDL_mixer/docs/SDL_mixer.html#SEC28)

Perhaps this function could be rewritten to:

func (chunk *Chunk) PlayChannel(channel, loops int) (int, error) {
    _channel := (C.int)(channel)
    _chunk := (*C.Mix_Chunk)(unsafe.Pointer(chunk))
    _loops := (C.int)(loops)
    retVal := int(C.Mix_PlayChannelTimed(_channel, _chunk, _loops, -1))
    if retVal == -1 {
            return -1, sdl.GetError()
    }
    return retVal, nil
}

Granted, it might be unnecessary to return the same channel as was input. Either way, comparing to 0 for error checking seems wrong according to the docs.

What is the state of a full go sdl port and how do I get involved?

Two things:

  • I see in the readme that there is talk, and a notion that a full go port of SDL could (and potentially should) be done. I feel this is the next step in go game (and other graphical application) development, and would love to be around if it happens.
  • Is their is an IRC channel or a website where I could keep posted, get stuck into the community or perhaps contribute some code?

Note: added this as an issue as i'm not quite sure where else to put it :)

SDL_MapRGB not implemented

I was attempting to follow this tutorial while translating to go: http://lazyfoo.net/tutorials/SDL/10_color_keying/index.php
The tutorial introduces color keying (identifying the transparent color in a surface):
bmp := img.Load("resources/foo.png")

//C++
SDL_SetColorKey( loadedSurface, SDL_TRUE, SDL_MapRGB( loadedSurface->format, 0, 0xFF, 0xFF ) );
//Go
bmp.SetColorKey(1, sdl.Color{0xFF,0xFF,0x00,0xFF}.Uint32()

Without a MapRGB function or anything similar I could identify I tried to use sdl.Color.Uint32(). However the ordering of the RGBA differs in my surface (hence the loadedsurface->format). Is there a way to perform this currently in this binding or does the function need to be implemented?

Thanks, full code: https://gist.github.com/EvanTheB/8eecaf5fd2428e743fd0

SDL2/SDL_filesystem.h: No such file or directory

I followed the installation instructions and installed the libsdl2 dev packages before trying the examples.

~/gocode/src/github.com/jackyb/go-sdl2$ go run examples/texture.go
github.com/jackyb/go-sdl2/sdl
sdl/sdl_filesystem.go:3:34: fatal error: SDL2/SDL_filesystem.h: No such file or directory
// #include <SDL2/SDL_filesystem.h>
^
compilation terminated.

I'm running Ubuntu 13.10. I have both the libsdl2 and libsdl2 dev packages installed through apt.

Refactoring Event functions

(See fixing Event functions issues first #10 )
So Carlos in the google groups thread suggested to make WaitEvent more like PollEvent by returning an Event instead of taking a pointer as a parameter.

I think the other functions can be refactored as well:

  • WaitEvent(*Event) int -> WaitEvent() Event
  • WaitEventTimeout(*Event, timeout) int -> WaitEventTimeout(timeout) Event
  • PushEvent(*Event) int -> PushEvent(Event) bool // This one's a bit superfluous

Peep Events is a little strange because the action parameter can change it from peeping, pushing, or getting an array of events. So my suggestion is to break that into separate functions by action:

PeepEvents([]Event, numevents, action, minType, maxType) int ->

  • PeepEvents(numevents, minType, maxType) []Event
  • GetEvents(numevents, minType, maxType) []Event
  • PushEvents([]Event) bool // numevents just len([]Event)

But ultimately this is your repo, so do you like any of these refactorings?

Installation trouble (homebrew / go get) - help please

Sorry for a newb questions here. I followed the homebrew installation steps. When I try to go get sdl2 I see this message:

~/code/go/src$ go get -v github.com/veandco/go-sdl2/sdl
github.com/veandco/go-sdl2/sdl

pkg-config --cflags sdl2

Package sdl2 was not found in the pkg-config search path.
Perhaps you should add the directory containing `sdl2.pc'
to the PKG_CONFIG_PATH environment variable
No package 'sdl2' found

I typed $PKG_CONFIG_PATH and it doesn't even appear to be an environement variable. I found sdl2.pc @ usr/local/cellar/sdl2/2.0.3/lib/pkgconfig/sdl2.pc - but I am a bit new and it seemed like if I needed to create a new environment variable with a path this specific it would have been in the instructions.

Thanks.

int vs int32

I've been writing some simple code and finding I'm doing a lot of casting to int32 which are used by Rect and Point. And used in lots of functions. However, several other functions like CreateWindow and Texture.Query work with regular ints. The Go compiler wants to do int by default and seems to be pretty strict about requiring explicit casting.

Going deeper, I see that SDL2 C code just uses int which is "platform dependent" but guaranteed to be at least 16bits. So if the C code is compiling to use the native word side by default, then I'm thinking the Go version should also use just plain int in all cases where the C code uses plain int. Thus reducing unnecessary casting.

I understand this would change the interface, but I think it would be a change for the better. People on 32bit machines would get both the C code and Go code compiled to 32bit values and people on 64bit machines would get their version.

I'm happy to submit a pull request if you support this idea.

non-utf8 functions in sdl-ttf

I recently saw, that the sdl-ttf wrapper has latin1 and utf8 support. Since go is utf8-only. I suggest to remove the non-utf8 version, since there is no way of providing a string that is encoded in latin1 (in the non ascii compatible range of course)

PNG Support

Hello,

pls, is PNG image loading support (LoadPNG) planned?

Thanks for reply.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.