Skip to content

Commit 2003e86

Browse files
committed
Sun Jan 26 12:51:09 PM CET 2025
1 parent 9528449 commit 2003e86

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
#go
2+
3+
* A [binding](https://github.com/veandco/go-sdl2) for SDL2 exists already for Go, so there is no need to use the C functions directly
4+
* A simple program to run a window and color it didn't work out of the box and `SDL_VIDEODRIVER=wayland` needs to be set.
5+
* The functions that takes structs as first parameter are adapted in the binding to be a method to the struct.
6+
7+
# Simple colored window
8+
9+
Adapted from [SDL2 tutorial](https://jan.newmarch.name/Wayland/SDL/). It opens a window, color it light red and wait for 3 seconds before closing.
10+
11+
```go
12+
package main
13+
14+
import (
15+
"log/slog"
16+
"os"
17+
"time"
18+
19+
"github.com/veandco/go-sdl2/sdl"
20+
)
21+
22+
func main() {
23+
slog.Info("Initializing...")
24+
if err := sdl.Init(sdl.INIT_EVERYTHING); err != nil {
25+
slog.Error("Failed to initialize SDL", "error", err)
26+
os.Exit(1)
27+
}
28+
29+
window, err := sdl.CreateWindow("Example", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, 1280, 720, sdl.WINDOWEVENT_SHOWN)
30+
if err != nil {
31+
slog.Error("Failed to create a window", "error", err)
32+
os.Exit(1)
33+
}
34+
35+
surface, err := window.GetSurface()
36+
if err != nil {
37+
slog.Error("Failed to get window surface", "error", err)
38+
os.Exit(1)
39+
}
40+
41+
c := sdl.MapRGB(surface.Format, 255, 90, 120)
42+
43+
if err := surface.FillRect(nil, c); err != nil {
44+
slog.Error("Failed to fill rect", "error", err)
45+
os.Exit(1)
46+
}
47+
48+
if err := window.UpdateSurface(); err != nil {
49+
slog.Error("Failed to update surface", "error", err)
50+
os.Exit(1)
51+
}
52+
53+
time.Sleep(time.Second * 3)
54+
55+
if err := window.Destroy(); err != nil {
56+
slog.Error("failed to destroy window", "error", err)
57+
}
58+
59+
sdl.Quit()
60+
}
61+
```
62+
63+
It needs to run using the following command otherwise the window appears black:
64+
```sh
65+
SDL_VIDEODRIVER=wayland go run main.go
66+
```
67+
68+
The output looks like the following, Also notice the error while closing the window:
69+
```
70+
2025/01/26 12:40:32 INFO Initializing...
71+
2025/01/26 12:40:35 ERROR failed to destroy window error="That operation is not supported"
72+
```

0 commit comments

Comments
 (0)