Repository: xyproto/sdl2-examples Branch: main Commit: 68d49f34dd12 Files: 306 Total size: 1.1 MB Directory structure: gitextract_uhvoelxn/ ├── .github/ │ ├── dependabot.yml │ └── workflows/ │ ├── assembly.yml │ ├── c.yml │ ├── cplusplus.yml │ ├── expired.yml │ └── other.yml ├── .gitignore ├── COMPILES.md ├── LICENSE ├── Makefile ├── README.md ├── assembly/ │ ├── Makefile │ ├── README.md │ ├── linux-i386/ │ │ ├── Makefile │ │ ├── README.md │ │ └── main.asm │ ├── linux-x86_64/ │ │ ├── Makefile │ │ ├── README.md │ │ └── main.asm │ ├── macos-x86_64/ │ │ ├── Makefile │ │ ├── README.md │ │ └── main.asm │ └── windows-x86_64/ │ ├── README.md │ └── main.asm ├── bench.sh ├── c++11/ │ ├── Makefile │ └── main.cpp ├── c++11-cmake/ │ ├── CMakeLists.txt │ ├── README.md │ └── main.cpp ├── c++14-cmake/ │ ├── CMakeLists.txt │ ├── README.md │ └── main.cpp ├── c++17-cmake/ │ ├── CMakeLists.txt │ ├── README.md │ └── main.cpp ├── c++20-cmake/ │ ├── CMakeLists.txt │ ├── README.md │ └── main.cpp ├── c++23-cmake/ │ ├── CMakeLists.txt │ ├── README.md │ └── main.cpp ├── c++98/ │ ├── Makefile │ ├── README.md │ └── main.cpp ├── c11/ │ ├── Makefile │ ├── README.md │ └── main.c ├── c18/ │ ├── Makefile │ ├── README.md │ └── main.c ├── c2x/ │ ├── Makefile │ ├── README.md │ └── main.c ├── c89/ │ ├── Makefile │ ├── README.md │ └── main.c ├── c99/ │ ├── Makefile │ ├── README.md │ └── main.c ├── crystal/ │ ├── Makefile │ ├── README.md │ ├── main.cr │ └── shard.yml ├── csharp/ │ ├── Makefile │ ├── README.md │ ├── main.cs │ └── main.csproj ├── d/ │ ├── .gitignore │ ├── Makefile │ ├── README.md │ ├── dub.json │ ├── dub.selections.json │ └── source/ │ └── app.d ├── dart/ │ ├── Makefile │ ├── main.dart │ └── pubspec.yaml ├── freebasic/ │ ├── Makefile │ ├── README.md │ └── main.bas ├── fsharp/ │ ├── Makefile │ ├── main.fs │ └── main.fsproj ├── gambas/ │ ├── .directory │ ├── .gitignore │ ├── .project │ ├── .src/ │ │ └── MMain.module │ └── Makefile ├── gccgo/ │ ├── Makefile │ ├── README.md │ ├── go.mod │ ├── go.sum │ ├── main.go │ └── vendor/ │ ├── github.com/ │ │ └── veandco/ │ │ └── go-sdl2/ │ │ ├── CONTRIBUTORS.md │ │ ├── LICENSE │ │ ├── _libs/ │ │ │ └── dummy.go │ │ ├── img/ │ │ │ ├── sdl_image.go │ │ │ ├── sdl_image_cgo.go │ │ │ ├── sdl_image_cgo_static.go │ │ │ └── sdl_image_wrapper.h │ │ └── sdl/ │ │ ├── TODO.md │ │ ├── audio.go │ │ ├── blendmode.go │ │ ├── clipboard.go │ │ ├── cpuinfo.go │ │ ├── endian.go │ │ ├── error.go │ │ ├── events.c │ │ ├── events.go │ │ ├── events.h │ │ ├── filesystem.go │ │ ├── gamecontroller.go │ │ ├── gesture.go │ │ ├── guid.go │ │ ├── haptic.go │ │ ├── helpers.go │ │ ├── hidapi.go │ │ ├── hints.c │ │ ├── hints.go │ │ ├── hints.h │ │ ├── joystick.go │ │ ├── keyboard.go │ │ ├── keycode.go │ │ ├── loadso.go │ │ ├── log.c │ │ ├── log.go │ │ ├── log.h │ │ ├── mouse.go │ │ ├── mutex.go │ │ ├── pixels.go │ │ ├── power.go │ │ ├── rect.go │ │ ├── render.go │ │ ├── rwops.go │ │ ├── scancode.go │ │ ├── sdl.go │ │ ├── sdl_cgo.go │ │ ├── sdl_cgo_static.go │ │ ├── sdl_wrapper.h │ │ ├── sensor.go │ │ ├── shape.go │ │ ├── surface.go │ │ ├── sysrender.go │ │ ├── system.c │ │ ├── system.go │ │ ├── system.h │ │ ├── system_android.go │ │ ├── system_linux.go │ │ ├── system_windows.go │ │ ├── syswm.go │ │ ├── syswm_cocoa.go │ │ ├── syswm_dfb.go │ │ ├── syswm_uikit.go │ │ ├── syswm_vivante.go │ │ ├── syswm_windows.go │ │ ├── syswm_x11.go │ │ ├── thread.go │ │ ├── timer.go │ │ ├── touch.go │ │ ├── version.go │ │ ├── video.go │ │ └── vulkan.go │ └── modules.txt ├── go/ │ ├── Makefile │ ├── README.md │ ├── go.mod │ ├── go.sum │ ├── main.go │ └── vendor/ │ ├── github.com/ │ │ └── veandco/ │ │ └── go-sdl2/ │ │ ├── CONTRIBUTORS.md │ │ ├── LICENSE │ │ ├── _libs/ │ │ │ └── dummy.go │ │ ├── img/ │ │ │ ├── sdl_image.go │ │ │ ├── sdl_image_cgo.go │ │ │ ├── sdl_image_cgo_static.go │ │ │ └── sdl_image_wrapper.h │ │ └── sdl/ │ │ ├── TODO.md │ │ ├── audio.go │ │ ├── blendmode.go │ │ ├── clipboard.go │ │ ├── cpuinfo.go │ │ ├── endian.go │ │ ├── error.go │ │ ├── events.c │ │ ├── events.go │ │ ├── events.h │ │ ├── filesystem.go │ │ ├── gamecontroller.go │ │ ├── gesture.go │ │ ├── guid.go │ │ ├── haptic.go │ │ ├── helpers.go │ │ ├── hidapi.go │ │ ├── hints.c │ │ ├── hints.go │ │ ├── hints.h │ │ ├── joystick.go │ │ ├── keyboard.go │ │ ├── keycode.go │ │ ├── loadso.go │ │ ├── log.c │ │ ├── log.go │ │ ├── log.h │ │ ├── mouse.go │ │ ├── mutex.go │ │ ├── pixels.go │ │ ├── power.go │ │ ├── rect.go │ │ ├── render.go │ │ ├── rwops.go │ │ ├── scancode.go │ │ ├── sdl.go │ │ ├── sdl_cgo.go │ │ ├── sdl_cgo_static.go │ │ ├── sdl_wrapper.h │ │ ├── sensor.go │ │ ├── shape.go │ │ ├── surface.go │ │ ├── sysrender.go │ │ ├── system.c │ │ ├── system.go │ │ ├── system.h │ │ ├── system_android.go │ │ ├── system_linux.go │ │ ├── system_windows.go │ │ ├── syswm.go │ │ ├── syswm_cocoa.go │ │ ├── syswm_dfb.go │ │ ├── syswm_uikit.go │ │ ├── syswm_vivante.go │ │ ├── syswm_windows.go │ │ ├── syswm_x11.go │ │ ├── thread.go │ │ ├── timer.go │ │ ├── touch.go │ │ ├── version.go │ │ ├── video.go │ │ └── vulkan.go │ └── modules.txt ├── haskell/ │ ├── .gitignore │ ├── Makefile │ ├── README.md │ ├── Setup.hs │ ├── app/ │ │ └── Main.hs │ ├── grumpycat.cabal │ ├── package.yaml │ ├── src/ │ │ └── Lib.hs │ ├── stack.yaml │ └── test/ │ └── Spec.hs ├── include/ │ └── sdl2.h ├── java22/ │ ├── Main.java │ ├── Makefile │ └── README.md ├── kotlin/ │ ├── .gitignore │ ├── Main.kt │ ├── Makefile │ ├── README.md │ └── sdl2.def ├── lisp/ │ ├── Makefile │ ├── README.md │ └── main.lisp ├── lua/ │ ├── Makefile │ ├── README.md │ └── main.lua ├── mruby/ │ ├── Makefile │ ├── README.md │ └── main.rb ├── nim/ │ ├── Makefile │ ├── README.md │ └── main.nim ├── objc-cmake/ │ ├── CMakeLists.txt │ ├── README.md │ └── main.m ├── objectpascal/ │ ├── Makefile │ ├── README.md │ ├── checkout.sh │ └── main.pas ├── ocaml/ │ ├── Makefile │ ├── README.md │ └── main.ml ├── odin/ │ ├── Makefile │ ├── README.md │ └── main.odin ├── python/ │ ├── Makefile │ ├── README.md │ └── main.py ├── ring/ │ ├── Makefile │ ├── README.md │ └── main.ring ├── run.sh ├── rust/ │ ├── .gitignore │ ├── Cargo.toml │ ├── Makefile │ ├── README.md │ └── src/ │ └── main.rs ├── scala/ │ ├── Main.scala │ ├── Makefile │ ├── README.md │ ├── build.sbt │ └── project/ │ └── plugins.sbt ├── v/ │ ├── Makefile │ ├── README.md │ └── main.v └── zig/ ├── Makefile ├── README.md ├── build.zig └── main.zig ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/dependabot.yml ================================================ # Set update schedule for GitHub Actions version: 2 updates: - package-ecosystem: "github-actions" directory: "/" schedule: # Check for updates to GitHub Actions every weekday interval: "daily" ================================================ FILE: .github/workflows/assembly.yml ================================================ name: assembly-examples on: push: branches: - '*' paths: - assembly/** pull_request: branches: - '*' paths: - assembly/** workflow_dispatch: jobs: make: runs-on: ubuntu-latest strategy: fail-fast: false matrix: tests_list: - { folder: "assembly/linux-x86_64" } steps: - uses: actions/checkout@v4 - name: install_dependencies run: | sudo apt update sudo apt install -y gnupg libgmp-dev libsdl2-dev libsdl2-image-dev nasm ninja-build - name: build run: | cd ${{ matrix.tests_list.folder }} make all ================================================ FILE: .github/workflows/c.yml ================================================ name: c-examples on: push: branches: - '*' paths: - c1*/** - c2*/** - c8*/** - c9*/** pull_request: branches: - '*' paths: - c1*/** - c2*/** - c8*/** - c9*/** workflow_dispatch: jobs: make: runs-on: ubuntu-latest strategy: fail-fast: false matrix: tests_list: - { folder: "c89" } - { folder: "c99" } - { folder: "c11" } - { folder: "c18" } - { folder: "c2x" } steps: - uses: actions/checkout@v4 - name: install_dependencies run: | sudo apt update sudo apt install -y cmake curl gnupg libgmp-dev libsdl2-dev libsdl2-image-dev nasm ninja-build - name: build run: | cd ${{ matrix.tests_list.folder }} make all ================================================ FILE: .github/workflows/cplusplus.yml ================================================ name: c-plus-plus-examples on: push: branches: - '*' paths: - 'c*-*/**' pull_request: branches: - '*' paths: - 'c*-*/**' jobs: cmake: runs-on: ubuntu-latest strategy: fail-fast: false matrix: tests_list: - { folder: "c++11-cmake" } - { folder: "c++14-cmake" } - { folder: "c++17-cmake" } - { folder: "c++20-cmake" } - { folder: "c++23-cmake" } steps: - uses: actions/checkout@v4 - name: install_dependencies run: | sudo apt update sudo apt install -y libsdl2-dev ninja-build cmake - name: build run: | cd ${{ matrix.tests_list.folder }} cmake -S . -B build -G Ninja ninja -C build make: runs-on: ubuntu-latest strategy: fail-fast: false matrix: tests_list: - { folder: "c++98" } - { folder: "c++11" } steps: - uses: actions/checkout@v4 - name: install_dependencies run: | sudo apt update sudo apt install -y cmake curl gnupg libgmp-dev libsdl2-dev libsdl2-image-dev mono-devel mono-mcs mono-runtime mono-vbnc nasm ninja-build curl -fsSL https://crystal-lang.org/install.sh | sudo bash -s -- --channel=stable - name: build run: | cd ${{ matrix.tests_list.folder }} make all ================================================ FILE: .github/workflows/expired.yml ================================================ name: 'Close stale issues and PRs' on: schedule: - cron: '0 */8 * * *' jobs: stale: runs-on: ubuntu-latest steps: - uses: actions/stale@v9 with: repo-token: ${{ secrets.GITHUB_TOKEN }} exempt-issue-milestones: 'future,alpha,beta,release,bugfix,improvement,enhancement,help wanted' exempt-pr-milestones: 'bugfix,improvement,enhancement,help wanted' exempt-all-pr-assignees: true stale-issue-message: 'This issue is stale because it has been open 120 days with no activity. Remove stale label or comment or this will be closed in 30 days.' stale-pr-message: 'This PR is stale because it has been open 120 days with no activity. Remove stale label or comment or this will be closed in 30 days.' close-issue-message: 'This issue was closed because it has been stalled for 30 days with no activity.' close-pr-message: 'This PR was closed because it has been stalled for 30 days with no activity.' days-before-issue-stale: 120 days-before-pr-stale: 120 days-before-issue-close: 30 days-before-pr-close: 30 ================================================ FILE: .github/workflows/other.yml ================================================ name: other-examples on: push: branches: - '*' paths: - crystal/ - csharp/ pull_request: branches: - '*' paths: - crystal/ - csharp/ workflow_dispatch: jobs: make: runs-on: ubuntu-latest strategy: fail-fast: false matrix: tests_list: - { folder: "crystal" } - { folder: "csharp" } steps: - uses: actions/checkout@v4 - name: install_dependencies run: | sudo apt update sudo apt install -y cmake curl gnupg libgmp-dev libsdl2-dev libsdl2-image-dev mono-devel mono-mcs mono-runtime mono-vbnc nasm ninja-build curl -fsSL https://crystal-lang.org/install.sh | sudo bash -s -- --channel=stable - name: build run: | cd ${{ matrix.tests_list.folder }} make all ================================================ FILE: .gitignore ================================================ # macOS .DS_Store # C3 *.dSYM # Java *.jar # Compiled Object files *.slo *.lo *.o *.obj # Compiled Dynamic libraries *.so *.dylib # Compiled Static libraries *.lai *.la *.a *.lib # Crystal crystal/sdl.cr/ crystal/lib crystal/bin/ # F# fsharp/bin/ fsharp/obj/ # OCaml *.cmi *.cmx # Executables *.exe *.out *.app main small go/go # Nimrod cache nimcache # Rust rust/sdl2/ Cargo.lock # C++ c++20-cxx/c++20-cxx c*/*.asm # Temporary databases *.dblite # CMake build/ CMakeCache.txt CMakeFiles inst/ # Ada *.ali *.ads *.adb *.adb.std* *.bexch # Zig zig/zig-cache zig/*.s zig/zig # Common Lisp lisp/quicklisp/ lisp/quicklisp.lisp # FreeBASIC freebasic/main # Odin odin/main # Object Pascal fpc/*.res objectpascal/*.res *.ppu fpc/SDL2/ objectpascal/SDL2/ # Scala scalanative/project/build.properties scalanative/target/ scalanative/project/target/ scalanative/project/project/ scalanative/main.jar # Dart dart/.dart_tool dart/pubspec.lock # C# csharp/bin/ csharp/obj/ csharp/*.exe zig/.*cache* ================================================ FILE: COMPILES.md ================================================ ## Does it compile and/or run? | Directory | ArchLinux | macOS/M2 | Comment | |--------------|-----------|----------|--------------------------------------------------| | ada | yes | no | look into Alire | | c++11 | | yes | | | c++11-cmake | | yes | | | c++14-cmake | | yes | | | c++17-cmake | | yes | | | c++20-cmake | | yes | | | c++23-cmake | | yes | | | c++98 | | yes | | | c2x | | yes | | | c11 | | yes | | | c18 | | yes | | | c89 | | yes | | | c99 | | yes | | | crystal | | yes | | | csharp | | yes | does not run on M2 | | d | | yes | does not run on M2 | | freebasic | | | not in homebrew | | gambas | | | not in homebrew | | gccgo | yes | | not in homebrew (might be, with the right flags) | | go | yes | yes | | | haskell | | | | | lisp | | no | | | lua | | | | | mruby | | | | | nim | | | | | objectpascal | | | | | ocaml | | | | | odin | | | | | pony | | | | | python | | | | | ring | | | | | rust | | no | needs homebrew paths | | v | | | | | zig | | no | tried adding lib, include and framework paths | ================================================ FILE: LICENSE ================================================ Copyright 2023 Alexander F. Rødseth Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================ FILE: Makefile ================================================ SAMPLES = assembly c89 c99 c11 c18 c++98 c++11 d objectivepascal go haskell mruby nim odin pony python ring rust v zig # These two currently does not build: # SAMPLES += ocaml # gccgo works, but installing gccgo conflicts with go # SAMPLES += gccgo .PHONY: all run clean fullclean all: @-$(foreach x,$(SAMPLES),make -C $(x);) run: @-$(foreach x,$(SAMPLES),make -C $(x) run;) clean: @-$(foreach x,$(SAMPLES),make -C $(x) clean;) fullclean: @-$(foreach x,$(SAMPLES),make -C $(x) fullclean;) ================================================ FILE: README.md ================================================ SDL2 Examples ============= [![sdl2-examples](https://github.com/xyproto/sdl2-examples/actions/workflows/main.yml/badge.svg)](https://github.com/xyproto/sdl2-examples/actions/workflows/main.yml) "hello world" for SDL2 for various programming languages. Each sample creates a window, displays an image, then waits two seconds and quits. All executables should ideally build and run on Linux, macOS, Windows, BSD* and more, but they should at least work on Linux. Most subdirectories contains `README.md` files with more details, and a `Makefile` to have one way of building each sample. For newer versions of macOS, the programs also appear to need an event loop for the window to show up, so I'm in the process of adding that to each example. The window just isn't shown if there is no event loop. Requirements ------------ * The SDL 2 library. * See the README.md file per sample for more information. Requirements for some of the languages -------------------------------------- * C compiler that supports C89 (ANSI C), C99 or C11, for the C samples * A C++ compiler for the C++ sample * GCC 4.8 or later (or clang++) for the C++11 sample * Go 1.1 or later and the sdl2 go package (`go get github.com/veandco/go-sdl2/sdl`) * MRuby with SDL2 added to the configuration file * Nim 0.9.4 and sdl2 installed with babel * Python 2 or 3 and PySDL2 * FPC 2.6.4 (or later than 2.4.0, must have Uint8, Uint16 and Uint32) * Lua (tested with Lua 5.3) and lua-sdl2 * If `tcc` is used for compiling one of the C examples, make sure to add [`-DSDL_DISABLE_IMMINTRIN_H=1`](https://www.mail-archive.com/tinycc-devel@nongnu.org/msg08821.html). Languages that are not added yet -------------------------------- - [ ] Ada (but there is an `ada` branch if you wish to give it a spin. Please create a PR if it works on Arch Linux and/or the Linux CI test passes!). - [ ] C3 (but there is a `c3` branch with "Hello World" in C3). - [ ] Fortran - [ ] Scheme Pull requests are welcome. General information ---------------------- * License: BSD-3 ================================================ FILE: assembly/Makefile ================================================ PLATFORMS = linux-i386 linux-x86_64 .PHONY: all run clean fullclean all: @-$(foreach x,$(PLATFORMS),make -C $(x);) run: @-$(foreach x,$(PLATFORMS),make -C $(x) run;) clean: @-$(foreach x,$(PLATFORMS),make -C $(x) clean;) fullclean: @-$(foreach x,$(PLATFORMS),make -C $(x) fullclean;) ================================================ FILE: assembly/README.md ================================================ Note that the executables that are generated from Assembly are only intended to work on the target system they are crafted for. ================================================ FILE: assembly/linux-i386/Makefile ================================================ .PHONY: all msg clean fullclean # Look for libraries in /usr/lib32 when linking if on i386, i686 or x86_32 ifeq ($(findstring $(shell uname -m),i386 i686 x86_32),) LDFLAGS+=-L/usr/lib32 endif all: msg main msg: @echo '--- i386 ---' main: nasm -felf32 main.asm -o main.o ld -m elf_i386 main.o -o main -dynamic-linker /lib/ld-linux.so.* -lc -lSDL2 $(LDFLAGS) run: msg main time ./main clean: rm -f main main.o fullclean: clean ================================================ FILE: assembly/linux-i386/README.md ================================================ Requirements ------------ * nasm * sdl2 ================================================ FILE: assembly/linux-i386/main.asm ================================================ section .text global _start extern printf extern exit extern SDL_Init extern SDL_CreateWindow extern SDL_CreateRenderer extern SDL_LoadBMP_RW extern SDL_RWFromFile extern SDL_CreateTextureFromSurface extern SDL_FreeSurface extern SDL_RenderClear extern SDL_RenderCopy extern SDL_RenderPresent extern SDL_Delay extern SDL_DestroyTexture extern SDL_DestroyRenderer extern SDL_DestroyWindow extern SDL_Quit extern SDL_GetError _start: push 62001 call SDL_Init add esp, 4 cmp eax, 0 jl init_err push 4 push 387 push 620 push 100 push 100 push create_window_arg0 call SDL_CreateWindow add esp, 24 cmp eax, 0 je create_window_err mov ebx, eax push 6 push -1 push eax call SDL_CreateRenderer add esp, 12 cmp eax, 0 je create_renderer_err mov esi, eax push readbin push bmp_path call SDL_RWFromFile add esp, 8 push 1 push eax call SDL_LoadBMP_RW add esp, 8 cmp eax, 0 je load_bmp_err mov edi, eax push eax push esi call SDL_CreateTextureFromSurface add esp, 8 cmp eax, 0 je create_tfs_err push edi mov edi, eax call SDL_FreeSurface add esp, 4 push ebx xor ebx, ebx loop0: push esi call SDL_RenderClear add esp, 4 push 0 push 0 push edi push esi call SDL_RenderCopy add esp, 16 push esi call SDL_RenderPresent add esp, 4 push 100 call SDL_Delay add esp, 4 inc ebx cmp ebx, 20 jl loop0 pop ebx push edi call SDL_DestroyTexture add esp, 4 push esi call SDL_DestroyRenderer add esp, 4 push ebx call SDL_DestroyWindow add esp, 4 call SDL_Quit push 0 call exit init_err: call SDL_GetError push eax push init_err_msg call printf add esp, 8 push 8 call exit create_window_err: call SDL_GetError push eax push create_window_err_msg call printf add esp, 8 push 8 call exit create_renderer_err: call SDL_GetError push eax push create_renderer_err_msg call printf add esp, 8 push ebx call SDL_DestroyWindow add esp, 4 call SDL_Quit push 8 call exit load_bmp_err: call SDL_GetError push eax push load_bmp_err_msg call printf add esp, 8 push esi call SDL_DestroyRenderer add esp, 4 push ebx call SDL_DestroyWindow add esp, 4 call SDL_Quit push 8 call exit create_tfs_err: call SDL_GetError push eax push create_tfs_err_msg call printf add esp, 8 push edi call SDL_FreeSurface add esp, 4 push esi call SDL_DestroyRenderer add esp, 4 push ebx call SDL_DestroyWindow add esp, 4 call SDL_Quit push 8 call exit section .data init_err_msg db "SDL_Init Error: %s", 10, 0 create_window_arg0 db "Hello World!", 0 create_window_err_msg db "SDL_CreateWindow Error: %s", 10, 0 create_renderer_err_msg db "SDL_CreateRenderer Error: %s", 10, 0 bmp_path db "../../img/grumpy-cat.bmp", 0 readbin db "rb", 0 load_bmp_err_msg db "SDL_LoadBMP Error: %s", 10, 0 create_tfs_err_msg db "SDL_CreateTextureFromSurface Error: %s", 10, 0 ================================================ FILE: assembly/linux-x86_64/Makefile ================================================ .PHONY: all msg clean fullclean all: msg main msg: @echo '--- x86_64 ---' main: nasm -felf64 main.asm -o main.o ld main.o -o main -dynamic-linker /lib64/ld-linux-x86-64.so.* -lc -lSDL2 run: msg main time ./main clean: rm -f main main.o fullclean: clean ================================================ FILE: assembly/linux-x86_64/README.md ================================================ Requirements ------------ * nasm * sdl2 ================================================ FILE: assembly/linux-x86_64/main.asm ================================================ section .text global _start extern printf extern exit extern SDL_Init extern SDL_CreateWindow extern SDL_CreateRenderer extern SDL_LoadBMP_RW extern SDL_RWFromFile extern SDL_CreateTextureFromSurface extern SDL_FreeSurface extern SDL_RenderClear extern SDL_RenderCopy extern SDL_RenderPresent extern SDL_Delay extern SDL_DestroyTexture extern SDL_DestroyRenderer extern SDL_DestroyWindow extern SDL_Quit extern SDL_GetError _start: mov rdi, 62001 call SDL_Init cmp rax, 0 jl init_err mov rdi, create_window_arg0 mov rsi, 100 mov rdx, 100 mov rcx, 620 mov r8, 387 mov r9, 4 call SDL_CreateWindow cmp rax, 0 je create_window_err mov r12, rax mov rdi, rax mov rsi, -1 mov rdx, 6 call SDL_CreateRenderer cmp rax, 0 je create_renderer_err mov r13, rax mov rdi, bmp_path mov rsi, readbin call SDL_RWFromFile mov rdi, rax mov rsi, 1 call SDL_LoadBMP_RW cmp rax, 0 je load_bmp_err mov r14, rax mov rdi, r13 mov rsi, rax call SDL_CreateTextureFromSurface cmp rax, 0 je create_tfs_err mov r15, rax mov rdi, r14 call SDL_FreeSurface xor r14, r14 loop0: mov rdi, r13 call SDL_RenderClear mov rdi, r13 mov rsi, r15 mov rdx, 0 mov rcx, 0 call SDL_RenderCopy mov rdi, r13 call SDL_RenderPresent mov rdi, 100 call SDL_Delay inc r14 cmp r14, 20 jl loop0 mov rdi, r15 call SDL_DestroyTexture mov rdi, r13 call SDL_DestroyRenderer mov rdi, r12 call SDL_DestroyWindow call SDL_Quit mov rdi, 0 call exit init_err: call SDL_GetError mov rsi, rax mov rdi, init_err_msg call printf mov rdi, 8 call exit create_window_err: call SDL_GetError mov rsi, rax mov rdi, create_window_err_msg call printf mov rdi, 8 call exit create_renderer_err: call SDL_GetError mov rsi, rax mov rdi, create_renderer_err_msg call printf mov rdi, r12 call SDL_DestroyWindow call SDL_Quit mov rdi, 8 call exit load_bmp_err: call SDL_GetError mov rsi, rax mov rdi, load_bmp_err_msg call printf mov rdi, r13 call SDL_DestroyRenderer mov rdi, r12 call SDL_DestroyWindow call SDL_Quit mov rdi, 8 call exit create_tfs_err: call SDL_GetError mov rsi, rax mov rdi, create_tfs_err_msg call printf mov rdi, r14 call SDL_FreeSurface mov rdi, r13 call SDL_DestroyRenderer mov rdi, r12 call SDL_DestroyWindow call SDL_Quit mov rdi, 8 call exit section .data init_err_msg db "SDL_Init Error: %s", 10, 0 create_window_arg0 db "Hello World!", 0 create_window_err_msg db "SDL_CreateWindow Error: %s", 10, 0 create_renderer_err_msg db "SDL_CreateRenderer Error: %s", 10, 0 bmp_path db "../../img/grumpy-cat.bmp", 0 readbin db "rb", 0 load_bmp_err_msg db "SDL_LoadBMP Error: %s", 10, 0 create_tfs_err_msg db "SDL_CreateTextureFromSurface Error: %s", 10, 0 ;asdf ================================================ FILE: assembly/macos-x86_64/Makefile ================================================ .PHONY: all msg clean fullclean all: msg main msg: @echo '--- x86_64 ---' main: nasm -fmacho64 main.asm -o main.o ld main.o -o main -lc -lSDL2 run: msg main time ./main clean: rm -f main main.o fullclean: clean ================================================ FILE: assembly/macos-x86_64/README.md ================================================ Requirements ------------ * nasm * Xcode Command Line Tools * sdl2 ================================================ FILE: assembly/macos-x86_64/main.asm ================================================ section .text global _main extern _printf extern _exit extern _SDL_Init extern _SDL_CreateWindow extern _SDL_CreateRenderer extern _SDL_LoadBMP_RW extern _SDL_RWFromFile extern _SDL_CreateTextureFromSurface extern _SDL_FreeSurface extern _SDL_RenderClear extern _SDL_RenderCopy extern _SDL_RenderPresent extern _SDL_Delay extern _SDL_DestroyTexture extern _SDL_DestroyRenderer extern _SDL_DestroyWindow extern _SDL_Quit extern _SDL_GetError _main: sub rsp, 8 mov rdi, 62001 call _SDL_Init cmp rax, 0 jl init_err mov rdi, create_window_arg0 mov rsi, 100 mov rdx, 100 mov rcx, 960 mov r8, 720 mov r9, 4 call _SDL_CreateWindow cmp rax, 0 je create_window_err mov r12, rax mov rdi, rax mov rsi, -1 mov rdx, 6 call _SDL_CreateRenderer cmp rax, 0 je create_renderer_err mov r13, rax mov rdi, bmp_path mov rsi, readbin call _SDL_RWFromFile mov rdi, rax mov rsi, 1 call _SDL_LoadBMP_RW cmp rax, 0 je load_bmp_err mov r14, rax mov rdi, r13 mov rsi, rax call _SDL_CreateTextureFromSurface cmp rax, 0 je create_tfs_err mov r15, rax mov rdi, r14 call _SDL_FreeSurface xor r14, r14 loop0: mov rdi, r13 call _SDL_RenderClear mov rdi, r13 mov rsi, r15 mov rdx, 0 mov rcx, 0 call _SDL_RenderCopy mov rdi, r13 call _SDL_RenderPresent mov rdi, 100 call _SDL_Delay inc r14 cmp r14, 20 jl loop0 mov rdi, r15 call _SDL_DestroyTexture mov rdi, r13 call _SDL_DestroyRenderer mov rdi, r12 call _SDL_DestroyWindow call _SDL_Quit mov rdi, 0 call _exit init_err: call _SDL_GetError mov rsi, rax mov rdi, init_err_msg call _printf mov rdi, 8 call _exit create_window_err: call _SDL_GetError mov rsi, rax mov rdi, create_window_err_msg call _printf mov rdi, 8 call _exit create_renderer_err: call _SDL_GetError mov rsi, rax mov rdi, create_renderer_err_msg call _printf mov rdi, r12 call _SDL_DestroyWindow call _SDL_Quit mov rdi, 8 call _exit load_bmp_err: call _SDL_GetError mov rsi, rax mov rdi, load_bmp_err_msg call _printf mov rdi, r13 call _SDL_DestroyRenderer mov rdi, r12 call _SDL_DestroyWindow call _SDL_Quit mov rdi, 8 call _exit create_tfs_err: call _SDL_GetError mov rsi, rax mov rdi, create_tfs_err_msg call _printf mov rdi, r14 call _SDL_FreeSurface mov rdi, r13 call _SDL_DestroyRenderer mov rdi, r12 call _SDL_DestroyWindow call _SDL_Quit mov rdi, 8 call _exit section .data init_err_msg db "SDL_Init Error: %s", 10, 0 create_window_arg0 db "Hello World!", 0 create_window_err_msg db "SDL_CreateWindow Error: %s", 10, 0 create_renderer_err_msg db "SDL_CreateRenderer Error: %s", 10, 0 bmp_path db "../../img/grumpy-cat.bmp", 0 readbin db "rb", 0 load_bmp_err_msg db "SDL_LoadBMP Error: %s", 10, 0 create_tfs_err_msg db "SDL_CreateTextureFromSurface Error: %s", 10, 0 ================================================ FILE: assembly/windows-x86_64/README.md ================================================ Requirements ------------ * nasm * GoLink * sdl2 ================================================ FILE: assembly/windows-x86_64/main.asm ================================================ section .text global Start extern printf extern exit extern SDL_Init extern SDL_CreateWindow extern SDL_CreateRenderer extern SDL_LoadBMP_RW extern SDL_RWFromFile extern SDL_CreateTextureFromSurface extern SDL_FreeSurface extern SDL_RenderClear extern SDL_RenderCopy extern SDL_RenderPresent extern SDL_Delay extern SDL_DestroyTexture extern SDL_DestroyRenderer extern SDL_DestroyWindow extern SDL_Quit extern SDL_GetError Start: sub rsp, 56 mov rcx, 62001 call SDL_Init cmp rax, 0 jl init_err mov rcx, create_window_arg0 mov rdx, 100 mov r8, 100 mov r9, 960 mov qword [rsp+32], 720 mov qword [rsp+40], 4 call SDL_CreateWindow cmp rax, 0 je create_window_err mov r12, rax mov rcx, rax mov rdx, -1 mov r8, 6 call SDL_CreateRenderer cmp rax, 0 je create_renderer_err mov r13, rax mov rcx, bmp_path mov rdx, readbin call SDL_RWFromFile mov rcx, rax mov rdx, 1 call SDL_LoadBMP_RW cmp rax, 0 je load_bmp_err mov r14, rax mov rcx, r13 mov rdx, rax call SDL_CreateTextureFromSurface cmp rax, 0 je create_tfs_err mov r15, rax mov rcx, r14 call SDL_FreeSurface xor r14, r14 loop0: mov rcx, r13 call SDL_RenderClear mov rcx, r13 mov rdx, r15 mov r8, 0 mov r9, 0 call SDL_RenderCopy mov rcx, r13 call SDL_RenderPresent mov rcx, 100 call SDL_Delay inc r14 cmp r14, 20 jl loop0 mov rcx, r15 call SDL_DestroyTexture mov rcx, r13 call SDL_DestroyRenderer mov rcx, r12 call SDL_DestroyWindow call SDL_Quit add rsp, 56 mov rcx, 0 call exit init_err: call SDL_GetError mov rdx, rax mov rcx, init_err_msg call printf add rsp, 56 mov rcx, 8 call exit create_window_err: call SDL_GetError mov rdx, rax mov rcx, create_window_err_msg call printf add rsp, 56 mov rcx, 8 call exit create_renderer_err: call SDL_GetError mov rdx, rax mov rcx, create_renderer_err_msg call printf mov rcx, r12 call SDL_DestroyWindow call SDL_Quit add rsp, 56 mov rcx, 8 call exit load_bmp_err: call SDL_GetError mov rdx, rax mov rcx, load_bmp_err_msg call printf mov rcx, r13 call SDL_DestroyRenderer mov rcx, r12 call SDL_DestroyWindow call SDL_Quit add rsp, 56 mov rcx, 8 call exit create_tfs_err: call SDL_GetError mov rdx, rax mov rcx, create_tfs_err_msg call printf mov rcx, r14 call SDL_FreeSurface mov rcx, r13 call SDL_DestroyRenderer mov rcx, r12 call SDL_DestroyWindow call SDL_Quit add rsp, 56 mov rcx, 8 call exit section .data init_err_msg db "SDL_Init Error: %s", 10, 0 create_window_arg0 db "Hello World!", 0 create_window_err_msg db "SDL_CreateWindow Error: %s", 10, 0 create_renderer_err_msg db "SDL_CreateRenderer Error: %s", 10, 0 bmp_path db "..\..\img\grumpy-cat.bmp", 0 readbin db "rb", 0 load_bmp_err_msg db "SDL_LoadBMP Error: %s", 10, 0 create_tfs_err_msg db "SDL_CreateTextureFromSurface Error: %s", 10, 0 ================================================ FILE: bench.sh ================================================ #!/bin/sh # # csv.sh # # Measure approximately how long it takes to build each example, # and how large the resulting executable is. # # The examples are (mostly) not size-optimized, so the sizes will vary # a lot, without saying much about the programming language. # # For instance, Go produces large executables by default, but when using # gccgo, -Os and upx, the executables are orders of magnitude smaller. # bench() { echo -n "$1;" pushd "$1" > /dev/null make -s clean > /dev/null echo -n $(time -f "%es" make -s 2>&1 | tail -1) echo -n ';' echo -n $(du -b "$2" | sed 's/[^0-9]//g') popd > /dev/null echo } cmakebench() { echo -n "$1;" pushd "$1" > /dev/null test -d build && rm -r build || true echo -n $(time -f "%es" cmake -S . -B build 2>&1 > /dev/null && make -C build 2>&1 >/dev/null | tr -d '\n') echo -n ';' echo -n $(du -b "build/$2" | sed 's/[^0-9]//g') popd > /dev/null echo } cxxbench() { echo -n "$1;" pushd "$1" > /dev/null cxx clean > /dev/null echo -n $(time -f "%es" cxx 2>&1 >/dev/null | tr -d '\n') echo -n ';' echo -n $(du -b "$2" | sed 's/[^0-9]//g') popd > /dev/null echo } stackbench() { echo -n "$1;" pushd "$1" > /dev/null stack clean > /dev/null echo -n $(time -f "%es" stack build 2>&1 | tail -1) echo -n ';' local filename=$(find . -executable -type f -name grumpycat-exe -printf "%T@ %Tc %p\n" | sort -n | tail -1 | rev | cut -d' ' -f1 | rev) echo -n $(du -b $filename) | tr ' ' '\n' | head -1 | tr -d '\n' popd > /dev/null echo } main() { echo 'language;compilation;bytesize' bench go go bench ada main for f in c89 c++98 c99 c11 c++11 c18 c2x; do bench "$f" main done for f in *-cmake; do cmakebench "$f" main done #cxxbench c++20-cxx c++20-cxx bench crystal bin/main bench csharp main bench d main bench objectivepascal main bench freebasic main stackbench haskell # TODO: Add the other languages as well, except for gccgo, mruby, lua and python } main ================================================ FILE: c++11/Makefile ================================================ CXX?=c++ SDL2FLAGS=$(shell pkg-config sdl2 --cflags --libs) CXXFLAGS?=-std=c++11 -Wall -pedantic -Werror -Wshadow -Wstrict-aliasing -Wstrict-overflow .PHONY: all msg clean fullclean all: msg main msg: @echo '--- C++11 ---' main: main.cpp ${CXX} ${CXXFLAGS} -O2 -o $@ $< ${SDL2FLAGS} small: main.cpp ${CXX} ${CXXFLAGS} -Os -o main $< ${SDL2FLAGS} -strip main -sstrip main debug: main.cpp ${CXX} ${CXXFLAGS} -O0 -g -o main $< ${SDL2FLAGS} asm: main.asm main.asm: main.cpp ${CXX} ${CFLAGS} -S -masm=intel -Og -o main.asm $< ${SDL2FLAGS} run: msg main time ./main clean: rm -f main *.o main.asm fullclean: clean ================================================ FILE: c++11/main.cpp ================================================ #include #include #include int main() { using std::cerr; using std::endl; if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { cerr << "SDL_Init Error: " << SDL_GetError() << endl; return EXIT_FAILURE; } SDL_Window* win = SDL_CreateWindow("Hello World!", 100, 100, 620, 387, SDL_WINDOW_SHOWN); if (win == nullptr) { cerr << "SDL_CreateWindow Error: " << SDL_GetError() << endl; return EXIT_FAILURE; } SDL_Renderer* ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (ren == nullptr) { cerr << "SDL_CreateRenderer Error" << SDL_GetError() << endl; if (win != nullptr) { SDL_DestroyWindow(win); } SDL_Quit(); return EXIT_FAILURE; } SDL_Surface* bmp = SDL_LoadBMP("../img/grumpy-cat.bmp"); if (bmp == nullptr) { cerr << "SDL_LoadBMP Error: " << SDL_GetError() << endl; if (ren != nullptr) { SDL_DestroyRenderer(ren); } if (win != nullptr) { SDL_DestroyWindow(win); } SDL_Quit(); return EXIT_FAILURE; } SDL_Texture* tex = SDL_CreateTextureFromSurface(ren, bmp); if (tex == nullptr) { cerr << "SDL_CreateTextureFromSurface Error: " << SDL_GetError() << endl; if (bmp != nullptr) { SDL_FreeSurface(bmp); } if (ren != nullptr) { SDL_DestroyRenderer(ren); } if (win != nullptr) { SDL_DestroyWindow(win); } SDL_Quit(); return EXIT_FAILURE; } SDL_FreeSurface(bmp); for (int i = 0; i < 20; i++) { SDL_RenderClear(ren); SDL_RenderCopy(ren, tex, nullptr, nullptr); SDL_RenderPresent(ren); SDL_Delay(100); } SDL_DestroyTexture(tex); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_SUCCESS; } ================================================ FILE: c++11-cmake/CMakeLists.txt ================================================ cmake_minimum_required(VERSION 3.26) project(main) aux_source_directory(. SRC_LIST) add_executable(${PROJECT_NAME} ${SRC_LIST}) target_include_directories(${PROJECT_NAME} PRIVATE ../include) target_compile_features(${PROJECT_NAME} PRIVATE cxx_std_11) target_compile_definitions(${PROJECT_NAME} PRIVATE IMGDIR="../img/") # For macOS M2 systems with SDL2 installed via Homebrew list(APPEND CMAKE_MODULE_PATH "/usr/local/lib/cmake/SDL2" "/opt/homebrew/lib/cmake/SDL2") list(APPEND CMAKE_PREFIX_PATH "/usr/local" "/opt/homebrew") find_package(SDL2 QUIET) if (SDL2_FOUND) message("Using SDL2 from find_package") target_include_directories(${PROJECT_NAME} PRIVATE ${SDL2_INCLUDE_DIRS}) target_link_libraries(${PROJECT_NAME} PRIVATE ${SDL2_LIBRARIES}) else() # Fall back on pkg-config include(FindPkgConfig) pkg_search_module(SDL2 REQUIRED sdl2) message("Using SDL2 from pkg-config") target_include_directories(${PROJECT_NAME} PRIVATE ${SDL2_INCLUDE_DIRS}) target_link_libraries(${PROJECT_NAME} PRIVATE ${SDL2_LIBRARIES}) endif() ================================================ FILE: c++11-cmake/README.md ================================================ SDL2, C++11 and CMake ===================== Requirements ------------ * CMake * Compiler that supports C++ (recent version of g++ or clang++) * SDL2 One way of building with C++11, SDL2 and CMake ---------------------------------------------- cmake -S . -B build -DCMAKE_BUILD_TYPE=Release make -C build Running ------- build/main Cleaning up the binary file and build directory ----------------------------------------------- rm -rf build/ main ================================================ FILE: c++11-cmake/main.cpp ================================================ #include #include #include int main() { using std::cerr; using std::endl; if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { cerr << "SDL_Init Error: " << SDL_GetError() << endl; return EXIT_FAILURE; } SDL_Window* win = SDL_CreateWindow("Hello World!", 100, 100, 620, 387, SDL_WINDOW_SHOWN); if (win == nullptr) { cerr << "SDL_CreateWindow Error: " << SDL_GetError() << endl; return EXIT_FAILURE; } SDL_Renderer* ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (ren == nullptr) { cerr << "SDL_CreateRenderer Error" << SDL_GetError() << endl; SDL_DestroyWindow(win); SDL_Quit(); return EXIT_FAILURE; } SDL_Surface* bmp = SDL_LoadBMP("../img/grumpy-cat.bmp"); if (bmp == nullptr) { cerr << "SDL_LoadBMP Error: " << SDL_GetError() << endl; SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_FAILURE; } SDL_Texture* tex = SDL_CreateTextureFromSurface(ren, bmp); if (tex == nullptr) { cerr << "SDL_CreateTextureFromSurface Error: " << SDL_GetError() << endl; SDL_FreeSurface(bmp); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_FAILURE; } SDL_FreeSurface(bmp); for (int i = 0; i < 20; i++) { SDL_RenderClear(ren); SDL_RenderCopy(ren, tex, nullptr, nullptr); SDL_RenderPresent(ren); SDL_Delay(100); } SDL_DestroyTexture(tex); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_SUCCESS; } ================================================ FILE: c++14-cmake/CMakeLists.txt ================================================ cmake_minimum_required(VERSION 3.26) project(main) aux_source_directory(. SRC_LIST) add_executable(${PROJECT_NAME} ${SRC_LIST}) target_include_directories(${PROJECT_NAME} PRIVATE ../include) target_compile_features(${PROJECT_NAME} PRIVATE cxx_std_14) target_compile_definitions(${PROJECT_NAME} PRIVATE IMGDIR="../img/") # For macOS M2 systems with SDL2 installed via Homebrew list(APPEND CMAKE_MODULE_PATH "/usr/local/lib/cmake/SDL2" "/opt/homebrew/lib/cmake/SDL2") list(APPEND CMAKE_PREFIX_PATH "/usr/local" "/opt/homebrew") # Try the modern way first find_package(SDL2 QUIET) if (SDL2_FOUND) message("Using SDL2 from find_package") target_include_directories(${PROJECT_NAME} PRIVATE ${SDL2_INCLUDE_DIRS}) target_link_libraries(${PROJECT_NAME} PRIVATE ${SDL2_LIBRARIES}) else() # Fall back on pkg-config include(FindPkgConfig) pkg_search_module(SDL2 REQUIRED sdl2) message("Using SDL2 from pkg-config") target_include_directories(${PROJECT_NAME} PRIVATE ${SDL2_INCLUDE_DIRS}) target_link_libraries(${PROJECT_NAME} PRIVATE ${SDL2_LIBRARIES}) endif() ================================================ FILE: c++14-cmake/README.md ================================================ SDL2, C++14 and CMake ===================== Requirements ------------ * CMake * Compiler that supports C++14 (recent version of `g++` or `clang++`) * SDL2 One way of building with C++14, SDL2 and CMake ---------------------------------------------- cmake -S . -B build -DCMAKE_BUILD_TYPE=Release make -C build Running ------- build/main Cleaning up the binary file and build directory ----------------------------------------------- rm -rf build/ ================================================ FILE: c++14-cmake/main.cpp ================================================ #include #include #include "sdl2.h" auto main() -> int { using std::cerr; using std::endl; auto sys = sdl2::make_sdlsystem(SDL_INIT_EVERYTHING); if (!sys) { cerr << "Error creating SDL2 system: " << SDL_GetError() << endl; return 1; } auto win = sdl2::make_window("Hello World!", 100, 100, 620, 387, SDL_WINDOW_SHOWN); if (!win) { cerr << "Error creating window: " << SDL_GetError() << endl; return 1; } auto ren = sdl2::make_renderer(win.get(), -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (!ren) { cerr << "Error creating renderer: " << SDL_GetError() << endl; return 1; } auto file = SDL_RWFromFile(IMGDIR "grumpy-cat.bmp", "rb"); if (file == nullptr) { cerr << "Error reading file: " << SDL_GetError() << endl; return 1; } auto bmp = sdl2::make_bmp(file); if (!bmp) { cerr << "Error creating surface: " << SDL_GetError() << endl; return 1; } auto tex = sdl2::make_texture(ren.get(), bmp.get()); if (!tex) { cerr << "Error creating texture: " << SDL_GetError() << endl; return 1; } for (int i = 0; i < 20; i++) { SDL_RenderClear(ren.get()); SDL_RenderCopy(ren.get(), tex.get(), nullptr, nullptr); SDL_RenderPresent(ren.get()); SDL_Delay(100); } return 0; } ================================================ FILE: c++17-cmake/CMakeLists.txt ================================================ cmake_minimum_required(VERSION 3.26) project(main) aux_source_directory(. SRC_LIST) add_executable(${PROJECT_NAME} ${SRC_LIST}) target_include_directories(${PROJECT_NAME} PRIVATE ../include) target_compile_features(${PROJECT_NAME} PRIVATE cxx_std_17) target_compile_definitions(${PROJECT_NAME} PRIVATE IMGDIR="../img/") # For macOS M2 systems with SDL2 installed via Homebrew list(APPEND CMAKE_MODULE_PATH "/usr/local/lib/cmake/SDL2" "/opt/homebrew/lib/cmake/SDL2") list(APPEND CMAKE_PREFIX_PATH "/usr/local" "/opt/homebrew") find_package(SDL2 QUIET) if (SDL2_FOUND) message("Using SDL2 from find_package") target_include_directories(${PROJECT_NAME} PRIVATE ${SDL2_INCLUDE_DIRS}) target_link_libraries(${PROJECT_NAME} PRIVATE ${SDL2_LIBRARIES}) else() # Fall back on pkg-config include(FindPkgConfig) pkg_search_module(SDL2 REQUIRED sdl2) message("Using SDL2 from pkg-config") target_include_directories(${PROJECT_NAME} PRIVATE ${SDL2_INCLUDE_DIRS}) target_link_libraries(${PROJECT_NAME} PRIVATE ${SDL2_LIBRARIES}) endif() ================================================ FILE: c++17-cmake/README.md ================================================ SDL2, C++17 and CMake ===================== Requirements ------------ * CMake * Compiler that supports C++17 (recent version of `g++` or `clang++`) * SDL2 One way of building with C++17, SDL2 and CMake ---------------------------------------------- cmake -S . -B build -DCMAKE_BUILD_TYPE=Release make -C build Running ------- build/main Cleaning up the binary file and build directory ----------------------------------------------- rm -rf build/ ================================================ FILE: c++17-cmake/main.cpp ================================================ #include #include #include "sdl2.h" auto main() -> int { using std::cerr; using std::endl; auto sys = sdl2::make_sdlsystem(SDL_INIT_EVERYTHING); if (!sys) { cerr << "Error creating SDL2 system: " << SDL_GetError() << endl; return 1; } auto win = sdl2::make_window("Hello World!", 100, 100, 620, 387, SDL_WINDOW_SHOWN); if (!win) { cerr << "Error creating window: " << SDL_GetError() << endl; return 1; } auto ren = sdl2::make_renderer(win.get(), -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (!ren) { cerr << "Error creating renderer: " << SDL_GetError() << endl; return 1; } auto file = SDL_RWFromFile(IMGDIR "grumpy-cat.bmp", "rb"); if (file == nullptr) { cerr << "Error reading file: " << SDL_GetError() << endl; return 1; } auto bmp = sdl2::make_bmp(file); if (!bmp) { cerr << "Error creating surface: " << SDL_GetError() << endl; return 1; } auto tex = sdl2::make_texture(ren.get(), bmp.get()); if (!tex) { cerr << "Error creating texture: " << SDL_GetError() << endl; return 1; } for (int i = 0; i < 20; i++) { SDL_RenderClear(ren.get()); SDL_RenderCopy(ren.get(), tex.get(), nullptr, nullptr); SDL_RenderPresent(ren.get()); SDL_Delay(100); } return 0; } ================================================ FILE: c++20-cmake/CMakeLists.txt ================================================ cmake_minimum_required(VERSION 3.26) project(main) aux_source_directory(. SRC_LIST) add_executable(${PROJECT_NAME} ${SRC_LIST}) target_include_directories(${PROJECT_NAME} PRIVATE ../include) target_compile_features(${PROJECT_NAME} PRIVATE cxx_std_20) target_compile_definitions(${PROJECT_NAME} PRIVATE IMGDIR="../img/") # For macOS M2 systems with SDL2 installed via Homebrew list(APPEND CMAKE_MODULE_PATH "/usr/local/lib/cmake/SDL2" "/opt/homebrew/lib/cmake/SDL2") list(APPEND CMAKE_PREFIX_PATH "/usr/local" "/opt/homebrew") find_package(SDL2 QUIET) if (SDL2_FOUND) message("Using SDL2 from find_package") target_include_directories(${PROJECT_NAME} PRIVATE ${SDL2_INCLUDE_DIRS}) target_link_libraries(${PROJECT_NAME} PRIVATE ${SDL2_LIBRARIES}) else() # Fall back on pkg-config include(FindPkgConfig) pkg_search_module(SDL2 REQUIRED sdl2) message("Using SDL2 from pkg-config") target_include_directories(${PROJECT_NAME} PRIVATE ${SDL2_INCLUDE_DIRS}) target_link_libraries(${PROJECT_NAME} PRIVATE ${SDL2_LIBRARIES}) endif() ================================================ FILE: c++20-cmake/README.md ================================================ SDL2, C++20 and CMake ===================== Requirements ------------ * CMake * Compiler that supports C++20 (recent version of `g++` or `clang++`) * SDL2 One way of building with C++20, SDL2 and CMake ---------------------------------------------- cmake -S . -B build -DCMAKE_BUILD_TYPE=Release make -C build Running ------- build/main Cleaning up the binary file and build directory ----------------------------------------------- rm -rf build/ ================================================ FILE: c++20-cmake/main.cpp ================================================ #include #include #include "sdl2.h" auto main() -> int { using std::cerr; using std::endl; auto sys = sdl2::make_sdlsystem(SDL_INIT_EVERYTHING); if (!sys) { cerr << "Error creating SDL2 system: " << SDL_GetError() << endl; return 1; } auto win = sdl2::make_window("Hello World!", 100, 100, 620, 387, SDL_WINDOW_SHOWN); if (!win) { cerr << "Error creating window: " << SDL_GetError() << endl; return 1; } auto ren = sdl2::make_renderer(win.get(), -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (!ren) { cerr << "Error creating renderer: " << SDL_GetError() << endl; return 1; } auto file = SDL_RWFromFile(IMGDIR "grumpy-cat.bmp", "rb"); if (file == nullptr) { cerr << "Error reading file: " << SDL_GetError() << endl; return 1; } auto bmp = sdl2::make_bmp(file); if (!bmp) { cerr << "Error creating surface: " << SDL_GetError() << endl; return 1; } auto tex = sdl2::make_texture(ren.get(), bmp.get()); if (!tex) { cerr << "Error creating texture: " << SDL_GetError() << endl; return 1; } for (int i = 0; i < 20; i++) { SDL_RenderClear(ren.get()); SDL_RenderCopy(ren.get(), tex.get(), nullptr, nullptr); SDL_RenderPresent(ren.get()); SDL_Delay(100); } return 0; } ================================================ FILE: c++23-cmake/CMakeLists.txt ================================================ cmake_minimum_required(VERSION 3.26) project(main) aux_source_directory(. SRC_LIST) add_executable(${PROJECT_NAME} ${SRC_LIST}) target_include_directories(${PROJECT_NAME} PRIVATE ../include) target_compile_features(${PROJECT_NAME} PRIVATE cxx_std_23) target_compile_definitions(${PROJECT_NAME} PRIVATE IMGDIR="../img/") # For macOS M2 systems with SDL2 installed via Homebrew list(APPEND CMAKE_MODULE_PATH "/usr/local/lib/cmake/SDL2" "/opt/homebrew/lib/cmake/SDL2") list(APPEND CMAKE_PREFIX_PATH "/usr/local" "/opt/homebrew") find_package(SDL2 QUIET) if (SDL2_FOUND) message("Using SDL2 from find_package") target_include_directories(${PROJECT_NAME} PRIVATE ${SDL2_INCLUDE_DIRS}) target_link_libraries(${PROJECT_NAME} PRIVATE ${SDL2_LIBRARIES}) else() # Fall back on pkg-config include(FindPkgConfig) pkg_search_module(SDL2 REQUIRED sdl2) message("Using SDL2 from pkg-config") target_include_directories(${PROJECT_NAME} PRIVATE ${SDL2_INCLUDE_DIRS}) target_link_libraries(${PROJECT_NAME} PRIVATE ${SDL2_LIBRARIES}) endif() ================================================ FILE: c++23-cmake/README.md ================================================ SDL2, C++23 and CMake ===================== Requirements ------------ * CMake * Compiler that supports C++23 (recent versions of `g++` or `clang++`, like GCC 11, supports `-std=c++2b`) * SDL2 One way of building with C++23, SDL2 and CMake ---------------------------------------------- cmake -S . -B build -DCMAKE_BUILD_TYPE=Release make -C build Running ------- build/main Cleaning up the binary file and build directory ----------------------------------------------- rm -rf build/ ================================================ FILE: c++23-cmake/main.cpp ================================================ #include #include #include "sdl2.h" auto main() -> int { using std::cerr; using std::endl; auto sys = sdl2::make_sdlsystem(SDL_INIT_EVERYTHING); if (!sys) { cerr << "Error creating SDL2 system: " << SDL_GetError() << endl; return 1; } auto win = sdl2::make_window("Hello World!", 100, 100, 620, 387, SDL_WINDOW_SHOWN); if (!win) { cerr << "Error creating window: " << SDL_GetError() << endl; return 1; } auto ren = sdl2::make_renderer(win.get(), -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (!ren) { cerr << "Error creating renderer: " << SDL_GetError() << endl; return 1; } auto file = SDL_RWFromFile(IMGDIR "grumpy-cat.bmp", "rb"); if (file == nullptr) { cerr << "Error reading file: " << SDL_GetError() << endl; return 1; } auto bmp = sdl2::make_bmp(file); if (!bmp) { cerr << "Error creating surface: " << SDL_GetError() << endl; return 1; } auto tex = sdl2::make_texture(ren.get(), bmp.get()); if (!tex) { cerr << "Error creating texture: " << SDL_GetError() << endl; return 1; } for (int i = 0; i < 20; i++) { SDL_RenderClear(ren.get()); SDL_RenderCopy(ren.get(), tex.get(), nullptr, nullptr); SDL_RenderPresent(ren.get()); SDL_Delay(100); } return 0; } ================================================ FILE: c++98/Makefile ================================================ CXX?=c++ SDL2FLAGS=$(shell pkg-config sdl2 --cflags --libs) CXXFLAGS?=-std=c++98 -Wall -pedantic -Werror -Wshadow -Wstrict-aliasing -Wstrict-overflow .PHONY: all msg clean fullclean all: msg main msg: @echo '--- C++98 ---' main: main.cpp ${CXX} ${CXXFLAGS} -O2 -o $@ $< ${SDL2FLAGS} small: main.cpp ${CXX} ${CXXFLAGS} -Os -o main $< ${SDL2FLAGS} -strip main -sstrip main debug: main.cpp ${CXX} ${CXXFLAGS} -O0 -g -o main $< ${SDL2FLAGS} asm: main.asm main.asm: main.cpp ${CXX} ${CFLAGS} -S -masm=intel -Og -o main.asm $< ${SDL2FLAGS} run: msg main time ./main clean: rm -f main *.o main.asm fullclean: clean ================================================ FILE: c++98/README.md ================================================ SDL2, C++98 and Make ==================== Requirements ------------ * Compiler that supports C++98 * pkg-config * SDL2 macOS ----- Install pkg-config using brew, or use `-LSDL2` in the Makefile instead of using pkg-config. ================================================ FILE: c++98/main.cpp ================================================ #include #include #include int main() { if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { std::cerr << "SDL_Init Error: " << SDL_GetError() << std::endl; return EXIT_FAILURE; } SDL_Window* win = SDL_CreateWindow("Hello World!", 100, 100, 620, 387, SDL_WINDOW_SHOWN); if (win == NULL) { std::cerr << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl; return EXIT_FAILURE; } SDL_Renderer* ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (ren == NULL) { std::cerr << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl; SDL_DestroyWindow(win); SDL_Quit(); return EXIT_FAILURE; } SDL_Surface* bmp = SDL_LoadBMP("../img/grumpy-cat.bmp"); if (bmp == NULL) { std::cerr << "SDL_LoadBMP Error: " << SDL_GetError() << std::endl; SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_FAILURE; } SDL_Texture* tex = SDL_CreateTextureFromSurface(ren, bmp); if (tex == NULL) { std::cerr << "SDL_CreateTextureFromSurface Error: " << SDL_GetError() << std::endl; SDL_FreeSurface(bmp); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_FAILURE; } SDL_FreeSurface(bmp); for (int i = 0; i < 20; i++) { SDL_RenderClear(ren); SDL_RenderCopy(ren, tex, NULL, NULL); SDL_RenderPresent(ren); SDL_Delay(100); } SDL_DestroyTexture(tex); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_SUCCESS; } ================================================ FILE: c11/Makefile ================================================ CC?=gcc SDL2FLAGS=$(shell pkg-config sdl2 --cflags --libs) CFLAGS?=-std=c11 -Wall -pedantic -Werror -Wshadow -Wstrict-aliasing -Wstrict-overflow .PHONY: all msg clean fullclean all: msg main msg: @echo '--- C11 ---' main: main.c ${CC} ${CFLAGS} -O2 -o $@ $< ${SDL2FLAGS} small: main.c ${CC} ${CFLAGS} -Os -o main $< ${SDL2FLAGS} -strip main -sstrip main debug: main.c ${CC} ${CFLAGS} -O1 -g -o main $< ${SDL2FLAGS} asm: main.asm main.asm: main.c ${CC} ${CFLAGS} -S -masm=intel -Og -o main.asm $< ${SDL2FLAGS} run: msg main time ./main clean: rm -f main *.o main.asm fullclean: clean ================================================ FILE: c11/README.md ================================================ ## Requirements * C11 compiler * pkg-config * SDL2 ## macOS Install pkg-config using brew, or use `-LSDL2` in the Makefile instead of using pkg-config. ================================================ FILE: c11/main.c ================================================ #include #include #include int main(void) { if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { fprintf(stderr, "SDL_Init Error: %s\n", SDL_GetError()); return EXIT_FAILURE; } SDL_Window* win = SDL_CreateWindow("Hello World!", 100, 100, 620, 387, SDL_WINDOW_SHOWN); if (win == NULL) { fprintf(stderr, "SDL_CreateWindow Error: %s\n", SDL_GetError()); return EXIT_FAILURE; } SDL_Renderer* ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (ren == NULL) { fprintf(stderr, "SDL_CreateRenderer Error: %s\n", SDL_GetError()); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_FAILURE; } SDL_Surface* bmp = SDL_LoadBMP("../img/grumpy-cat.bmp"); if (bmp == NULL) { fprintf(stderr, "SDL_LoadBMP Error: %s\n", SDL_GetError()); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_FAILURE; } SDL_Texture* tex = SDL_CreateTextureFromSurface(ren, bmp); if (tex == NULL) { fprintf(stderr, "SDL_CreateTextureFromSurface Error: %s\n", SDL_GetError()); SDL_FreeSurface(bmp); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_FAILURE; } SDL_FreeSurface(bmp); for (int i = 0; i < 20; i++) { SDL_RenderClear(ren); SDL_RenderCopy(ren, tex, NULL, NULL); SDL_RenderPresent(ren); SDL_Delay(100); } SDL_DestroyTexture(tex); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_SUCCESS; } ================================================ FILE: c18/Makefile ================================================ CC?=gcc SDL2FLAGS=$(shell pkg-config sdl2 --cflags --libs) CFLAGS?=-std=c18 -Wall -pedantic -Werror -Wshadow -Wstrict-aliasing -Wstrict-overflow .PHONY: all msg clean fullclean all: msg main msg: @echo '--- C18 ---' main: main.c ${CC} ${CFLAGS} -O2 -o $@ $< ${SDL2FLAGS} small: main.c ${CC} ${CFLAGS} -Os -o main $< ${SDL2FLAGS} -strip main -sstrip main debug: main.c ${CC} ${CFLAGS} -O1 -g -o main $< ${SDL2FLAGS} asm: main.asm main.asm: main.c ${CC} ${CFLAGS} -S -masm=intel -Og -o main.asm $< ${SDL2FLAGS} run: msg main time ./main clean: rm -f main *.o main.asm fullclean: clean ================================================ FILE: c18/README.md ================================================ ## Requirements * C18 compiler * pkg-config * SDL2 ## macOS Install pkg-config using brew, or use `-LSDL2` in the Makefile instead of using pkg-config. ================================================ FILE: c18/main.c ================================================ #include #include #include int main(void) { if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { fprintf(stderr, "SDL_Init Error: %s\n", SDL_GetError()); return EXIT_FAILURE; } SDL_Window* win = SDL_CreateWindow("Hello World!", 100, 100, 620, 387, SDL_WINDOW_SHOWN); if (win == NULL) { fprintf(stderr, "SDL_CreateWindow Error: %s\n", SDL_GetError()); return EXIT_FAILURE; } SDL_Renderer* ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (ren == NULL) { fprintf(stderr, "SDL_CreateRenderer Error: %s\n", SDL_GetError()); if (win != NULL) { SDL_DestroyWindow(win); } SDL_Quit(); return EXIT_FAILURE; } SDL_Surface* bmp = SDL_LoadBMP("../img/grumpy-cat.bmp"); if (bmp == NULL) { fprintf(stderr, "SDL_LoadBMP Error: %s\n", SDL_GetError()); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_FAILURE; } SDL_Texture* tex = SDL_CreateTextureFromSurface(ren, bmp); if (tex == NULL) { fprintf(stderr, "SDL_CreateTextureFromSurface Error: %s\n", SDL_GetError()); SDL_FreeSurface(bmp); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_FAILURE; } SDL_FreeSurface(bmp); for (int i = 0; i < 20; i++) { SDL_RenderClear(ren); SDL_RenderCopy(ren, tex, NULL, NULL); SDL_RenderPresent(ren); SDL_Delay(100); } SDL_DestroyTexture(tex); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_SUCCESS; } ================================================ FILE: c2x/Makefile ================================================ CC?=gcc SDL2FLAGS=$(shell pkg-config sdl2 --cflags --libs) CFLAGS?=-std=c2x -Wall -pedantic -Werror -Wshadow -Wstrict-aliasing -Wstrict-overflow .PHONY: all msg clean fullclean all: msg main msg: @echo '--- C2X ---' main: main.c ${CC} ${CFLAGS} -O2 -o $@ $< ${SDL2FLAGS} small: main.c ${CC} ${CFLAGS} -Os -o main $< ${SDL2FLAGS} -strip main -sstrip main debug: main.c ${CC} ${CFLAGS} -O1 -g -o main $< ${SDL2FLAGS} asm: main.asm main.asm: main.c ${CC} ${CFLAGS} -S -masm=intel -Og -o main.asm $< ${SDL2FLAGS} run: msg main time ./main clean: rm -f main *.o main.asm fullclean: clean ================================================ FILE: c2x/README.md ================================================ ## Requirements * C2X compiler (GCC 9 or later, Clang 9 or later) * pkg-config * SDL2 ## macOS Install pkg-config using brew, or use `-LSDL2` in the Makefile instead of using pkg-config. ================================================ FILE: c2x/main.c ================================================ #include #include #include int main() { if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { fprintf(stderr, "SDL_Init Error: %s\n", SDL_GetError()); return EXIT_FAILURE; } SDL_Window* win = SDL_CreateWindow("Hello World!", 100, 100, 620, 387, SDL_WINDOW_SHOWN); if (win == NULL) { fprintf(stderr, "SDL_CreateWindow Error: %s\n", SDL_GetError()); return EXIT_FAILURE; } SDL_Renderer* ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (ren == NULL) { fprintf(stderr, "SDL_CreateRenderer Error: %s\n", SDL_GetError()); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_FAILURE; } SDL_Surface* bmp = SDL_LoadBMP("../img/grumpy-cat.bmp"); if (bmp == NULL) { fprintf(stderr, "SDL_LoadBMP Error: %s\n", SDL_GetError()); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_FAILURE; } SDL_Texture* tex = SDL_CreateTextureFromSurface(ren, bmp); if (tex == NULL) { fprintf(stderr, "SDL_CreateTextureFromSurface Error: %s\n", SDL_GetError()); SDL_FreeSurface(bmp); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_FAILURE; } SDL_FreeSurface(bmp); for (int i = 0; i < 20; i++) { SDL_RenderClear(ren); SDL_RenderCopy(ren, tex, NULL, NULL); SDL_RenderPresent(ren); SDL_Delay(100); } SDL_DestroyTexture(tex); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_SUCCESS; } ================================================ FILE: c89/Makefile ================================================ CC?=gcc SDL2FLAGS=$(shell pkg-config sdl2 --cflags --libs) CFLAGS?=-ansi -Wall -pedantic -Werror -Wshadow -Wstrict-aliasing -Wstrict-overflow .PHONY: all msg clean fullclean all: msg main msg: @echo '--- C89 (ANSI C) ---' main: main.c ${CC} ${CFLAGS} -O2 -o $@ $< ${SDL2FLAGS} small: main.c ${CC} ${CFLAGS} -Os -o main $< ${SDL2FLAGS} -strip main -sstrip main debug: main.c ${CC} ${CFLAGS} -O1 -g -o main $< ${SDL2FLAGS} asm: main.asm main.asm: main.c ${CC} ${CFLAGS} -S -masm=intel -Og -o main.asm $< ${SDL2FLAGS} run: msg main time ./main clean: rm -f main *.o main.asm fullclean: clean ================================================ FILE: c89/README.md ================================================ ## Requirements * C89 (ANSI C) compiler * pkg-config * SDL2 ## macOS Install pkg-config using brew, or use `-LSDL2` in the Makefile instead of using pkg-config. ================================================ FILE: c89/main.c ================================================ #include #include #include int main(void) { SDL_Window* win; SDL_Renderer* ren; SDL_Surface* bmp; SDL_Texture* tex; int i; if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { fprintf(stderr, "SDL_Init Error: %s\n", SDL_GetError()); return EXIT_FAILURE; } win = SDL_CreateWindow("Hello World!", 100, 100, 620, 387, SDL_WINDOW_SHOWN); if (win == NULL) { fprintf(stderr, "SDL_CreateWindow Error: %s\n", SDL_GetError()); return EXIT_FAILURE; } ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (ren == NULL) { fprintf(stderr, "SDL_CreateRenderer Error: %s\n", SDL_GetError()); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_FAILURE; } bmp = SDL_LoadBMP("../img/grumpy-cat.bmp"); if (bmp == NULL) { fprintf(stderr, "SDL_LoadBMP Error: %s\n", SDL_GetError()); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_FAILURE; } tex = SDL_CreateTextureFromSurface(ren, bmp); if (tex == NULL) { fprintf(stderr, "SDL_CreateTextureFromSurface Error: %s\n", SDL_GetError()); SDL_FreeSurface(bmp); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_FAILURE; } SDL_FreeSurface(bmp); for (i = 0; i < 20; i++) { SDL_RenderClear(ren); SDL_RenderCopy(ren, tex, NULL, NULL); SDL_RenderPresent(ren); SDL_Delay(100); } SDL_DestroyTexture(tex); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_SUCCESS; } ================================================ FILE: c99/Makefile ================================================ CC?=gcc SDL2FLAGS=$(shell pkg-config sdl2 --cflags --libs) CFLAGS?=-std=c99 -Wall -pedantic -Werror -Wshadow -Wstrict-aliasing -Wstrict-overflow .PHONY: all msg clean fullclean all: msg main msg: @echo '--- C99 ---' main: main.c ${CC} ${CFLAGS} -O2 -o $@ $< ${SDL2FLAGS} small: main.c ${CC} ${CFLAGS} -Os -o main $< ${SDL2FLAGS} -strip main -sstrip main debug: main.c ${CC} ${CFLAGS} -O1 -g -o main $< ${SDL2FLAGS} asm: main.asm main.asm: main.c ${CC} ${CFLAGS} -S -masm=intel -Og -o main.asm $< ${SDL2FLAGS} run: msg main time ./main clean: rm -f main *.o main.asm fullclean: clean ================================================ FILE: c99/README.md ================================================ ## Requirements * C99 compiler * pkg-config * SDL2 ## macOS Install pkg-config using brew, or use `-LSDL2` in the Makefile instead of using pkg-config. ================================================ FILE: c99/main.c ================================================ #include #include #include #include int main(void) { if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { fprintf(stderr, "SDL_Init Error: %s\n", SDL_GetError()); return EXIT_FAILURE; } SDL_Window* win = SDL_CreateWindow("Hello World!", -1, -1, 620, 387, SDL_WINDOW_SHOWN); if (win == NULL) { fprintf(stderr, "SDL_CreateWindow Error: %s\n", SDL_GetError()); return EXIT_FAILURE; } SDL_Renderer* ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (ren == NULL) { fprintf(stderr, "SDL_CreateRenderer Error: %s\n", SDL_GetError()); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_FAILURE; } SDL_Surface* bmp = SDL_LoadBMP("../img/grumpy-cat.bmp"); if (bmp == NULL) { fprintf(stderr, "SDL_LoadBMP Error: %s\n", SDL_GetError()); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_FAILURE; } SDL_Texture* tex = SDL_CreateTextureFromSurface(ren, bmp); if (tex == NULL) { fprintf(stderr, "SDL_CreateTextureFromSurface Error: %s\n", SDL_GetError()); SDL_FreeSurface(bmp); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_FAILURE; } SDL_FreeSurface(bmp); SDL_Event e; bool quit = false; Uint32 startTime = SDL_GetTicks(); while (!quit) { while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) { quit = true; } if (e.type == SDL_KEYDOWN) { if (e.key.keysym.sym == SDLK_ESCAPE) { quit = true; } } } Uint32 elapsedTime = SDL_GetTicks() - startTime; if (elapsedTime > 2000) { break; } SDL_RenderClear(ren); SDL_RenderCopy(ren, tex, NULL, NULL); SDL_RenderPresent(ren); SDL_Delay(100); } SDL_DestroyTexture(tex); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return EXIT_SUCCESS; } ================================================ FILE: crystal/Makefile ================================================ .PHONY: all msg sdl2 clean fullclean all: msg bin/main msg: @echo '--- Crystal ---' bin/main: shard.yml main.cr @echo -n '[main] Compiling...' @shards -q build @echo 'ok' run: msg bin/main time ./bin/main clean: rm -f bin/main fullclean: clean rm -rf bin lib ================================================ FILE: crystal/README.md ================================================ # Crystal SDL2 example Tested with Crystal 1.0.0 and Crystal 1.1.0 on Arch Linux. Requires both `crystal` and `shards`. ================================================ FILE: crystal/main.cr ================================================ require "sdl" require "sdl/image" begin SDL.init(SDL::Init::VIDEO) at_exit { SDL.quit } SDL::IMG.init(SDL::IMG::Init::PNG) at_exit { SDL::IMG.quit } window = SDL::Window.new("Hello World!", 620, 387) renderer = SDL::Renderer.new(window, SDL::Renderer::Flags::ACCELERATED | SDL::Renderer::Flags::PRESENTVSYNC) texture = SDL::IMG.load(File.join(__DIR__, "..", "img", "grumpy-cat.png"), renderer) start_time = Time.monotonic quit = false until quit case event = SDL::Event.poll when SDL::Event::Quit quit = true when SDL::Event::Keyboard quit = true if event.keydown? && event.sym.escape? end break if (Time.monotonic - start_time) > 2.seconds renderer.clear renderer.copy(texture) renderer.present sleep(100.milliseconds) end rescue ex abort "Error: #{ex.message}" end ================================================ FILE: crystal/shard.yml ================================================ name: main version: 0.1.0 authors: - Alexander F. Rødseth dependencies: sdl: github: ysbaddaden/sdl.cr targets: main: main: main.cr crystal: 1.1.1 license: MIT ================================================ FILE: csharp/Makefile ================================================ .PHONY: all msg clean fullclean check-config MONO_VERSION ?= 4.5 ifeq ($(shell uname -s), Darwin) MONO_ETC := $(shell dirname $(shell dirname $(shell realpath $(shell which mono))))/etc/mono else MONO_ETC := /etc/mono endif MONO_CONFIG := $(MONO_ETC)/config MACHINE_CONFIG := $(MONO_ETC)/$(MONO_VERSION)/machine.config all: msg check-config main msg: @echo '--- C# ---' main.exe: main.cs mcs -unsafe -out:$@ $< main: main.exe @echo "Mono config file: $(MONO_CONFIG)" @echo "Machine config file: $(MACHINE_CONFIG)" mkbundle -o $@ --deps --simple --static --i18n none --machine-config $(MACHINE_CONFIG) --config $(MONO_CONFIG) $< rm -f main.exe run: msg main time ./main clean: rm -f main main.exe temp.* *crash*.json check-config: @if [ ! -f $(MACHINE_CONFIG) ]; then \ echo "ERROR: The file $(MACHINE_CONFIG) does not exist."; \ exit 1; \ fi @if [ ! -f $(MONO_CONFIG) ]; then \ echo "ERROR: The file $(MONO_CONFIG) does not exist."; \ exit 1; \ fi ================================================ FILE: csharp/README.md ================================================ # C# + SDL2 example SDL2 must either be installed, or be available as a shared library. ## Arch Linux ### Building and running with Mono Building: msc /unsafe main.cs Running: mono main.exe ### Building and running as a native executable `mkbundle` comes with `mono`. Building: make Running: ./main ### Building with `csc` and running with Wine This builds a Windows GUI executable. Building: csc /target:winexe /unsafe main.cs Running: wine main.exe ## Windows ### Building Either place csc.exe in the `PATH` and build with that, using: csc /target:winexe /unsafe main.cs Or use the full path, for example: C:\Windows\Microsoft.NET\Framework\v3.5\csc /target:winexe /unsafe main.cs ## macOS Apple Silicon (M1/M2/M3/aarch64) is not currently supported (as of 2024-08-06). Running `make run` will: * Create a `main.exe` file, but for the wrong CPU. * Bundle the `main.exe` file into a `main` executable, which will look correct when using `file`. But running `./main` will output an error message a bit like this one: Error mapping file: mono_file_map_error failed file:./main length:0x4685824X offset:0x3944448X error:Invalid argument(0x16) Here is the status of macOS/M1/M2/aarch64 support for Mono: * https://github.com/mono/mono/issues/21092 ### SDL2 `SDL2.dll` is included (zlib license). It can also be downloaded from here: https://www.libsdl.org/download-2.0.php This text came together with the `SDL2.dll` binary: ``` The Simple DirectMedia Layer (SDL for short) is a cross-platform library designed to make it easy to write multi-media software, such as games and emulators. The Simple DirectMedia Layer library source code is available from: https://www.libsdl.org/ This library is distributed under the terms of the zlib license: http://www.zlib.net/zlib_license.html ``` ## macOS On a macOS with a M2 CPU, a main.exe and main file is built, but they did not run correctly here, neither directly, with mono or with wine. Pull requests are welcome. ================================================ FILE: csharp/main.cs ================================================ using System; using System.Runtime.InteropServices; using System.Text; public class HelloWorld { // From SDL.h private const UInt32 SDL_INIT_VIDEO = 0x00000020; // From SDL_video.h private const Int32 SDL_WINDOWPOS_UNDEFINED = 0x1FFF0000; private const UInt32 SDL_WINDOW_SHOWN = 0x00000004; // From SDL_render.h private const UInt32 SDL_RENDERER_ACCELERATED = 0x00000002; private const UInt32 SDL_RENDERER_PRESENTVSYNC = 0x00000004; [DllImport("SDL2")] private static extern unsafe Int32 SDL_Init(UInt32 flags); [DllImport("SDL2")] private static extern unsafe IntPtr SDL_CreateWindow( [MarshalAs(UnmanagedType.LPStr)] string title, int x, int y, int w, int h, uint flags ); [DllImport("SDL2")] private static extern unsafe IntPtr SDL_CreateRenderer( IntPtr win, int index, uint flags ); [DllImport("SDL2")] private static extern unsafe IntPtr SDL_CreateTextureFromSurface( IntPtr renderer, IntPtr surface ); [DllImport("SDL2")] private static extern unsafe void SDL_DestroyRenderer( IntPtr renderer ); [DllImport("SDL2")] private static extern unsafe void SDL_DestroyWindow( IntPtr window ); [DllImport("SDL2")] private static extern unsafe void SDL_FreeSurface( IntPtr surface ); [DllImport("SDL2")] private static extern unsafe void SDL_DestroyTexture( IntPtr texture ); [DllImport("SDL2")] private static extern unsafe Int32 SDL_RenderClear( IntPtr renderer ); [DllImport("SDL2")] private static extern unsafe Int32 SDL_RenderCopy( IntPtr renderer, IntPtr texture, IntPtr srcrect, IntPtr dstrect ); [DllImport("SDL2")] private static extern unsafe void SDL_RenderPresent( IntPtr renderer ); [DllImport("SDL2")] private static extern unsafe IntPtr SDL_LoadBMP_RW( IntPtr src, int freesrc ); [DllImport("SDL2")] private static extern unsafe IntPtr SDL_RWFromFile( [MarshalAs(UnmanagedType.LPStr)] string filename, [MarshalAs(UnmanagedType.LPStr)] string permissions ); [DllImport("SDL2")] private static extern unsafe void SDL_Quit(); [DllImport("SDL2")] private static extern unsafe byte* SDL_GetError(); // Call SDL_GetError() and return the C string as a C# String private static unsafe string SDL_GetErrorString() { StringBuilder sb = new StringBuilder(); byte* errStr = SDL_GetError(); int i = 0; while (errStr[i] != 0) // trust that the string returned from SDL_GetError() is properly terminated { sb.Append(Convert.ToChar(errStr[i])); i++; } return sb.ToString(); } // Print the SDL_GetError() error message to stderr, with a preceding topic and also " Error: " private static void PrintErr(string topic) { Console.Error.WriteLine(topic + " Error: " + SDL_GetErrorString()); } public class SDLWindow : IDisposable { public IntPtr Handle { get; private set; } public SDLWindow(string title, int x, int y, int w, int h, uint flags) { Handle = SDL_CreateWindow(title, x, y, w, h, flags); if (Handle == IntPtr.Zero) { throw new Exception("SDL_CreateWindow Error: " + SDL_GetErrorString()); } } public void Dispose() { if (Handle != IntPtr.Zero) { SDL_DestroyWindow(Handle); Handle = IntPtr.Zero; } } } public class SDLRenderer : IDisposable { public IntPtr Handle { get; private set; } public SDLRenderer(SDLWindow window, int index, uint flags) { Handle = SDL_CreateRenderer(window.Handle, index, flags); if (Handle == IntPtr.Zero) { throw new Exception("SDL_CreateRenderer Error: " + SDL_GetErrorString()); } } public void Dispose() { if (Handle != IntPtr.Zero) { SDL_DestroyRenderer(Handle); Handle = IntPtr.Zero; } } } public class SDLTexture : IDisposable { public IntPtr Handle { get; private set; } public SDLTexture(SDLRenderer renderer, IntPtr surface) { Handle = SDL_CreateTextureFromSurface(renderer.Handle, surface); if (Handle == IntPtr.Zero) { throw new Exception("SDL_CreateTextureFromSurface Error: " + SDL_GetErrorString()); } } public void Dispose() { if (Handle != IntPtr.Zero) { SDL_DestroyTexture(Handle); Handle = IntPtr.Zero; } } } public static int Main(string[] args) { if (SDL_Init(SDL_INIT_VIDEO) != 0) { PrintErr("SDL_Init"); return 1; } using (var window = new SDLWindow("Hello, World!", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 620, 387, SDL_WINDOW_SHOWN)) using (var renderer = new SDLRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC)) { IntPtr rwop = SDL_RWFromFile("../img/grumpy-cat.bmp", "rb"); if (rwop == IntPtr.Zero) { PrintErr("SDL_RWFromFile"); return 1; } IntPtr bmp = SDL_LoadBMP_RW(rwop, 1); // this also frees rwop if (bmp == IntPtr.Zero) { PrintErr("SDL_LoadBMP_RW"); return 1; } using (var texture = new SDLTexture(renderer, bmp)) { SDL_FreeSurface(bmp); for (int i = 0; i < 20; i++) { SDL_RenderClear(renderer.Handle); SDL_RenderCopy(renderer.Handle, texture.Handle, IntPtr.Zero, IntPtr.Zero); SDL_RenderPresent(renderer.Handle); System.Threading.Thread.Sleep(100); } } } SDL_Quit(); return 0; } } ================================================ FILE: csharp/main.csproj ================================================  Exe net8.0 enable enable true ================================================ FILE: d/.gitignore ================================================ bin/ main ================================================ FILE: d/Makefile ================================================ .PHONY: all msg clean fullclean all: msg main msg: @echo '--- D ---' main: source/app.d @echo -n '[main] Compiling...' @dub -q build @echo 'ok' run: msg main time ./main clean: rm -f main fullclean: clean ================================================ FILE: d/README.md ================================================ # D + SDL2 This example is based on public domain code from Peter Cartwright https://github.com/pokedpeter/dlang-derelict-sdl2-example1 ================================================ FILE: d/dub.json ================================================ { "name": "main", "authors": [ "Peter Cartwright" ], "description": "An example using Derelict and SDL2 in d", "copyright": "Copyright © 2016, Peter Cartwright", "license": "public domain", "dependencies": { "derelict-sdl2": "~>2.1.4" }, "targetPath": "." } ================================================ FILE: d/dub.selections.json ================================================ { "fileVersion": 1, "versions": { "derelict-sdl2": "2.1.4", "derelict-util": "2.0.6" } } ================================================ FILE: d/source/app.d ================================================ // Based on https://github.com/pokedpeter/dlang-derelict-sdl2-example1 import std.stdio; import derelict.sdl2.sdl; import derelict.sdl2.image; import std.conv; void main() { DerelictSDL2.load(); DerelictSDL2Image.load(); // Initialise SDL if (SDL_Init(SDL_INIT_VIDEO) != 0) { writeln("SDL_Init: ", SDL_GetError()); } // Initialise IMG int flags = IMG_INIT_PNG; if ((IMG_Init(flags) & flags) != flags) { writeln("IMG_Init: ", to!string(IMG_GetError())); } // Load image SDL_Surface *imgSurf = IMG_Load("../img/grumpy-cat.png"); if (imgSurf is null) { writeln("IMG_Load: ", to!string(IMG_GetError())); } // Create a window SDL_Window* appWin = SDL_CreateWindow( "Hello, World!", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, imgSurf.w, imgSurf.h, SDL_WINDOW_OPENGL ); if (appWin is null) { writefln("SDL_CreateWindow: ", SDL_GetError()); return; } // Get the window surface SDL_Surface *winSurf = SDL_GetWindowSurface(appWin); if (winSurf is null) { writeln("SDL_GetWindowSurface: ", SDL_GetError()); } // Define a colour for the surface, based on RGB values int colour = SDL_MapRGB(winSurf.format, 0xFF, 0xFF, 0xFF); // Fill the window surface with the colour SDL_FillRect(winSurf, null, colour); // Copy loaded image to window surface SDL_Rect dstRect; dstRect.x = 0; dstRect.y = 0; SDL_BlitSurface(imgSurf, null, winSurf, &dstRect); // Copy the window surface to the screen SDL_UpdateWindowSurface(appWin); // Polling for events for (int i = 0; i < 20; i++) { SDL_Delay(100); } // Close and destroy the window if (appWin !is null) { SDL_DestroyWindow(appWin); } // Tidy up IMG_Quit(); SDL_Quit(); } ================================================ FILE: dart/Makefile ================================================ .PHONY: msg run clean all: msg main msg: @echo '--- Dart ---' pubspec.lock: pubspec.yaml dart pub get main: pubspec.lock main.dart dart compile exe main.dart -o main run: time ./main clean: rm -f main fullclean: clean rm -f pubspec.lock ================================================ FILE: dart/main.dart ================================================ import 'dart:ffi'; import 'package:ffi/ffi.dart'; // From SDL.h const int SDL_INIT_VIDEO = 0x00000020; // From SDL_video.h const int SDL_WINDOWPOS_UNDEFINED = 0x1FFF0000; const int SDL_WINDOW_SHOWN = 0x00000004; // From SDL_render.h const int SDL_RENDERER_ACCELERATED = 0x00000002; const int SDL_RENDERER_PRESENTVSYNC = 0x00000004; // Load the SDL2 library final DynamicLibrary sdlLib = DynamicLibrary.open('libSDL2.so'); // Define the signature of the C functions typedef SDL_InitC = Int32 Function(Uint32 flags); typedef SDL_InitDart = int Function(int flags); typedef SDL_CreateWindowC = Pointer Function(Pointer title, Int32 x, Int32 y, Int32 w, Int32 h, Uint32 flags); typedef SDL_CreateWindowDart = Pointer Function(Pointer title, int x, int y, int w, int h, int flags); typedef SDL_CreateRendererC = Pointer Function(Pointer win, Int32 index, Uint32 flags); typedef SDL_CreateRendererDart = Pointer Function(Pointer win, int index, int flags); typedef SDL_CreateTextureFromSurfaceC = Pointer Function(Pointer renderer, Pointer surface); typedef SDL_CreateTextureFromSurfaceDart = Pointer Function(Pointer renderer, Pointer surface); typedef SDL_DestroyRendererC = Void Function(Pointer renderer); typedef SDL_DestroyRendererDart = void Function(Pointer renderer); typedef SDL_DestroyWindowC = Void Function(Pointer window); typedef SDL_DestroyWindowDart = void Function(Pointer window); typedef SDL_FreeSurfaceC = Void Function(Pointer surface); typedef SDL_FreeSurfaceDart = void Function(Pointer surface); typedef SDL_DestroyTextureC = Void Function(Pointer texture); typedef SDL_DestroyTextureDart = void Function(Pointer texture); typedef SDL_RenderClearC = Int32 Function(Pointer renderer); typedef SDL_RenderClearDart = int Function(Pointer renderer); typedef SDL_RenderCopyC = Int32 Function(Pointer renderer, Pointer texture, Pointer srcrect, Pointer dstrect); typedef SDL_RenderCopyDart = int Function(Pointer renderer, Pointer texture, Pointer srcrect, Pointer dstrect); typedef SDL_RenderPresentC = Void Function(Pointer renderer); typedef SDL_RenderPresentDart = void Function(Pointer renderer); typedef SDL_RWFromFileC = Pointer Function(Pointer file, Pointer mode); typedef SDL_RWFromFileDart = Pointer Function(Pointer file, Pointer mode); typedef SDL_LoadBMP_RWC = Pointer Function(Pointer src, Int32 freesrc); typedef SDL_LoadBMP_RWDart = Pointer Function(Pointer src, int freesrc); typedef SDL_DelayC = Void Function(Uint32 ms); typedef SDL_DelayDart = void Function(int ms); typedef SDL_QuitC = Void Function(); typedef SDL_QuitDart = void Function(); void main() { // Look up the functions final SDL_Init = sdlLib.lookupFunction('SDL_Init'); final SDL_CreateWindow = sdlLib.lookupFunction('SDL_CreateWindow'); final SDL_CreateRenderer = sdlLib.lookupFunction('SDL_CreateRenderer'); final SDL_CreateTextureFromSurface = sdlLib.lookupFunction('SDL_CreateTextureFromSurface'); final SDL_DestroyRenderer = sdlLib.lookupFunction('SDL_DestroyRenderer'); final SDL_DestroyWindow = sdlLib.lookupFunction('SDL_DestroyWindow'); final SDL_FreeSurface = sdlLib.lookupFunction('SDL_FreeSurface'); final SDL_DestroyTexture = sdlLib.lookupFunction('SDL_DestroyTexture'); final SDL_RenderClear = sdlLib.lookupFunction('SDL_RenderClear'); final SDL_RenderCopy = sdlLib.lookupFunction('SDL_RenderCopy'); final SDL_RenderPresent = sdlLib.lookupFunction('SDL_RenderPresent'); final SDL_RWFromFile = sdlLib.lookupFunction('SDL_RWFromFile'); final SDL_LoadBMP_RW = sdlLib.lookupFunction('SDL_LoadBMP_RW'); final SDL_Delay = sdlLib.lookupFunction('SDL_Delay'); final SDL_Quit = sdlLib.lookupFunction('SDL_Quit'); SDL_Init(SDL_INIT_VIDEO); final titleCString = 'Hello, World!'.toNativeUtf8(); var window = SDL_CreateWindow(titleCString, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 620, 387, SDL_WINDOW_SHOWN); var renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); final bmpFileCString = '../img/grumpy-cat.bmp'.toNativeUtf8(); final modeCString = 'rb'.toNativeUtf8(); var rwop = SDL_RWFromFile(bmpFileCString, modeCString); var bmp = SDL_LoadBMP_RW(rwop, 1); var texture = SDL_CreateTextureFromSurface(renderer, bmp); SDL_FreeSurface(bmp); for (int i = 0; i < 20; i++) { SDL_RenderClear(renderer); SDL_RenderCopy(renderer, texture, nullptr, nullptr); SDL_RenderPresent(renderer); SDL_Delay(100); } SDL_DestroyTexture(texture); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); calloc.free(titleCString); calloc.free(bmpFileCString); calloc.free(modeCString); SDL_Quit(); } ================================================ FILE: dart/pubspec.yaml ================================================ name: main description: SDL2 Example version: 1.0.0 homepage: https://github.com/xyproto/sdl2-examples environment: sdk: '>=3.0.0 <4.0.0' dependencies: ffi: ^2.0.2 executables: main: ================================================ FILE: freebasic/Makefile ================================================ .PHONY: all msg clean fullclean all: msg main msg: @echo '--- FreeBASIC ---' main: main.bas @echo -n '[main] Compiling...' @fbc main.bas @echo 'ok' run: msg main time ./main fullclean: clean: rm -f *.o main ================================================ FILE: freebasic/README.md ================================================ # FreeBASIC Tested on Arch Linux with the `fbc-git` package from AUR. SDL2 must be included with the FreeBASIC installation on your system for this example to work. ================================================ FILE: freebasic/main.bas ================================================ #include "SDL2/SDL.bi" #include "SDL2/SDL_image.bi" #include "SDL2/SDL_ttf.bi" SDL_Init(SDL_INIT_VIDEO) IMG_Init(0) var win = SDL_CreateWindow("Hello world!", 100, 100, 620, 387, 0) var ren = SDL_CreateRenderer(win, -1, 0) '' Load the image into a surface and then into a texture var img = IMG_Load("../img/grumpy-cat.bmp") var tex = SDL_CreateTextureFromSurface(ren, img) SDL_FreeSurface(img) : img = NULL for i as Integer = 0 to 20 SDL_RenderClear(ren) SDL_RenderCopy(ren, tex, NULL, NULL) SDL_RenderPresent(ren) SDL_Delay(100) next i SDL_DestroyTexture(tex) SDL_DestroyRenderer(ren) SDL_DestroyWindow(win) SDL_Quit() ================================================ FILE: fsharp/Makefile ================================================ .PHONY: all msg clean all: msg bin msg: @echo '--- F# ---' bin: main.fsproj main.fs dotnet build --sc --nologo --ucr run: msg bin time dotnet run clean: rm -rf bin/ obj/ ================================================ FILE: fsharp/main.fs ================================================ module Main open System open System.Runtime.InteropServices open System.Text open Microsoft.FSharp.NativeInterop let SDL_INIT_VIDEO : uint32 = 0x00000020u let SDL_WINDOWPOS_UNDEFINED : int32 = 0x1FFF0000 let SDL_WINDOW_SHOWN : uint32 = 0x00000004u let SDL_RENDERER_ACCELERATED : uint32 = 0x00000002u let SDL_RENDERER_PRESENTVSYNC : uint32 = 0x00000004u [] extern int32 SDL_Init(uint32 flags) [] extern IntPtr SDL_CreateWindow(string title, int x, int y, int w, int h, uint32 flags) [] extern IntPtr SDL_CreateRenderer(IntPtr win, int index, uint32 flags) [] extern IntPtr SDL_CreateTextureFromSurface(IntPtr renderer, IntPtr surface) [] extern void SDL_DestroyRenderer(IntPtr renderer) [] extern void SDL_DestroyWindow(IntPtr window) [] extern void SDL_FreeSurface(IntPtr surface) [] extern void SDL_DestroyTexture(IntPtr texture) [] extern int32 SDL_RenderClear(IntPtr renderer) [] extern int32 SDL_RenderCopy(IntPtr renderer, IntPtr texture, IntPtr srcrect, IntPtr dstrect) [] extern void SDL_RenderPresent(IntPtr renderer) [] extern IntPtr SDL_LoadBMP_RW(IntPtr src, int freesrc) [] extern IntPtr SDL_RWFromFile(string filename, string permissions) [] extern void SDL_Quit() [] extern IntPtr SDL_GetError() let printErr (topic: string) = let errPtr = SDL_GetError() let errString = Marshal.PtrToStringAnsi(errPtr) Console.Error.WriteLine($"{topic} Error: {errString}") [] let main argv = if SDL_Init(SDL_INIT_VIDEO) <> 0 then printErr "SDL_Init" 1 else let win = SDL_CreateWindow("Hello, World!", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 620, 387, SDL_WINDOW_SHOWN) if win = IntPtr.Zero then printErr "SDL_CreateWindow" 1 else let ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED ||| SDL_RENDERER_PRESENTVSYNC) if ren = IntPtr.Zero then printErr "SDL_CreateRenderer" SDL_DestroyWindow win SDL_Quit() 1 else let rwop = SDL_RWFromFile("../img/grumpy-cat.bmp", "rb") if rwop = IntPtr.Zero then printErr "SDL_RWFromFile" SDL_DestroyRenderer ren SDL_DestroyWindow win SDL_Quit() 1 else let bmp = SDL_LoadBMP_RW(rwop, 1) // this also frees rwop if bmp = IntPtr.Zero then printErr "SDL_LoadBMP_RW" SDL_DestroyRenderer ren SDL_DestroyWindow win SDL_Quit() 1 else let tex = SDL_CreateTextureFromSurface(ren, bmp) SDL_FreeSurface(bmp) if tex = IntPtr.Zero then printErr "SDL_CreateTextureFromSurface" SDL_DestroyRenderer ren SDL_DestroyWindow win SDL_Quit() 1 else for i in 1 .. 20 do SDL_RenderClear ren |> ignore SDL_RenderCopy(ren, tex, IntPtr.Zero, IntPtr.Zero) |> ignore SDL_RenderPresent ren System.Threading.Thread.Sleep(100) SDL_DestroyTexture tex SDL_DestroyRenderer ren SDL_DestroyWindow win SDL_Quit() 0 ================================================ FILE: fsharp/main.fsproj ================================================ Release Exe net8.0 YourNamespace true ================================================ FILE: gambas/.directory ================================================ [Desktop Entry] Icon=./.icon.png ================================================ FILE: gambas/.gitignore ================================================ #---- Gambas files to ignore (v5) *.gambas .lock *~ core core.* vgcore vgcore.* .kdbg* .*.prof .lang/*.pot .gambas/* .settings .startup .list .info main #---- ================================================ FILE: gambas/.project ================================================ # Gambas Project File 3.0 Title=Grumpy Cat Startup=MMain Version=1.0.12 Component=gb.image Component=gb.sdl2 Component=gb.opengl TabSize=2 Language=en_US Packager=1 ================================================ FILE: gambas/.src/MMain.module ================================================ ' Gambas module file Private hWindow As Window Private hTimer As Timer Private hImage As Image Public Sub Main() hWindow = New Window As "MainWindow" With hWindow .Resize(620, 387) .Resizable = False .FrameRate = 60 .Title = "Hello World!" .Show End With hImage = Image.Load(Application.Dir &/ "../img/grumpy-cat.bmp") hTimer = New Timer As "QuitTimer" With hTimer .Delay = 2000 .Enabled = True End With End Public Sub MainWindow_Draw() Draw.Clear Draw.Image(hImage, 0, 0, 620, 387) End Public Sub QuitTimer_Timer() hTimer.Enabled = False hWindow.Close() Quit End ================================================ FILE: gambas/Makefile ================================================ .PHONY: all main msg clean fullclean all: msg main msg: @echo '--- Gambas ---' main: main.bas gbc3 gba3 -o main run: msg main time ./main clean: rm -f main fullclean: clean ================================================ FILE: gccgo/Makefile ================================================ .PHONY: all clean debug main msg run small static CFLAGS?=$(shell pkg-config sdl2 --cflags --libs) all: CFLAGS+=-O2 all: main small: CFLAGS+=-Os small: main sstrip main debug: CFLAGS+=-O0 -g debug: main static: CFLAGS+=-O2 -static static: main main: go build -v -compiler gccgo -gccgoflags '${CFLAGS}' -o main msg: @echo '--- GCCGO ---' run: ./main clean: go clean ================================================ FILE: gccgo/README.md ================================================ Works with gccgo 8.2.1 and the latest version of go-sdl2. Requirements: * The SDL2 library and headers installed on your system. * For macOS, remember to install the Development Libraries (place the SDL2 framework in `/Library/Frameworks`). * The latest version of `gccgo` (tested with `gccgo 8.2.1`). * The `sdl2` package: go get github.com/veandco/go-sdl2/sdl Building: make Running: ./main ================================================ FILE: gccgo/go.mod ================================================ module github.com/xyproto/sdl2-examples/gccgo go 1.18 require github.com/veandco/go-sdl2 v0.4.36 ================================================ FILE: gccgo/go.sum ================================================ github.com/veandco/go-sdl2 v0.4.36 h1:Ltydev536rRQodmIrTWFZ3dRp5A+/6t5CYvbi4Kvia0= github.com/veandco/go-sdl2 v0.4.36/go.mod h1:OROqMhHD43nT4/i9crJukyVecjPNYYuCofep6SNiAjY= ================================================ FILE: gccgo/main.go ================================================ package main import ( "log" "path/filepath" "github.com/veandco/go-sdl2/img" "github.com/veandco/go-sdl2/sdl" ) func main() { // Initialize if err := sdl.Init(sdl.INIT_EVERYTHING); err != nil { log.Fatalln("Init Error:", err) } // Make sure to quit when the function returns defer sdl.Quit() // Create the window win, err := sdl.CreateWindow("Hello World!", 100, 100, 620, 387, sdl.WINDOW_SHOWN) if err != nil { log.Fatalln("CreateWindow Error:", err) } defer win.Destroy() // Create a renderer ren, err := sdl.CreateRenderer(win, -1, sdl.RENDERER_ACCELERATED|sdl.RENDERER_PRESENTVSYNC) if err != nil { log.Fatalln("CreateRenderer Error:", err) } defer ren.Destroy() // Load the image as a texture tex, err := img.LoadTexture(ren, filepath.Join("..", "img", "grumpy-cat.png")) if err != nil { log.Fatalln("LoadTexture Error:", err) } defer tex.Destroy() for i := 0; i < 20; i++ { // Clear the renderer and display the image/texture ren.Clear() ren.Copy(tex, nil, nil) ren.Present() // Wait 100 ms sdl.Delay(100) } } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/CONTRIBUTORS.md ================================================ Contributors ============ Here's the list of contributors with their respective Github URLs. * [Jacky Boen](https://github.com/jackyb) * [HardWareGuy](https://github.com/HardWareGuy) * [akovaski](https://github.com/akovaski) * [Jeromy Johnson](https://github.com/whyrusleeping) * [Cai Lei](https://github.com/ccll) * [Arne Döring](https://github.com/krux02) * [Marcus von Appen](https://github.com/marcusva) * [Tom Murray](https://github.com/TomMurray) * [Ian Davis](https://github.com/iand) * [hschendel](https://github.com/hschendel) * [Ingo Oeser](https://github.com/nightlyone) * [nlordell](https://github.com/nlordell) * [Ben Davies](https://github.com/JalfResi) * [Bastien Dejean](https://github.com/baskerville) * [Pirmin Tapken](https://github.com/PirminTapken) * [Robert Lillack](https://github.com/roblillack) * [Marcell Jusztin](https://github.com/morcmarc) * [Stan Schwertly](https://github.com/Stantheman) * [Michael Vetter](https://github.com/jubalh) * [Tom Fogal](https://github.com/tfogal) * [Philipp Meinen](https://github.com/PhiCode) * [Thomas McGrew](https://github.com/mcgrew) * [Geoff Catlin](https://github.com/gcatlin) * [Schobers](https://github.com/Schobers) * [Jan Tuitman](https://github.com/jantuitman) * [Nick Powell](https://github.com/THUNDERGROOVE) * [Steven R. Wiley](https://github.com/srwiley) * [Franco Lazzarino](https://github.com/flazz) * [Jason Alan Palmer](https://github.com/jalan) * [Seuk Won Kang](https://github.com/kasworld) * [Brandon Mulcahy](https://github.com/jangler) * [Tim Anema](https://github.com/tanema) * [Tyler Compton](https://github.com/velovix) * [Nicolas Hess](https://github.com/n0dev) * [Stephen Noonan](https://github.com/tycho) * [Guilherme Freitas Nemeth](https://github.com/glhrmfrts) * [Charney Kaye](https://github.com/charneykaye) * [Lars Scheme](https://github.com/gonutz) * [Emil Laine](https://github.com/emlai) * [Sergey Parshukov](https://github.com/jBugman) * [Casey DeLorme](https://github.com/cdelorme) * [Andreas T. Jonsson](https://github.com/andreas-jonsson) * [Milan Nikolic](https://github.com/gen2brain) * [Mike Gerow](https://github.com/gerow) * [Lilis Iskandar](https://github.com/veeableful) * [tfriedel6](https://github.com/tfriedel6) * [Eric Bronner](https://github.com/MoonWatcher582) * [Julien Castelain](https://github.com/julien) * [Robert Wallis](https://github.com/robert-wallis) * [Chae-Young Song](https://github.com/chaeyoungsong) * [Robert Wallis](https://github.com/robert-wallis) * [Lennart Buhl](https://github.com/r41d) * [Giovanni Bajo](https://github.com/rasky) * [Laurent Vaucher](https://github.com/slowfrog) * [Mike](https://github.com/barbeque) * [Tomas Virgl](https://github.com/tvi) * [Aye Aye Maung](https://github.com/ZeroXLR) * [Anton Malashin](https://github.com/malashin) * [John Perkins](https://github.com/mpath) * [jclc](https://github.com/jclc) * [flga](https://github.com/flga) _if anyone is missing, let me know!.. or you can add yourself in :)_ ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/LICENSE ================================================ Copyright (c) 2013, Go-SDL2 Authors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Go-SDL2 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/_libs/dummy.go ================================================ package dummy ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/img/sdl_image.go ================================================ // Package img is a simple library to load images of various formats as SDL surfaces. package img //#include //#include "sdl_image_wrapper.h" import "C" import "unsafe" import "errors" import "github.com/veandco/go-sdl2/sdl" // Flags which may be passed to img.Init() to load support of image formats, can be bitwise OR'd together. const ( INIT_JPG = 0x00000001 // JPG INIT_PNG = 0x00000002 // PNG INIT_TIF = 0x00000004 // TIF INIT_WEBP = 0x00000008 // WebP ) // LinkedVersion returns the version of the dynamically linked SDL_image library. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_7.html) func LinkedVersion() *sdl.Version { return (*sdl.Version)(unsafe.Pointer(C.IMG_Linked_Version())) } // Init loads dynamic libraries and prepares them for use. Flags should be one or more flags from IMG_InitFlags OR'd together. It returns the flags successfully initialized, or 0 on failure. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_8.html) func Init(flags int) error { _flags := (C.int)(flags) ret := int(C.IMG_Init(_flags)) if ret == 0 { return GetError() } return nil } // Quit unloads libraries loaded with img.Init(). // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_9.html) func Quit() { C.IMG_Quit() } // GetError returns the last error that occurred, or an empty string if there hasn't been an error message set since the last call to sdl.ClearError(). // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_45.html) func GetError() error { e := C.IMG_GetError() if e == nil { return nil } return errors.New(C.GoString(e)) } // LoadTypedRW loads an image from an SDL data source. The 'type' may be one of: "BMP", "GIF", "PNG", etc. If the image format supports a transparent pixel, SDL will set the colorkey for the surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_13.html) func LoadTypedRW(src *sdl.RWops, freesrc bool, type_ string) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _freesrc := (C.int)(sdl.Btoi(freesrc)) _type := C.CString(type_) defer C.free(unsafe.Pointer(_type)) _surface := C.IMG_LoadTyped_RW(_src, _freesrc, _type) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // Load loads a file for use as an image in a new surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_11.html) func Load(file string) (*sdl.Surface, error) { _file := C.CString(file) defer C.free(unsafe.Pointer(_file)) _surface := C.IMG_Load(_file) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadRW loads an image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_12.html) func LoadRW(src *sdl.RWops, freesrc bool) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _freesrc := (C.int)(sdl.Btoi(freesrc)) _surface := C.IMG_Load_RW(_src, _freesrc) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadTexture loads an image directly into a render texture. func LoadTexture(renderer *sdl.Renderer, file string) (*sdl.Texture, error) { _renderer := (*C.SDL_Renderer)(unsafe.Pointer(renderer)) _file := C.CString(file) defer C.free(unsafe.Pointer(_file)) _surface := C.IMG_LoadTexture(_renderer, _file) if _surface == nil { return nil, GetError() } return (*sdl.Texture)(unsafe.Pointer(_surface)), nil } // LoadTextureRW loads an image from an SDL data source directly into a render texture. func LoadTextureRW(renderer *sdl.Renderer, src *sdl.RWops, freesrc bool) (*sdl.Texture, error) { _renderer := (*C.SDL_Renderer)(unsafe.Pointer(renderer)) _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _freesrc := (C.int)(sdl.Btoi(freesrc)) _surface := C.IMG_LoadTexture_RW(_renderer, _src, _freesrc) if _surface == nil { return nil, GetError() } return (*sdl.Texture)(unsafe.Pointer(_surface)), nil } // IsICO reports whether ICO format is supported and image data is readable as an ICO. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_31.html) func IsICO(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isICO(_src)) > 0 } // IsCUR reports whether CUR format is supported and image data is readable as a CUR. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_30.html) func IsCUR(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isCUR(_src)) > 0 } // IsBMP reports whether BMP format is supported and image data is readable as a BMP. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_32.html) func IsBMP(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isBMP(_src)) > 0 } // IsGIF reports whether GIF format is supported and image data is readable as a GIF. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_37.html) func IsGIF(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isGIF(_src)) > 0 } // IsJPG reports whether JPG format is supported and image data is readable as a JPG. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_38.html) func IsJPG(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isJPG(_src)) > 0 } // IsLBM reports whether LBM format is supported and image data is readable as an LBM. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_41.html) func IsLBM(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isLBM(_src)) > 0 } // IsPCX reports whether PCX format is supported and image data is readable as a PCX. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_36.html) func IsPCX(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isPCX(_src)) > 0 } // IsPNG reports whether PNG format is supported and image data is readable as a PNG. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_40.html) func IsPNG(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isPNG(_src)) > 0 } // IsPNM reports whether PNM format is supported and image data is readable as a PNM. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_33.html) func IsPNM(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isPNM(_src)) > 0 } // IsTIF reports whether TIF format is supported and image data is readable as a TIF. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_39.html) func IsTIF(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isTIF(_src)) > 0 } // IsXCF reports whether XCF format is supported and image data is readable as an XCF. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_35.html) func IsXCF(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isXCF(_src)) > 0 } // IsXPM reports whether XPM format is supported and image data is readable as an XPM. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_34.html) func IsXPM(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isXPM(_src)) > 0 } // IsXV reports whether XV format is supported and image data is readable as an XV thumbnail. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_42.html) func IsXV(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isXV(_src)) > 0 } // IsWEBP reports whether WEBP format is supported and image data is readable as a WEBP. func IsWEBP(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isWEBP(_src)) > 0 } // LoadICORW loads an ICO image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_15.html) func LoadICORW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadICO_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadCURRW loads a CUR image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_14.html) func LoadCURRW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadCUR_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadBMPRW loads a BMP image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_16.html) func LoadBMPRW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadBMP_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadGIFRW loads a GIF image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_21.html) func LoadGIFRW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadGIF_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadJPGRW loads a JPG image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_22.html) func LoadJPGRW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadJPG_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadLBMRW loads an LBM image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_26.html) func LoadLBMRW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadLBM_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadPCXRW loads a PCX image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_20.html) func LoadPCXRW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadPCX_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadPNGRW loads a PNG image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_24.html) func LoadPNGRW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadPNG_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadPNMRW loads a PNM image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_17.html) func LoadPNMRW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadPNM_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadTGARW loads a TGA image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_25.html) func LoadTGARW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadTGA_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadTIFRW loads a TIF image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_23.html) func LoadTIFRW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadTIF_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadXCFRW loads an XCF image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_19.html) func LoadXCFRW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadXCF_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadXPMRW loads an XPM image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_18.html) func LoadXPMRW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadXPM_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadXVRW loads an XV thumbnail image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_27.html) func LoadXVRW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadXV_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadWEBPRW loads a WEBP image from an SDL data source for use as a surface. func LoadWEBPRW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadWEBP_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // ReadXPMFromArray loads an XPM image from xpm data for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_28.html) func ReadXPMFromArray(xpm string) (*sdl.Surface, error) { _xpm := C.CString(xpm) defer C.free(unsafe.Pointer(_xpm)) _surface := C.IMG_ReadXPMFromArray(&_xpm) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // SavePNG saves a surface as PNG file. func SavePNG(surface *sdl.Surface, file string) error { _surface := (*C.SDL_Surface)(unsafe.Pointer(surface)) _file := C.CString(file) defer C.free(unsafe.Pointer(_file)) _ret := C.IMG_SavePNG(_surface, _file) if _ret < 0 { return GetError() } return nil } // SavePNGRW saves a surface to an SDL data source. func SavePNGRW(surface *sdl.Surface, dst *sdl.RWops, freedst int) error { _surface := (*C.SDL_Surface)(unsafe.Pointer(surface)) _dst := (*C.SDL_RWops)(unsafe.Pointer(dst)) _freedst := (C.int)(freedst) _ret := C.IMG_SavePNG_RW(_surface, _dst, _freedst) if _ret < 0 { return GetError() } return nil } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/img/sdl_image_cgo.go ================================================ // +build !static package img //#cgo linux freebsd darwin pkg-config: sdl2 //#cgo linux freebsd darwin LDFLAGS: -lSDL2_image //#cgo windows LDFLAGS: -lSDL2 -lSDL2_image import "C" ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/img/sdl_image_cgo_static.go ================================================ // +build static package img //#cgo CFLAGS: -I${SRCDIR}/../_libs/include -I${SRCDIR}/../_libs/include/SDL2 //#cgo LDFLAGS: -L${SRCDIR}/../_libs //#cgo linux,386 LDFLAGS: -lSDL2_image_linux_386 -Wl,--no-undefined -lpng_linux_386 -ljpeg_linux_386 -lSDL2_linux_386 -lm -ldl -lz -lasound -lm -ldl -lpthread -lX11 -lXext -lXcursor -lXinerama -lXi -lXrandr -lXss -lXxf86vm -lpthread -lrt //#cgo linux,amd64 LDFLAGS: -lSDL2_image_linux_amd64 -Wl,--no-undefined -lpng_linux_amd64 -ljpeg_linux_amd64 -lSDL2_linux_amd64 -lm -ldl -lz -lasound -lm -ldl -lpthread -lX11 -lXext -lXcursor -lXinerama -lXi -lXrandr -lXss -lXxf86vm -lpthread -lrt //#cgo windows,386 LDFLAGS: -lSDL2_image_windows_386 -Wl,--no-undefined -lpng_windows_386 -ljpeg_windows_386 -lz_windows_386 -lSDL2_windows_386 -lSDL2main_windows_386 -Wl,--no-undefined -lm -ldinput8 -ldxguid -ldxerr8 -luser32 -lgdi32 -lwinmm -limm32 -lole32 -loleaut32 -lshell32 -lversion -luuid -lsetupapi -static-libgcc //#cgo windows,amd64 LDFLAGS: -lSDL2_image_windows_amd64 -Wl,--no-undefined -lpng_windows_amd64 -ljpeg_windows_amd64 -lz_windows_amd64 -lSDL2_windows_amd64 -lSDL2main_windows_amd64 -Wl,--no-undefined -lm -ldinput8 -ldxguid -ldxerr8 -luser32 -lgdi32 -lwinmm -limm32 -lole32 -loleaut32 -lshell32 -lversion -luuid -lsetupapi -static-libgcc //#cgo darwin,amd64 LDFLAGS: -lSDL2_image_darwin_amd64 -lSDL2_darwin_amd64 -lpng_darwin_amd64 -ljpeg_darwin_amd64 -lm -lz -liconv -Wl,-framework,CoreAudio -Wl,-framework,AudioToolbox -Wl,-framework,ForceFeedback -lobjc -Wl,-framework,CoreVideo -Wl,-framework,Cocoa -Wl,-framework,Carbon -Wl,-framework,IOKit -Wl,-framework,Metal //#cgo darwin,arm64 LDFLAGS: -lSDL2_image_darwin_arm64 -lSDL2_darwin_arm64 -lpng_darwin_arm64 -ljpeg_darwin_arm64 -lm -lz -liconv -Wl,-framework,CoreAudio -Wl,-framework,AudioToolbox -Wl,-framework,ForceFeedback -lobjc -Wl,-framework,CoreVideo -Wl,-framework,Cocoa -Wl,-framework,Carbon -Wl,-framework,IOKit -Wl,-framework,Metal //#cgo android,arm LDFLAGS: -lSDL2_image_android_arm -Wl,--no-undefined -lpng_android_arm -ljpeg_android_arm -lSDL2_android_arm -lm -ldl -lz -llog -landroid -lGLESv2 -lGLESv1_CM //#cgo linux,arm,!android LDFLAGS: -L/opt/vc/lib -L/opt/vc/lib64 -lSDL2_image_linux_arm -Wl,--no-undefined -lpng_linux_arm -ljpeg_linux_arm -lSDL2_linux_arm -lm -ldl -lz -liconv -lbcm_host -lvcos -lvchiq_arm -pthread import "C" ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/img/sdl_image_wrapper.h ================================================ #if defined(__WIN32) #include #include #else #include #endif ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/TODO.md ================================================ ## 2.0.16 [x] SDL_FlashWindow() to get a user’s attention [x] SDL_GetAudioDeviceSpec() to get the preferred audio format of a device [x] SDL_SetWindowAlwaysOnTop() to dynamically change the SDL_WINDOW_ALWAYS_ON_TOP flag for a window [x] SDL_SetWindowKeyboardGrab() to support grabbing the keyboard independently of the mouse [x] SDL_SoftStretchLinear() to do bilinear scaling between 32-bit software surfaces [x] SDL_UpdateNVTexture() to update streaming NV12/21 textures [x] SDL_GameControllerSendEffect() and SDL_JoystickSendEffect() to allow sending custom trigger effects to the DualSense controller [x] SDL_GameControllerGetSensorDataRate() to get the sensor data rate for PlayStation and Nintendo Switch controllers ### Windows [?] SDL_SetWindowsMessageHook() to set a function that is called for all Windows messages [?] SDL_RenderGetD3D11Device() to get the D3D11 device used by the SDL renderer ### Linux [x] SDL_HINT_AUDIO_INCLUDE_MONITORS to control whether PulseAudio recording should include monitor devices [x] SDL_HINT_AUDIO_DEVICE_STREAM_ROLE to describe the role of your application for audio control panels ### Android: [?] SDL_AndroidShowToast() to show a lightweight notification ## 2.0.14 [x] SDL_GameControllerGetSerial() [x] SDL_GameControllerHasAxis() [x] SDL_GameControllerHasButton() [x] SDL_GameControllerGetNumTouchpads() [x] SDL_GameControllerGetNumTouchpadFingers() [x] SDL_GameControllerGetTouchpadFinger() [x] SDL_GameControllerHasSensor() [x] SDL_GameControllerSetSensorEnabled() [x] SDL_GameControllerIsSensorEnabled() [x] SDL_GameControllerGetSensorData [x] SDL_GameControllerRumbleTriggers() [x] SDL_GameControllerHasLED() [x] SDL_GameControllerSetLED() [x] SDL_JoystickGetSerial() [x] SDL_JoystickRumbleTriggers() [x] SDL_JoystickHasLED() [x] SDL_JoystickSetLED() [x] SDL_JoystickAttachVirtual() [x] SDL_JoystickDetachVirtual() [x] SDL_JoystickIsVirtual() [x] SDL_JoystickSetVirtualAxis() [x] SDL_JoystickSetVirtualButton() [x] SDL_JoystickSetVirtualHat() [x] SDL_LockSensors() [x] SDL_UnlockSensors() [x] SDL_HAPTIC_STEERING_AXIS [x] SDL_GetPreferredLocales() [x] SDL_OpenURL() [x] SDL_HasSurfaceRLE() [x] SDL_SIMDRealloc() [x] SDL_GetErrorMsg() [x] SDL_Metal_GetLayer() [x] SDL_Metal_GetDrawableSize() [x] SDL_HINT_JOYSTICK_HIDAPI_PS5 [x] SDL_HINT_MOUSE_RELATIVE_SCALING [x] SDL_HINT_PREFERRED_LOCALES [x] SDL_HINT_JOYSTICK_RAWINPUT [x] SDL_HINT_JOYSTICK_HIDAPI_CORRELATE_XINPUT [x] SDL_HINT_AUDIO_DEVICE_APP_NAME [x] SDL_HINT_AUDIO_DEVICE_STREAM_NAME [x] SDL_HINT_LINUX_JOYSTICK_DEADZONES [x] SDL_HINT_THREAD_PRIORITY_POLICY [x] SDL_HINT_THREAD_FORCE_REALTIME_TIME_CRITICAL [x] SDL_HINT_ANDROID_BLOCK_ON_PAUSE_PAUSEAUDIO [x] SDL_HINT_EMSCRIPTEN_ASYNCIFY [x] SDL_PIXELFORMAT_XRGB4444 [x] SDL_PIXELFORMAT_XBGR4444 [x] SDL_PIXELFORMAT_XRGB1555 [x] SDL_PIXELFORMAT_XBGR1555 [x] SDL_PIXELFORMAT_XRGB8888 [x] SDL_PIXELFORMAT_XBGR8888 [x] SDL_WINDOW_METAL [x] SDL_AndroidRequestPermission() ## 2.0.12 [x] SDL_GameControllerTypeForIndex [x] SDL_GameControllerGetType [x] SDL_GameControllerFromPlayerIndex [x] SDL_GameControllerSetPlayerIndex [x] SDL_JoystickFromPlayerIndex [x] SDL_JoystickSetPlayerIndex [x] SDL_GetTextureScaleMode [x] SDL_SetTextureScaleMode [x] SDL_LockTextureToSurface [x] SDL_BLENDMODE_MUL [x] SDL_TouchFingerEvent update [x] SDL_HasARMSIMD [x] SDL_HINT_DISPLAY_USABLE_BOUNDS [x] SDL_HINT_GAMECONTROLLERTYPE [x] SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS [x] SDL_HINT_JOYSTICK_HIDAPI_GAMECUBE [x] SDL_HINT_VIDEO_X11_WINDOW_VISUALID [x] SDL_HINT_VIDEO_X11_FORCE_EGL [x] SDL_Metal_CreateView [x] SDL_Metal_DestroyView [x] SDL_GetAndroidSDKVersion ## 2.0.10 [x] SDL_SIMDGetAlignment [x] SDL_SIMDAlloc [x] SDL_SIMDFree [x] SDL_RenderDrawPointF [x] SDL_RenderDrawPointsF [x] SDL_RenderDrawLineF [x] SDL_RenderDrawLinesF [x] SDL_RenderDrawRectF [x] SDL_RenderDrawRectsF [x] SDL_RenderFillRectF [x] SDL_RenderFillRectsF [x] SDL_RenderCopyF [x] SDL_RenderCopyExF [x] SDL_GetTouchDeviceType [x] SDL_RenderFlush [x] SDL_HINT_RENDER_BATCHING [x] SDL_HINT_EVENT_LOGGING [x] SDL_HINT_GAMECONTROLLERCONFIG_FILE [x] SDL_HINT_MOUSE_TOUCH_EVENTS ## 2.0.9 [x] SDL_SENSORUPDATE [x] SDL_DISPLAYEVENT [x] SDL_JoystickGetDevicePlayerIndex [x] SDL_JoystickGetPlayerIndex [x] SDL_GameControllerGetPlayerIndex [x] SDL_GameControllerRumble [x] SDL_JoystickRumble [x] SDL_GameControllerMappingForDeviceIndex [x] SDL_HINT_MOUSE_DOUBLE_CLICK_TIME [x] SDL_HINT_MOUSE_DOUBLE_CLICK_RADIUS [x] SDL_HasColorKey [x] SDL_HasAVX512F [x] SDL_IsTablet [?] SDL_THREAD_PRIORITY_TIME_CRITICAL ## 2.0.8 ### Hints [x] SDL_HINT_IOS_HIDE_HOME_INDICATOR [x] SDL_HINT_RETURN_KEY_HIDES_IME [x] SDL_HINT_TV_REMOTE_AS_JOYSTICK [x] SDL_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR [x] SDL_HINT_VIDEO_DOUBLE_BUFFER ### Surface [x] SDL_SetYUVConversionMode() [x] SDL_GetYUVConversionMode() ### Android [x] SDL_IsAndroidTV() ### Mac OS X / iOS / tvOS [x] SDL_RenderGetMetalLayer() [x] SDL_RenderGetMetalCommandEncoder() ### Windows UWP [ ] SDL_WinRTGetDeviceFamily() ## 2.0.7 ### General Audio - [x] SDL_NewAudioStream() - [x] SDL_AudioStreamPut() - [x] SDL_AudioStreamGet() - [x] SDL_AudioStreamAvailable() - [x] SDL_AudioStreamFlush() - [x] SDL_AudioStreamClear() - [x] SDL_FreeAudioStream() Joystick - [x] SDL_LockJoysticks() - [x] SDL_UnlockJoysticks() Stdinc - [ ] SDL_GetMemoryFunctions() - [ ] SDL_SetMemoryFunctions() - [ ] SDL_GetNumAllocations() ## 2.0.6 ### General Blend Mode - [x] SDL_ComposeCustomBlendMode() CPU Info - [x] SDL_HasNEON() Game Controller - [x] SDL_GameControllerGetVendor() - [x] SDL_GameControllerGetProduct() - [x] SDL_GameControllerGetProductVersion() - [x] SDL_GameControllerNumMappings() - [x] SDL_GameControllerMappingForIndex() Hints - [x] SDL_HINT_AUDIO_RESAMPLING_MODE - [x] SDL_HINT_RENDER_LOGICAL_SIZE_MODE - [x] SDL_HINT_MOUSE_NORMAL_SPEED_SCALE - [x] SDL_HINT_MOUSE_RELATIVE_SPEED_SCALE - [x] SDL_HINT_TOUCH_MOUSE_EVENTS Joystick - [x] SDL_JoystickGetDeviceVendor() - [x] SDL_JoystickGetDeviceProduct() - [x] SDL_JoystickGetDeviceProductVersion() - [x] SDL_JoystickGetDeviceType() - [x] SDL_JoystickGetDeviceInstanceID() - [x] SDL_JoystickGetVendor() - [x] SDL_JoystickGetProduct() - [x] SDL_JoystickGetProductVersion() - [x] SDL_JoystickGetType() - [x] SDL_JoystickGetAxisInitialState() RW Ops - [x] SDL_LoadFile() - [x] SDL_LoadFile_RW() Surface - [x] SDL_DuplicateSurface() Vulkan - [x] SDL_Vulkan_LoadLibrary() - [x] SDL_Vulkan_GetVkGetInstanceProcAddr() - [x] SDL_Vulkan_GetInstanceExtensions() - [x] SDL_Vulkan_CreateSurface() - [x] SDL_Vulkan_GetDrawableSize() - [x] SDL_Vulkan_UnloadLibrary() ### Windows Hints - [x] SDL_HINT_WINDOWS_INTRESOURCE_ICON - [x] SDL_HINT_WINDOWS_INTRESOURCE_ICON_SMALL ## Miscellaneous - [ ] Add ability to set window title bar color on runtime ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/audio.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,4)) #if defined(WARN_OUTDATED) #pragma message("SDL_QueueAudio is not supported before SDL 2.0.4") #endif static int SDL_QueueAudio(SDL_AudioDeviceID dev, const void *data, Uint32 len) { return -1; } static Uint32 SDL_GetQueuedAudioSize(SDL_AudioDeviceID dev_id) { return 0; } static void SDL_ClearQueuedAudio(SDL_AudioDeviceID dev) { } #endif #if !(SDL_VERSION_ATLEAST(2,0,5)) #if defined(WARN_OUTDATED) #pragma message("SDL_DequeueAudio is not supported before SDL 2.0.5") #endif static int SDL_DequeueAudio(SDL_AudioDeviceID dev, const void *data, Uint32 len) { return -1; } #endif #if !(SDL_VERSION_ATLEAST(2,0,7)) struct _SDL_AudioStream; typedef struct _SDL_AudioStream SDL_AudioStream; #if defined(WARN_OUTDATED) #pragma message("SDL_NewAudioStream is not supported before SDL 2.0.7") #endif static SDL_AudioStream * SDL_NewAudioStream(const SDL_AudioFormat src_format, const Uint8 src_channels, const int src_rate, const SDL_AudioFormat dst_format, const Uint8 dst_channels, const int dst_rate) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_AudioStreamPut is not supported before SDL 2.0.7") #endif static int SDL_AudioStreamPut(SDL_AudioStream *stream, const void *buf, int len) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_AudioStreamGet is not supported before SDL 2.0.7") #endif static int SDL_AudioStreamGet(SDL_AudioStream *stream, void *buf, int len) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_AudioStreamAvailable is not supported before SDL 2.0.7") #endif static int SDL_AudioStreamAvailable(SDL_AudioStream *stream) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_AudioStreamFlush is not supported before SDL 2.0.7") #endif static int SDL_AudioStreamFlush(SDL_AudioStream *stream) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_AudioStreamClear is not supported before SDL 2.0.7") #endif static int SDL_AudioStreamClear(SDL_AudioStream *stream) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_FreeAudioStream is not supported before SDL 2.0.7") #endif static void SDL_FreeAudioStream(SDL_AudioStream *stream) { } #endif #if !(SDL_VERSION_ATLEAST(2,0,16)) #if defined(WARN_OUTDATED) #pragma message("SDL_GetAudioDeviceSpec is not supported before SDL 2.0.16") #endif static int SDL_GetAudioDeviceSpec(int index, int iscapture, SDL_AudioSpec *spec) { return -1; } #endif */ import "C" import ( "reflect" "unsafe" ) // Audio format masks. // (https://wiki.libsdl.org/SDL_AudioFormat) const ( AUDIO_MASK_BITSIZE = C.SDL_AUDIO_MASK_BITSIZE // (0xFF) AUDIO_MASK_DATATYPE = C.SDL_AUDIO_MASK_DATATYPE // (1<<8) AUDIO_MASK_ENDIAN = C.SDL_AUDIO_MASK_ENDIAN // (1<<12) AUDIO_MASK_SIGNED = C.SDL_AUDIO_MASK_SIGNED // (1<<15) ) // Audio format values. // (https://wiki.libsdl.org/SDL_AudioFormat) const ( AUDIO_S8 = C.AUDIO_S8 // signed 8-bit samples AUDIO_U8 = C.AUDIO_U8 // unsigned 8-bit samples AUDIO_S16LSB = C.AUDIO_S16LSB // signed 16-bit samples in little-endian byte order AUDIO_S16MSB = C.AUDIO_S16MSB // signed 16-bit samples in big-endian byte order AUDIO_S16SYS = C.AUDIO_S16SYS // signed 16-bit samples in native byte order AUDIO_S16 = C.AUDIO_S16 // AUDIO_S16LSB AUDIO_U16LSB = C.AUDIO_U16LSB // unsigned 16-bit samples in little-endian byte order AUDIO_U16MSB = C.AUDIO_U16MSB // unsigned 16-bit samples in big-endian byte order AUDIO_U16SYS = C.AUDIO_U16SYS // unsigned 16-bit samples in native byte order AUDIO_U16 = C.AUDIO_U16 // AUDIO_U16LSB AUDIO_S32LSB = C.AUDIO_S32LSB // 32-bit integer samples in little-endian byte order AUDIO_S32MSB = C.AUDIO_S32MSB // 32-bit integer samples in big-endian byte order AUDIO_S32SYS = C.AUDIO_S32SYS // 32-bit integer samples in native byte order AUDIO_S32 = C.AUDIO_S32 // AUDIO_S32LSB AUDIO_F32LSB = C.AUDIO_F32LSB // 32-bit floating point samples in little-endian byte order AUDIO_F32MSB = C.AUDIO_F32MSB // 32-bit floating point samples in big-endian byte order AUDIO_F32SYS = C.AUDIO_F32SYS // 32-bit floating point samples in native byte order AUDIO_F32 = C.AUDIO_F32 // AUDIO_F32LSB ) // AllowedChanges flags specify how SDL should behave when a device cannot offer a specific feature. If the application requests a feature that the hardware doesn't offer, SDL will always try to get the closest equivalent. Used in OpenAudioDevice(). // (https://wiki.libsdl.org/SDL_OpenAudioDevice) const ( AUDIO_ALLOW_FREQUENCY_CHANGE = C.SDL_AUDIO_ALLOW_FREQUENCY_CHANGE AUDIO_ALLOW_FORMAT_CHANGE = C.SDL_AUDIO_ALLOW_FORMAT_CHANGE AUDIO_ALLOW_CHANNELS_CHANGE = C.SDL_AUDIO_ALLOW_CHANNELS_CHANGE AUDIO_ALLOW_ANY_CHANGE = C.SDL_AUDIO_ALLOW_ANY_CHANGE ) // An enumeration of audio device states used in GetAudioDeviceStatus() and GetAudioStatus(). // (https://wiki.libsdl.org/SDL_AudioStatus) const ( AUDIO_STOPPED AudioStatus = C.SDL_AUDIO_STOPPED // audio device is stopped AUDIO_PLAYING = C.SDL_AUDIO_PLAYING // audio device is playing AUDIO_PAUSED = C.SDL_AUDIO_PAUSED // audio device is paused ) // MIX_MAXVOLUME is the full audio volume value used in MixAudioFormat() and AudioFormat(). // (https://wiki.libsdl.org/SDL_MixAudioFormat) const MIX_MAXVOLUME = C.SDL_MIX_MAXVOLUME // full audio volume // AudioFormat is an enumeration of audio formats. // (https://wiki.libsdl.org/SDL_AudioFormat) type AudioFormat uint16 // AudioCallback is a function to call when the audio device needs more data.` // (https://wiki.libsdl.org/SDL_AudioSpec) type AudioCallback C.SDL_AudioCallback // AudioFilter is the filter list used in AudioCVT() (internal use) // (https://wiki.libsdl.org/SDL_AudioCVT) type AudioFilter C.SDL_AudioFilter // AudioDeviceID is ID of an audio device previously opened with OpenAudioDevice(). // (https://wiki.libsdl.org/SDL_OpenAudioDevice) type AudioDeviceID uint32 // AudioStatus is an enumeration of audio device states. // (https://wiki.libsdl.org/SDL_AudioStatus) type AudioStatus uint32 type cAudioStatus C.SDL_AudioStatus // AudioSpec contains the audio output format. It also contains a callback that is called when the audio device needs more data. // (https://wiki.libsdl.org/SDL_AudioSpec) type AudioSpec struct { Freq int32 // DSP frequency (samples per second) Format AudioFormat // audio data format Channels uint8 // number of separate sound channels Silence uint8 // audio buffer silence value (calculated) Samples uint16 // audio buffer size in samples (power of 2) _ uint16 // padding Size uint32 // audio buffer size in bytes (calculated) Callback AudioCallback // the function to call when the audio device needs more data UserData unsafe.Pointer // a pointer that is passed to callback (otherwise ignored by SDL) } type cAudioSpec C.SDL_AudioSpec // AudioCVT contains audio data conversion information. // (https://wiki.libsdl.org/SDL_AudioCVT) type AudioCVT struct { Needed int32 // set to 1 if conversion possible SrcFormat AudioFormat // source audio format DstFormat AudioFormat // target audio format RateIncr float64 // rate conversion increment Buf unsafe.Pointer // the buffer to hold entire audio data. Use AudioCVT.BufAsSlice() for access via a Go slice Len int32 // length of original audio buffer LenCVT int32 // length of converted audio buffer LenMult int32 // buf must be len*len_mult big LenRatio float64 // given len, final size is len*len_ratio filters [10]AudioFilter // filter list (internal use) filterIndex int32 // current audio conversion function (internal use) } type cAudioCVT C.SDL_AudioCVT // AudioStream is a new audio conversion interface. // (https://wiki.libsdl.org/SDL_AudioStream) type AudioStream C.SDL_AudioStream func (fmt AudioFormat) c() C.SDL_AudioFormat { return C.SDL_AudioFormat(fmt) } func (id AudioDeviceID) c() C.SDL_AudioDeviceID { return C.SDL_AudioDeviceID(id) } func (as *AudioSpec) cptr() *C.SDL_AudioSpec { return (*C.SDL_AudioSpec)(unsafe.Pointer(as)) } func (cvt *AudioCVT) cptr() *C.SDL_AudioCVT { return (*C.SDL_AudioCVT)(unsafe.Pointer(cvt)) } func (stream *AudioStream) cptr() *C.SDL_AudioStream { return (*C.SDL_AudioStream)(unsafe.Pointer(stream)) } // BitSize returns audio formats bit size. // (https://wiki.libsdl.org/SDL_AudioFormat) func (fmt AudioFormat) BitSize() uint8 { return uint8(fmt & AUDIO_MASK_BITSIZE) } // IsFloat reports whether audio format is float. // (https://wiki.libsdl.org/SDL_AudioFormat) func (fmt AudioFormat) IsFloat() bool { return (fmt & AUDIO_MASK_DATATYPE) > 0 } // IsBigEndian reports whether audio format is big-endian. // (https://wiki.libsdl.org/SDL_AudioFormat) func (fmt AudioFormat) IsBigEndian() bool { return (fmt & AUDIO_MASK_ENDIAN) > 0 } // IsSigned reports whether audio format is signed. // (https://wiki.libsdl.org/SDL_AudioFormat) func (fmt AudioFormat) IsSigned() bool { return (fmt & AUDIO_MASK_SIGNED) > 0 } // IsInt reports whether audio format is integer. // (https://wiki.libsdl.org/SDL_AudioFormat) func (fmt AudioFormat) IsInt() bool { return !fmt.IsFloat() } // IsLittleEndian reports whether audio format is little-endian. // (https://wiki.libsdl.org/SDL_AudioFormat) func (fmt AudioFormat) IsLittleEndian() bool { return !fmt.IsBigEndian() } // IsUnsigned reports whether audio format is unsigned. // (https://wiki.libsdl.org/SDL_AudioFormat) func (fmt AudioFormat) IsUnsigned() bool { return !fmt.IsSigned() } // AllocBuf allocates the requested memory for AudioCVT buffer. func (cvt *AudioCVT) AllocBuf(size uintptr) { cvt.Buf = C.malloc(C.size_t(size)) } // FreeBuf deallocates the memory previously allocated from AudioCVT buffer. func (cvt *AudioCVT) FreeBuf() { C.free(cvt.Buf) } // BufAsSlice returns AudioCVT.buf as byte slice. // NOTE: Must be used after ConvertAudio() because it uses LenCVT as slice length. func (cvt AudioCVT) BufAsSlice() []byte { var b []byte sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b)) sliceHeader.Len = int(cvt.LenCVT) sliceHeader.Cap = int(cvt.Len * cvt.LenMult) sliceHeader.Data = uintptr(unsafe.Pointer(cvt.Buf)) return b } // GetNumAudioDrivers returns the number of built-in audio drivers. // (https://wiki.libsdl.org/SDL_GetNumAudioDrivers) func GetNumAudioDrivers() int { return int(C.SDL_GetNumAudioDrivers()) } // GetAudioDriver returns the name of a built in audio driver. // (https://wiki.libsdl.org/SDL_GetAudioDriver) func GetAudioDriver(index int) string { return string(C.GoString(C.SDL_GetAudioDriver(C.int(index)))) } // AudioInit initializes a particular audio driver. // (https://wiki.libsdl.org/SDL_AudioInit) func AudioInit(driverName string) error { _driverName := C.CString(driverName) defer C.free(unsafe.Pointer(_driverName)) if C.SDL_AudioInit(_driverName) != 0 { return GetError() } return nil } // AudioQuit shuts down audio if you initialized it with AudioInit(). // (https://wiki.libsdl.org/SDL_AudioQuit) func AudioQuit() { C.SDL_AudioQuit() } // GetCurrentAudioDriver returns the name of the current audio driver. // (https://wiki.libsdl.org/SDL_GetCurrentAudioDriver) func GetCurrentAudioDriver() string { return string(C.GoString(C.SDL_GetCurrentAudioDriver())) } // OpenAudio opens the audio device. New programs might want to use OpenAudioDevice() instead. // (https://wiki.libsdl.org/SDL_OpenAudio) func OpenAudio(desired, obtained *AudioSpec) error { if C.SDL_OpenAudio(desired.cptr(), obtained.cptr()) != 0 { return GetError() } return nil } // GetNumAudioDevices returns the number of built-in audio devices. // (https://wiki.libsdl.org/SDL_GetNumAudioDevices) func GetNumAudioDevices(isCapture bool) int { return int(C.SDL_GetNumAudioDevices(C.int(Btoi(isCapture)))) } // GetAudioDeviceName returns the name of a specific audio device. // (https://wiki.libsdl.org/SDL_GetAudioDeviceName) func GetAudioDeviceName(index int, isCapture bool) string { return string(C.GoString(C.SDL_GetAudioDeviceName(C.int(index), C.int(Btoi(isCapture))))) } // OpenAudioDevice opens a specific audio device. // (https://wiki.libsdl.org/SDL_OpenAudioDevice) func OpenAudioDevice(device string, isCapture bool, desired, obtained *AudioSpec, allowedChanges int) (AudioDeviceID, error) { _device := C.CString(device) if device == "" { _device = nil } defer C.free(unsafe.Pointer(_device)) if id := AudioDeviceID(C.SDL_OpenAudioDevice(_device, C.int(Btoi(isCapture)), desired.cptr(), obtained.cptr(), C.int(allowedChanges))); id > 0 { return id, nil } return 0, GetError() } // GetAudioStatus returns the current audio state of the audio device. New programs might want to use GetAudioDeviceStatus() instead. // (https://wiki.libsdl.org/SDL_GetAudioStatus) func GetAudioStatus() AudioStatus { return (AudioStatus)(C.SDL_GetAudioStatus()) } // GetAudioDeviceStatus returns the current audio state of an audio device. // (https://wiki.libsdl.org/SDL_GetAudioDeviceStatus) func GetAudioDeviceStatus(dev AudioDeviceID) AudioStatus { return (AudioStatus)(C.SDL_GetAudioDeviceStatus(dev.c())) } // PauseAudio pauses and unpauses the audio device. New programs might want to use SDL_PauseAudioDevice() instead. // (https://wiki.libsdl.org/SDL_PauseAudio) func PauseAudio(pauseOn bool) { C.SDL_PauseAudio(C.int(Btoi(pauseOn))) } // PauseAudioDevice pauses and unpauses audio playback on a specified device. // (https://wiki.libsdl.org/SDL_PauseAudioDevice) func PauseAudioDevice(dev AudioDeviceID, pauseOn bool) { C.SDL_PauseAudioDevice(dev.c(), C.int(Btoi(pauseOn))) } // LoadWAVRW loads a WAVE from the data source, automatically freeing that source if freeSrc is true. // (https://wiki.libsdl.org/SDL_LoadWAV_RW) func LoadWAVRW(src *RWops, freeSrc bool) ([]byte, *AudioSpec) { var _audioBuf *C.Uint8 var _audioLen C.Uint32 audioSpec := (*AudioSpec)(unsafe.Pointer(C.SDL_LoadWAV_RW(src.cptr(), C.int(Btoi(freeSrc)), (&AudioSpec{}).cptr(), &_audioBuf, &_audioLen))) var b []byte sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b)) sliceHeader.Len = (int)(_audioLen) sliceHeader.Cap = (int)(_audioLen) sliceHeader.Data = uintptr(unsafe.Pointer(_audioBuf)) return b, audioSpec } // LoadWAV loads a WAVE from a file. // (https://wiki.libsdl.org/SDL_LoadWAV) func LoadWAV(file string) ([]byte, *AudioSpec) { _file := C.CString(file) _rb := C.CString("rb") defer C.free(unsafe.Pointer(_file)) defer C.free(unsafe.Pointer(_rb)) var _audioBuf *C.Uint8 var _audioLen C.Uint32 audioSpec := (*AudioSpec)(unsafe.Pointer(C.SDL_LoadWAV_RW(C.SDL_RWFromFile(_file, _rb), 1, (&AudioSpec{}).cptr(), &_audioBuf, &_audioLen))) var b []byte sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b)) sliceHeader.Len = (int)(_audioLen) sliceHeader.Cap = (int)(_audioLen) sliceHeader.Data = uintptr(unsafe.Pointer(_audioBuf)) return b, audioSpec } // FreeWAV frees data previously allocated with LoadWAV() or LoadWAVRW(). // (https://wiki.libsdl.org/SDL_FreeWAV) func FreeWAV(audioBuf []uint8) { sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&audioBuf)) _audioBuf := (*C.Uint8)(unsafe.Pointer(sliceHeader.Data)) C.SDL_FreeWAV(_audioBuf) } // BuildAudioCVT initializes an AudioCVT structure for conversion. // (https://wiki.libsdl.org/SDL_BuildAudioCVT) func BuildAudioCVT(cvt *AudioCVT, srcFormat AudioFormat, srcChannels uint8, srcRate int, dstFormat AudioFormat, dstChannels uint8, dstRate int) (converted bool, err error) { switch int(C.SDL_BuildAudioCVT(cvt.cptr(), srcFormat.c(), C.Uint8(srcChannels), C.int(srcRate), dstFormat.c(), C.Uint8(dstChannels), C.int(dstRate))) { case 1: return true, nil case 0: return false, nil } return false, GetError() } // ConvertAudio converts audio data to a desired audio format. // (https://wiki.libsdl.org/SDL_ConvertAudio) func ConvertAudio(cvt *AudioCVT) error { _cvt := (*C.SDL_AudioCVT)(unsafe.Pointer(cvt)) if C.SDL_ConvertAudio(_cvt) != 0 { return GetError() } return nil } // QueueAudio queues more audio on non-callback devices. // (https://wiki.libsdl.org/SDL_QueueAudio) func QueueAudio(dev AudioDeviceID, data []byte) error { sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&data)) _data := unsafe.Pointer(sliceHeader.Data) _len := (C.Uint32)(sliceHeader.Len) if C.SDL_QueueAudio(dev.c(), _data, _len) != 0 { return GetError() } return nil } // DequeueAudio dequeues more audio on non-callback devices. Returns the number of bytes dequeued, which could be less than requested // (https://wiki.libsdl.org/SDL_DequeueAudio) func DequeueAudio(dev AudioDeviceID, data []byte) (n int, err error) { sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&data)) _data := unsafe.Pointer(sliceHeader.Data) _len := (C.Uint32)(sliceHeader.Len) if dequeued := int(C.SDL_DequeueAudio(dev.c(), _data, _len)); dequeued > 0 { return dequeued, nil } return 0, GetError() } // GetQueuedAudioSize returns the number of bytes of still-queued audio. // (https://wiki.libsdl.org/SDL_GetQueuedAudioSize) func GetQueuedAudioSize(dev AudioDeviceID) uint32 { return uint32(C.SDL_GetQueuedAudioSize(dev.c())) } // ClearQueuedAudio drops any queued audio data waiting to be sent to the hardware. // (https://wiki.libsdl.org/SDL_ClearQueuedAudio) func ClearQueuedAudio(dev AudioDeviceID) { C.SDL_ClearQueuedAudio(dev.c()) } // MixAudio mixes audio data. New programs might want to use MixAudioFormat() instead. // (https://wiki.libsdl.org/SDL_MixAudio) func MixAudio(dst, src *uint8, len uint32, volume int) { _dst := (*C.Uint8)(unsafe.Pointer(dst)) _src := (*C.Uint8)(unsafe.Pointer(src)) C.SDL_MixAudio(_dst, _src, C.Uint32(len), C.int(volume)) } // MixAudioFormat mixes audio data in a specified format. // (https://wiki.libsdl.org/SDL_MixAudioFormat) func MixAudioFormat(dst, src *uint8, format AudioFormat, len uint32, volume int) { _dst := (*C.Uint8)(unsafe.Pointer(dst)) _src := (*C.Uint8)(unsafe.Pointer(src)) C.SDL_MixAudioFormat(_dst, _src, format.c(), C.Uint32(len), C.int(volume)) } // LockAudio locks the audio device. New programs might want to use LockAudioDevice() instead. // (https://wiki.libsdl.org/SDL_LockAudio) func LockAudio() { C.SDL_LockAudio() } // LockAudioDevice locks out the audio callback function for a specified device. // (https://wiki.libsdl.org/SDL_LockAudioDevice) func LockAudioDevice(dev AudioDeviceID) { C.SDL_LockAudioDevice(dev.c()) } // UnlockAudio unlocks the audio device. New programs might want to use UnlockAudioDevice() instead. // (https://wiki.libsdl.org/SDL_UnlockAudio) func UnlockAudio() { C.SDL_UnlockAudio() } // UnlockAudioDevice unlocks the audio callback function for a specified device. // (https://wiki.libsdl.org/SDL_UnlockAudioDevice) func UnlockAudioDevice(dev AudioDeviceID) { C.SDL_UnlockAudioDevice(dev.c()) } // CloseAudio closes the audio device. New programs might want to use CloseAudioDevice() instead. // (https://wiki.libsdl.org/SDL_CloseAudio) func CloseAudio() { C.SDL_CloseAudio() } // CloseAudioDevice shuts down audio processing and closes the audio device. // (https://wiki.libsdl.org/SDL_CloseAudioDevice) func CloseAudioDevice(dev AudioDeviceID) { C.SDL_CloseAudioDevice(dev.c()) } // NewAudioStream creates a new audio stream // TODO: (https://wiki.libsdl.org/SDL_NewAudioStream) func NewAudioStream(srcFormat AudioFormat, srcChannels uint8, srcRate int, dstFormat AudioFormat, dstChannels uint8, dstRate int) (stream *AudioStream, err error) { _srcFormat := C.SDL_AudioFormat(srcFormat) _srcChannels := C.Uint8(srcChannels) _srcRate := C.int(srcRate) _dstFormat := C.SDL_AudioFormat(dstFormat) _dstChannels := C.Uint8(dstChannels) _dstRate := C.int(dstRate) stream = (*AudioStream)(C.SDL_NewAudioStream(_srcFormat, _srcChannels, _srcRate, _dstFormat, _dstChannels, _dstRate)) if stream == nil { err = GetError() } return } // Put adds data to be converted/resampled to the stream // TODO: (https://wiki.libsdl.org/SDL_AudioStreamPut) func (stream *AudioStream) Put(buf []byte) (err error) { sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&buf)) _buf := unsafe.Pointer(sliceHeader.Data) _len := C.int(len(buf)) ret := int(C.SDL_AudioStreamPut(stream.cptr(), _buf, _len)) err = errorFromInt(ret) return } // Get gets converted/resampled data from the stream. Returns the number of bytes read from the stream. // (https://wiki.libsdl.org/SDL_AudioStreamGet) func (stream *AudioStream) Get(buf []byte) (n int, err error) { sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&buf)) _buf := unsafe.Pointer(sliceHeader.Data) _len := C.int(len(buf)) if ret := int(C.SDL_AudioStreamGet(stream.cptr(), _buf, _len)); ret < 0 { return 0, errorFromInt(ret) } else { return ret, nil } } // Available gets the number of converted/resampled bytes available // TODO: (https://wiki.libsdl.org/SDL_AudioStreamAvailable) func (stream *AudioStream) Available() (err error) { ret := int(C.SDL_AudioStreamAvailable(stream.cptr())) err = errorFromInt(ret) return } // Flush tells the stream that you're done sending data, and anything being buffered // should be converted/resampled and made available immediately. // TODO: (https://wiki.libsdl.org/SDL_AudioStreamFlush) func (stream *AudioStream) Flush() (err error) { ret := int(C.SDL_AudioStreamFlush(stream.cptr())) err = errorFromInt(ret) return } // Clear clears any pending data in the stream without converting it // TODO: (https://wiki.libsdl.org/SDL_AudioStreamClear) func (stream *AudioStream) Clear() { C.SDL_AudioStreamClear(stream.cptr()) } // Free frees the audio stream // TODO: (https://wiki.libsdl.org/SDL_AudoiStreamFree) func (stream *AudioStream) Free() { C.SDL_FreeAudioStream(stream.cptr()) } // GetAudioDeviceSpec returns the preferred audio format of a specific audio device. // (https://wiki.libsdl.org/SDL_GetAudioDeviceSpec) func GetAudioDeviceSpec(index int, isCapture bool) (spec *AudioSpec, err error) { spec = &AudioSpec{} err = errorFromInt(int(C.SDL_GetAudioDeviceSpec(C.int(index), C.int(Btoi(isCapture)), spec.cptr()))) return } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/blendmode.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,6)) #if defined(WARN_OUTDATED) #pragma message("SDL_BLENDMODE_INVALID is not supported before SDL 2.0.6") #endif #define SDL_BLENDMODE_INVALID (0x7FFFFFFF) #if defined(WARN_OUTDATED) #pragma message("SDL_BlendOperation is not supported before SDL 2.0.6") #endif typedef enum { SDL_BLENDOPERATION_ADD = 0x1, SDL_BLENDOPERATION_SUBTRACT = 0x2, SDL_BLENDOPERATION_REV_SUBTRACT = 0x3, SDL_BLENDOPERATION_MINIMUM = 0x4, SDL_BLENDOPERATION_MAXIMUM = 0x5 } SDL_BlendOperation; #if defined(WARN_OUTDATED) #pragma message("SDL_BlendFactor is not supported before SDL 2.0.6") #endif typedef enum { SDL_BLENDFACTOR_ZERO = 0x1, SDL_BLENDFACTOR_ONE = 0x2, SDL_BLENDFACTOR_SRC_COLOR = 0x3, SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR = 0x4, SDL_BLENDFACTOR_SRC_ALPHA = 0x5, SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA = 0x6, SDL_BLENDFACTOR_DST_COLOR = 0x7, SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR = 0x8, SDL_BLENDFACTOR_DST_ALPHA = 0x9, SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA = 0xA } SDL_BlendFactor; #if defined(WARN_OUTDATED) #pragma message("SDL_ComposeCustomBlendMode is not supported before SDL 2.0.6") #endif SDL_BlendMode SDLCALL SDL_ComposeCustomBlendMode(SDL_BlendFactor srcColorFactor, SDL_BlendFactor dstColorFactor, SDL_BlendOperation colorOperation, SDL_BlendFactor srcAlphaFactor, SDL_BlendFactor dstAlphaFactor, SDL_BlendOperation alphaOperation) { return SDL_BLENDMODE_NONE; } #endif */ import "C" import "unsafe" // BlendMode is an enumeration of blend modes used in Render.Copy() and drawing operations. // (https://wiki.libsdl.org/SDL_BlendMode) type BlendMode uint32 const ( BLENDMODE_NONE = C.SDL_BLENDMODE_NONE // no blending BLENDMODE_BLEND = C.SDL_BLENDMODE_BLEND // alpha blending BLENDMODE_ADD = C.SDL_BLENDMODE_ADD // additive blending BLENDMODE_MOD = C.SDL_BLENDMODE_MOD // color modulate BLENDMODE_INVALID = C.SDL_BLENDMODE_INVALID ) func (bm BlendMode) c() C.SDL_BlendMode { return C.SDL_BlendMode(C.Uint32(bm)) } func (bm *BlendMode) cptr() *C.SDL_BlendMode { return (*C.SDL_BlendMode)(unsafe.Pointer(bm)) } // BlendOperation is an enumeration of blend operations used when creating a custom blend mode with ComposeCustomBlendMode(). // (https://wiki.libsdl.org/SDL_BlendOperation) type BlendOperation C.SDL_BlendOperation const ( BLENDOPERATION_ADD = C.SDL_BLENDOPERATION_ADD BLENDOPERATION_SUBTRACT = C.SDL_BLENDOPERATION_SUBTRACT BLENDOPERATION_REV_SUBTRACT = C.SDL_BLENDOPERATION_REV_SUBTRACT BLENDOPERATION_MINIMUM = C.SDL_BLENDOPERATION_MINIMUM BLENDOPERATION_MAXIMUM = C.SDL_BLENDOPERATION_MAXIMUM ) // BlendFactor is an enumeration of blend factors used when creating a custom blend mode with ComposeCustomBlendMode(). // (https://wiki.libsdl.org/SDL_BlendFactor) type BlendFactor C.SDL_BlendFactor const ( BLENDFACTOR_ZERO = C.SDL_BLENDFACTOR_ZERO // 0, 0, 0, 0 BLENDFACTOR_ONE = C.SDL_BLENDFACTOR_ONE // 1, 1, 1, 1 BLENDFACTOR_SRC_COLOR = C.SDL_BLENDFACTOR_SRC_COLOR // srcR, srcG, srcB, srcA BLENDFACTOR_ONE_MINUS_SRC_COLOR = C.SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR // 1-srcR, 1-srcG, 1-srcB, 1-srcA BLENDFACTOR_SRC_ALPHA = C.SDL_BLENDFACTOR_SRC_ALPHA // srcA, srcA, srcA, srcA BLENDFACTOR_ONE_MINUS_SRC_ALPHA = C.SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA // 1-srcA, 1-srcA, 1-srcA, 1-srcA BLENDFACTOR_DST_COLOR = C.SDL_BLENDFACTOR_DST_COLOR // dstR, dstG, dstB, dstA BLENDFACTOR_ONE_MINUS_DST_COLOR = C.SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR // 1-dstR, 1-dstG, 1-dstB, 1-dstA BLENDFACTOR_DST_ALPHA = C.SDL_BLENDFACTOR_DST_ALPHA // dstA, dstA, dstA, dstA BLENDFACTOR_ONE_MINUS_DST_ALPHA = C.SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA // 1-dstA, 1-dstA, 1-dstA, 1-dstA ) // ComposeCustomBlendMode creates a custom blend mode, which may or may not be supported by a given renderer // The result of the blend mode operation will be: // dstRGB = dstRGB * dstColorFactor colorOperation srcRGB * srcColorFactor // and // dstA = dstA * dstAlphaFactor alphaOperation srcA * srcAlphaFactor // (https://wiki.libsdl.org/SDL_ComposeCustomBlendMode) func ComposeCustomBlendMode(srcColorFactor, dstColorFactor BlendFactor, colorOperation BlendOperation, srcAlphaFactor, dstAlphaFactor BlendFactor, alphaOperation BlendOperation) BlendMode { _srcColorFactor := C.SDL_BlendFactor(srcColorFactor) _dstColorFactor := C.SDL_BlendFactor(dstColorFactor) _colorOperation := C.SDL_BlendOperation(colorOperation) _srcAlphaFactor := C.SDL_BlendFactor(srcAlphaFactor) _dstAlphaFactor := C.SDL_BlendFactor(dstAlphaFactor) _alphaOperation := C.SDL_BlendOperation(alphaOperation) return BlendMode(C.SDL_ComposeCustomBlendMode(_srcColorFactor, _dstColorFactor, _colorOperation, _srcAlphaFactor, _dstAlphaFactor, _alphaOperation)) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/clipboard.go ================================================ package sdl // #include "sdl_wrapper.h" import "C" import "unsafe" // SetClipboardText puts UTF-8 text into the clipboard. // (https://wiki.libsdl.org/SDL_SetClipboardText) func SetClipboardText(text string) error { _text := C.CString(text) defer C.free(unsafe.Pointer(_text)) if C.SDL_SetClipboardText(_text) < 0 { return GetError() } return nil } // GetClipboardText returns UTF-8 text from the clipboard. // (https://wiki.libsdl.org/SDL_GetClipboardText) func GetClipboardText() (string, error) { text := C.SDL_GetClipboardText() if text == nil { return "", GetError() } defer C.SDL_free(unsafe.Pointer(text)) _text := C.GoString(text) return _text, nil } // HasClipboardText reports whether the clipboard exists and contains a text string that is non-empty. // (https://wiki.libsdl.org/SDL_HasClipboardText) func HasClipboardText() bool { return C.SDL_HasClipboardText() > 0 } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/cpuinfo.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,9)) #if defined(WARN_OUTDATED) #pragma message("SDL_HasAVX512F is not supported before SDL 2.0.9") #endif static inline SDL_bool SDL_HasAVX512F() { return SDL_FALSE; } #endif #if !(SDL_VERSION_ATLEAST(2,0,1)) #if defined(WARN_OUTDATED) #pragma message("SDL_GetSystemRAM is not supported before SDL 2.0.1") #endif static inline int SDL_GetSystemRAM() { return -1; } #endif #if !(SDL_VERSION_ATLEAST(2,0,2)) #if defined(WARN_OUTDATED) #pragma message("SDL_HasAVX is not supported before SDL 2.0.2") #endif static inline SDL_bool SDL_HasAVX() { return SDL_FALSE; } #endif #if !(SDL_VERSION_ATLEAST(2,0,4)) #if defined(WARN_OUTDATED) #pragma message("SDL_HasAVX2 is not supported before SDL 2.0.4") #endif static inline SDL_bool SDL_HasAVX2() { return SDL_FALSE; } #endif #if !(SDL_VERSION_ATLEAST(2,0,6)) #if defined(WARN_OUTDATED) #pragma message("SDL_HasNEON is not supported before SDL 2.0.4") #endif static inline SDL_bool SDL_HasNEON() { return SDL_FALSE; } #endif #if !(SDL_VERSION_ATLEAST(2,0,10)) #if defined(WARN_OUTDATED) #pragma message("SDL_SIMDGetAlignment is not supported before SDL 2.0.10") #endif static inline size_t SDL_SIMDGetAlignment(void) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_SIMDAlloc is not supported before SDL 2.0.10") #endif static inline void * SDL_SIMDAlloc(const size_t len) { return NULL; } #if defined(WARN_OUTDATED) #pragma message("SDL_SIMDFree is not supported before SDL 2.0.10") #endif static inline void SDL_SIMDFree(void *ptr) { } #endif */ import "C" import "unsafe" // CACHELINE_SIZE is a cacheline size used for padding. const CACHELINE_SIZE = C.SDL_CACHELINE_SIZE // GetCPUCount returns the number of CPU cores available. // (https://wiki.libsdl.org/SDL_GetCPUCount) func GetCPUCount() int { return int(C.SDL_GetCPUCount()) } // GetCPUCacheLineSize returns the L1 cache line size of the CPU. // (https://wiki.libsdl.org/SDL_GetCPUCacheLineSize) func GetCPUCacheLineSize() int { return int(C.SDL_GetCPUCacheLineSize()) } // HasRDTSC reports whether the CPU has the RDTSC instruction. // (https://wiki.libsdl.org/SDL_HasRDTSC) func HasRDTSC() bool { return C.SDL_HasRDTSC() > 0 } // HasAltiVec reports whether the CPU has AltiVec features. // (https://wiki.libsdl.org/SDL_HasAltiVec) func HasAltiVec() bool { return C.SDL_HasAltiVec() > 0 } // HasMMX reports whether the CPU has MMX features. // (https://wiki.libsdl.org/SDL_HasMMX) func HasMMX() bool { return C.SDL_HasMMX() > 0 } // Has3DNow reports whether the CPU has 3DNow! features. // (https://wiki.libsdl.org/SDL_Has3DNow) func Has3DNow() bool { return C.SDL_Has3DNow() > 0 } // HasSSE reports whether the CPU has SSE features. // (https://wiki.libsdl.org/SDL_HasSSE) func HasSSE() bool { return C.SDL_HasSSE() > 0 } // HasSSE2 reports whether the CPU has SSE2 features. // (https://wiki.libsdl.org/SDL_HasSSE2) func HasSSE2() bool { return C.SDL_HasSSE2() > 0 } // HasSSE3 reports whether the CPU has SSE3 features. // (https://wiki.libsdl.org/SDL_HasSSE3) func HasSSE3() bool { return C.SDL_HasSSE3() > 0 } // HasSSE41 reports whether the CPU has SSE4.1 features. // (https://wiki.libsdl.org/SDL_HasSSE41) func HasSSE41() bool { return C.SDL_HasSSE41() > 0 } // HasSSE42 reports whether the CPU has SSE4.2 features. // (https://wiki.libsdl.org/SDL_HasSSE42) func HasSSE42() bool { return C.SDL_HasSSE42() > 0 } // GetSystemRAM returns the amount of RAM configured in the system. // (https://wiki.libsdl.org/SDL_GetSystemRAM) func GetSystemRAM() int { return int(C.SDL_GetSystemRAM()) } // HasAVX reports whether the CPU has AVX features. // (https://wiki.libsdl.org/SDL_HasAVX) func HasAVX() bool { return C.SDL_HasAVX() > 0 } // HasAVX512F reports whether the CPU has AVX-512F (foundation) features. // TODO: (https://wiki.libsdl.org/SDL_HasAVX512F) func HasAVX512F() bool { return C.SDL_HasAVX512F() > 0 } // HasAVX2 reports whether the CPU has AVX2 features. // (https://wiki.libsdl.org/SDL_HasAVX2) func HasAVX2() bool { return C.SDL_HasAVX2() > 0 } // HasNEON reports whether the CPU has NEON features. // (https://wiki.libsdl.org/SDL_HasNEON) func HasNEON() bool { return C.SDL_HasNEON() > 0 } // SIMDGetAlignment reports the alignment this system needs for SIMD allocations. // TODO: (https://wiki.libsdl.org/SDL_SIMDGetAlignment) func SIMDGetAlignment() int { return int(C.SDL_SIMDGetAlignment()) } // SIMDAlloc allocates memory in a SIMD-friendly way. // TODO: (https://wiki.libsdl.org/SDL_SIMDAlloc) func SIMDAlloc(_len int) unsafe.Pointer { return C.SDL_SIMDAlloc(C.size_t(_len)) } // SIMDFree deallocates memory obtained from SDL_SIMDAlloc. // TODO: (https://wiki.libsdl.org/SDL_SIMDFree) func SIMDFree(p unsafe.Pointer) { C.SDL_SIMDFree(p) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/endian.go ================================================ package sdl // #include "sdl_wrapper.h" import "C" // Endian-specific values. // (https://wiki.libsdl.org/CategoryEndian) const ( BYTEORDER = C.SDL_BYTEORDER // macro that corresponds to the byte order used by the processor type it was compiled for LIL_ENDIAN = C.SDL_LIL_ENDIAN // byte order is 1234, where the least significant byte is stored first BIG_ENDIAN = C.SDL_BIG_ENDIAN // byte order is 4321, where the most significant byte is stored first ) ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/error.go ================================================ package sdl /* #include "sdl_wrapper.h" void GoSetError(const char *fmt) { SDL_SetError("%s", fmt); } */ // #include "sdl_wrapper.h" import "C" import "errors" var emptyCString *C.char = C.CString("") var ErrInvalidParameters = errors.New("Invalid Parameters") // SDL error codes with their corresponding predefined strings. const ( ENOMEM ErrorCode = C.SDL_ENOMEM // out of memory EFREAD = C.SDL_EFREAD // error reading from datastream EFWRITE = C.SDL_EFWRITE // error writing to datastream EFSEEK = C.SDL_EFSEEK // error seeking in datastream UNSUPPORTED = C.SDL_UNSUPPORTED // that operation is not supported LASTERROR = C.SDL_LASTERROR // the highest numbered predefined error ) // ErrorCode is an error code used in SDL error messages. type ErrorCode uint32 type cErrorCode C.SDL_errorcode func (ec ErrorCode) c() C.SDL_errorcode { return C.SDL_errorcode(ec) } // GetError returns the last error that occurred, or an empty string if there hasn't been an error message set since the last call to ClearError(). // (https://wiki.libsdl.org/SDL_GetError) func GetError() error { if err := C.SDL_GetError(); err != nil { gostr := C.GoString(err) // SDL_GetError returns "an empty string if there hasn't been an error message" if len(gostr) > 0 { return errors.New(gostr) } } return nil } // SetError set the SDL error message. // (https://wiki.libsdl.org/SDL_SetError) func SetError(err error) { if err != nil { C.GoSetError(C.CString(err.Error())) return } C.GoSetError(emptyCString) } // ClearError clears any previous error message. // (https://wiki.libsdl.org/SDL_ClearError) func ClearError() { C.SDL_ClearError() } // Error sets the SDL error message to the specified error code. func Error(code ErrorCode) { C.SDL_Error(code.c()) } // OutOfMemory sets SDL error message to ENOMEM (out of memory). func OutOfMemory() { Error(ENOMEM) } // Unsupported sets SDL error message to UNSUPPORTED (that operation is not supported). func Unsupported() { Error(UNSUPPORTED) } // errorFromInt returns GetError() if passed negative value, otherwise it returns nil. func errorFromInt(code int) (err error) { if code < 0 { err = GetError() if err == nil { err = errors.New("Unknown error (probably using old version of SDL2 and the function called is not supported?)") } } return } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/events.c ================================================ #include "_cgo_export.h" #include "events.h" SDL_Event event; void setEventFilter() { SDL_SetEventFilter((SDL_EventFilter)goSetEventFilterCallback, NULL); } void clearEventFilter() { SDL_SetEventFilter(NULL, NULL); } void filterEvents(void *userdata) { SDL_FilterEvents((SDL_EventFilter)goEventFilterCallback, userdata); } void addEventWatch(void *userdata) { SDL_AddEventWatch((SDL_EventFilter)goEventFilterCallback, userdata); } void delEventWatch(void *userdata) { SDL_DelEventWatch((SDL_EventFilter)goEventFilterCallback, userdata); } int PollEvent() { return SDL_PollEvent(&event); } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/events.go ================================================ package sdl /* #include "sdl_wrapper.h" #include "events.h" #if !SDL_VERSION_ATLEAST(2,0,9) #define SDL_DISPLAYEVENT (0x150) #endif #if !SDL_VERSION_ATLEAST(2,0,2) #define SDL_RENDER_TARGETS_RESET (0x2000) #endif #if !SDL_VERSION_ATLEAST(2,0,4) #if defined(WARN_OUTDATED) #pragma message("SDL_KEYMAPCHANGED is not supported before SDL 2.0.4") #endif #define SDL_KEYMAPCHANGED (0x304) #if defined(WARN_OUTDATED) #pragma message("SDL_AUDIODEVICEADDED is not supported before SDL 2.0.4") #endif #define SDL_AUDIODEVICEADDED (0x1100) #if defined(WARN_OUTDATED) #pragma message("SDL_AUDIODEVICEREMOVED is not supported before SDL 2.0.4") #endif #define SDL_AUDIODEVICEREMOVED (0x1101) #if defined(WARN_OUTDATED) #pragma message("SDL_RENDER_DEVICE_RESET is not supported before SDL 2.0.4") #endif #define SDL_RENDER_DEVICE_RESET (0x2001) #if defined(WARN_OUTDATED) #pragma message("SDL_AudioDeviceEvent is not supported before SDL 2.0.4") #endif typedef struct SDL_AudioDeviceEvent { Uint32 type; Uint32 timestamp; Uint32 which; Uint8 iscapture; Uint8 padding1; Uint8 padding2; Uint8 padding3; } SDL_AudioDeviceEvent; #endif #if !SDL_VERSION_ATLEAST(2,0,5) #if defined(WARN_OUTDATED) #pragma message("SDL_DROPTEXT is not supported before SDL 2.0.5") #endif #define SDL_DROPTEXT (0x1001) #if defined(WARN_OUTDATED) #pragma message("SDL_DROPBEGIN is not supported before SDL 2.0.5") #endif #define SDL_DROPBEGIN (0x1002) #if defined(WARN_OUTDATED) #pragma message("SDL_DROPCOMPLETE is not supported before SDL 2.0.5") #endif #define SDL_DROPCOMPLETE (0x1003) #endif #if !SDL_VERSION_ATLEAST(2,0,9) #define SDL_SENSORUPDATE (0x1200) typedef struct SDL_SensorEvent { Uint32 type; Uint32 timestamp; Sint32 which; float data[6]; } SDL_SensorEvent; #endif #if !SDL_VERSION_ATLEAST(2,0,22) #if defined(WARN_OUTDATED) #pragma message("SDL_TEXTEDITING_EXT is not supported before SDL 2.0.22") #endif #define SDL_TEXTEDITING_EXT (0x305) #endif // NOTE: To prevent build from failing when using older SDL2, we create a // structure definiton that directly maps to the SDL2 struct definition if // using the latest SDL2. Otherwise, we copy the latest definition and paste // it here. #if SDL_VERSION_ATLEAST(2,0,22) typedef SDL_MouseButtonEvent MouseButtonEvent; typedef SDL_MouseWheelEvent MouseWheelEvent; typedef SDL_TouchFingerEvent TouchFingerEvent; typedef SDL_DropEvent DropEvent; #else typedef struct MouseButtonEvent { Uint32 type; // ::SDL_MOUSEBUTTONDOWN or ::SDL_MOUSEBUTTONUP Uint32 timestamp; Uint32 windowID; // The window with mouse focus, if any Uint32 which; // The mouse instance id, or SDL_TOUCH_MOUSEID Uint8 button; // The mouse button index Uint8 state; // ::SDL_PRESSED or ::SDL_RELEASED Uint8 clicks; // 1 for single-click, 2 for double-click, etc. Uint8 padding1; Sint32 x; // X coordinate, relative to window Sint32 y; // Y coordinate, relative to window } MouseButtonEvent; typedef struct MouseWheelEvent { Uint32 type; // ::SDL_MOUSEWHEEL Uint32 timestamp; // In milliseconds, populated using SDL_GetTicks() Uint32 windowID; // The window with mouse focus, if any Uint32 which; // The mouse instance id, or SDL_TOUCH_MOUSEID Sint32 x; // The amount scrolled horizontally, positive to the right and negative to the left Sint32 y; // The amount scrolled vertically, positive away from the user and negative toward the user Uint32 direction; // Set to one of the SDL_MOUSEWHEEL_* defines. When FLIPPED the values in X and Y will be opposite. Multiply by -1 to change them back float preciseX; // The amount scrolled horizontally, positive to the right and negative to the left, with float precision (added in 2.0.18) float preciseY; // The amount scrolled vertically, positive away from the user and negative toward the user, with float precision (added in 2.0.18) } MouseWheelEvent; typedef struct TouchFingerEvent { Uint32 type; // ::SDL_FINGERMOTION or ::SDL_FINGERDOWN or ::SDL_FINGERUP Uint32 timestamp; // In milliseconds, populated using SDL_GetTicks() SDL_TouchID touchId; // The touch device id SDL_FingerID fingerId; // float x; // Normalized in the range 0...1 float y; // Normalized in the range 0...1 float dx; // Normalized in the range -1...1 float dy; // Normalized in the range -1...1 float pressure; // Normalized in the range 0...1 Uint32 windowID; // The window underneath the finger, if any } TouchFingerEvent; typedef struct DropEvent { Uint32 type; // ::SDL_DROPBEGIN or ::SDL_DROPFILE or ::SDL_DROPTEXT or ::SDL_DROPCOMPLETE Uint32 timestamp; // In milliseconds, populated using SDL_GetTicks() char *file; // The file name, which should be freed with SDL_free(), is NULL on begin/complete Uint32 windowID; // The window that was dropped on, if any } DropEvent; #endif #if !SDL_VERSION_ATLEAST(2,24,0) #if defined(WARN_OUTDATED) #pragma message("SDL_JOYBATTEYUPDATED is not supported before SDL 2.24.0") #endif #define SDL_JOYBATTERYUPDATED (1543) #if !SDL_VERSION_ATLEAST(2,0,4) typedef enum { SDL_JOYSTICK_POWER_UNKNOWN = -1, SDL_JOYSTICK_POWER_EMPTY, SDL_JOYSTICK_POWER_LOW, SDL_JOYSTICK_POWER_MEDIUM, SDL_JOYSTICK_POWER_FULL, SDL_JOYSTICK_POWER_WIRED, SDL_JOYSTICK_POWER_MAX } SDL_JoystickPowerLevel; #endif typedef struct SDL_JoyBatteryEvent { Uint32 type; Uint32 timestamp; SDL_JoystickID which; SDL_JoystickPowerLevel level; } SDL_JoyBatteryEvent; #endif */ import "C" import ( "reflect" "sync" "unsafe" ) var ( eventFilterCache EventFilter eventWatches = make(map[EventWatchHandle]*eventFilterCallbackContext) lastEventWatchHandleMutex sync.Mutex lastEventWatchHandle EventWatchHandle cevent C.SDL_Event ) // Enumeration of the types of events that can be delivered. // (https://wiki.libsdl.org/SDL_EventType) const ( FIRSTEVENT = C.SDL_FIRSTEVENT // do not remove (unused) // Application events QUIT = C.SDL_QUIT // user-requested quit // Android, iOS and WinRT events APP_TERMINATING = C.SDL_APP_TERMINATING // OS is terminating the application APP_LOWMEMORY = C.SDL_APP_LOWMEMORY // OS is low on memory; free some APP_WILLENTERBACKGROUND = C.SDL_APP_WILLENTERBACKGROUND // application is entering background APP_DIDENTERBACKGROUND = C.SDL_APP_DIDENTERBACKGROUND //application entered background APP_WILLENTERFOREGROUND = C.SDL_APP_WILLENTERFOREGROUND // application is entering foreground APP_DIDENTERFOREGROUND = C.SDL_APP_DIDENTERFOREGROUND // application entered foreground // Display events DISPLAYEVENT = C.SDL_DISPLAYEVENT // Display state change // Window events WINDOWEVENT = C.SDL_WINDOWEVENT // window state change SYSWMEVENT = C.SDL_SYSWMEVENT // system specific event // Keyboard events KEYDOWN = C.SDL_KEYDOWN // key pressed KEYUP = C.SDL_KEYUP // key released TEXTEDITING = C.SDL_TEXTEDITING // keyboard text editing (composition) TEXTINPUT = C.SDL_TEXTINPUT // keyboard text input TEXTEDITING_EXT = C.SDL_TEXTEDITING_EXT // keyboard text editing (composition) KEYMAPCHANGED = C.SDL_KEYMAPCHANGED // keymap changed due to a system event such as an input language or keyboard layout change (>= SDL 2.0.4) // Mouse events MOUSEMOTION = C.SDL_MOUSEMOTION // mouse moved MOUSEBUTTONDOWN = C.SDL_MOUSEBUTTONDOWN // mouse button pressed MOUSEBUTTONUP = C.SDL_MOUSEBUTTONUP // mouse button released MOUSEWHEEL = C.SDL_MOUSEWHEEL // mouse wheel motion // Joystick events JOYAXISMOTION = C.SDL_JOYAXISMOTION // joystick axis motion JOYBALLMOTION = C.SDL_JOYBALLMOTION // joystick trackball motion JOYHATMOTION = C.SDL_JOYHATMOTION // joystick hat position change JOYBUTTONDOWN = C.SDL_JOYBUTTONDOWN // joystick button pressed JOYBUTTONUP = C.SDL_JOYBUTTONUP // joystick button released JOYDEVICEADDED = C.SDL_JOYDEVICEADDED // joystick connected JOYDEVICEREMOVED = C.SDL_JOYDEVICEREMOVED // joystick disconnected // Game controller events CONTROLLERAXISMOTION = C.SDL_CONTROLLERAXISMOTION // controller axis motion CONTROLLERBUTTONDOWN = C.SDL_CONTROLLERBUTTONDOWN // controller button pressed CONTROLLERBUTTONUP = C.SDL_CONTROLLERBUTTONUP // controller button released CONTROLLERDEVICEADDED = C.SDL_CONTROLLERDEVICEADDED // controller connected CONTROLLERDEVICEREMOVED = C.SDL_CONTROLLERDEVICEREMOVED // controller disconnected CONTROLLERDEVICEREMAPPED = C.SDL_CONTROLLERDEVICEREMAPPED // controller mapping updated // Touch events FINGERDOWN = C.SDL_FINGERDOWN // user has touched input device FINGERUP = C.SDL_FINGERUP // user stopped touching input device FINGERMOTION = C.SDL_FINGERMOTION // user is dragging finger on input device // Gesture events DOLLARGESTURE = C.SDL_DOLLARGESTURE DOLLARRECORD = C.SDL_DOLLARRECORD MULTIGESTURE = C.SDL_MULTIGESTURE // Clipboard events CLIPBOARDUPDATE = C.SDL_CLIPBOARDUPDATE // the clipboard changed // Drag and drop events DROPFILE = C.SDL_DROPFILE // the system requests a file open DROPTEXT = C.SDL_DROPTEXT // text/plain drag-and-drop event DROPBEGIN = C.SDL_DROPBEGIN // a new set of drops is beginning (NULL filename) DROPCOMPLETE = C.SDL_DROPCOMPLETE // current set of drops is now complete (NULL filename) // Audio hotplug events AUDIODEVICEADDED = C.SDL_AUDIODEVICEADDED // a new audio device is available (>= SDL 2.0.4) AUDIODEVICEREMOVED = C.SDL_AUDIODEVICEREMOVED // an audio device has been removed (>= SDL 2.0.4) // Sensor events SENSORUPDATE = C.SDL_SENSORUPDATE // a sensor was updated // Render events RENDER_TARGETS_RESET = C.SDL_RENDER_TARGETS_RESET // the render targets have been reset and their contents need to be updated (>= SDL 2.0.2) RENDER_DEVICE_RESET = C.SDL_RENDER_DEVICE_RESET // the device has been reset and all textures need to be recreated (>= SDL 2.0.4) // These are for your use, and should be allocated with RegisterEvents() USEREVENT = C.SDL_USEREVENT // a user-specified event LASTEVENT = C.SDL_LASTEVENT // (only for bounding internal arrays) ) // Actions for PeepEvents(). // (https://wiki.libsdl.org/SDL_PeepEvents) const ( ADDEVENT = C.SDL_ADDEVENT // up to numevents events will be added to the back of the event queue PEEKEVENT = C.SDL_PEEKEVENT // up to numevents events at the front of the event queue, within the specified minimum and maximum type, will be returned and will not be removed from the queue GETEVENT = C.SDL_GETEVENT // up to numevents events at the front of the event queue, within the specified minimum and maximum type, will be returned and will be removed from the queue ) // Toggles for different event state functions. const ( QUERY = C.SDL_QUERY IGNORE = C.SDL_IGNORE DISABLE = C.SDL_DISABLE ENABLE = C.SDL_ENABLE ) // Event is a union of all event structures used in SDL. // (https://wiki.libsdl.org/SDL_Event) type Event interface { GetType() uint32 // GetType returns the event type GetTimestamp() uint32 // GetTimestamp returns the timestamp of the event } // CEvent is a union of all event structures used in SDL. // (https://wiki.libsdl.org/SDL_Event) type CEvent struct { Type uint32 _ [52]byte // padding } // CommonEvent contains common event data. // (https://wiki.libsdl.org/SDL_Event) type CommonEvent struct { Type uint32 // the event type Timestamp uint32 // timestamp of the event } // GetType returns the event type. func (e *CommonEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *CommonEvent) GetTimestamp() uint32 { return e.Timestamp } // DisplayEvent contains common event data. // (https://wiki.libsdl.org/SDL_Event) type DisplayEvent struct { Type uint32 // the event type Timestamp uint32 // timestamp of the event Display uint32 // the associated display index Event uint8 // TODO: (https://wiki.libsdl.org/SDL_DisplayEventID) _ uint8 // padding _ uint8 // padding _ uint8 // padding Data1 int32 // event dependent data } // GetType returns the event type. func (e *DisplayEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *DisplayEvent) GetTimestamp() uint32 { return e.Timestamp } // WindowEvent contains window state change event data. // (https://wiki.libsdl.org/SDL_WindowEvent) type WindowEvent struct { Type uint32 // WINDOWEVENT Timestamp uint32 // timestamp of the event WindowID uint32 // the associated window Event uint8 // (https://wiki.libsdl.org/SDL_WindowEventID) _ uint8 // padding _ uint8 // padding _ uint8 // padding Data1 int32 // event dependent data Data2 int32 // event dependent data } type cWindowEvent C.SDL_WindowEvent // GetType returns the event type. func (e *WindowEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *WindowEvent) GetTimestamp() uint32 { return e.Timestamp } // KeyboardEvent contains keyboard key down event information. // (https://wiki.libsdl.org/SDL_KeyboardEvent) type KeyboardEvent struct { Type uint32 // KEYDOWN, KEYUP Timestamp uint32 // timestamp of the event WindowID uint32 // the window with keyboard focus, if any State uint8 // PRESSED, RELEASED Repeat uint8 // non-zero if this is a key repeat _ uint8 // padding _ uint8 // padding Keysym Keysym // Keysym representing the key that was pressed or released } type cKeyboardEvent C.SDL_KeyboardEvent // GetType returns the event type. func (e *KeyboardEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *KeyboardEvent) GetTimestamp() uint32 { return e.Timestamp } // TextEditingEvent contains keyboard text editing event information. // (https://wiki.libsdl.org/SDL_TextEditingEvent) type TextEditingEvent struct { Type uint32 // TEXTEDITING Timestamp uint32 // timestamp of the event WindowID uint32 // the window with keyboard focus, if any Text [C.SDL_TEXTINPUTEVENT_TEXT_SIZE]byte // the null-terminated editing text in UTF-8 encoding Start int32 // the location to begin editing from Length int32 // the number of characters to edit from the start point } type cTextEditingEvent C.SDL_TextEditingEvent // GetType returns the event type. func (e *TextEditingEvent) GetType() uint32 { return e.Type } // GetText returns the text as string func (e *TextEditingEvent) GetText() string { length := func(buf []byte) int { for i := range buf { if buf[i] == 0 { return i } } return 0 }(e.Text[:]) text := e.Text[:length] return string(text) } // GetTimestamp returns the timestamp of the event. func (e *TextEditingEvent) GetTimestamp() uint32 { return e.Timestamp } // TextInputEvent contains keyboard text input event information. // (https://wiki.libsdl.org/SDL_TextInputEvent) type TextInputEvent struct { Type uint32 // TEXTINPUT Timestamp uint32 // timestamp of the event WindowID uint32 // the window with keyboard focus, if any Text [C.SDL_TEXTINPUTEVENT_TEXT_SIZE]byte // the null-terminated input text in UTF-8 encoding } type cTextInputEvent C.SDL_TextInputEvent // GetType returns the event type. func (e *TextInputEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *TextInputEvent) GetTimestamp() uint32 { return e.Timestamp } // GetText returns the text as string func (e *TextInputEvent) GetText() string { length := func(buf []byte) int { for i := range buf { if buf[i] == 0 { return i } } return 0 }(e.Text[:]) text := e.Text[:length] return string(text) } // MouseMotionEvent contains mouse motion event information. // (https://wiki.libsdl.org/SDL_MouseMotionEvent) type MouseMotionEvent struct { Type uint32 // MOUSEMOTION Timestamp uint32 // timestamp of the event WindowID uint32 // the window with mouse focus, if any Which uint32 // the mouse instance id, or TOUCH_MOUSEID State uint32 // BUTTON_LEFT, BUTTON_MIDDLE, BUTTON_RIGHT, BUTTON_X1, BUTTON_X2 X int32 // X coordinate, relative to window Y int32 // Y coordinate, relative to window XRel int32 // relative motion in the X direction YRel int32 // relative motion in the Y direction } type cMouseMotionEvent C.SDL_MouseMotionEvent // GetType returns the event type. func (e *MouseMotionEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *MouseMotionEvent) GetTimestamp() uint32 { return e.Timestamp } // MouseButtonEvent contains mouse button event information. // (https://wiki.libsdl.org/SDL_MouseButtonEvent) type MouseButtonEvent struct { Type uint32 // MOUSEBUTTONDOWN, MOUSEBUTTONUP Timestamp uint32 // timestamp of the event WindowID uint32 // the window with mouse focus, if any Which uint32 // the mouse instance id, or TOUCH_MOUSEID Button uint8 // BUTTON_LEFT, BUTTON_MIDDLE, BUTTON_RIGHT, BUTTON_X1, BUTTON_X2 State uint8 // PRESSED, RELEASED Clicks uint8 // 1 for single-click, 2 for double-click, etc. (>= SDL 2.0.2) _ uint8 // padding X int32 // X coordinate, relative to window Y int32 // Y coordinate, relative to window } type cMouseButtonEvent C.SDL_MouseButtonEvent // GetType returns the event type. func (e *MouseButtonEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *MouseButtonEvent) GetTimestamp() uint32 { return e.Timestamp } // MouseWheelEvent contains mouse wheel event information. // (https://wiki.libsdl.org/SDL_MouseWheelEvent) type MouseWheelEvent struct { Type uint32 // MOUSEWHEEL Timestamp uint32 // timestamp of the event WindowID uint32 // the window with mouse focus, if any Which uint32 // the mouse instance id, or TOUCH_MOUSEID X int32 // the amount scrolled horizontally, positive to the right and negative to the left Y int32 // the amount scrolled vertically, positive away from the user and negative toward the user Direction uint32 // MOUSEWHEEL_NORMAL, MOUSEWHEEL_FLIPPED (>= SDL 2.0.4) PreciseX float32 // The amount scrolled horizontally, positive to the right and negative to the left, with float precision (added in 2.0.18) PreciseY float32 // The amount scrolled vertically, positive away from the user and negative toward the user, with float precision (added in 2.0.18) } type cMouseWheelEvent C.SDL_MouseWheelEvent // GetType returns the event type. func (e *MouseWheelEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *MouseWheelEvent) GetTimestamp() uint32 { return e.Timestamp } // JoyAxisEvent contains joystick axis motion event information. // (https://wiki.libsdl.org/SDL_JoyAxisEvent) type JoyAxisEvent struct { Type uint32 // JOYAXISMOTION Timestamp uint32 // timestamp of the event Which JoystickID // the instance id of the joystick that reported the event Axis uint8 // the index of the axis that changed _ uint8 // padding _ uint8 // padding _ uint8 // padding Value int16 // the current position of the axis (range: -32768 to 32767) _ uint16 // padding } type cJoyAxisEvent C.SDL_JoyAxisEvent // GetType returns the event type. func (e *JoyAxisEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *JoyAxisEvent) GetTimestamp() uint32 { return e.Timestamp } // JoyBallEvent contains joystick trackball motion event information. // (https://wiki.libsdl.org/SDL_JoyBallEvent) type JoyBallEvent struct { Type uint32 // JOYBALLMOTION Timestamp uint32 // timestamp of the event Which JoystickID // the instance id of the joystick that reported the event Ball uint8 // the index of the trackball that changed _ uint8 // padding _ uint8 // padding _ uint8 // padding XRel int16 // the relative motion in the X direction YRel int16 // the relative motion in the Y direction } type cJoyBallEvent C.SDL_JoyBallEvent // GetType returns the event type. func (e *JoyBallEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *JoyBallEvent) GetTimestamp() uint32 { return e.Timestamp } // JoyHatEvent contains joystick hat position change event information. // (https://wiki.libsdl.org/SDL_JoyHatEvent) type JoyHatEvent struct { Type uint32 // JOYHATMOTION Timestamp uint32 // timestamp of the event Which JoystickID // the instance id of the joystick that reported the event Hat uint8 // the index of the hat that changed Value uint8 // HAT_LEFTUP, HAT_UP, HAT_RIGHTUP, HAT_LEFT, HAT_CENTERED, HAT_RIGHT, HAT_LEFTDOWN, HAT_DOWN, HAT_RIGHTDOWN _ uint8 // padding _ uint8 // padding } type cJoyHatEvent C.SDL_JoyHatEvent // GetType returns the event type. func (e *JoyHatEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *JoyHatEvent) GetTimestamp() uint32 { return e.Timestamp } // JoyButtonEvent contains joystick button event information. // (https://wiki.libsdl.org/SDL_JoyButtonEvent) type JoyButtonEvent struct { Type uint32 // JOYBUTTONDOWN, JOYBUTTONUP Timestamp uint32 // timestamp of the event Which JoystickID // the instance id of the joystick that reported the event Button uint8 // the index of the button that changed State uint8 // PRESSED, RELEASED _ uint8 // padding _ uint8 // padding } type cJoyButtonEvent C.SDL_JoyButtonEvent // GetType returns the event type. func (e *JoyButtonEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *JoyButtonEvent) GetTimestamp() uint32 { return e.Timestamp } // JoyDeviceAddedEvent contains joystick device event information. // (https://wiki.libsdl.org/SDL_JoyDeviceEvent) type JoyDeviceAddedEvent struct { Type uint32 // JOYDEVICEADDED Timestamp uint32 // the timestamp of the event Which JoystickID // the joystick device index } // GetType returns the event type. func (e *JoyDeviceAddedEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *JoyDeviceAddedEvent) GetTimestamp() uint32 { return e.Timestamp } // JoyDeviceRemovedEvent contains joystick device event information. // (https://wiki.libsdl.org/SDL_JoyDeviceEvent) type JoyDeviceRemovedEvent struct { Type uint32 // JOYDEVICEREMOVED Timestamp uint32 // the timestamp of the event Which JoystickID // the instance id } // GetType returns the event type. func (e *JoyDeviceRemovedEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *JoyDeviceRemovedEvent) GetTimestamp() uint32 { return e.Timestamp } // ControllerAxisEvent contains game controller axis motion event information. // (https://wiki.libsdl.org/SDL_ControllerAxisEvent) type ControllerAxisEvent struct { Type uint32 // CONTROLLERAXISMOTION Timestamp uint32 // the timestamp of the event Which JoystickID // the joystick instance id Axis uint8 // the controller axis (https://wiki.libsdl.org/SDL_GameControllerAxis) _ uint8 // padding _ uint8 // padding _ uint8 // padding Value int16 // the axis value (range: -32768 to 32767) _ uint16 // padding } type cControllerAxisEvent C.SDL_ControllerAxisEvent // GetType returns the event type. func (e *ControllerAxisEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *ControllerAxisEvent) GetTimestamp() uint32 { return e.Timestamp } // ControllerButtonEvent contains game controller button event information. // (https://wiki.libsdl.org/SDL_ControllerButtonEvent) type ControllerButtonEvent struct { Type uint32 // CONTROLLERBUTTONDOWN, CONTROLLERBUTTONUP Timestamp uint32 // the timestamp of the event Which JoystickID // the joystick instance id Button uint8 // the controller button (https://wiki.libsdl.org/SDL_GameControllerButton) State uint8 // PRESSED, RELEASED _ uint8 // padding _ uint8 // padding } type cControllerButtonEvent C.SDL_ControllerButtonEvent // GetType returns the event type. func (e *ControllerButtonEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *ControllerButtonEvent) GetTimestamp() uint32 { return e.Timestamp } // ControllerDeviceEvent contains controller device event information. // (https://wiki.libsdl.org/SDL_ControllerDeviceEvent) type ControllerDeviceEvent struct { Type uint32 // CONTROLLERDEVICEADDED, CONTROLLERDEVICEREMOVED, SDL_CONTROLLERDEVICEREMAPPED Timestamp uint32 // the timestamp of the event Which JoystickID // the joystick device index for the CONTROLLERDEVICEADDED event or instance id for the CONTROLLERDEVICEREMOVED or CONTROLLERDEVICEREMAPPED event } type cControllerDeviceEvent C.SDL_ControllerDeviceEvent // GetType returns the event type. func (e *ControllerDeviceEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *ControllerDeviceEvent) GetTimestamp() uint32 { return e.Timestamp } // AudioDeviceEvent contains audio device event information. // (https://wiki.libsdl.org/SDL_AudioDeviceEvent) type AudioDeviceEvent struct { Type uint32 // AUDIODEVICEADDED, AUDIODEVICEREMOVED Timestamp uint32 // the timestamp of the event Which uint32 // the audio device index for the AUDIODEVICEADDED event (valid until next GetNumAudioDevices() call), AudioDeviceID for the AUDIODEVICEREMOVED event IsCapture uint8 // zero if an audio output device, non-zero if an audio capture device _ uint8 // padding _ uint8 // padding _ uint8 // padding } type cAudioDeviceEvent C.SDL_AudioDeviceEvent // GetType returns the event type. func (e *AudioDeviceEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *AudioDeviceEvent) GetTimestamp() uint32 { return e.Timestamp } // TouchFingerEvent contains finger touch event information. // (https://wiki.libsdl.org/SDL_TouchFingerEvent) type TouchFingerEvent struct { Type uint32 // FINGERMOTION, FINGERDOWN, FINGERUP Timestamp uint32 // timestamp of the event TouchID TouchID // the touch device id FingerID FingerID // the finger id X float32 // the x-axis location of the touch event, normalized (0...1) Y float32 // the y-axis location of the touch event, normalized (0...1) DX float32 // the distance moved in the x-axis, normalized (-1...1) DY float32 // the distance moved in the y-axis, normalized (-1...1) Pressure float32 // the quantity of pressure applied, normalized (0...1) } type cTouchFingerEvent C.SDL_TouchFingerEvent // GetType returns the event type. func (e *TouchFingerEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *TouchFingerEvent) GetTimestamp() uint32 { return e.Timestamp } // MultiGestureEvent contains multiple finger gesture event information. // (https://wiki.libsdl.org/SDL_MultiGestureEvent) type MultiGestureEvent struct { Type uint32 // MULTIGESTURE Timestamp uint32 // timestamp of the event TouchID TouchID // the touch device id DTheta float32 // the amount that the fingers rotated during this motion DDist float32 // the amount that the fingers pinched during this motion X float32 // the normalized center of gesture Y float32 // the normalized center of gesture NumFingers uint16 // the number of fingers used in the gesture _ uint16 // padding } type cMultiGestureEvent C.SDL_MultiGestureEvent // GetType returns the event type. func (e *MultiGestureEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *MultiGestureEvent) GetTimestamp() uint32 { return e.Timestamp } // DollarGestureEvent contains complex gesture event information. // (https://wiki.libsdl.org/SDL_DollarGestureEvent) type DollarGestureEvent struct { Type uint32 // DOLLARGESTURE, DOLLARRECORD Timestamp uint32 // timestamp of the event TouchID TouchID // the touch device id GestureID GestureID // the unique id of the closest gesture to the performed stroke NumFingers uint32 // the number of fingers used to draw the stroke Error float32 // the difference between the gesture template and the actual performed gesture (lower error is a better match) X float32 // the normalized center of gesture Y float32 // the normalized center of gesture } type cDollarGestureEvent C.SDL_DollarGestureEvent // GetType returns the event type. func (e *DollarGestureEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *DollarGestureEvent) GetTimestamp() uint32 { return e.Timestamp } // DropEvent contains an event used to request a file open by the system. // (https://wiki.libsdl.org/SDL_DropEvent) type DropEvent struct { Type uint32 // DROPFILE, DROPTEXT, DROPBEGIN, DROPCOMPLETE Timestamp uint32 // timestamp of the event File string // the file name WindowID uint32 // the window that was dropped on, if any } type tDropEvent struct { Type uint32 Timestamp uint32 File unsafe.Pointer WindowID uint32 } type cDropEvent C.SDL_DropEvent // GetType returns the event type. func (e *DropEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *DropEvent) GetTimestamp() uint32 { return e.Timestamp } // SensorEvent contains data from sensors such as accelerometer and gyroscope // (https://wiki.libsdl.org/SDL_SensorEvent) type SensorEvent struct { Type uint32 // SDL_SENSORUPDATE Timestamp uint32 // In milliseconds, populated using SDL_GetTicks() Which int32 // The instance ID of the sensor Data [6]float32 // Up to 6 values from the sensor - additional values can be queried using SDL_SensorGetData() } type cSensorEvent C.SDL_SensorEvent // GetType returns the event type. func (e *SensorEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *SensorEvent) GetTimestamp() uint32 { return e.Timestamp } // RenderEvent contains render event information. // (https://wiki.libsdl.org/SDL_EventType) type RenderEvent struct { Type uint32 // the event type Timestamp uint32 // timestamp of the event } // GetType returns the event type. func (e *RenderEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *RenderEvent) GetTimestamp() uint32 { return e.Timestamp } // QuitEvent contains the "quit requested" event. // (https://wiki.libsdl.org/SDL_QuitEvent) type QuitEvent struct { Type uint32 // QUIT Timestamp uint32 // timestamp of the event } // GetType returns the event type. func (e *QuitEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *QuitEvent) GetTimestamp() uint32 { return e.Timestamp } // OSEvent contains OS specific event information. type OSEvent struct { Type uint32 // the event type Timestamp uint32 // timestamp of the event } // GetType returns the event type. func (e *OSEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *OSEvent) GetTimestamp() uint32 { return e.Timestamp } // ClipboardEvent contains clipboard event information. // (https://wiki.libsdl.org/SDL_EventType) type ClipboardEvent struct { Type uint32 // CLIPBOARDUPDATE Timestamp uint32 // timestamp of the event } // GetType returns the event type. func (e *ClipboardEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *ClipboardEvent) GetTimestamp() uint32 { return e.Timestamp } // UserEvent contains an application-defined event type. // (https://wiki.libsdl.org/SDL_UserEvent) type UserEvent struct { Type uint32 // value obtained from RegisterEvents() Timestamp uint32 // timestamp of the event WindowID uint32 // the associated window, if any Code int32 // user defined event code Data1 unsafe.Pointer // user defined data pointer Data2 unsafe.Pointer // user defined data pointer } type cUserEvent C.SDL_UserEvent // GetType returns the event type. func (e *UserEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *UserEvent) GetTimestamp() uint32 { return e.Timestamp } // SysWMEvent contains a video driver dependent system event. // (https://wiki.libsdl.org/SDL_SysWMEvent) type SysWMEvent struct { Type uint32 // SYSWMEVENT Timestamp uint32 // timestamp of the event Msg *SysWMmsg // driver dependent data, defined in SDL_syswm.h } type cSysWMEvent C.SDL_SysWMEvent // GetType returns the event type. func (e *SysWMEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *SysWMEvent) GetTimestamp() uint32 { return e.Timestamp } // EventAction is the action to take in PeepEvents() function. // (https://wiki.libsdl.org/SDL_PeepEvents) type EventAction C.SDL_eventaction // EventFilter is the function to call when an event happens. // (https://wiki.libsdl.org/SDL_SetEventFilter) type EventFilter interface { FilterEvent(e Event, userdata interface{}) bool } type eventFilterFunc func(Event, interface{}) bool type eventFilterCallbackContext struct { filter EventFilter handle EventWatchHandle userdata interface{} } // EventWatchHandle is an event watch callback added with AddEventWatch(). type EventWatchHandle uintptr func (action EventAction) c() C.SDL_eventaction { return C.SDL_eventaction(action) } // PumpEvents pumps the event loop, gathering events from the input devices. // (https://wiki.libsdl.org/SDL_PumpEvents) func PumpEvents() { C.SDL_PumpEvents() } // PeepEvents checks the event queue for messages and optionally return them. // (https://wiki.libsdl.org/SDL_PeepEvents) func PeepEvents(events []Event, action EventAction, minType, maxType uint32) (storedEvents int, err error) { if events == nil { return 0, nil } var _events []CEvent = make([]CEvent, len(events)) if action == ADDEVENT { // the contents of _events matter if they are to be added for i := 0; i < len(events); i++ { _events[i] = *cEvent(events[i]) } } _pevents := (*C.SDL_Event)(unsafe.Pointer(&_events[0])) storedEvents = int(C.SDL_PeepEvents(_pevents, C.int(len(events)), action.c(), C.Uint32(minType), C.Uint32(maxType))) if action != ADDEVENT { // put events into slice, events unchanged if action = ADDEVENT for i := 0; i < storedEvents; i++ { events[i] = goEvent(&_events[i]) } } if storedEvents < 0 { err = GetError() } return } // HasEvent checks for the existence of certain event types in the event queue. // (https://wiki.libsdl.org/SDL_HasEvent) func HasEvent(type_ uint32) bool { return C.SDL_HasEvent(C.Uint32(type_)) != 0 } // HasEvents checks for the existence of a range of event types in the event queue. // (https://wiki.libsdl.org/SDL_HasEvents) func HasEvents(minType, maxType uint32) bool { return C.SDL_HasEvents(C.Uint32(minType), C.Uint32(maxType)) != 0 } // FlushEvent clears events from the event queue. // (https://wiki.libsdl.org/SDL_FlushEvent) func FlushEvent(type_ uint32) { C.SDL_FlushEvent(C.Uint32(type_)) } // FlushEvents clears events from the event queue. // (https://wiki.libsdl.org/SDL_FlushEvents) func FlushEvents(minType, maxType uint32) { C.SDL_FlushEvents(C.Uint32(minType), C.Uint32(maxType)) } // PollEvent polls for currently pending events. // (https://wiki.libsdl.org/SDL_PollEvent) func PollEvent() Event { ret := C.PollEvent() if ret == 0 { return nil } return goEvent((*CEvent)(unsafe.Pointer(&C.event))) } func goEvent(cevent *CEvent) Event { switch cevent.Type { case DISPLAYEVENT: return (*DisplayEvent)(unsafe.Pointer(cevent)) case WINDOWEVENT: return (*WindowEvent)(unsafe.Pointer(cevent)) case SYSWMEVENT: return (*SysWMEvent)(unsafe.Pointer(cevent)) case KEYDOWN, KEYUP: return (*KeyboardEvent)(unsafe.Pointer(cevent)) case TEXTEDITING: return (*TextEditingEvent)(unsafe.Pointer(cevent)) case TEXTINPUT: return (*TextInputEvent)(unsafe.Pointer(cevent)) case MOUSEMOTION: return (*MouseMotionEvent)(unsafe.Pointer(cevent)) case MOUSEBUTTONDOWN, MOUSEBUTTONUP: return (*MouseButtonEvent)(unsafe.Pointer(cevent)) case MOUSEWHEEL: return (*MouseWheelEvent)(unsafe.Pointer(cevent)) case JOYAXISMOTION: return (*JoyAxisEvent)(unsafe.Pointer(cevent)) case JOYBALLMOTION: return (*JoyBallEvent)(unsafe.Pointer(cevent)) case JOYHATMOTION: return (*JoyHatEvent)(unsafe.Pointer(cevent)) case JOYBUTTONDOWN, JOYBUTTONUP: return (*JoyButtonEvent)(unsafe.Pointer(cevent)) case JOYDEVICEADDED: return (*JoyDeviceAddedEvent)(unsafe.Pointer(cevent)) case JOYDEVICEREMOVED: return (*JoyDeviceRemovedEvent)(unsafe.Pointer(cevent)) case CONTROLLERAXISMOTION: return (*ControllerAxisEvent)(unsafe.Pointer(cevent)) case CONTROLLERBUTTONDOWN, CONTROLLERBUTTONUP: return (*ControllerButtonEvent)(unsafe.Pointer(cevent)) case CONTROLLERDEVICEADDED, CONTROLLERDEVICEREMOVED, CONTROLLERDEVICEREMAPPED: return (*ControllerDeviceEvent)(unsafe.Pointer(cevent)) case AUDIODEVICEADDED, AUDIODEVICEREMOVED: return (*AudioDeviceEvent)(unsafe.Pointer(cevent)) case FINGERMOTION, FINGERDOWN, FINGERUP: return (*TouchFingerEvent)(unsafe.Pointer(cevent)) case MULTIGESTURE: return (*MultiGestureEvent)(unsafe.Pointer(cevent)) case DOLLARGESTURE, DOLLARRECORD: return (*DollarGestureEvent)(unsafe.Pointer(cevent)) case DROPFILE, DROPTEXT, DROPBEGIN, DROPCOMPLETE: e := (*tDropEvent)(unsafe.Pointer(cevent)) event := DropEvent{Type: e.Type, Timestamp: e.Timestamp, File: C.GoString((*C.char)(e.File)), WindowID: e.WindowID} C.SDL_free(e.File) return &event case SENSORUPDATE: return (*SensorEvent)(unsafe.Pointer(cevent)) case RENDER_TARGETS_RESET, RENDER_DEVICE_RESET: return (*RenderEvent)(unsafe.Pointer(cevent)) case QUIT: return (*QuitEvent)(unsafe.Pointer(cevent)) case CLIPBOARDUPDATE: return (*ClipboardEvent)(unsafe.Pointer(cevent)) default: if cevent.Type >= USEREVENT { // all events beyond USEREVENT are UserEvents to be registered with RegisterEvents return (*UserEvent)(unsafe.Pointer(cevent)) } return (*CommonEvent)(unsafe.Pointer(cevent)) } } func cEvent(event Event) *CEvent { evv := reflect.ValueOf(event) p := evv.Elem() return (*CEvent)(unsafe.Pointer(p.UnsafeAddr())) } // WaitEventTimeout waits until the specified timeout (in milliseconds) for the next available event. // (https://wiki.libsdl.org/SDL_WaitEventTimeout) func WaitEventTimeout(timeout int) Event { var cevent CEvent _event := (*C.SDL_Event)(unsafe.Pointer(&cevent)) ok := int(C.SDL_WaitEventTimeout(_event, C.int(timeout))) if ok == 0 { return nil } return goEvent(&cevent) } // WaitEvent waits indefinitely for the next available event. // (https://wiki.libsdl.org/SDL_WaitEvent) func WaitEvent() Event { var cevent CEvent _event := (*C.SDL_Event)(unsafe.Pointer(&cevent)) ok := int(C.SDL_WaitEvent(_event)) if ok == 0 { return nil } return goEvent(&cevent) } // PushEvent adds an event to the event queue. // (https://wiki.libsdl.org/SDL_PushEvent) func PushEvent(event Event) (filtered bool, err error) { _event := (*C.SDL_Event)(unsafe.Pointer(cEvent(event))) if ok := int(C.SDL_PushEvent(_event)); ok < 0 { filtered, err = false, GetError() } else if ok == 0 { filtered, err = true, nil } return } func (ef eventFilterFunc) FilterEvent(e Event, userdata interface{}) bool { return ef(e, userdata) } func newEventFilterCallbackContext(filter EventFilter, userdata interface{}) *eventFilterCallbackContext { lastEventWatchHandleMutex.Lock() defer lastEventWatchHandleMutex.Unlock() // Look for the next available watch handle (this should be immediate // unless you're creating a LOT of handlers). for { if _, ok := eventWatches[lastEventWatchHandle]; !ok { break } lastEventWatchHandle++ } e := &eventFilterCallbackContext{filter, lastEventWatchHandle, userdata} eventWatches[lastEventWatchHandle] = e lastEventWatchHandle++ return e } func (e *eventFilterCallbackContext) cptr() unsafe.Pointer { return unsafe.Pointer(e.handle) } //export goSetEventFilterCallback func goSetEventFilterCallback(data unsafe.Pointer, e *C.SDL_Event) C.int { // No check for eventFilterCache != nil. Why? because it should never be // nil since the callback is set/unset based on the last filter being nil // /non-nil. If there is an issue, then it should panic here so we can // figure out why that is. return wrapEventFilterCallback(eventFilterCache, e, nil) } //export goEventFilterCallback func goEventFilterCallback(userdata unsafe.Pointer, e *C.SDL_Event) C.int { // same sort of reasoning with goSetEventFilterCallback, userdata should // always be non-nil and represent a valid eventFilterCallbackContext. If // it doesn't a panic will let us know that there something wrong and the // problem can be fixed. context := eventWatches[EventWatchHandle(userdata)] return wrapEventFilterCallback(context.filter, e, context.userdata) } func wrapEventFilterCallback(filter EventFilter, e *C.SDL_Event, userdata interface{}) C.int { gev := goEvent((*CEvent)(unsafe.Pointer(e))) result := filter.FilterEvent(gev, userdata) if result { return C.SDL_TRUE } return C.SDL_FALSE } // SetEventFilter sets up a filter to process all events before they change internal state and are posted to the internal event queue. // (https://wiki.libsdl.org/SDL_SetEventFilter) func SetEventFilter(filter EventFilter, userdata interface{}) { if eventFilterCache == nil && filter == nil { // nothing to do... return } if eventFilterCache == nil && filter != nil { // We had no event filter before and do now; lets set // goSetEventFilterCallback() as the event filter. C.setEventFilter() } else if eventFilterCache != nil && filter == nil { // We had an event filter before, but no longer do, lets clear the // event filter C.clearEventFilter() } eventFilterCache = filter } // SetEventFilterFunc sets up a function to process all events before they change internal state and are posted to the internal event queue. // (https://wiki.libsdl.org/SDL_SetEventFilter) func SetEventFilterFunc(filterFunc eventFilterFunc, userdata interface{}) { SetEventFilter(filterFunc, userdata) } // GetEventFilter queries the current event filter. // (https://wiki.libsdl.org/SDL_GetEventFilter) func GetEventFilter() EventFilter { return eventFilterCache } func isCEventFilterSet() bool { return C.SDL_GetEventFilter(nil, nil) == C.SDL_TRUE } // FilterEvents run a specific filter function on the current event queue, removing any events for which the filter returns 0. // (https://wiki.libsdl.org/SDL_FilterEvents) func FilterEvents(filter EventFilter, userdata interface{}) { context := newEventFilterCallbackContext(filter, userdata) C.filterEvents(context.cptr()) } // FilterEventsFunc run a specific function on the current event queue, removing any events for which the filter returns 0. // (https://wiki.libsdl.org/SDL_FilterEvents) func FilterEventsFunc(filter eventFilterFunc, userdata interface{}) { FilterEvents(filter, userdata) } // AddEventWatch adds a callback to be triggered when an event is added to the event queue. // (https://wiki.libsdl.org/SDL_AddEventWatch) func AddEventWatch(filter EventFilter, userdata interface{}) EventWatchHandle { context := newEventFilterCallbackContext(filter, userdata) C.addEventWatch(context.cptr()) return context.handle } // AddEventWatchFunc adds a callback function to be triggered when an event is added to the event queue. // (https://wiki.libsdl.org/SDL_AddEventWatch) func AddEventWatchFunc(filterFunc eventFilterFunc, userdata interface{}) EventWatchHandle { return AddEventWatch(filterFunc, userdata) } // DelEventWatch removes an event watch callback added with AddEventWatch(). // (https://wiki.libsdl.org/SDL_DelEventWatch) func DelEventWatch(handle EventWatchHandle) { context, ok := eventWatches[handle] if !ok { return } delete(eventWatches, context.handle) C.delEventWatch(context.cptr()) } // EventState sets the state of processing events by type. // (https://wiki.libsdl.org/SDL_EventState) func EventState(type_ uint32, state int) uint8 { return uint8(C.SDL_EventState(C.Uint32(type_), C.int(state))) } // GetEventState returns the current processing state of the specified event // (https://wiki.libsdl.org/SDL_EventState) func GetEventState(type_ uint32) uint8 { return uint8(C.SDL_EventState(C.Uint32(type_), QUERY)) } // RegisterEvents allocates a set of user-defined events, and return the beginning event number for that set of events. // (https://wiki.libsdl.org/SDL_RegisterEvents) func RegisterEvents(numEvents int) uint32 { return uint32(C.SDL_RegisterEvents(C.int(numEvents))) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/events.h ================================================ #ifndef _GO_SDL_EVENTS_H #define _GO_SDL_EVENTS_H #if defined(_WIN32) #include #else #include #endif extern SDL_Event event; extern void setEventFilter(); extern void clearEventFilter(); extern void filterEvents(void *userdata); extern void addEventWatch(void *userdata); extern void delEventWatch(void *userdata); extern int PollEvent(); #endif ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/filesystem.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,1)) #if defined(WARN_OUTDATED) #pragma message("SDL_GetBasePath is not supported before SDL 2.0.1") #endif static inline char* SDL_GetBasePath() { return NULL; } #if defined(WARN_OUTDATED) #pragma message("SDL_GetPrefPath is not supported before SDL 2.0.1") #endif static inline char* SDL_GetPrefPath(const char *org, const char *app) { return NULL; } #endif */ import "C" import "unsafe" // GetBasePath returns the directory where the application was run from. This is where the application data directory is. // (https://wiki.libsdl.org/SDL_GetBasePath) func GetBasePath() string { _val := C.SDL_GetBasePath() defer C.SDL_free(unsafe.Pointer(_val)) return C.GoString(_val) } // GetPrefPath returns the "pref dir". This is meant to be where the application can write personal files (Preferences and save games, etc.) that are specific to the application. This directory is unique per user and per application. // (https://wiki.libsdl.org/SDL_GetPrefPath) func GetPrefPath(org, app string) string { _org := C.CString(org) _app := C.CString(app) defer C.free(unsafe.Pointer(_org)) defer C.free(unsafe.Pointer(_app)) _val := C.SDL_GetPrefPath(_org, _app) defer C.SDL_free(unsafe.Pointer(_val)) return C.GoString(_val) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/gamecontroller.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,4)) #if defined(WARN_OUTDATED) #pragma message("SDL_GameControllerFromInstanceID is not supported before SDL 2.0.4") #endif static SDL_GameController* SDL_GameControllerFromInstanceID(SDL_JoystickID joyid) { return NULL; } #endif #if !(SDL_VERSION_ATLEAST(2,0,6)) #if defined(WARN_OUTDATED) #pragma message("SDL_GameControllerGetVendor is not supported before SDL 2.0.6") #pragma message("SDL_GameControllerGetProduct is not supported before SDL 2.0.6") #pragma message("SDL_GameControllerGetProductVersion is not supported before SDL 2.0.6") #pragma message("SDL_GameControllerNumMappings is not supported before SDL 2.0.6") #pragma message("SDL_GameControllerMappingForIndex is not supported before SDL 2.0.6") #endif static Uint16 SDL_GameControllerGetVendor(SDL_GameController* gamecontroller) { return 0; } static Uint16 SDL_GameControllerGetProduct(SDL_GameController* gamecontroller) { return 0; } static Uint16 SDL_GameControllerGetProductVersion(SDL_GameController* gamecontroller) { return 0; } static int SDL_GameControllerNumMappings(void) { return 0; } static char* SDL_GameControllerMappingForIndex(int mapping_index) { return NULL; } #endif #if !(SDL_VERSION_ATLEAST(2,0,9)) #if defined(WARN_OUTDATED) #pragma message("SDL_GameControllerGetPlayerIndex is not supported before SDL 2.0.9") #pragma message("SDL_GameControllerRumble is not supported before SDL 2.0.9") #pragma message("SDL_GameControllerMappingForDeviceIndex is not supported before SDL 2.0.9") #endif typedef enum { SDL_SENSOR_INVALID = -1, SDL_SENSOR_UNKNOWN, SDL_SENSOR_ACCEL, SDL_SENSOR_GYRO } SDL_SensorType; static int SDL_GameControllerGetPlayerIndex(SDL_GameController *gamecontroller) { return -1; } static int SDL_GameControllerRumble(SDL_GameController *gamecontroller, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble, Uint32 duration_ms) { return -1; } static char *SDL_GameControllerMappingForDeviceIndex(int joystick_index) { return NULL; } #endif #if !(SDL_VERSION_ATLEAST(2,0,12)) typedef enum { SDL_CONTROLLER_TYPE_UNKNOWN = 0, SDL_CONTROLLER_TYPE_XBOX360, SDL_CONTROLLER_TYPE_XBOXONE, SDL_CONTROLLER_TYPE_PS3, SDL_CONTROLLER_TYPE_PS4, SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO } SDL_GameControllerType; #if defined(WARN_OUTDATED) #pragma message("SDL_GameControllerTypeForIndex is not supported before SDL 2.0.12") #pragma message("SDL_GameControllerGetType is not supported before SDL 2.0.12") #pragma message("SDL_GameControllerFromPlayerIndex is not supported before SDL 2.0.12") #pragma message("SDL_GameControllerSetPlayerIndex is not supported before SDL 2.0.12") #endif static SDL_GameControllerType SDL_GameControllerTypeForIndex(int joystick_index) { return SDL_CONTROLLER_TYPE_UNKNOWN; } static SDL_GameControllerType SDL_GameControllerGetType(SDL_GameController *gamecontroller) { return SDL_CONTROLLER_TYPE_UNKNOWN; } static SDL_GameController * SDL_GameControllerFromPlayerIndex(int player_index) { return NULL; } static void SDL_GameControllerSetPlayerIndex(SDL_GameController *gamecontroller, int player_index) { // do nothing } #endif #if !(SDL_VERSION_ATLEAST(2,0,14)) #define SDL_CONTROLLER_TYPE_VIRTUAL (6) #define SDL_CONTROLLER_TYPE_PS5 (7) #if defined(WARN_OUTDATED) #pragma message("SDL_GameControllerGetSerial is not supported before SDL 2.0.14") #pragma message("SDL_GameControllerHasAxis is not supported before SDL 2.0.14") #pragma message("SDL_GameControllerHasButton is not supported before SDL 2.0.14") #pragma message("SDL_GameControllerGetNumTouchpads is not supported before SDL 2.0.14") #pragma message("SDL_GameControllerGetNumTouchpadFingers is not supported before SDL 2.0.14") #pragma message("SDL_GameControllerGetTouchpadFinger is not supported before SDL 2.0.14") #pragma message("SDL_GameControllerHasSensor is not supported before SDL 2.0.14") #pragma message("SDL_GameControllerSetSensorEnabled is not supported before SDL 2.0.14") #pragma message("SDL_GameControllerIsSensorEnabled is not supported before SDL 2.0.14") #pragma message("SDL_GameControllerGetSensorData is not supported before SDL 2.0.14") #pragma message("SDL_GameControllerRumbleTriggers is not supported before SDL 2.0.14") #pragma message("SDL_GameControllerHasLED is not supported before SDL 2.0.14") #pragma message("SDL_GameControllerSetLED is not supported before SDL 2.0.14") #endif static const char * SDLCALL SDL_GameControllerGetSerial(SDL_GameController *gamecontroller) { return NULL; } static SDL_bool SDL_GameControllerHasAxis(SDL_GameController *gamecontroller, SDL_GameControllerAxis axis) { return SDL_FALSE; } static SDL_bool SDLCALL SDL_GameControllerHasButton(SDL_GameController *gamecontroller, SDL_GameControllerButton button) { return SDL_FALSE; } static int SDLCALL SDL_GameControllerGetNumTouchpads(SDL_GameController *gamecontroller) { return 0; } static int SDL_GameControllerGetNumTouchpadFingers(SDL_GameController *gamecontroller, int touchpad) { return 0; } static int SDL_GameControllerGetTouchpadFinger(SDL_GameController *gamecontroller, int touchpad, int finger, Uint8 *state, float *x, float *y, float *pressure) { return -1; } static SDL_bool SDL_GameControllerHasSensor(SDL_GameController *gamecontroller, SDL_SensorType type) { return SDL_FALSE; } static int SDL_GameControllerSetSensorEnabled(SDL_GameController *gamecontroller, SDL_SensorType type, SDL_bool enabled) { return -1; } static SDL_bool SDL_GameControllerIsSensorEnabled(SDL_GameController *gamecontroller, SDL_SensorType type) { return SDL_FALSE; } static int SDL_GameControllerGetSensorData(SDL_GameController *gamecontroller, SDL_SensorType type, float *data, int num_values) { return -1; } static int SDL_GameControllerRumbleTriggers(SDL_GameController *gamecontroller, Uint16 left_rumble, Uint16 right_rumble, Uint32 duration_ms) { return -1; } static SDL_bool SDL_GameControllerHasLED(SDL_GameController *gamecontroller) { return SDL_FALSE; } static int SDL_GameControllerSetLED(SDL_GameController *gamecontroller, Uint8 red, Uint8 green, Uint8 blue) { return -1; } #endif #if !(SDL_VERSION_ATLEAST(2,0,16)) #if defined(WARN_OUTDATED) #pragma message("SDL_GameControllerSendEffect is not supported before SDL 2.0.16") #pragma message("SDL_GameControllerGetSensorDataRate is not supported before SDL 2.0.16") #endif static int SDL_GameControllerSendEffect(SDL_GameController *gamecontroller, const void *data, int size) { return -1; } static float SDL_GameControllerGetSensorDataRate(SDL_GameController *gamecontroller, SDL_SensorType type) { return 0.0f; } #endif #if !(SDL_VERSION_ATLEAST(2,0,18)) #if defined(WARN_OUTDATED) #pragma message("SDL_GameControllerHasRumble is not supported before SDL 2.0.18") #pragma message("SDL_GameControllerHasRumbleTriggers is not supported before SDL 2.0.18") #pragma message("SDL_GameControllerGetAppleSFSymbolsNameForButton is not supported before SDL 2.0.18") #pragma message("SDL_GameControllerGetAppleSFSymbolsNameForAxis is not supported before SDL 2.0.18") #endif static SDL_bool SDL_GameControllerHasRumble(SDL_GameController *gamecontroller) { return SDL_FALSE; } static SDL_bool SDL_GameControllerHasRumbleTriggers(SDL_GameController *gamecontroller) { return SDL_FALSE; } static const char* SDL_GameControllerGetAppleSFSymbolsNameForButton(SDL_GameController *gamecontroller, SDL_GameControllerButton button) { return NULL; } static const char* SDL_GameControllerGetAppleSFSymbolsNameForAxis(SDL_GameController *gamecontroller, SDL_GameControllerAxis axis) { return NULL; } #endif */ import "C" import ( "encoding/binary" "unsafe" ) // Types of game controller inputs. const ( CONTROLLER_BINDTYPE_NONE = C.SDL_CONTROLLER_BINDTYPE_NONE CONTROLLER_BINDTYPE_BUTTON = C.SDL_CONTROLLER_BINDTYPE_BUTTON CONTROLLER_BINDTYPE_AXIS = C.SDL_CONTROLLER_BINDTYPE_AXIS CONTROLLER_BINDTYPE_HAT = C.SDL_CONTROLLER_BINDTYPE_HAT ) // An enumeration of axes available from a controller. // (https://wiki.libsdl.org/SDL_GameControllerAxis) const ( CONTROLLER_AXIS_INVALID = C.SDL_CONTROLLER_AXIS_INVALID CONTROLLER_AXIS_LEFTX = C.SDL_CONTROLLER_AXIS_LEFTX CONTROLLER_AXIS_LEFTY = C.SDL_CONTROLLER_AXIS_LEFTY CONTROLLER_AXIS_RIGHTX = C.SDL_CONTROLLER_AXIS_RIGHTX CONTROLLER_AXIS_RIGHTY = C.SDL_CONTROLLER_AXIS_RIGHTY CONTROLLER_AXIS_TRIGGERLEFT = C.SDL_CONTROLLER_AXIS_TRIGGERLEFT CONTROLLER_AXIS_TRIGGERRIGHT = C.SDL_CONTROLLER_AXIS_TRIGGERRIGHT CONTROLLER_AXIS_MAX = C.SDL_CONTROLLER_AXIS_MAX ) // An enumeration of buttons available from a controller. // (https://wiki.libsdl.org/SDL_GameControllerButton) const ( CONTROLLER_BUTTON_INVALID = C.SDL_CONTROLLER_BUTTON_INVALID CONTROLLER_BUTTON_A = C.SDL_CONTROLLER_BUTTON_A CONTROLLER_BUTTON_B = C.SDL_CONTROLLER_BUTTON_B CONTROLLER_BUTTON_X = C.SDL_CONTROLLER_BUTTON_X CONTROLLER_BUTTON_Y = C.SDL_CONTROLLER_BUTTON_Y CONTROLLER_BUTTON_BACK = C.SDL_CONTROLLER_BUTTON_BACK CONTROLLER_BUTTON_GUIDE = C.SDL_CONTROLLER_BUTTON_GUIDE CONTROLLER_BUTTON_START = C.SDL_CONTROLLER_BUTTON_START CONTROLLER_BUTTON_LEFTSTICK = C.SDL_CONTROLLER_BUTTON_LEFTSTICK CONTROLLER_BUTTON_RIGHTSTICK = C.SDL_CONTROLLER_BUTTON_RIGHTSTICK CONTROLLER_BUTTON_LEFTSHOULDER = C.SDL_CONTROLLER_BUTTON_LEFTSHOULDER CONTROLLER_BUTTON_RIGHTSHOULDER = C.SDL_CONTROLLER_BUTTON_RIGHTSHOULDER CONTROLLER_BUTTON_DPAD_UP = C.SDL_CONTROLLER_BUTTON_DPAD_UP CONTROLLER_BUTTON_DPAD_DOWN = C.SDL_CONTROLLER_BUTTON_DPAD_DOWN CONTROLLER_BUTTON_DPAD_LEFT = C.SDL_CONTROLLER_BUTTON_DPAD_LEFT CONTROLLER_BUTTON_DPAD_RIGHT = C.SDL_CONTROLLER_BUTTON_DPAD_RIGHT CONTROLLER_BUTTON_MAX = C.SDL_CONTROLLER_BUTTON_MAX ) // GameControllerBindType is a type of game controller input. type GameControllerBindType C.SDL_GameControllerBindType // GameControllerAxis is an axis on a game controller. // (https://wiki.libsdl.org/SDL_GameControllerAxis) type GameControllerAxis C.SDL_GameControllerAxis // GameControllerButton is a button on a game controller. // (https://wiki.libsdl.org/SDL_GameControllerButton) type GameControllerButton C.SDL_GameControllerButton // GameController used to identify an SDL game controller. type GameController C.SDL_GameController // GameControllerButtonBind SDL joystick layer binding for controller button/axis mapping. type GameControllerButtonBind C.SDL_GameControllerButtonBind func (ctrl *GameController) cptr() *C.SDL_GameController { return (*C.SDL_GameController)(unsafe.Pointer(ctrl)) } func (axis GameControllerAxis) c() C.SDL_GameControllerAxis { return C.SDL_GameControllerAxis(axis) } func (btn GameControllerButton) c() C.SDL_GameControllerButton { return C.SDL_GameControllerButton(btn) } // GameControllerAddMapping adds support for controllers that SDL is unaware of or to cause an existing controller to have a different binding. // (https://wiki.libsdl.org/SDL_GameControllerAddMapping) func GameControllerAddMapping(mappingString string) int { _mappingString := C.CString(mappingString) defer C.free(unsafe.Pointer(_mappingString)) return int(C.SDL_GameControllerAddMapping(_mappingString)) } // GameControllerNumMappings returns the number of mappings installed. func GameControllerNumMappings() int { return int(C.SDL_GameControllerNumMappings()) } // GameControllerMappingForIndex returns the game controller mapping string at a particular index. func GameControllerMappingForIndex(index int) string { mappingString := C.SDL_GameControllerMappingForIndex(C.int(index)) defer C.free(unsafe.Pointer(mappingString)) return C.GoString(mappingString) } // GameControllerMappingForGUID returns the game controller mapping string for a given GUID. // (https://wiki.libsdl.org/SDL_GameControllerMappingForGUID) func GameControllerMappingForGUID(guid JoystickGUID) string { mappingString := C.SDL_GameControllerMappingForGUID(guid.c()) defer C.free(unsafe.Pointer(mappingString)) return C.GoString(mappingString) } // IsGameController reports whether the given joystick is supported by the game controller interface. // (https://wiki.libsdl.org/SDL_IsGameController) func IsGameController(index int) bool { return C.SDL_IsGameController(C.int(index)) == C.SDL_TRUE } // GameControllerNameForIndex returns the implementation dependent name for the game controller. // (https://wiki.libsdl.org/SDL_GameControllerNameForIndex) func GameControllerNameForIndex(index int) string { return C.GoString(C.SDL_GameControllerNameForIndex(C.int(index))) } // GameControllerMappingForDeviceIndex returns the game controller mapping string at a particular index. func GameControllerMappingForDeviceIndex(index int) string { mappingString := C.SDL_GameControllerMappingForDeviceIndex(C.int(index)) defer C.free(unsafe.Pointer(mappingString)) return C.GoString(mappingString) } // GameControllerOpen opens a gamecontroller for use. // (https://wiki.libsdl.org/SDL_GameControllerOpen) func GameControllerOpen(index int) *GameController { return (*GameController)(C.SDL_GameControllerOpen(C.int(index))) } // GameControllerFromInstanceID returns the GameController associated with an instance id. // (https://wiki.libsdl.org/SDL_GameControllerFromInstanceID) func GameControllerFromInstanceID(joyid JoystickID) *GameController { return (*GameController)(C.SDL_GameControllerFromInstanceID(joyid.c())) } // Name returns the implementation dependent name for an opened game controller. // (https://wiki.libsdl.org/SDL_GameControllerName) func (ctrl *GameController) Name() string { return C.GoString(C.SDL_GameControllerName(ctrl.cptr())) } // PlayerIndex the player index of an opened game controller, or -1 if it's not available. // TODO: (https://wiki.libsdl.org/SDL_GameControllerGetPlayerIndex) func (ctrl *GameController) PlayerIndex() int { return int(C.SDL_GameControllerGetPlayerIndex(ctrl.cptr())) } // Vendor returns the USB vendor ID of an opened controller, if available, 0 otherwise. func (ctrl *GameController) Vendor() int { return int(C.SDL_GameControllerGetVendor(ctrl.cptr())) } // Product returns the USB product ID of an opened controller, if available, 0 otherwise. func (ctrl *GameController) Product() int { return int(C.SDL_GameControllerGetProduct(ctrl.cptr())) } // ProductVersion returns the product version of an opened controller, if available, 0 otherwise. func (ctrl *GameController) ProductVersion() int { return int(C.SDL_GameControllerGetProductVersion(ctrl.cptr())) } // Attached reports whether a controller has been opened and is currently connected. // (https://wiki.libsdl.org/SDL_GameControllerGetAttached) func (ctrl *GameController) Attached() bool { return C.SDL_GameControllerGetAttached(ctrl.cptr()) == C.SDL_TRUE } // Mapping returns the current mapping of a Game Controller. // (https://wiki.libsdl.org/SDL_GameControllerMapping) func (ctrl *GameController) Mapping() string { mappingString := C.SDL_GameControllerMapping(ctrl.cptr()) defer C.free(unsafe.Pointer(mappingString)) return C.GoString(mappingString) } // Joystick returns the Joystick ID from a Game Controller. The game controller builds on the Joystick API, but to be able to use the Joystick's functions with a gamepad, you need to use this first to get the joystick object. // (https://wiki.libsdl.org/SDL_GameControllerGetJoystick) func (ctrl *GameController) Joystick() *Joystick { return (*Joystick)(unsafe.Pointer(C.SDL_GameControllerGetJoystick(ctrl.cptr()))) } // GameControllerEventState returns the current state of, enable, or disable events dealing with Game Controllers. This will not disable Joystick events, which can also be fired by a controller (see https://wiki.libsdl.org/SDL_JoystickEventState). // (https://wiki.libsdl.org/SDL_GameControllerEventState) func GameControllerEventState(state int) int { return int(C.SDL_GameControllerEventState(C.int(state))) } // GameControllerUpdate manually pumps game controller updates if not using the loop. // (https://wiki.libsdl.org/SDL_GameControllerUpdate) func GameControllerUpdate() { C.SDL_GameControllerUpdate() } // GameControllerGetAxisFromString converts a string into an enum representation for a GameControllerAxis. // (https://wiki.libsdl.org/SDL_GameControllerGetAxisFromString) func GameControllerGetAxisFromString(pchString string) GameControllerAxis { _pchString := C.CString(pchString) defer C.free(unsafe.Pointer(_pchString)) return GameControllerAxis(C.SDL_GameControllerGetAxisFromString(_pchString)) } // GameControllerGetStringForAxis converts from an axis enum to a string. // (https://wiki.libsdl.org/SDL_GameControllerGetStringForAxis) func GameControllerGetStringForAxis(axis GameControllerAxis) string { return C.GoString(C.SDL_GameControllerGetStringForAxis(axis.c())) } // BindForAxis returns the SDL joystick layer binding for a controller button mapping. // (https://wiki.libsdl.org/SDL_GameControllerGetBindForAxis) func (ctrl *GameController) BindForAxis(axis GameControllerAxis) GameControllerButtonBind { return GameControllerButtonBind(C.SDL_GameControllerGetBindForAxis(ctrl.cptr(), axis.c())) } // Axis returns the current state of an axis control on a game controller. // (https://wiki.libsdl.org/SDL_GameControllerGetAxis) func (ctrl *GameController) Axis(axis GameControllerAxis) int16 { return int16(C.SDL_GameControllerGetAxis(ctrl.cptr(), axis.c())) } // GameControllerGetButtonFromString turns a string into a button mapping. // (https://wiki.libsdl.org/SDL_GameControllerGetButtonFromString) func GameControllerGetButtonFromString(pchString string) GameControllerButton { _pchString := C.CString(pchString) defer C.free(unsafe.Pointer(_pchString)) return GameControllerButton(C.SDL_GameControllerGetButtonFromString(_pchString)) } // GameControllerGetStringForButton turns a button enum into a string mapping. // (https://wiki.libsdl.org/SDL_GameControllerGetStringForButton) func GameControllerGetStringForButton(btn GameControllerButton) string { return C.GoString(C.SDL_GameControllerGetStringForButton(btn.c())) } // BindForButton returns the SDL joystick layer binding for this controller button mapping. // (https://wiki.libsdl.org/SDL_GameControllerGetBindForButton) func (ctrl *GameController) BindForButton(btn GameControllerButton) GameControllerButtonBind { return GameControllerButtonBind(C.SDL_GameControllerGetBindForButton(ctrl.cptr(), btn.c())) } // Rumble triggers a rumble effect // Each call to this function cancels any previous rumble effect, and calling it with 0 intensity stops any rumbling. // // lowFrequencyRumble - The intensity of the low frequency (left) rumble motor, from 0 to 0xFFFF // highFrequencyRumble - The intensity of the high frequency (right) rumble motor, from 0 to 0xFFFF // durationMS - The duration of the rumble effect, in milliseconds // // Returns error if rumble isn't supported on this joystick. // // TODO: (https://wiki.libsdl.org/SDL_GameControllerRumble) func (ctrl *GameController) Rumble(lowFrequencyRumble, highFrequencyRumble uint16, durationMS uint32) error { return errorFromInt(int(C.SDL_GameControllerRumble(ctrl.cptr(), C.Uint16(lowFrequencyRumble), C.Uint16(highFrequencyRumble), C.Uint32(durationMS)))) } // Button returns the current state of a button on a game controller. // (https://wiki.libsdl.org/SDL_GameControllerGetButton) func (ctrl *GameController) Button(btn GameControllerButton) byte { return byte(C.SDL_GameControllerGetButton(ctrl.cptr(), btn.c())) } // Close closes a game controller previously opened with GameControllerOpen(). // (https://wiki.libsdl.org/SDL_GameControllerClose) func (ctrl *GameController) Close() { C.SDL_GameControllerClose(ctrl.cptr()) } // Type returns the type of game controller input for this SDL joystick layer binding. func (bind *GameControllerButtonBind) Type() int { return int(bind.bindType) } // Button returns button mapped for this SDL joystick layer binding. func (bind *GameControllerButtonBind) Button() int { val, _ := binary.Varint(bind.value[:4]) return int(val) } // Axis returns axis mapped for this SDL joystick layer binding. func (bind *GameControllerButtonBind) Axis() int { val, _ := binary.Varint(bind.value[:4]) return int(val) } // Hat returns hat mapped for this SDL joystick layer binding. func (bind *GameControllerButtonBind) Hat() int { val, _ := binary.Varint(bind.value[:4]) return int(val) } // HatMask returns hat mask for this SDL joystick layer binding. func (bind *GameControllerButtonBind) HatMask() int { val, _ := binary.Varint(bind.value[4:8]) return int(val) } // SendEffect sends a controller specific effect packet. // (https://wiki.libsdl.org/SDL_GameControllerSendEffect) func (ctrl *GameController) SendEffect(data []byte) (err error) { _size := C.int(len(data)) return errorFromInt(int(C.SDL_GameControllerSendEffect(ctrl.cptr(), unsafe.Pointer(&data[0]), _size))) } // GetSensorDataRate gets the data rate (number of events per second) of a game controller sensor. // (https://wiki.libsdl.org/SDL_GameControllerGetSensorDataRate) func (ctrl *GameController) SensorDataRate(typ SensorType) (rate float32) { return float32(C.SDL_GameControllerGetSensorDataRate(ctrl.cptr(), C.SDL_SensorType(typ))) } // HasRumble queries whether a game controller has rumble support. // (https://wiki.libsdl.org/SDL_GameControllerHasRumble) func (ctrl *GameController) HasRumble() bool { return C.SDL_GameControllerHasRumble(ctrl.cptr()) == C.SDL_TRUE } // HasRumbleTriggers queries whether a game controller has rumble support on triggers. // (https://wiki.libsdl.org/SDL_GameControllerHasRumbleTriggers) func (ctrl *GameController) HasRumbleTriggers() bool { return C.SDL_GameControllerHasRumbleTriggers(ctrl.cptr()) == C.SDL_TRUE } // GetAppleSFSymbolsNameForButton returns the sfSymbolsName for a given button on a game controller on Apple platforms. // (https://wiki.libsdl.org/SDL_GameControllerGetAppleSFSymbolsNameForButton) func (ctrl *GameController) GetAppleSFSymbolsNameForButton(button GameControllerButton) (sfSymbolsName string) { _button := C.SDL_GameControllerButton(button) _sfSymbolsName := C.SDL_GameControllerGetAppleSFSymbolsNameForButton(ctrl.cptr(), _button) sfSymbolsName = C.GoString(_sfSymbolsName) return } // GetAppleSFSymbolsNameForAxis returns the sfSymbolsName for a given axis on a game controller on Apple platforms. // (https://wiki.libsdl.org/SDL_GameControllerGetAppleSFSymbolsNameForAxis) func (ctrl *GameController) SDL_GameControllerGetAppleSFSymbolsNameForAxis(axis GameControllerAxis) (sfSymbolsName string) { _axis := C.SDL_GameControllerAxis(axis) _sfSymbolsName := C.SDL_GameControllerGetAppleSFSymbolsNameForAxis(ctrl.cptr(), _axis) sfSymbolsName = C.GoString(_sfSymbolsName) return } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/gesture.go ================================================ package sdl // #include "sdl_wrapper.h" import "C" // GestureID is the unique id of the closest gesture to the performed stroke. type GestureID C.SDL_GestureID func (g GestureID) c() C.SDL_GestureID { return C.SDL_GestureID(g) } // RecordGesture begins recording a gesture on a specified touch device or all touch devices. // (https://wiki.libsdl.org/SDL_RecordGesture) func RecordGesture(t TouchID) int { return int(C.SDL_RecordGesture(t.c())) } // SaveAllDollarTemplates saves all currently loaded Dollar Gesture templates. // (https://wiki.libsdl.org/SDL_SaveAllDollarTemplates) func SaveAllDollarTemplates(src *RWops) int { return int(C.SDL_SaveAllDollarTemplates(src.cptr())) } // SaveDollarTemplate saves a currently loaded Dollar Gesture template. // (https://wiki.libsdl.org/SDL_SaveDollarTemplate) func SaveDollarTemplate(g GestureID, src *RWops) int { return int(C.SDL_SaveDollarTemplate(g.c(), src.cptr())) } // LoadDollarTemplates loads Dollar Gesture templates from a file. // (https://wiki.libsdl.org/SDL_LoadDollarTemplates) func LoadDollarTemplates(t TouchID, src *RWops) int { return int(C.SDL_LoadDollarTemplates(t.c(), src.cptr())) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/guid.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !SDL_VERSION_ATLEAST(2,24,0) #if defined(WARN_OUTDATED) #pragma message("SDL_GUIDToString is not supported before SDL 2.24.0") #pragma message("SDL_GUIDFromString is not supported before SDL 2.24.0") #endif typedef struct { Uint8 data[16]; } SDL_GUID; static inline void SDL_GUIDToString(SDL_GUID guid, char *pszGUID, int cbGUID) { return; } static inline SDL_GUID SDL_GUIDFromString(const char *pchGUID) { SDL_GUID guid; return guid; } #endif */ import "C" import ( "unsafe" ) type GUID C.SDL_GUID // ToString returns an ASCII string representation for a given GUID. func (guid GUID) ToString() (ascii string) { _cap := C.size_t(33) _buf := (*C.char)(C.SDL_malloc(_cap)) defer C.SDL_free(unsafe.Pointer(_buf)) C.SDL_GUIDToString(C.SDL_GUID(guid), _buf, C.int(_cap)) return C.GoString(_buf) } // GUIDFromString converts a GUID string into a GUID structure. func GUIDFromString(ascii string) (guid GUID) { _ascii := C.CString(ascii) return GUID(C.SDL_GUIDFromString(_ascii)) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/haptic.go ================================================ package sdl // #include "sdl_wrapper.h" import "C" import "unsafe" // Haptic effects. // (https://wiki.libsdl.org/SDL_HapticEffect) const ( HAPTIC_CONSTANT = C.SDL_HAPTIC_CONSTANT // constant haptic effect HAPTIC_SINE = C.SDL_HAPTIC_SINE // periodic haptic effect that simulates sine waves HAPTIC_LEFTRIGHT = C.SDL_HAPTIC_LEFTRIGHT // haptic effect for direct control over high/low frequency motors HAPTIC_TRIANGLE = C.SDL_HAPTIC_TRIANGLE // periodic haptic effect that simulates triangular waves HAPTIC_SAWTOOTHUP = C.SDL_HAPTIC_SAWTOOTHUP // periodic haptic effect that simulates saw tooth up waves HAPTIC_SAWTOOTHDOWN = C.SDL_HAPTIC_SAWTOOTHDOWN // periodic haptic effect that simulates saw tooth down waves HAPTIC_RAMP = C.SDL_HAPTIC_RAMP // ramp haptic effect HAPTIC_SPRING = C.SDL_HAPTIC_SPRING // condition haptic effect that simulates a spring. Effect is based on the axes position HAPTIC_DAMPER = C.SDL_HAPTIC_DAMPER // condition haptic effect that simulates dampening. Effect is based on the axes velocity HAPTIC_INERTIA = C.SDL_HAPTIC_INERTIA // condition haptic effect that simulates inertia. Effect is based on the axes acceleration HAPTIC_FRICTION = C.SDL_HAPTIC_FRICTION // condition haptic effect that simulates friction. Effect is based on the axes movement HAPTIC_CUSTOM = C.SDL_HAPTIC_CUSTOM // user defined custom haptic effect HAPTIC_GAIN = C.SDL_HAPTIC_GAIN // device supports setting the global gain HAPTIC_AUTOCENTER = C.SDL_HAPTIC_AUTOCENTER // device supports setting autocenter HAPTIC_STATUS = C.SDL_HAPTIC_STATUS // device can be queried for effect status HAPTIC_PAUSE = C.SDL_HAPTIC_PAUSE // device can be paused //HAPTIC_SQUARE = C.SDL_HAPTIC_SQUARE (back in SDL 2.1) ) // Direction encodings. // (https://wiki.libsdl.org/SDL_HapticDirection) const ( HAPTIC_POLAR = C.SDL_HAPTIC_POLAR // uses polar coordinates for the direction HAPTIC_CARTESIAN = C.SDL_HAPTIC_CARTESIAN // uses cartesian coordinates for the direction HAPTIC_SPHERICAL = C.SDL_HAPTIC_SPHERICAL // uses spherical coordinates for the direction HAPTIC_INFINITY = C.SDL_HAPTIC_INFINITY // used to play a device an infinite number of times ) // Haptic identifies an SDL haptic. // (https://wiki.libsdl.org/CategoryForceFeedback) type Haptic C.SDL_Haptic // HapticDirection contains a haptic direction. // (https://wiki.libsdl.org/SDL_HapticDirection) type HapticDirection struct { Type byte // the type of encoding Dir [3]int32 // the encoded direction } // HapticConstant contains a template for a constant effect. // (https://wiki.libsdl.org/SDL_HapticConstant) type HapticConstant struct { Type uint16 // HAPTIC_CONSTANT Direction HapticDirection // direction of the effect Length uint32 // duration of the effect Delay uint16 // delay before starting the effect Button uint16 // button that triggers the effect Interval uint16 // how soon it can be triggered again after button Level int16 // strength of the constant effect AttackLength uint16 // duration of the attack AttackLevel uint16 // level at the start of the attack FadeLength uint16 // duration of the fade FadeLevel uint16 // level at the end of the fade } func (he *HapticConstant) cHapticEffect() *C.SDL_HapticEffect { return (*C.SDL_HapticEffect)(unsafe.Pointer(he)) } // HapticPeriodic contains a template for a periodic effect. // (https://wiki.libsdl.org/SDL_HapticPeriodic) type HapticPeriodic struct { Type uint16 // HAPTIC_SINE, HAPTIC_LEFTRIGHT, HAPTIC_TRIANGLE, HAPTIC_SAWTOOTHUP, HAPTIC_SAWTOOTHDOWN Direction HapticDirection // direction of the effect Length uint32 // duration of the effect Delay uint16 // delay before starting the effect Button uint16 // button that triggers the effect Interval uint16 // how soon it can be triggered again after button Period uint16 // period of the wave Magnitude int16 // peak value; if negative, equivalent to 180 degrees extra phase shift Offset int16 // mean value of the wave Phase uint16 // positive phase shift given by hundredth of a degree AttackLength uint16 // duration of the attack AttackLevel uint16 // level at the start of the attack FadeLength uint16 // duration of the fade FadeLevel uint16 // level at the end of the fade } func (he *HapticPeriodic) cHapticEffect() *C.SDL_HapticEffect { return (*C.SDL_HapticEffect)(unsafe.Pointer(he)) } // HapticCondition contains a template for a condition effect. // (https://wiki.libsdl.org/SDL_HapticCondition) type HapticCondition struct { Type uint16 // HAPTIC_SPRING, HAPTIC_DAMPER, HAPTIC_INERTIA, HAPTIC_FRICTION Direction HapticDirection // direction of the effect - not used at the moment Length uint32 // duration of the effect Delay uint16 // delay before starting the effect Button uint16 // button that triggers the effect Interval uint16 // how soon it can be triggered again after button RightSat [3]uint16 // level when joystick is to the positive side; max 0xFFFF LeftSat [3]uint16 // level when joystick is to the negative side; max 0xFFFF RightCoeff [3]int16 // how fast to increase the force towards the positive side LeftCoeff [3]int16 // how fast to increase the force towards the negative side Deadband [3]uint16 // size of the dead zone; max 0xFFFF: whole axis-range when 0-centered Center [3]int16 // position of the dead zone } func (he *HapticCondition) cHapticEffect() *C.SDL_HapticEffect { return (*C.SDL_HapticEffect)(unsafe.Pointer(he)) } // HapticRamp contains a template for a ramp effect. // (https://wiki.libsdl.org/SDL_HapticRamp) type HapticRamp struct { Type uint16 // HAPTIC_RAMP Direction HapticDirection // direction of the effect Length uint32 // duration of the effect Delay uint16 // delay before starting the effect Button uint16 // button that triggers the effect Interval uint16 // how soon it can be triggered again after button Start int16 // beginning strength level End int16 // ending strength level AttackLength uint16 // duration of the attack AttackLevel uint16 // level at the start of the attack FadeLength uint16 // duration of the fade FadeLevel uint16 // level at the end of the fade } func (he *HapticRamp) cHapticEffect() *C.SDL_HapticEffect { return (*C.SDL_HapticEffect)(unsafe.Pointer(he)) } // HapticLeftRight contains a template for a left/right effect. // (https://wiki.libsdl.org/SDL_HapticLeftRight) type HapticLeftRight struct { Type uint16 // HAPTIC_LEFTRIGHT Length uint32 // duration of the effect LargeMagnitude uint16 // control of the large controller motor SmallMagnitude uint16 // control of the small controller motor } func (he *HapticLeftRight) cHapticEffect() *C.SDL_HapticEffect { return (*C.SDL_HapticEffect)(unsafe.Pointer(he)) } // HapticCustom contains a template for a custom effect. // (https://wiki.libsdl.org/SDL_HapticCustom) type HapticCustom struct { Type uint16 // SDL_HAPTIC_CUSTOM Direction HapticDirection // direction of the effect Length uint32 // duration of the effect Delay uint16 // delay before starting the effect Button uint16 // button that triggers the effect Interval uint16 // how soon it can be triggered again after button Channels uint8 // axes to use, minimum of 1 Period uint16 // sample periods Samples uint16 // amount of samples Data *uint16 // should contain channels*samples items AttackLength uint16 // duration of the attack AttackLevel uint16 // level at the start of the attack FadeLength uint16 // duration of the fade FadeLevel uint16 // level at the end of the fade } func (he *HapticCustom) cHapticEffect() *C.SDL_HapticEffect { return (*C.SDL_HapticEffect)(unsafe.Pointer(he)) } // HapticEffect union that contains the generic template for any haptic effect. // (https://wiki.libsdl.org/SDL_HapticEffect) type HapticEffect interface { cHapticEffect() *C.SDL_HapticEffect } func (h *Haptic) cptr() *C.SDL_Haptic { return (*C.SDL_Haptic)(unsafe.Pointer(h)) } // NumHaptics returns the number of haptic devices attached to the system. // (https://wiki.libsdl.org/SDL_NumHaptics) func NumHaptics() (int, error) { i := int(C.SDL_NumHaptics()) return i, errorFromInt(i) } // HapticName returns the implementation dependent name of a haptic device. // (https://wiki.libsdl.org/SDL_HapticName) func HapticName(index int) (string, error) { name := C.SDL_HapticName(C.int(index)) if name == nil { return "", GetError() } return C.GoString(name), nil } // HapticOpen opens a haptic device for use. // (https://wiki.libsdl.org/SDL_HapticOpen) func HapticOpen(index int) (*Haptic, error) { haptic := (*Haptic)(unsafe.Pointer(C.SDL_HapticOpen(C.int(index)))) if haptic == nil { return nil, GetError() } return haptic, nil } // HapticOpened reports whether the haptic device at the designated index has been opened. // (https://wiki.libsdl.org/SDL_HapticOpened) func HapticOpened(index int) (bool, error) { ret := int(C.SDL_HapticOpened(C.int(index))) if ret == 0 { return false, GetError() } return ret == 1, nil } // HapticIndex returns the index of a haptic device. // (https://wiki.libsdl.org/SDL_HapticIndex) func HapticIndex(h *Haptic) (int, error) { i := int(C.SDL_HapticIndex(h.cptr())) return i, errorFromInt(i) } // MouseIsHaptic reports whether or not the current mouse has haptic capabilities. // (https://wiki.libsdl.org/SDL_MouseIsHaptic) func MouseIsHaptic() (bool, error) { ret := int(C.SDL_MouseIsHaptic()) return ret == C.SDL_TRUE, errorFromInt(ret) } // HapticOpenFromMouse open a haptic device from the current mouse. // (https://wiki.libsdl.org/SDL_HapticOpenFromMouse) func HapticOpenFromMouse() (*Haptic, error) { haptic := (*Haptic)(unsafe.Pointer(C.SDL_HapticOpenFromMouse())) if haptic == nil { return nil, GetError() } return haptic, nil } // JoystickIsHaptic reports whether a joystick has haptic features. // (https://wiki.libsdl.org/SDL_JoystickIsHaptic) func JoystickIsHaptic(joy *Joystick) (bool, error) { ret := int(C.SDL_JoystickIsHaptic(joy.cptr())) return ret == C.SDL_TRUE, errorFromInt(ret) } // HapticOpenFromJoystick opens a haptic device for use from a joystick device. // (https://wiki.libsdl.org/SDL_HapticOpenFromJoystick) func HapticOpenFromJoystick(joy *Joystick) (*Haptic, error) { haptic := (*Haptic)(unsafe.Pointer(C.SDL_HapticOpenFromJoystick(joy.cptr()))) if haptic == nil { return nil, GetError() } return haptic, nil } // Close closes a haptic device previously opened with HapticOpen(). // (https://wiki.libsdl.org/SDL_HapticClose) func (h *Haptic) Close() { C.SDL_HapticClose(h.cptr()) } // NumAxes returns the number of haptic axes the device has. // (https://wiki.libsdl.org/SDL_HapticNumAxes) func (h *Haptic) NumAxes() (int, error) { i := int(C.SDL_HapticNumAxes(h.cptr())) return i, errorFromInt(i) } // NumEffects returns the number of effects a haptic device can store. // (https://wiki.libsdl.org/SDL_HapticNumEffects) func (h *Haptic) NumEffects() (int, error) { i := int(C.SDL_HapticNumEffects(h.cptr())) return i, errorFromInt(i) } // NumEffectsPlaying returns the number of effects a haptic device can play at the same time. // (https://wiki.libsdl.org/SDL_HapticNumEffectsPlaying) func (h *Haptic) NumEffectsPlaying() (int, error) { i := int(C.SDL_HapticNumEffectsPlaying(h.cptr())) return i, errorFromInt(i) } // Query returns haptic device's supported features in bitwise manner. // (https://wiki.libsdl.org/SDL_HapticQuery) func (h *Haptic) Query() (uint32, error) { i := uint32(C.SDL_HapticQuery(h.cptr())) if i == 0 { return 0, GetError() } return i, nil } // EffectSupported reports whether an effect is supported by a haptic device. // Pass pointer to a Haptic struct (Constant|Periodic|Condition|Ramp|LeftRight|Custom) instead of HapticEffect union. // (https://wiki.libsdl.org/SDL_HapticEffectSupported) func (h *Haptic) EffectSupported(he HapticEffect) (bool, error) { ret := int(C.SDL_HapticEffectSupported( h.cptr(), he.cHapticEffect())) return ret == C.SDL_TRUE, errorFromInt(ret) } // NewEffect creates a new haptic effect on a specified device. // Pass pointer to a Haptic struct (Constant|Periodic|Condition|Ramp|LeftRight|Custom) instead of HapticEffect union. // (https://wiki.libsdl.org/SDL_HapticNewEffect) func (h *Haptic) NewEffect(he HapticEffect) (int, error) { ret := int(C.SDL_HapticNewEffect( h.cptr(), he.cHapticEffect())) return ret, errorFromInt(ret) } // UpdateEffect updates the properties of an effect. // Pass pointer to a Haptic struct (Constant|Periodic|Condition|Ramp|LeftRight|Custom) instead of HapticEffect union. // (https://wiki.libsdl.org/SDL_HapticUpdateEffect) func (h *Haptic) UpdateEffect(effect int, data HapticEffect) error { return errorFromInt(int( C.SDL_HapticUpdateEffect( h.cptr(), C.int(effect), data.cHapticEffect()))) } // RunEffect runs the haptic effect on its associated haptic device. // (https://wiki.libsdl.org/SDL_HapticRunEffect) func (h *Haptic) RunEffect(effect int, iterations uint32) error { return errorFromInt(int( C.SDL_HapticRunEffect( h.cptr(), C.int(effect), C.Uint32(iterations)))) } // StopEffect stops the haptic effect on its associated haptic device. // (https://wiki.libsdl.org/SDL_HapticStopEffect) func (h *Haptic) StopEffect(effect int) error { return errorFromInt(int( C.SDL_HapticStopEffect(h.cptr(), C.int(effect)))) } // DestroyEffect destroys a haptic effect on the device. // (https://wiki.libsdl.org/SDL_HapticDestroyEffect) func (h *Haptic) DestroyEffect(effect int) { C.SDL_HapticDestroyEffect(h.cptr(), C.int(effect)) } // GetEffectStatus returns the status of the current effect on the specified haptic device. // (https://wiki.libsdl.org/SDL_HapticGetEffectStatus) func (h *Haptic) GetEffectStatus(effect int) (int, error) { i := int(C.SDL_HapticGetEffectStatus(h.cptr(), C.int(effect))) return i, errorFromInt(i) } // SetGain sets the global gain of the specified haptic device. // (https://wiki.libsdl.org/SDL_HapticSetGain) func (h *Haptic) SetGain(gain int) error { return errorFromInt(int( C.SDL_HapticSetGain(h.cptr(), C.int(gain)))) } // SetAutocenter sets the global autocenter of the device. // (https://wiki.libsdl.org/SDL_HapticSetAutocenter) func (h *Haptic) SetAutocenter(autocenter int) error { return errorFromInt(int( C.SDL_HapticSetAutocenter(h.cptr(), C.int(autocenter)))) } // Pause pauses a haptic device. // (https://wiki.libsdl.org/SDL_HapticPause) func (h *Haptic) Pause() error { return errorFromInt(int( C.SDL_HapticPause(h.cptr()))) } // Unpause unpauses a haptic device. // (https://wiki.libsdl.org/SDL_HapticUnpause) func (h *Haptic) Unpause() error { return errorFromInt(int( C.SDL_HapticUnpause(h.cptr()))) } // StopAll stops all the currently playing effects on a haptic device. // (https://wiki.libsdl.org/SDL_HapticStopAll) func (h *Haptic) StopAll() error { return errorFromInt(int( C.SDL_HapticStopAll(h.cptr()))) } // RumbleSupported reports whether rumble is supported on a haptic device. // (https://wiki.libsdl.org/SDL_HapticRumbleSupported) func (h *Haptic) RumbleSupported() (bool, error) { ret := int(C.SDL_HapticRumbleSupported(h.cptr())) return ret == C.SDL_TRUE, errorFromInt(ret) } // RumbleInit initializes the haptic device for simple rumble playback. // (https://wiki.libsdl.org/SDL_HapticRumbleInit) func (h *Haptic) RumbleInit() error { return errorFromInt(int( C.SDL_HapticRumbleInit(h.cptr()))) } // RumblePlay runs a simple rumble effect on a haptic device. // (https://wiki.libsdl.org/SDL_HapticRumblePlay) func (h *Haptic) RumblePlay(strength float32, length uint32) error { return errorFromInt(int( C.SDL_HapticRumblePlay(h.cptr(), C.float(strength), C.Uint32(length)))) } // RumbleStop stops the simple rumble on a haptic device. // (https://wiki.libsdl.org/SDL_HapticRumbleStop) func (h *Haptic) RumbleStop() error { return errorFromInt(int( C.SDL_HapticRumbleStop(h.cptr()))) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/helpers.go ================================================ package sdl // Btoi returns 0 or 1 according to the value of b. func Btoi(b bool) int { if b == true { return 1 } return 0 } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/hidapi.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,18)) #if defined(WARN_OUTDATED) #pragma message("SDL_hid_init is not supported before SDL 2.0.18") #pragma message("SDL_hid_exit is not supported before SDL 2.0.18") #pragma message("SDL_hid_device_change_count is not supported before SDL 2.0.18") #pragma message("SDL_hid_enumerate is not supported before SDL 2.0.18") #pragma message("SDL_hid_free_enumeration is not supported before SDL 2.0.18") #pragma message("SDL_hid_open is not supported before SDL 2.0.18") #pragma message("SDL_hid_open_path is not supported before SDL 2.0.18") #pragma message("SDL_hid_write is not supported before SDL 2.0.18") #pragma message("SDL_hid_read_timeout is not supported before SDL 2.0.18") #pragma message("SDL_hid_read is not supported before SDL 2.0.18") #pragma message("SDL_hid_set_nonblocking is not supported before SDL 2.0.18") #pragma message("SDL_hid_send_feature_report is not supported before SDL 2.0.18") #pragma message("SDL_hid_get_feature_report is not supported before SDL 2.0.18") #pragma message("SDL_hid_close is not supported before SDL 2.0.18") #pragma message("SDL_hid_get_manufacturer_string is not supported before SDL 2.0.18") #pragma message("SDL_hid_get_product_string is not supported before SDL 2.0.18") #pragma message("SDL_hid_get_serial_number_string is not supported before SDL 2.0.18") #pragma message("SDL_hid_get_indexed_string is not supported before SDL 2.0.18") #pragma message("SDL_hid_ble_scan is not supported before SDL 2.0.18") #endif struct SDL_hid_device_; typedef struct SDL_hid_device_ SDL_hid_device; // opaque hidapi structure // hidapi info structure // Information about a connected HID device typedef struct SDL_hid_device_info { // Platform-specific device path char *path; // Device Vendor ID unsigned short vendor_id; // Device Product ID unsigned short product_id; // Serial Number wchar_t *serial_number; // Device Release Number in binary-coded decimal, also known as Device Version Number unsigned short release_number; // Manufacturer String wchar_t *manufacturer_string; // Product string wchar_t *product_string; // Usage Page for this Device/Interface (Windows/Mac only). unsigned short usage_page; // Usage for this Device/Interface (Windows/Mac only). unsigned short usage; // The USB interface which this logical device represents. // Valid on both Linux implementations in all cases. // Valid on the Windows implementation only if the device // contains more than one interface. int interface_number; // Additional information about the USB interface. // Valid on libusb and Android implementations. int interface_class; int interface_subclass; int interface_protocol; // Pointer to the next device struct SDL_hid_device_info *next; } SDL_hid_device_info; static int SDL_hid_init(void) { return -1; } static int SDL_hid_exit(void) { return -1; } static Uint32 SDL_hid_device_change_count(void) { return 0; } static SDL_hid_device_info * SDL_hid_enumerate(unsigned short vendor_id, unsigned short product_id) { return NULL; } static void SDL_hid_free_enumeration(SDL_hid_device_info *devs) { } static SDL_hid_device * SDL_hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number) { return NULL; } static SDL_hid_device * SDL_hid_open_path(const char *path, int bExclusive) { return NULL; } static int SDL_hid_write(SDL_hid_device *dev, const unsigned char *data, size_t length) { return -1; } static int SDL_hid_read_timeout(SDL_hid_device *dev, unsigned char *data, size_t length, int milliseconds) { return -1; } static int SDL_hid_read(SDL_hid_device *dev, unsigned char *data, size_t length) { return -1; } static int SDL_hid_set_nonblocking(SDL_hid_device *dev, int nonblock) { return -1; } static int SDL_hid_send_feature_report(SDL_hid_device *dev, const unsigned char *data, size_t length) { return -1; } static int SDL_hid_get_feature_report(SDL_hid_device *dev, unsigned char *data, size_t length) { return -1; } static void SDL_hid_close(SDL_hid_device *dev) { } static int SDL_hid_get_manufacturer_string(SDL_hid_device *dev, wchar_t *string, size_t maxlen) { return -1; } static int SDL_hid_get_product_string(SDL_hid_device *dev, wchar_t *string, size_t maxlen) { return -1; } static int SDL_hid_get_serial_number_string(SDL_hid_device *dev, wchar_t *string, size_t maxlen) { return -1; } static int SDL_hid_get_indexed_string(SDL_hid_device *dev, int string_index, wchar_t *string, size_t maxlen) { return -1; } static void SDL_hid_ble_scan(SDL_bool active) { } #endif */ import "C" import "unsafe" type HIDDevice C.SDL_hid_device type HIDDeviceInfo struct { path *C.char VendorID uint16 ProductID uint16 SerialNumber *C.wchar_t ReleaseNumber uint16 ManufacturerString *C.wchar_t ProductString *C.wchar_t UsagePage uint16 Usage uint16 InterfaceNumber int32 InterfaceClass int32 InterfaceSubclass int32 InterfaceProtocol int32 next *HIDDeviceInfo } func (info *HIDDeviceInfo) Path() string { return C.GoString(info.path) } // HIDInit initializes the HIDAPI library. // (https://wiki.libsdl.org/SDL_hid_init) func HIDInit() (err error) { ret := C.SDL_hid_init() return errorFromInt(int(ret)) } // HIDExit finalizes the HIDAPI library. // (https://wiki.libsdl.org/SDL_hid_exit) func HIDExit() (err error) { ret := C.SDL_hid_exit() return errorFromInt(int(ret)) } // HIDDeviceChangeCount checks to see if devices may have been added or removed. // (https://wiki.libsdl.org/SDL_hid_device_change_count) func HIDDeviceChangeCount() (n uint32) { return uint32(C.SDL_hid_device_change_count()) } // HIDEnumerate enumerates the HID devices. // (https://wiki.libsdl.org/SDL_hid_enumerate) func HIDEnumerate(vendorID, productID uint16) (info *HIDDeviceInfo) { _vendorID := C.Uint16(vendorID) _productID := C.Uint16(productID) info = (*HIDDeviceInfo)(unsafe.Pointer(C.SDL_hid_enumerate(_vendorID, _productID))) return } // HIDFreeEnumeration frees an enumeration Linked List. // (https://wiki.libsdl.org/SDL_hid_free_enumeration) func HIDFreeEnumeration(info *HIDDeviceInfo) { _info := (*C.SDL_hid_device_info)(unsafe.Pointer(info)) C.SDL_hid_free_enumeration(_info) } // HIDOpen opens a HID device using a Vendor ID (VID), Product ID (PID) and optionally a serial number. // (https://wiki.libsdl.org/SDL_hid_open) func HIDOpen(vendorID, productID uint16, _serialNumber *C.wchar_t) (device *HIDDevice) { _vendorID := C.Uint16(vendorID) _productID := C.Uint16(productID) _device := C.SDL_hid_open(_vendorID, _productID, _serialNumber) return (*HIDDevice)(_device) } // HIDOpenPath opens a HID device by its path name. // (https://wiki.libsdl.org/SDL_hid_open_path) func HIDOpenPath(path string, exclusive bool) (device *HIDDevice) { _path := C.CString(path) defer C.free(unsafe.Pointer(_path)) _exclusive := C.int(0) if exclusive { _exclusive = C.int(1) } _device := C.SDL_hid_open_path(_path, _exclusive) return (*HIDDevice)(_device) } // Write writes an Output report to a HID device. // (https://wiki.libsdl.org/SDL_hid_write) func (device *HIDDevice) Write(data []byte) (n int, err error) { _length := C.size_t(len(data)) _data := (*C.uchar)(unsafe.Pointer(&data[0])) _device := (*C.SDL_hid_device)(device) n = int(C.SDL_hid_write(_device, _data, _length)) return n, errorFromInt(n) } // ReadTimeout reads an Input report from a HID device with timeout. // (https://wiki.libsdl.org/SDL_hid_read_timeout) func (device *HIDDevice) ReadTimeout(data []byte, milliseconds int) (n int, err error) { _length := C.size_t(len(data)) _data := (*C.uchar)(unsafe.Pointer(&data[0])) _device := (*C.SDL_hid_device)(device) _milliseconds := C.int(milliseconds) n = int(C.SDL_hid_read_timeout(_device, _data, _length, _milliseconds)) return n, errorFromInt(n) } // Read an Input report from a HID device. // (https://wiki.libsdl.org/SDL_hid_read) func (device *HIDDevice) Read(data []byte) (n int, err error) { _length := C.size_t(len(data)) _data := (*C.uchar)(unsafe.Pointer(&data[0])) _device := (*C.SDL_hid_device)(device) n = int(C.SDL_hid_read(_device, _data, _length)) return n, errorFromInt(n) } // SetNonBlocking sets the device handle to be non-blocking. // (https://wiki.libsdl.org/SDL_hid_set_nonblocking) func (device *HIDDevice) SetNonBlocking(nonblock bool) (err error) { _device := (*C.SDL_hid_device)(device) _nonblock := C.int(Btoi(nonblock)) return errorFromInt(int(C.SDL_hid_set_nonblocking(_device, _nonblock))) } // SendFeatureReport sends a Feature report to the device. // (https://wiki.libsdl.org/SDL_hid_send_feature_report) func (device *HIDDevice) SendFeatureReport(data []byte) (n int, err error) { _length := C.size_t(len(data)) _data := (*C.uchar)(unsafe.Pointer(&data[0])) _device := (*C.SDL_hid_device)(device) n = int(C.SDL_hid_send_feature_report(_device, _data, _length)) return n, errorFromInt(n) } // GetFeatureReport gets a feature report from a HID device. // (https://wiki.libsdl.org/SDL_hid_get_feature_report) func (device *HIDDevice) GetFeatureReport(data []byte) (n int, err error) { _length := C.size_t(len(data)) _data := (*C.uchar)(unsafe.Pointer(&data[0])) _device := (*C.SDL_hid_device)(device) n = int(C.SDL_hid_get_feature_report(_device, _data, _length)) return n, errorFromInt(n) } // Close closes a HID device. // (https://wiki.libsdl.org/SDL_hid_close) func (device *HIDDevice) Close() { _device := (*C.SDL_hid_device)(device) C.SDL_hid_close(_device) } // GetManufacturerString gets The Manufacturer String from a HID device. // (https://wiki.libsdl.org/SDL_hid_get_manufacturer_string) func (device *HIDDevice) GetManufacturerString(_str *C.wchar_t, _maxlen C.size_t) (err error) { _device := (*C.SDL_hid_device)(device) return errorFromInt(int(C.SDL_hid_get_manufacturer_string(_device, _str, _maxlen))) } // GetProductString gets The Product String from a HID device. // (https://wiki.libsdl.org/SDL_hid_get_product_string) func (device *HIDDevice) GetProductString(_str *C.wchar_t, _maxlen C.size_t) (err error) { _device := (*C.SDL_hid_device)(device) return errorFromInt(int(C.SDL_hid_get_product_string(_device, _str, _maxlen))) } // GetSerialNumberString gets The SerialNumber String from a HID device. // (https://wiki.libsdl.org/SDL_hid_get_serial_number_string) func (device *HIDDevice) GetSerialNumberString(_str *C.wchar_t, _maxlen C.size_t) (err error) { _device := (*C.SDL_hid_device)(device) return errorFromInt(int(C.SDL_hid_get_serial_number_string(_device, _str, _maxlen))) } // GetIndexedString gets a string from a HID device, based on its string index. // (https://wiki.libsdl.org/SDL_hid_get_indexed_string) func (device *HIDDevice) GetIndexedString(index int, _str *C.wchar_t, _maxlen C.size_t) (err error) { _device := (*C.SDL_hid_device)(device) _index := C.int(index) return errorFromInt(int(C.SDL_hid_get_indexed_string(_device, _index, _str, _maxlen))) } // HIDBLEScan starts or stops a BLE scan on iOS and tvOS to pair Steam Controllers. // (https://wiki.libsdl.org/SDL_hid_ble_scan) func (device *HIDDevice) HIDBLEScan(active bool) { _active := C.SDL_bool(Btoi(active)) C.SDL_hid_ble_scan(_active) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/hints.c ================================================ #include "_cgo_export.h" #include "sdl_wrapper.h" #include "hints.h" void hintCallback(void *userdata, const char *name, const char *oldValue, const char *newValue) { goHintCallback((char *) name, (char *) oldValue, (char *) newValue); } void addHintCallback(const char *name) { SDL_AddHintCallback(name, hintCallback, NULL); } void delHintCallback(const char *name) { SDL_DelHintCallback(name, hintCallback, NULL);} ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/hints.go ================================================ package sdl /* #include "sdl_wrapper.h" #include "hints.h" #if !(SDL_VERSION_ATLEAST(2,0,20)) #define SDL_HINT_RENDER_LINE_METHOD "" #endif #if !(SDL_VERSION_ATLEAST(2,0,18)) #define SDL_HINT_APP_NAME "" #endif #if !(SDL_VERSION_ATLEAST(2,0,16)) #define SDL_HINT_JOYSTICK_RAWINPUT_CORRELATE_XINPUT "" #define SDL_HINT_AUDIO_INCLUDE_MONITORS "" #define SDL_HINT_AUDIO_DEVICE_STREAM_ROLE "" #endif #if !(SDL_VERSION_ATLEAST(2,0,14)) #define SDL_HINT_JOYSTICK_HIDAPI_PS5 "" #define SDL_HINT_MOUSE_RELATIVE_SCALING "" #define SDL_HINT_PREFERRED_LOCALES "" #define SDL_HINT_JOYSTICK_RAWINPUT "" #define SDL_HINT_JOYSTICK_HIDAPI_CORRELATE_XINPUT "" #define SDL_HINT_AUDIO_DEVICE_APP_NAME "" #define SDL_HINT_AUDIO_DEVICE_STREAM_NAME "" #define SDL_HINT_LINUX_JOYSTICK_DEADZONES "" #define SDL_HINT_THREAD_PRIORITY_POLICY "" #define SDL_HINT_THREAD_FORCE_REALTIME_TIME_CRITICAL "" #define SDL_HINT_ANDROID_BLOCK_ON_PAUSE_PAUSEAUDIO "" #define SDL_HINT_EMSCRIPTEN_ASYNCIFY "" #endif #if !(SDL_VERSION_ATLEAST(2,0,12)) #define SDL_HINT_DISPLAY_USABLE_BOUNDS "" #define SDL_HINT_GAMECONTROLLERTYPE "" #define SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS "" #define SDL_HINT_JOYSTICK_HIDAPI_GAMECUBE "" #define SDL_HINT_VIDEO_X11_WINDOW_VISUALID "" #define SDL_HINT_VIDEO_X11_FORCE_EGL "" #endif #if !(SDL_VERSION_ATLEAST(2,0,9)) #define SDL_HINT_MOUSE_DOUBLE_CLICK_TIME "" #define SDL_HINT_MOUSE_DOUBLE_CLICK_RADIUS "" #define SDL_HINT_JOYSTICK_HIDAPI_STEAM "" #endif #if !(SDL_VERSION_ATLEAST(2,0,8)) #define SDL_HINT_IOS_HIDE_HOME_INDICATOR "" #define SDL_HINT_RETURN_KEY_HIDES_IME "" #define SDL_HINT_TV_REMOTE_AS_JOYSTICK "" #define SDL_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR "" #define SDL_HINT_VIDEO_DOUBLE_BUFFER "" #endif #if !(SDL_VERSION_ATLEAST(2,0,6)) #define SDL_HINT_AUDIO_RESAMPLING_MODE "" #define SDL_HINT_RENDER_LOGICAL_SIZE_MODE "" #define SDL_HINT_MOUSE_NORMAL_SPEED_SCALE "" #define SDL_HINT_MOUSE_RELATIVE_SPEED_SCALE "" #define SDL_HINT_TOUCH_MOUSE_EVENTS "" #define SDL_HINT_WINDOWS_INTRESOURCE_ICON "" #define SDL_HINT_WINDOWS_INTRESOURCE_ICON_SMALL "" #endif #if !(SDL_VERSION_ATLEAST(2,0,4)) #define SDL_HINT_NO_SIGNAL_HANDLERS "" #define SDL_HINT_THREAD_STACK_SIZE "" #define SDL_HINT_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN "" #define SDL_HINT_WINDOWS_ENABLE_MESSAGELOOP "" #define SDL_HINT_WINDOWS_NO_CLOSE_ON_ALT_F4 "" #define SDL_HINT_XINPUT_USE_OLD_JOYSTICK_MAPPING "" #define SDL_HINT_MAC_BACKGROUND_APP "" #define SDL_HINT_IME_INTERNAL_EDITING "" #define SDL_HINT_VIDEO_X11_NET_WM_PING "" #define SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH "" #define SDL_HINT_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION "" #define SDL_HINT_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION "" #endif #if !(SDL_VERSION_ATLEAST(2,0,3)) #define SDL_HINT_WINRT_PRIVACY_POLICY_URL "" #define SDL_HINT_WINRT_PRIVACY_POLICY_LABEL "" #define SDL_HINT_WINRT_HANDLE_BACK_BUTTON "" #define SDL_HINT_RENDER_DIRECT3D11_DEBUG "" #endif #if !(SDL_VERSION_ATLEAST(2,0,2)) #define SDL_HINT_ACCELEROMETER_AS_JOYSTICK "" #define SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK "" #define SDL_HINT_VIDEO_ALLOW_SCREENSAVER "" #define SDL_HINT_MOUSE_RELATIVE_MODE_WARP "" #define SDL_HINT_VIDEO_WIN_D3DCOMPILER "" #define SDL_HINT_VIDEO_WINDOW_SHARE_PIXEL_FORMAT "" #define SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES "" #endif #if !(SDL_VERSION_ATLEAST(2,0,1)) #define SDL_HINT_RENDER_DIRECT3D_THREADSAFE "" #define SDL_HINT_VIDEO_HIGHDPI_DISABLED "" #endif #if !(SDL_VERSION_ATLEAST(2,0,10)) #if defined(WARN_OUTDATED) #pragma message("SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH has been removed in SDL 2.0.10") #endif #define SDL_HINT_RENDER_BATCHING "" #define SDL_HINT_EVENT_LOGGING "" #define SDL_HINT_GAMECONTROLLERCONFIG_FILE "" #define SDL_HINT_ANDROID_BLOCK_ON_PAUSE "" #define SDL_HINT_MOUSE_TOUCH_EVENTS "" #else #define SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH "" // For compatibility #endif #if SDL_VERSION_ATLEAST(2,0,16) #if defined(WARN_OUTDATED) #pragma message("SDL_HINT_JOYSTICK_HIDAPI_CORRELATE_XINPUT has been replaced by SDL_HINT_JOYSTICK_RAWINPUT_CORRELATE_XINPUT in SDL 2.0.16") #endif #define SDL_HINT_JOYSTICK_HIDAPI_CORRELATE_XINPUT (SDL_HINT_JOYSTICK_RAWINPUT_CORRELATE_XINPUT) #endif #if !SDL_VERSION_ATLEAST(2,0,18) #define SDL_HINT_IME_SHOW_UI "" #define SDL_HINT_JOYSTICK_DEVICE "" #define SDL_HINT_LINUX_JOYSTICK_CLASSIC "" #define SDL_HINT_SCREENSAVER_INHIBIT_ACTIVITY_NAME "" #define SDL_HINT_VIDEO_EGL_ALLOW_TRANSPARENCY "" #endif #if !SDL_VERSION_ATLEAST(2,0,22) #define SDL_HINT_IME_SUPPORT_EXTENDED_TEXT "" #define SDL_HINT_MOUSE_RELATIVE_MODE_CENTER "" #define SDL_HINT_MOUSE_AUTO_CAPTURE "" #define SDL_HINT_VIDEO_FOREIGN_WINDOW_OPENGL "" #define SDL_HINT_VIDEO_FOREIGN_WINDOW_VULKAN "" #define SDL_HINT_QUIT_ON_LAST_WINDOW_CLOSE "" #define SDL_HINT_JOYSTICK_ROG_CHAKRAM "" #define SDL_HINT_X11_WINDOW_TYPE "" #define SDL_HINT_VIDEO_WAYLAND_PREFER_LIBDECOR "" #endif */ import "C" import "unsafe" // Configuration hints // (https://wiki.libsdl.org/CategoryHints) const ( HINT_FRAMEBUFFER_ACCELERATION = C.SDL_HINT_FRAMEBUFFER_ACCELERATION // specifies how 3D acceleration is used with Window.GetSurface() HINT_RENDER_DRIVER = C.SDL_HINT_RENDER_DRIVER // specifies which render driver to use HINT_RENDER_OPENGL_SHADERS = C.SDL_HINT_RENDER_OPENGL_SHADERS // specifies whether the OpenGL render driver uses shaders HINT_RENDER_DIRECT3D_THREADSAFE = C.SDL_HINT_RENDER_DIRECT3D_THREADSAFE // specifies whether the Direct3D device is initialized for thread-safe operations HINT_RENDER_DIRECT3D11_DEBUG = C.SDL_HINT_RENDER_DIRECT3D11_DEBUG // specifies a variable controlling whether to enable Direct3D 11+'s Debug Layer HINT_RENDER_SCALE_QUALITY = C.SDL_HINT_RENDER_SCALE_QUALITY // specifies scaling quality HINT_RENDER_VSYNC = C.SDL_HINT_RENDER_VSYNC // specifies whether sync to vertical refresh is enabled or disabled in CreateRenderer() to avoid tearing HINT_VIDEO_ALLOW_SCREENSAVER = C.SDL_HINT_VIDEO_ALLOW_SCREENSAVER // specifies whether the screensaver is enabled HINT_VIDEO_X11_NET_WM_PING = C.SDL_HINT_VIDEO_X11_NET_WM_PING // specifies whether the X11 _NET_WM_PING protocol should be supported HINT_VIDEO_X11_XVIDMODE = C.SDL_HINT_VIDEO_X11_XVIDMODE // specifies whether the X11 VidMode extension should be used HINT_VIDEO_X11_XINERAMA = C.SDL_HINT_VIDEO_X11_XINERAMA // specifies whether the X11 Xinerama extension should be used HINT_VIDEO_X11_XRANDR = C.SDL_HINT_VIDEO_X11_XRANDR // specifies whether the X11 XRandR extension should be used HINT_GRAB_KEYBOARD = C.SDL_HINT_GRAB_KEYBOARD // specifies whether grabbing input grabs the keyboard HINT_MOUSE_DOUBLE_CLICK_TIME = C.SDL_HINT_MOUSE_DOUBLE_CLICK_TIME // specifies the double click time, in milliseconds HINT_MOUSE_DOUBLE_CLICK_RADIUS = C.SDL_HINT_MOUSE_DOUBLE_CLICK_RADIUS // specifies the double click radius, in pixels. HINT_MOUSE_RELATIVE_MODE_WARP = C.SDL_HINT_MOUSE_RELATIVE_MODE_WARP // specifies whether relative mouse mode is implemented using mouse warping HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS = C.SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS // specifies if a Window is minimized if it loses key focus when in fullscreen mode HINT_IDLE_TIMER_DISABLED = C.SDL_HINT_IDLE_TIMER_DISABLED // specifies a variable controlling whether the idle timer is disabled on iOS HINT_IME_INTERNAL_EDITING = C.SDL_HINT_IME_INTERNAL_EDITING // specifies whether certain IMEs should handle text editing internally instead of sending TextEditingEvents HINT_ORIENTATIONS = C.SDL_HINT_ORIENTATIONS // specifies a variable controlling which orientations are allowed on iOS HINT_ACCELEROMETER_AS_JOYSTICK = C.SDL_HINT_ACCELEROMETER_AS_JOYSTICK // specifies whether the Android / iOS built-in accelerometer should be listed as a joystick device, rather than listing actual joysticks only HINT_XINPUT_ENABLED = C.SDL_HINT_XINPUT_ENABLED // specifies if Xinput gamepad devices are detected HINT_XINPUT_USE_OLD_JOYSTICK_MAPPING = C.SDL_HINT_XINPUT_USE_OLD_JOYSTICK_MAPPING // specifies that SDL should use the old axis and button mapping for XInput devices HINT_GAMECONTROLLERCONFIG = C.SDL_HINT_GAMECONTROLLERCONFIG // specifies extra gamecontroller db entries HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS = C.SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS // specifies if joystick (and gamecontroller) events are enabled even when the application is in the background HINT_ALLOW_TOPMOST = C.SDL_HINT_ALLOW_TOPMOST // specifies if top most bit on an SDL Window can be set HINT_THREAD_STACK_SIZE = C.SDL_HINT_THREAD_STACK_SIZE // specifies a variable specifying SDL's threads stack size in bytes or "0" for the backend's default size HINT_TIMER_RESOLUTION = C.SDL_HINT_TIMER_RESOLUTION // specifies the timer resolution in milliseconds HINT_VIDEO_HIGHDPI_DISABLED = C.SDL_HINT_VIDEO_HIGHDPI_DISABLED // specifies if high-DPI windows ("Retina" on Mac and iOS) are not allowed HINT_MAC_BACKGROUND_APP = C.SDL_HINT_MAC_BACKGROUND_APP // specifies if the SDL app should not be forced to become a foreground process on Mac OS X HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK = C.SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK // specifies whether ctrl+click should generate a right-click event on Mac HINT_VIDEO_WIN_D3DCOMPILER = C.SDL_HINT_VIDEO_WIN_D3DCOMPILER // specifies which shader compiler to preload when using the Chrome ANGLE binaries HINT_VIDEO_WINDOW_SHARE_PIXEL_FORMAT = C.SDL_HINT_VIDEO_WINDOW_SHARE_PIXEL_FORMAT // specifies the address of another Window* (as a hex string formatted with "%p") HINT_WINRT_PRIVACY_POLICY_URL = C.SDL_HINT_WINRT_PRIVACY_POLICY_URL // specifies a URL to a WinRT app's privacy policy HINT_WINRT_PRIVACY_POLICY_LABEL = C.SDL_HINT_WINRT_PRIVACY_POLICY_LABEL // specifies a label text for a WinRT app's privacy policy link HINT_WINRT_HANDLE_BACK_BUTTON = C.SDL_HINT_WINRT_HANDLE_BACK_BUTTON // specifies a variable to allow back-button-press events on Windows Phone to be marked as handled HINT_VIDEO_MAC_FULLSCREEN_SPACES = C.SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES // specifies policy for fullscreen Spaces on Mac OS X HINT_NO_SIGNAL_HANDLERS = C.SDL_HINT_NO_SIGNAL_HANDLERS // specifies not to catch the SIGINT or SIGTERM signals HINT_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN = C.SDL_HINT_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN // specifies whether the window frame and title bar are interactive when the cursor is hidden HINT_WINDOWS_ENABLE_MESSAGELOOP = C.SDL_HINT_WINDOWS_ENABLE_MESSAGELOOP // specifies whether the windows message loop is processed by SDL HINT_WINDOWS_NO_CLOSE_ON_ALT_F4 = C.SDL_HINT_WINDOWS_NO_CLOSE_ON_ALT_F4 // specifies that SDL should not to generate WINDOWEVENT_CLOSE events for Alt+F4 on Microsoft Windows HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH = C.SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH // specifies a variable to control whether mouse and touch events are to be treated together or separately HINT_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION = C.SDL_HINT_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION // specifies the Android APK expansion main file version HINT_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION = C.SDL_HINT_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION // specifies the Android APK expansion patch file version HINT_AUDIO_RESAMPLING_MODE = C.SDL_HINT_AUDIO_RESAMPLING_MODE // specifies a variable controlling speed/quality tradeoff of audio resampling HINT_RENDER_LOGICAL_SIZE_MODE = C.SDL_HINT_RENDER_LOGICAL_SIZE_MODE // specifies a variable controlling the scaling policy for SDL_RenderSetLogicalSize HINT_MOUSE_NORMAL_SPEED_SCALE = C.SDL_HINT_MOUSE_NORMAL_SPEED_SCALE // specifies a variable setting the speed scale for mouse motion, in floating point, when the mouse is not in relative mode HINT_MOUSE_RELATIVE_SPEED_SCALE = C.SDL_HINT_MOUSE_RELATIVE_SPEED_SCALE // specifies a variable setting the scale for mouse motion, in floating point, when the mouse is in relative mode HINT_MOUSE_TOUCH_EVENTS = C.SDL_HINT_MOUSE_TOUCH_EVENTS // specifies a variable to control whether mouse events should generate synthetic touch events HINT_TOUCH_MOUSE_EVENTS = C.SDL_HINT_TOUCH_MOUSE_EVENTS // specifies a variable controlling whether touch events should generate synthetic mouse events HINT_WINDOWS_INTRESOURCE_ICON = C.SDL_HINT_WINDOWS_INTRESOURCE_ICON // specifies a variable to specify custom icon resource id from RC file on Windows platform HINT_WINDOWS_INTRESOURCE_ICON_SMALL = C.SDL_HINT_WINDOWS_INTRESOURCE_ICON_SMALL // specifies a variable to specify custom icon resource id from RC file on Windows platform HINT_IOS_HIDE_HOME_INDICATOR = C.SDL_HINT_IOS_HIDE_HOME_INDICATOR // specifies a variable controlling whether the home indicator bar on iPhone X should be hidden. HINT_RETURN_KEY_HIDES_IME = C.SDL_HINT_RETURN_KEY_HIDES_IME // specifies a variable to control whether the return key on the soft keyboard should hide the soft keyboard on Android and iOS. HINT_TV_REMOTE_AS_JOYSTICK = C.SDL_HINT_TV_REMOTE_AS_JOYSTICK // specifies a variable controlling whether the Android / tvOS remotes should be listed as joystick devices, instead of sending keyboard events. HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR = C.SDL_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR // specifies a variable controlling whether the X11 _NET_WM_BYPASS_COMPOSITOR hint should be used. HINT_VIDEO_DOUBLE_BUFFER = C.SDL_HINT_VIDEO_DOUBLE_BUFFER // specifies a variable that tells the video driver that we only want a double buffer. HINT_RENDER_BATCHING = C.SDL_HINT_RENDER_BATCHING // specifies a variable controlling whether the 2D render API is compatible or efficient. HINT_EVENT_LOGGING = C.SDL_HINT_EVENT_LOGGING // specifies a variable controlling whether SDL logs all events pushed onto its internal queue. HINT_GAMECONTROLLERCONFIG_FILE = C.SDL_HINT_GAMECONTROLLERCONFIG_FILE // specifies a variable that lets you provide a file with extra gamecontroller db entries. HINT_ANDROID_BLOCK_ON_PAUSE = C.SDL_HINT_ANDROID_BLOCK_ON_PAUSE // specifies a variable to control whether the event loop will block itself when the app is paused. HINT_DISPLAY_USABLE_BOUNDS = C.SDL_HINT_DISPLAY_USABLE_BOUNDS // Override for SDL_GetDisplayUsableBounds(). HINT_GAMECONTROLLERTYPE = C.SDL_HINT_GAMECONTROLLERTYPE // Overrides the automatic controller type detection. HINT_GAMECONTROLLER_USE_BUTTON_LABELS = C.SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS // If set, game controller face buttons report their values according to their labels instead of their positional layout. HINT_JOYSTICK_HIDAPI_GAMECUBE = C.SDL_HINT_JOYSTICK_HIDAPI_GAMECUBE // A variable controlling whether the HIDAPI driver for Nintendo GameCube controllers should be used. HINT_VIDEO_X11_WINDOW_VISUALID = C.SDL_HINT_VIDEO_X11_WINDOW_VISUALID // A variable forcing the visual ID chosen for new X11 windows. HINT_VIDEO_X11_FORCE_EGL = C.SDL_HINT_VIDEO_X11_FORCE_EGL // A variable controlling whether X11 should use GLX or EGL by default. HINT_JOYSTICK_HIDAPI_PS5 = C.SDL_HINT_JOYSTICK_HIDAPI_PS5 // A variable controlling whether the HIDAPI driver for PS5 controllers should be used. HINT_MOUSE_RELATIVE_SCALING = C.SDL_HINT_MOUSE_RELATIVE_SCALING // A variable controlling whether relative mouse motion is affected by renderer scaling. HINT_PREFERRED_LOCALES = C.SDL_HINT_PREFERRED_LOCALES // Override for SDL_GetPreferredLocales(). HINT_JOYSTICK_RAWINPUT = C.SDL_HINT_JOYSTICK_RAWINPUT // A variable controlling whether the RAWINPUT joystick drivers should be used for better handling XInput-capable devices. HINT_JOYSTICK_RAWINPUT_CORRELATE_XINPUT = C.SDL_HINT_JOYSTICK_RAWINPUT_CORRELATE_XINPUT // A variable controlling whether the HIDAPI driver for XBox controllers on Windows should pull correlated data from XInput. HINT_JOYSTICK_HIDAPI_CORRELATE_XINPUT = C.SDL_HINT_JOYSTICK_HIDAPI_CORRELATE_XINPUT // A variable controlling whether the HIDAPI driver for XBox controllers on Windows should pull correlated data from XInput. HINT_AUDIO_DEVICE_APP_NAME = C.SDL_HINT_AUDIO_DEVICE_APP_NAME // Specify an application name for an audio device. HINT_AUDIO_DEVICE_STREAM_NAME = C.SDL_HINT_AUDIO_DEVICE_STREAM_NAME // Specify an application name for an audio device. HINT_LINUX_JOYSTICK_DEADZONES = C.SDL_HINT_LINUX_JOYSTICK_DEADZONES // A variable controlling whether joysticks on Linux adhere to their HID-defined deadzones or return unfiltered values. HINT_THREAD_PRIORITY_POLICY = C.SDL_HINT_THREAD_PRIORITY_POLICY // A string specifying additional information to use with SDL_SetThreadPriority. HINT_THREAD_FORCE_REALTIME_TIME_CRITICAL = C.SDL_HINT_THREAD_FORCE_REALTIME_TIME_CRITICAL // Specifies whether SDL_THREAD_PRIORITY_TIME_CRITICAL should be treated as realtime. HINT_ANDROID_BLOCK_ON_PAUSE_PAUSEAUDIO = C.SDL_HINT_ANDROID_BLOCK_ON_PAUSE_PAUSEAUDIO // A variable to control whether SDL will pause audio in background (Requires SDL_ANDROID_BLOCK_ON_PAUSE as "Non blocking"). HINT_EMSCRIPTEN_ASYNCIFY = C.SDL_HINT_EMSCRIPTEN_ASYNCIFY // Disable giving back control to the browser automatically when running with asyncify. HINT_AUDIO_INCLUDE_MONITORS = C.SDL_HINT_AUDIO_INCLUDE_MONITORS // Control whether PulseAudio recording should include monitor devices HINT_AUDIO_DEVICE_STREAM_ROLE = C.SDL_HINT_AUDIO_DEVICE_STREAM_ROLE // Describe the role of your application for audio control panels HINT_APP_NAME = C.SDL_HINT_APP_NAME // Lets you specify the application name sent to the OS when required HINT_VIDEO_EGL_ALLOW_TRANSPARENCY = C.SDL_HINT_VIDEO_EGL_ALLOW_TRANSPARENCY // A variable controlling whether the EGL window is allowed to be composited as transparent, rather than opaque HINT_IME_SHOW_UI = C.SDL_HINT_IME_SHOW_UI // A variable to control whether certain IMEs should show native UI components (such as the Candidate List) instead of suppressing them HINT_IME_SUPPORT_EXTENDED_TEXT = C.SDL_HINT_IME_SUPPORT_EXTENDED_TEXT // A variable to control if extended IME text support is enabled. HINT_SCREENSAVER_INHIBIT_ACTIVITY_NAME = C.SDL_HINT_SCREENSAVER_INHIBIT_ACTIVITY_NAME // This hint lets you specify the "activity name" sent to the OS when SDL_DisableScreenSaver() is used (or the screensaver is automatically disabled) HINT_LINUX_JOYSTICK_CLASSIC = C.SDL_HINT_LINUX_JOYSTICK_CLASSIC // A variable controlling whether to use the classic /dev/input/js* joystick interface or the newer /dev/input/event* joystick interface on Linux HINT_JOYSTICK_DEVICE = C.SDL_HINT_JOYSTICK_DEVICE // This variable is currently only used by the Linux joystick driver HINT_JOYSTICK_HIDAPI_STEAM = C.SDL_HINT_JOYSTICK_HIDAPI_STEAM // A variable controlling whether the HIDAPI driver for Steam Controllers should be used HINT_RENDER_LINE_METHOD = C.SDL_HINT_RENDER_LINE_METHOD // A variable controlling how the 2D render API renders lines HINT_MOUSE_RELATIVE_MODE_CENTER = C.SDL_HINT_MOUSE_RELATIVE_MODE_CENTER // A variable controlling whether relative mouse mode constrains the mouse to the center of the window HINT_MOUSE_AUTO_CAPTURE = C.SDL_HINT_MOUSE_AUTO_CAPTURE // A variable controlling whether the mouse is captured while mouse buttons are pressed HINT_VIDEO_FOREIGN_WINDOW_OPENGL = C.SDL_HINT_VIDEO_FOREIGN_WINDOW_OPENGL // When calling SDL_CreateWindowFrom(), make the window compatible with OpenGL HINT_VIDEO_FOREIGN_WINDOW_VULKAN = C.SDL_HINT_VIDEO_FOREIGN_WINDOW_VULKAN // When calling SDL_CreateWindowFrom(), make the window compatible with Vulkan HINT_QUIT_ON_LAST_WINDOW_CLOSE = C.SDL_HINT_QUIT_ON_LAST_WINDOW_CLOSE // A variable that decides whether to send SDL_QUIT when closing the final window HINT_JOYSTICK_ROG_CHAKRAM = C.SDL_HINT_JOYSTICK_ROG_CHAKRAM // A variable controlling whether the ROG Chakram mice should show up as joysticks HINT_X11_WINDOW_TYPE = C.SDL_HINT_X11_WINDOW_TYPE // A variable that forces X11 windows to create as a custom type HINT_VIDEO_WAYLAND_PREFER_LIBDECOR = C.SDL_HINT_VIDEO_WAYLAND_PREFER_LIBDECOR // A variable controlling whether the libdecor Wayland backend is preferred over native decrations ) // An enumeration of hint priorities. // (https://wiki.libsdl.org/SDL_HintPriority) const ( HINT_DEFAULT = C.SDL_HINT_DEFAULT // low priority, used for default values HINT_NORMAL = C.SDL_HINT_NORMAL // medium priority HINT_OVERRIDE = C.SDL_HINT_OVERRIDE // high priority ) // HintCallback is the function to call when the hint value changes. type HintCallback func(data interface{}, name, oldValue, newValue string) // HintCallbackAndData contains a callback function and userdata. type HintCallbackAndData struct { callback HintCallback // the function to call when the hint value changes data interface{} // data to pass to the callback function } var hintCallbacks = make(map[string]HintCallbackAndData) // HintPriority is a hint priority used in SetHintWithPriority(). // (https://wiki.libsdl.org/SDL_HintPriority) type HintPriority C.SDL_HintPriority func (hp HintPriority) c() C.SDL_HintPriority { return C.SDL_HintPriority(hp) } // SetHintWithPriority sets a hint with a specific priority. // (https://wiki.libsdl.org/SDL_SetHintWithPriority) func SetHintWithPriority(name, value string, hp HintPriority) bool { _name := C.CString(name) _value := C.CString(value) defer C.free(unsafe.Pointer(_name)) defer C.free(unsafe.Pointer(_value)) return C.SDL_SetHintWithPriority(_name, _value, hp.c()) > 0 } // SetHint sets a hint with normal priority. // (https://wiki.libsdl.org/SDL_SetHint) func SetHint(name, value string) bool { _name := C.CString(name) _value := C.CString(value) defer C.free(unsafe.Pointer(_name)) defer C.free(unsafe.Pointer(_value)) return C.SDL_SetHint(_name, _value) > 0 } // GetHint returns the value of a hint. // (https://wiki.libsdl.org/SDL_GetHint) func GetHint(name string) string { _name := C.CString(name) defer C.free(unsafe.Pointer(_name)) return C.GoString(C.SDL_GetHint(_name)) } // ClearHints clears all hints. // (https://wiki.libsdl.org/SDL_ClearHints) func ClearHints() { C.SDL_ClearHints() } // AddHintCallback adds a function to watch a particular hint. // (https://wiki.libsdl.org/SDL_AddHintCallback) func AddHintCallback(name string, fn HintCallback, data interface{}) { _name := C.CString(name) hintCallbacks[name] = HintCallbackAndData{ callback: fn, data: data, } C.addHintCallback(_name) } // DelHintCallback removes a function watching a particular hint. // (https://wiki.libsdl.org/SDL_DelHintCallback) func DelHintCallback(name string) { _name := C.CString(name) delete(hintCallbacks, name) C.delHintCallback(_name) } //export goHintCallback func goHintCallback(_name, _oldValue, _newValue *C.char) { name := C.GoString(_name) oldValue := C.GoString(_oldValue) newValue := C.GoString(_newValue) if cb, ok := hintCallbacks[name]; ok { cb.callback(cb.data, name, oldValue, newValue) } } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/hints.h ================================================ void hintCallback(void *userdata, const char *name, const char *oldValue, const char *newValue); void addHintCallback(const char *name); void delHintCallback(const char *name); ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/joystick.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,4)) #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickPowerLevel is not supported before SDL 2.0.4") #endif typedef enum { SDL_JOYSTICK_POWER_UNKNOWN = -1, SDL_JOYSTICK_POWER_EMPTY, SDL_JOYSTICK_POWER_LOW, SDL_JOYSTICK_POWER_MEDIUM, SDL_JOYSTICK_POWER_FULL, SDL_JOYSTICK_POWER_WIRED, SDL_JOYSTICK_POWER_MAX } SDL_JoystickPowerLevel; #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickCurrentPowerLevel is not supported before SDL 2.0.4") #endif static SDL_JoystickPowerLevel SDL_JoystickCurrentPowerLevel(SDL_Joystick* joystick) { return SDL_JOYSTICK_POWER_UNKNOWN; } #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickFromInstanceID is not supported before SDL 2.0.4") #endif static SDL_Joystick* SDL_JoystickFromInstanceID(SDL_JoystickID joyid) { return NULL; } #endif #if !(SDL_VERSION_ATLEAST(2,0,6)) #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickType is not supported before SDL 2.0.6") #endif typedef enum { SDL_JOYSTICK_TYPE_UNKNOWN, SDL_JOYSTICK_TYPE_GAMECONTROLLER, SDL_JOYSTICK_TYPE_WHEEL, SDL_JOYSTICK_TYPE_ARCADE_STICK, SDL_JOYSTICK_TYPE_FLIGHT_STICK, SDL_JOYSTICK_TYPE_DANCE_PAD, SDL_JOYSTICK_TYPE_GUITAR, SDL_JOYSTICK_TYPE_DRUM_KIT, SDL_JOYSTICK_TYPE_ARCADE_PAD, SDL_JOYSTICK_TYPE_THROTTLE } SDL_JoystickType; #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickGetDeviceVendor is not supported before SDL 2.0.6") #endif static Uint16 SDL_JoystickGetDeviceVendor(int device_index) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickGetDeviceProduct is not supported before SDL 2.0.6") #endif static Uint16 SDL_JoystickGetDeviceProduct(int device_index) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickGetDeviceProductVersion is not supported before SDL 2.0.6") #endif static Uint16 SDL_JoystickGetDeviceProductVersion(int device_index) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickGetDeviceType is not supported before SDL 2.0.6") #endif static SDL_JoystickType SDL_JoystickGetDeviceType(int device_index) { return SDL_JOYSTICK_TYPE_UNKNOWN; } #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickGetDeviceInstanceID is not supported before SDL 2.0.6") #endif static SDL_JoystickID SDL_JoystickGetDeviceInstanceID(int device_index) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickGetVendor is not supported before SDL 2.0.6") #endif static Uint16 SDL_JoystickGetVendor(SDL_Joystick* joystick) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickGetProduct is not supported before SDL 2.0.6") #endif static Uint16 SDL_JoystickGetProduct(SDL_Joystick* joystick) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickGetProductVersion is not supported before SDL 2.0.6") #endif static Uint16 SDL_JoystickGetProductVersion(SDL_Joystick* joystick) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickGetType is not supported before SDL 2.0.6") #endif static SDL_JoystickType SDL_JoystickGetType(SDL_Joystick* joystick) { return SDL_JOYSTICK_TYPE_UNKNOWN; } #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickGetAxisInitialState is not supported before SDL 2.0.6") #endif static SDL_bool SDL_JoystickGetAxisInitialState(SDL_Joystick* joystick, int axis, Sint16* state) { return SDL_FALSE; } #endif #if !(SDL_VERSION_ATLEAST(2,0,7)) #if defined(WARN_OUTDATED) #pragma message("SDL_LockJoysticks is not supported before SDL 2.0.7") #endif static void SDL_LockJoysticks() { } #if defined(WARN_OUTDATED) #pragma message("SDL_UnlockJoysticks is not supported before SDL 2.0.7") #endif static void SDL_UnlockJoysticks() { } #endif #if !(SDL_VERSION_ATLEAST(2,0,9)) #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickGetDevicePlayerIndex is not supported before SDL 2.0.9") #endif static int SDL_JoystickGetDevicePlayerIndex(int device_index) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickGetPlayerIndex is not supported before SDL 2.0.9") #endif static int SDL_JoystickGetPlayerIndex(SDL_Joystick *joystick) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickRumble is not supported before SDL 2.0.9") #endif static int SDL_JoystickRumble(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble, Uint32 duration_ms) { return -1; } #endif #if !(SDL_VERSION_ATLEAST(2,0,18)) #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickHasRumble is not supported before SDL 2.0.18") #pragma message("SDL_JoystickHasRumbleTriggers is not supported before SDL 2.0.18") #endif static SDL_bool SDL_JoystickHasRumble(SDL_Joystick *joystick) { return SDL_FALSE; } static SDL_bool SDL_JoystickHasRumbleTriggers(SDL_Joystick *joystick) { return SDL_FALSE; } #endif */ import "C" import "unsafe" // Hat positions. // (https://wiki.libsdl.org/SDL_JoystickGetHat) const ( HAT_CENTERED = C.SDL_HAT_CENTERED HAT_UP = C.SDL_HAT_UP HAT_RIGHT = C.SDL_HAT_RIGHT HAT_DOWN = C.SDL_HAT_DOWN HAT_LEFT = C.SDL_HAT_LEFT HAT_RIGHTUP = C.SDL_HAT_RIGHTUP HAT_RIGHTDOWN = C.SDL_HAT_RIGHTDOWN HAT_LEFTUP = C.SDL_HAT_LEFTUP HAT_LEFTDOWN = C.SDL_HAT_LEFTDOWN ) // Types of a joystick. const ( JOYSTICK_TYPE_UNKNOWN = C.SDL_JOYSTICK_TYPE_UNKNOWN JOYSTICK_TYPE_GAMECONTROLLER = C.SDL_JOYSTICK_TYPE_GAMECONTROLLER JOYSTICK_TYPE_WHEEL = C.SDL_JOYSTICK_TYPE_WHEEL JOYSTICK_TYPE_ARCADE_STICK = C.SDL_JOYSTICK_TYPE_ARCADE_STICK JOYSTICK_TYPE_FLIGHT_STICK = C.SDL_JOYSTICK_TYPE_FLIGHT_STICK JOYSTICK_TYPE_DANCE_PAD = C.SDL_JOYSTICK_TYPE_DANCE_PAD JOYSTICK_TYPE_GUITAR = C.SDL_JOYSTICK_TYPE_GUITAR JOYSTICK_TYPE_DRUM_KIT = C.SDL_JOYSTICK_TYPE_DRUM_KIT JOYSTICK_TYPE_ARCADE_PAD = C.SDL_JOYSTICK_TYPE_ARCADE_PAD JOYSTICK_TYPE_THROTTLE = C.SDL_JOYSTICK_TYPE_THROTTLE ) // An enumeration of battery levels of a joystick. // (https://wiki.libsdl.org/SDL_JoystickPowerLevel) const ( JOYSTICK_POWER_UNKNOWN = C.SDL_JOYSTICK_POWER_UNKNOWN JOYSTICK_POWER_EMPTY = C.SDL_JOYSTICK_POWER_EMPTY JOYSTICK_POWER_LOW = C.SDL_JOYSTICK_POWER_LOW JOYSTICK_POWER_MEDIUM = C.SDL_JOYSTICK_POWER_MEDIUM JOYSTICK_POWER_FULL = C.SDL_JOYSTICK_POWER_FULL JOYSTICK_POWER_WIRED = C.SDL_JOYSTICK_POWER_WIRED JOYSTICK_POWER_MAX = C.SDL_JOYSTICK_POWER_MAX ) // Joystick is an SDL joystick. type Joystick C.SDL_Joystick // JoystickGUID is a stable unique id for a joystick device. type JoystickGUID C.SDL_JoystickGUID // JoystickID is joystick's instance id. type JoystickID C.SDL_JoystickID // JoystickType is a type of a joystick. type JoystickType C.SDL_JoystickType // JoystickPowerLevel is a battery level of a joystick. type JoystickPowerLevel C.SDL_JoystickPowerLevel func (joy *Joystick) cptr() *C.SDL_Joystick { return (*C.SDL_Joystick)(unsafe.Pointer(joy)) } func (guid JoystickGUID) c() C.SDL_JoystickGUID { return C.SDL_JoystickGUID(guid) } func (joyid JoystickID) c() C.SDL_JoystickID { return C.SDL_JoystickID(joyid) } // NumJoysticks returns the number of joysticks attached to the system. // (https://wiki.libsdl.org/SDL_NumJoysticks) func NumJoysticks() int { return (int)(C.SDL_NumJoysticks()) } // JoystickNameForIndex returns the implementation dependent name of a joystick. // (https://wiki.libsdl.org/SDL_JoystickNameForIndex) func JoystickNameForIndex(index int) string { return (C.GoString)(C.SDL_JoystickNameForIndex(C.int(index))) } // JoystickGetDevicePlayerIndex returns the player index of a joystick, or -1 if it's not available // TODO: (https://wiki.libsdl.org/SDL_JoystickGetDevicePlayerIndex) func JoystickGetDevicePlayerIndex(index int) int { return int(C.SDL_JoystickGetDevicePlayerIndex(C.int(index))) } // JoystickGetDeviceGUID returns the implementation dependent GUID for the joystick at a given device index. // (https://wiki.libsdl.org/SDL_JoystickGetDeviceGUID) func JoystickGetDeviceGUID(index int) JoystickGUID { return (JoystickGUID)(C.SDL_JoystickGetDeviceGUID(C.int(index))) } // JoystickGetDeviceVendor returns the USB vendor ID of a joystick, if available, 0 otherwise. func JoystickGetDeviceVendor(index int) int { return int(C.SDL_JoystickGetDeviceVendor(C.int(index))) } // JoystickGetDeviceProduct returns the USB product ID of a joystick, if available, 0 otherwise. func JoystickGetDeviceProduct(index int) int { return int(C.SDL_JoystickGetDeviceProduct(C.int(index))) } // JoystickGetDeviceProductVersion returns the product version of a joystick, if available, 0 otherwise. func JoystickGetDeviceProductVersion(index int) int { return int(C.SDL_JoystickGetDeviceProductVersion(C.int(index))) } // JoystickGetDeviceType returns the type of a joystick. func JoystickGetDeviceType(index int) JoystickType { return JoystickType(C.SDL_JoystickGetDeviceType(C.int(index))) } // JoystickGetDeviceInstanceID returns the instance ID of a joystick. func JoystickGetDeviceInstanceID(index int) JoystickID { return JoystickID(C.SDL_JoystickGetDeviceInstanceID(C.int(index))) } // JoystickGetGUIDString returns an ASCII string representation for a given JoystickGUID. // (https://wiki.libsdl.org/SDL_JoystickGetGUIDString) func JoystickGetGUIDString(guid JoystickGUID) string { _pszGUID := make([]rune, 1024) pszGUID := C.CString(string(_pszGUID[:])) defer C.free(unsafe.Pointer(pszGUID)) C.SDL_JoystickGetGUIDString(guid.c(), pszGUID, C.int(unsafe.Sizeof(_pszGUID))) return C.GoString(pszGUID) } // JoystickGetGUIDFromString converts a GUID string into a JoystickGUID structure. // (https://wiki.libsdl.org/SDL_JoystickGetGUIDFromString) func JoystickGetGUIDFromString(pchGUID string) JoystickGUID { _pchGUID := C.CString(pchGUID) defer C.free(unsafe.Pointer(_pchGUID)) return (JoystickGUID)(C.SDL_JoystickGetGUIDFromString(_pchGUID)) } // JoystickUpdate updates the current state of the open joysticks. // (https://wiki.libsdl.org/SDL_JoystickUpdate) func JoystickUpdate() { C.SDL_JoystickUpdate() } // JoystickEventState enables or disables joystick event polling. // (https://wiki.libsdl.org/SDL_JoystickEventState) func JoystickEventState(state int) int { return (int)(C.SDL_JoystickEventState(C.int(state))) } // JoystickOpen opens a joystick for use. // (https://wiki.libsdl.org/SDL_JoystickOpen) func JoystickOpen(index int) *Joystick { return (*Joystick)(C.SDL_JoystickOpen(C.int(index))) } // JoystickFromInstanceID returns the Joystick associated with an instance id. // (https://wiki.libsdl.org/SDL_JoystickFromInstanceID) func JoystickFromInstanceID(joyid JoystickID) *Joystick { return (*Joystick)(C.SDL_JoystickFromInstanceID(joyid.c())) } // LockJoysticks locks joysticks for multi-threaded access to the joystick API // TODO: (https://wiki.libsdl.org/SDL_LockJoysticks) func LockJoysticks() { C.SDL_LockJoysticks() } // UnlockJoysticks unlocks joysticks for multi-threaded access to the joystick API // TODO: (https://wiki.libsdl.org/SDL_UnlockJoysticks) func UnlockJoysticks() { C.SDL_UnlockJoysticks() } // Name returns the implementation dependent name of a joystick. // (https://wiki.libsdl.org/SDL_JoystickName) func (joy *Joystick) Name() string { return (C.GoString)(C.SDL_JoystickName(joy.cptr())) } // PlayerIndex returns the player index of an opened joystick, or -1 if it's not available. // (https://wiki.libsdl.org/SDL_JoystickGetPlayerIndex) func (joy *Joystick) PlayerIndex() int { return int(C.SDL_JoystickGetPlayerIndex(joy.cptr())) } // GUID returns the implementation-dependent GUID for the joystick. // (https://wiki.libsdl.org/SDL_JoystickGetGUID) func (joy *Joystick) GUID() JoystickGUID { return (JoystickGUID)(C.SDL_JoystickGetGUID(joy.cptr())) } // Vendor returns the USB vendor ID of an opened joystick, if available, 0 otherwise. func (joy *Joystick) Vendor() int { return int(C.SDL_JoystickGetVendor(joy.cptr())) } // Product returns the USB product ID of an opened joystick, if available, 0 otherwise. func (joy *Joystick) Product() int { return int(C.SDL_JoystickGetProduct(joy.cptr())) } // ProductVersion returns the product version of an opened joystick, if available, 0 otherwise. func (joy *Joystick) ProductVersion() int { return int(C.SDL_JoystickGetProductVersion(joy.cptr())) } // Type returns the the type of an opened joystick. func (joy *Joystick) Type() JoystickType { return JoystickType(C.SDL_JoystickGetType(joy.cptr())) } // Attached returns the status of a specified joystick. // (https://wiki.libsdl.org/SDL_JoystickGetAttached) func (joy *Joystick) Attached() bool { return C.SDL_JoystickGetAttached(joy.cptr()) == C.SDL_TRUE } // InstanceID returns the instance ID of an opened joystick. // (https://wiki.libsdl.org/SDL_JoystickInstanceID) func (joy *Joystick) InstanceID() JoystickID { return (JoystickID)(C.SDL_JoystickInstanceID(joy.cptr())) } // NumAxes returns the number of general axis controls on a joystick. // (https://wiki.libsdl.org/SDL_JoystickNumAxes) func (joy *Joystick) NumAxes() int { return (int)(C.SDL_JoystickNumAxes(joy.cptr())) } // NumBalls returns the number of trackballs on a joystick. // (https://wiki.libsdl.org/SDL_JoystickNumBalls) func (joy *Joystick) NumBalls() int { return (int)(C.SDL_JoystickNumBalls(joy.cptr())) } // NumHats returns the number of POV hats on a joystick. // (https://wiki.libsdl.org/SDL_JoystickNumHats) func (joy *Joystick) NumHats() int { return (int)(C.SDL_JoystickNumHats(joy.cptr())) } // NumButtons returns the number of buttons on a joystick. // (https://wiki.libsdl.org/SDL_JoystickNumButtons) func (joy *Joystick) NumButtons() int { return (int)(C.SDL_JoystickNumButtons(joy.cptr())) } // Axis returns the current state of an axis control on a joystick. // (https://wiki.libsdl.org/SDL_JoystickGetAxis) func (joy *Joystick) Axis(axis int) int16 { return (int16)(C.SDL_JoystickGetAxis(joy.cptr(), C.int(axis))) } // AxisInitialState returns the initial state of an axis control on a joystick, ok is true if this axis has any initial value. func (joy *Joystick) AxisInitialState(axis int) (state int16, ok bool) { ok = C.SDL_JoystickGetAxisInitialState(joy.cptr(), C.int(axis), (*C.Sint16)(&state)) == C.SDL_TRUE return } // Hat returns the current state of a POV hat on a joystick. // (https://wiki.libsdl.org/SDL_JoystickGetHat) func (joy *Joystick) Hat(hat int) byte { return (byte)(C.SDL_JoystickGetHat(joy.cptr(), C.int(hat))) } // Ball returns the ball axis change since the last poll. // (https://wiki.libsdl.org/SDL_JoystickGetBall) func (joy *Joystick) Ball(ball int, dx, dy *int32) int { _dx := (*C.int)(unsafe.Pointer(dx)) _dy := (*C.int)(unsafe.Pointer(dy)) return (int)(C.SDL_JoystickGetBall(joy.cptr(), C.int(ball), _dx, _dy)) } // Button the current state of a button on a joystick. // (https://wiki.libsdl.org/SDL_JoystickGetButton) func (joy *Joystick) Button(button int) byte { return (byte)(C.SDL_JoystickGetButton(joy.cptr(), C.int(button))) } // Rumble triggers a rumble effect // Each call to this function cancels any previous rumble effect, and calling it with 0 intensity stops any rumbling. // // lowFrequencyRumble - The intensity of the low frequency (left) rumble motor, from 0 to 0xFFFF // highFrequencyRumble - The intensity of the high frequency (right) rumble motor, from 0 to 0xFFFF // durationMS - The duration of the rumble effect, in milliseconds // // Returns error if rumble isn't supported on this joystick. // // TODO: (https://wiki.libsdl.org/SDL_JoystickRumble) func (joy *Joystick) Rumble(lowFrequencyRumble, highFrequencyRumble uint16, durationMS uint32) error { return errorFromInt(int(C.SDL_JoystickRumble(joy.cptr(), C.Uint16(lowFrequencyRumble), C.Uint16(highFrequencyRumble), C.Uint32(durationMS)))) } // Close closes a joystick previously opened with JoystickOpen(). // (https://wiki.libsdl.org/SDL_JoystickClose) func (joy *Joystick) Close() { C.SDL_JoystickClose(joy.cptr()) } // CurrentPowerLevel returns the battery level of a joystick as JoystickPowerLevel. // (https://wiki.libsdl.org/SDL_JoystickCurrentPowerLevel) func (joy *Joystick) CurrentPowerLevel() JoystickPowerLevel { return JoystickPowerLevel(C.SDL_JoystickCurrentPowerLevel(joy.cptr())) } // HasRumble queries whether a game controller has rumble support. // (https://wiki.libsdl.org/SDL_JoystickHasRumble) func (ctrl *Joystick) HasRumble() bool { return C.SDL_JoystickHasRumble(ctrl.cptr()) == C.SDL_TRUE } // HasRumbleTriggers queries whether a game controller has rumble support on triggers. // (https://wiki.libsdl.org/SDL_JoystickHasRumbleTriggers) func (ctrl *Joystick) HasRumbleTriggers() bool { return C.SDL_JoystickHasRumbleTriggers(ctrl.cptr()) == C.SDL_TRUE } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/keyboard.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,22)) #if defined(WARN_OUTDATED) #pragma message("SDL_IsTextInputShown is not supported before SDL 2.0.22") #pragma message("SDL_ClearComposition is not supported before SDL 2.0.22") #endif static inline SDL_bool SDL_IsTextInputShown(void) { return SDL_FALSE; } static inline void SDL_ClearComposition(void) { } #endif */ import "C" import ( "reflect" "unsafe" ) // Keysym contains key information used in key events. // (https://wiki.libsdl.org/SDL_Keysym) type Keysym struct { Scancode Scancode // SDL physical key code Sym Keycode // SDL virtual key code Mod uint16 // current key modifiers unused uint32 // unused } // GetKeyboardFocus returns the window which currently has keyboard focus. // (https://wiki.libsdl.org/SDL_GetKeyboardFocus) func GetKeyboardFocus() *Window { return (*Window)(unsafe.Pointer(C.SDL_GetKeyboardFocus())) } // GetKeyboardState returns a snapshot of the current state of the keyboard. // (https://wiki.libsdl.org/SDL_GetKeyboardState) func GetKeyboardState() []uint8 { var numkeys C.int start := C.SDL_GetKeyboardState(&numkeys) sh := reflect.SliceHeader{} sh.Len = int(numkeys) sh.Cap = int(numkeys) sh.Data = uintptr(unsafe.Pointer(start)) return *(*[]uint8)(unsafe.Pointer(&sh)) } // GetModState returns the current key modifier state for the keyboard. // (https://wiki.libsdl.org/SDL_GetModState) func GetModState() Keymod { return (Keymod)(C.SDL_GetModState()) } // SetModState sets the current key modifier state for the keyboard. // (https://wiki.libsdl.org/SDL_SetModState) func SetModState(mod Keymod) { C.SDL_SetModState(mod.c()) } // GetKeyFromScancode returns the key code corresponding to the given scancode according to the current keyboard layout. // (https://wiki.libsdl.org/SDL_GetKeyFromScancode) func GetKeyFromScancode(code Scancode) Keycode { return (Keycode)(C.SDL_GetKeyFromScancode(code.c())) } // GetScancodeFromKey returns the scancode corresponding to the given key code according to the current keyboard layout. // (https://wiki.libsdl.org/SDL_GetScancodeFromKey) func GetScancodeFromKey(code Keycode) Scancode { return (Scancode)(C.SDL_GetScancodeFromKey(code.c())) } // GetScancodeName returns a human-readable name for a scancode // (https://wiki.libsdl.org/SDL_GetScancodeName) func GetScancodeName(code Scancode) string { return (C.GoString)(C.SDL_GetScancodeName(code.c())) } // GetScancodeFromName returns a scancode from a human-readable name. // (https://wiki.libsdl.org/SDL_GetScancodeFromName) func GetScancodeFromName(name string) Scancode { _name := C.CString(name) defer C.free(unsafe.Pointer(_name)) return (Scancode)(C.SDL_GetScancodeFromName(_name)) } // GetKeyName returns a human-readable name for a key. // (https://wiki.libsdl.org/SDL_GetKeyName) func GetKeyName(code Keycode) string { return (C.GoString)(C.SDL_GetKeyName(code.c())) } // GetKeyFromName returns a key code from a human-readable name. // (https://wiki.libsdl.org/SDL_GetKeyFromName) func GetKeyFromName(name string) Keycode { _name := C.CString(name) defer C.free(unsafe.Pointer(_name)) return (Keycode)(C.SDL_GetKeyFromName(_name)) } // StartTextInput starts accepting Unicode text input events. // (https://wiki.libsdl.org/SDL_StartTextInput) func StartTextInput() { C.SDL_StartTextInput() } // IsTextInputActive checks whether or not Unicode text input events are enabled. // (https://wiki.libsdl.org/SDL_IsTextInputActive) func IsTextInputActive() bool { return C.SDL_IsTextInputActive() > 0 } // StopTextInput stops receiving any text input events. // (https://wiki.libsdl.org/SDL_StopTextInput) func StopTextInput() { C.SDL_StopTextInput() } // SetTextInputRect sets the rectangle used to type Unicode text inputs. // (https://wiki.libsdl.org/SDL_SetTextInputRect) func SetTextInputRect(rect *Rect) { C.SDL_SetTextInputRect(rect.cptr()) } // HasScreenKeyboardSupport reports whether the platform has some screen keyboard support. // (https://wiki.libsdl.org/SDL_HasScreenKeyboardSupport) func HasScreenKeyboardSupport() bool { return C.SDL_HasScreenKeyboardSupport() > 0 } // IsScreenKeyboardShown reports whether the screen keyboard is shown for given window. // (https://wiki.libsdl.org/SDL_IsScreenKeyboardShown) func IsScreenKeyboardShown(window *Window) bool { return C.SDL_IsScreenKeyboardShown(window.cptr()) > 0 } // IsTextInputShown returns if an IME Composite or Candidate window is currently shown. // (https://wiki.libsdl.org/SDL_IsTextInputShown) func IsTextInputShown() bool { return C.SDL_IsTextInputShown() > 0 } // ClearComposition dismisses the composition window/IME without disabling the subsystem. // (https://wiki.libsdl.org/SDL_ClearComposition) func ClearComposition() { C.SDL_ClearComposition() } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/keycode.go ================================================ package sdl // #include "sdl_wrapper.h" import "C" const K_SCANCODE_MASK = 1 << 30 // The SDL virtual key representation. // (https://wiki.libsdl.org/SDL_Keycode) // (https://wiki.libsdl.org/SDLKeycodeLookup) const ( K_UNKNOWN = C.SDLK_UNKNOWN // "" (no name, empty string) K_RETURN = C.SDLK_RETURN // "Return" (the Enter key (main keyboard)) K_ESCAPE = C.SDLK_ESCAPE // "Escape" (the Esc key) K_BACKSPACE = C.SDLK_BACKSPACE // "Backspace" K_TAB = C.SDLK_TAB // "Tab" (the Tab key) K_SPACE = C.SDLK_SPACE // "Space" (the Space Bar key(s)) K_EXCLAIM = C.SDLK_EXCLAIM // "!" K_QUOTEDBL = C.SDLK_QUOTEDBL // """ K_HASH = C.SDLK_HASH // "#" K_PERCENT = C.SDLK_PERCENT // "%" K_DOLLAR = C.SDLK_DOLLAR // "$" K_AMPERSAND = C.SDLK_AMPERSAND // "&" K_QUOTE = C.SDLK_QUOTE // "'" K_LEFTPAREN = C.SDLK_LEFTPAREN // "(" K_RIGHTPAREN = C.SDLK_RIGHTPAREN // ")" K_ASTERISK = C.SDLK_ASTERISK // "*" K_PLUS = C.SDLK_PLUS // "+" K_COMMA = C.SDLK_COMMA // "," K_MINUS = C.SDLK_MINUS // "-" K_PERIOD = C.SDLK_PERIOD // "." K_SLASH = C.SDLK_SLASH // "/" K_0 = C.SDLK_0 // "0" K_1 = C.SDLK_1 // "1" K_2 = C.SDLK_2 // "2" K_3 = C.SDLK_3 // "3" K_4 = C.SDLK_4 // "4" K_5 = C.SDLK_5 // "5" K_6 = C.SDLK_6 // "6" K_7 = C.SDLK_7 // "7" K_8 = C.SDLK_8 // "8" K_9 = C.SDLK_9 // "9" K_COLON = C.SDLK_COLON // ":" K_SEMICOLON = C.SDLK_SEMICOLON // ";" K_LESS = C.SDLK_LESS // "<" K_EQUALS = C.SDLK_EQUALS // "=" K_GREATER = C.SDLK_GREATER // ">" K_QUESTION = C.SDLK_QUESTION // "?" K_AT = C.SDLK_AT // "@" /* Skip uppercase letters */ K_LEFTBRACKET = C.SDLK_LEFTBRACKET // "[" K_BACKSLASH = C.SDLK_BACKSLASH // "\" K_RIGHTBRACKET = C.SDLK_RIGHTBRACKET // "]" K_CARET = C.SDLK_CARET // "^" K_UNDERSCORE = C.SDLK_UNDERSCORE // "_" K_BACKQUOTE = C.SDLK_BACKQUOTE // "`" K_a = C.SDLK_a // "A" K_b = C.SDLK_b // "B" K_c = C.SDLK_c // "C" K_d = C.SDLK_d // "D" K_e = C.SDLK_e // "E" K_f = C.SDLK_f // "F" K_g = C.SDLK_g // "G" K_h = C.SDLK_h // "H" K_i = C.SDLK_i // "I" K_j = C.SDLK_j // "J" K_k = C.SDLK_k // "K" K_l = C.SDLK_l // "L" K_m = C.SDLK_m // "M" K_n = C.SDLK_n // "N" K_o = C.SDLK_o // "O" K_p = C.SDLK_p // "P" K_q = C.SDLK_q // "Q" K_r = C.SDLK_r // "R" K_s = C.SDLK_s // "S" K_t = C.SDLK_t // "T" K_u = C.SDLK_u // "U" K_v = C.SDLK_v // "V" K_w = C.SDLK_w // "W" K_x = C.SDLK_x // "X" K_y = C.SDLK_y // "Y" K_z = C.SDLK_z // "Z" K_CAPSLOCK = C.SDLK_CAPSLOCK // "CapsLock" K_F1 = C.SDLK_F1 // "F1" K_F2 = C.SDLK_F2 // "F2" K_F3 = C.SDLK_F3 // "F3" K_F4 = C.SDLK_F4 // "F4" K_F5 = C.SDLK_F5 // "F5" K_F6 = C.SDLK_F6 // "F6" K_F7 = C.SDLK_F7 // "F7" K_F8 = C.SDLK_F8 // "F8" K_F9 = C.SDLK_F9 // "F9" K_F10 = C.SDLK_F10 // "F10" K_F11 = C.SDLK_F11 // "F11" K_F12 = C.SDLK_F12 // "F12" K_PRINTSCREEN = C.SDLK_PRINTSCREEN // "PrintScreen" K_SCROLLLOCK = C.SDLK_SCROLLLOCK // "ScrollLock" K_PAUSE = C.SDLK_PAUSE // "Pause" (the Pause / Break key) K_INSERT = C.SDLK_INSERT // "Insert" (insert on PC, help on some Mac keyboards (but does send code 73, not 117)) K_HOME = C.SDLK_HOME // "Home" K_PAGEUP = C.SDLK_PAGEUP // "PageUp" K_DELETE = C.SDLK_DELETE // "Delete" K_END = C.SDLK_END // "End" K_PAGEDOWN = C.SDLK_PAGEDOWN // "PageDown" K_RIGHT = C.SDLK_RIGHT // "Right" (the Right arrow key (navigation keypad)) K_LEFT = C.SDLK_LEFT // "Left" (the Left arrow key (navigation keypad)) K_DOWN = C.SDLK_DOWN // "Down" (the Down arrow key (navigation keypad)) K_UP = C.SDLK_UP // "Up" (the Up arrow key (navigation keypad)) K_NUMLOCKCLEAR = C.SDLK_NUMLOCKCLEAR // "Numlock" (the Num Lock key (PC) / the Clear key (Mac)) K_KP_DIVIDE = C.SDLK_KP_DIVIDE // "Keypad /" (the / key (numeric keypad)) K_KP_MULTIPLY = C.SDLK_KP_MULTIPLY // "Keypad *" (the * key (numeric keypad)) K_KP_MINUS = C.SDLK_KP_MINUS // "Keypad -" (the - key (numeric keypad)) K_KP_PLUS = C.SDLK_KP_PLUS // "Keypad +" (the + key (numeric keypad)) K_KP_ENTER = C.SDLK_KP_ENTER // "Keypad Enter" (the Enter key (numeric keypad)) K_KP_1 = C.SDLK_KP_1 // "Keypad 1" (the 1 key (numeric keypad)) K_KP_2 = C.SDLK_KP_2 // "Keypad 2" (the 2 key (numeric keypad)) K_KP_3 = C.SDLK_KP_3 // "Keypad 3" (the 3 key (numeric keypad)) K_KP_4 = C.SDLK_KP_4 // "Keypad 4" (the 4 key (numeric keypad)) K_KP_5 = C.SDLK_KP_5 // "Keypad 5" (the 5 key (numeric keypad)) K_KP_6 = C.SDLK_KP_6 // "Keypad 6" (the 6 key (numeric keypad)) K_KP_7 = C.SDLK_KP_7 // "Keypad 7" (the 7 key (numeric keypad)) K_KP_8 = C.SDLK_KP_8 // "Keypad 8" (the 8 key (numeric keypad)) K_KP_9 = C.SDLK_KP_9 // "Keypad 9" (the 9 key (numeric keypad)) K_KP_0 = C.SDLK_KP_0 // "Keypad 0" (the 0 key (numeric keypad)) K_KP_PERIOD = C.SDLK_KP_PERIOD // "Keypad ." (the . key (numeric keypad)) K_APPLICATION = C.SDLK_APPLICATION // "Application" (the Application / Compose / Context Menu (Windows) key) K_POWER = C.SDLK_POWER // "Power" (The USB document says this is a status flag, not a physical key - but some Mac keyboards do have a power key.) K_KP_EQUALS = C.SDLK_KP_EQUALS // "Keypad =" (the = key (numeric keypad)) K_F13 = C.SDLK_F13 // "F13" K_F14 = C.SDLK_F14 // "F14" K_F15 = C.SDLK_F15 // "F15" K_F16 = C.SDLK_F16 // "F16" K_F17 = C.SDLK_F17 // "F17" K_F18 = C.SDLK_F18 // "F18" K_F19 = C.SDLK_F19 // "F19" K_F20 = C.SDLK_F20 // "F20" K_F21 = C.SDLK_F21 // "F21" K_F22 = C.SDLK_F22 // "F22" K_F23 = C.SDLK_F23 // "F23" K_F24 = C.SDLK_F24 // "F24" K_EXECUTE = C.SDLK_EXECUTE // "Execute" K_HELP = C.SDLK_HELP // "Help" K_MENU = C.SDLK_MENU // "Menu" K_SELECT = C.SDLK_SELECT // "Select" K_STOP = C.SDLK_STOP // "Stop" K_AGAIN = C.SDLK_AGAIN // "Again" (the Again key (Redo)) K_UNDO = C.SDLK_UNDO // "Undo" K_CUT = C.SDLK_CUT // "Cut" K_COPY = C.SDLK_COPY // "Copy" K_PASTE = C.SDLK_PASTE // "Paste" K_FIND = C.SDLK_FIND // "Find" K_MUTE = C.SDLK_MUTE // "Mute" K_VOLUMEUP = C.SDLK_VOLUMEUP // "VolumeUp" K_VOLUMEDOWN = C.SDLK_VOLUMEDOWN // "VolumeDown" K_KP_COMMA = C.SDLK_KP_COMMA // "Keypad ," (the Comma key (numeric keypad)) K_KP_EQUALSAS400 = C.SDLK_KP_EQUALSAS400 // "Keypad = (AS400)" (the Equals AS400 key (numeric keypad)) K_ALTERASE = C.SDLK_ALTERASE // "AltErase" (Erase-Eaze) K_SYSREQ = C.SDLK_SYSREQ // "SysReq" (the SysReq key) K_CANCEL = C.SDLK_CANCEL // "Cancel" K_CLEAR = C.SDLK_CLEAR // "Clear" K_PRIOR = C.SDLK_PRIOR // "Prior" K_RETURN2 = C.SDLK_RETURN2 // "Return" K_SEPARATOR = C.SDLK_SEPARATOR // "Separator" K_OUT = C.SDLK_OUT // "Out" K_OPER = C.SDLK_OPER // "Oper" K_CLEARAGAIN = C.SDLK_CLEARAGAIN // "Clear / Again" K_CRSEL = C.SDLK_CRSEL // "CrSel" K_EXSEL = C.SDLK_EXSEL // "ExSel" K_KP_00 = C.SDLK_KP_00 // "Keypad 00" (the 00 key (numeric keypad)) K_KP_000 = C.SDLK_KP_000 // "Keypad 000" (the 000 key (numeric keypad)) K_THOUSANDSSEPARATOR = C.SDLK_THOUSANDSSEPARATOR // "ThousandsSeparator" (the Thousands Separator key) K_DECIMALSEPARATOR = C.SDLK_DECIMALSEPARATOR // "DecimalSeparator" (the Decimal Separator key) K_CURRENCYUNIT = C.SDLK_CURRENCYUNIT // "CurrencyUnit" (the Currency Unit key) K_CURRENCYSUBUNIT = C.SDLK_CURRENCYSUBUNIT // "CurrencySubUnit" (the Currency Subunit key) K_KP_LEFTPAREN = C.SDLK_KP_LEFTPAREN // "Keypad (" (the Left Parenthesis key (numeric keypad)) K_KP_RIGHTPAREN = C.SDLK_KP_RIGHTPAREN // "Keypad )" (the Right Parenthesis key (numeric keypad)) K_KP_LEFTBRACE = C.SDLK_KP_LEFTBRACE // "Keypad {" (the Left Brace key (numeric keypad)) K_KP_RIGHTBRACE = C.SDLK_KP_RIGHTBRACE // "Keypad }" (the Right Brace key (numeric keypad)) K_KP_TAB = C.SDLK_KP_TAB // "Keypad Tab" (the Tab key (numeric keypad)) K_KP_BACKSPACE = C.SDLK_KP_BACKSPACE // "Keypad Backspace" (the Backspace key (numeric keypad)) K_KP_A = C.SDLK_KP_A // "Keypad A" (the A key (numeric keypad)) K_KP_B = C.SDLK_KP_B // "Keypad B" (the B key (numeric keypad)) K_KP_C = C.SDLK_KP_C // "Keypad C" (the C key (numeric keypad)) K_KP_D = C.SDLK_KP_D // "Keypad D" (the D key (numeric keypad)) K_KP_E = C.SDLK_KP_E // "Keypad E" (the E key (numeric keypad)) K_KP_F = C.SDLK_KP_F // "Keypad F" (the F key (numeric keypad)) K_KP_XOR = C.SDLK_KP_XOR // "Keypad XOR" (the XOR key (numeric keypad)) K_KP_POWER = C.SDLK_KP_POWER // "Keypad ^" (the Power key (numeric keypad)) K_KP_PERCENT = C.SDLK_KP_PERCENT // "Keypad %" (the Percent key (numeric keypad)) K_KP_LESS = C.SDLK_KP_LESS // "Keypad <" (the Less key (numeric keypad)) K_KP_GREATER = C.SDLK_KP_GREATER // "Keypad >" (the Greater key (numeric keypad)) K_KP_AMPERSAND = C.SDLK_KP_AMPERSAND // "Keypad &" (the & key (numeric keypad)) K_KP_DBLAMPERSAND = C.SDLK_KP_DBLAMPERSAND // "Keypad &&" (the && key (numeric keypad)) K_KP_VERTICALBAR = C.SDLK_KP_VERTICALBAR // "Keypad |" (the | key (numeric keypad)) K_KP_DBLVERTICALBAR = C.SDLK_KP_DBLVERTICALBAR // "Keypad ||" (the || key (numeric keypad)) K_KP_COLON = C.SDLK_KP_COLON // "Keypad :" (the : key (numeric keypad)) K_KP_HASH = C.SDLK_KP_HASH // "Keypad #" (the # key (numeric keypad)) K_KP_SPACE = C.SDLK_KP_SPACE // "Keypad Space" (the Space key (numeric keypad)) K_KP_AT = C.SDLK_KP_AT // "Keypad @" (the @ key (numeric keypad)) K_KP_EXCLAM = C.SDLK_KP_EXCLAM // "Keypad !" (the ! key (numeric keypad)) K_KP_MEMSTORE = C.SDLK_KP_MEMSTORE // "Keypad MemStore" (the Mem Store key (numeric keypad)) K_KP_MEMRECALL = C.SDLK_KP_MEMRECALL // "Keypad MemRecall" (the Mem Recall key (numeric keypad)) K_KP_MEMCLEAR = C.SDLK_KP_MEMCLEAR // "Keypad MemClear" (the Mem Clear key (numeric keypad)) K_KP_MEMADD = C.SDLK_KP_MEMADD // "Keypad MemAdd" (the Mem Add key (numeric keypad)) K_KP_MEMSUBTRACT = C.SDLK_KP_MEMSUBTRACT // "Keypad MemSubtract" (the Mem Subtract key (numeric keypad)) K_KP_MEMMULTIPLY = C.SDLK_KP_MEMMULTIPLY // "Keypad MemMultiply" (the Mem Multiply key (numeric keypad)) K_KP_MEMDIVIDE = C.SDLK_KP_MEMDIVIDE // "Keypad MemDivide" (the Mem Divide key (numeric keypad)) K_KP_PLUSMINUS = C.SDLK_KP_PLUSMINUS // "Keypad +/-" (the +/- key (numeric keypad)) K_KP_CLEAR = C.SDLK_KP_CLEAR // "Keypad Clear" (the Clear key (numeric keypad)) K_KP_CLEARENTRY = C.SDLK_KP_CLEARENTRY // "Keypad ClearEntry" (the Clear Entry key (numeric keypad)) K_KP_BINARY = C.SDLK_KP_BINARY // "Keypad Binary" (the Binary key (numeric keypad)) K_KP_OCTAL = C.SDLK_KP_OCTAL // "Keypad Octal" (the Octal key (numeric keypad)) K_KP_DECIMAL = C.SDLK_KP_DECIMAL // "Keypad Decimal" (the Decimal key (numeric keypad)) K_KP_HEXADECIMAL = C.SDLK_KP_HEXADECIMAL // "Keypad Hexadecimal" (the Hexadecimal key (numeric keypad)) K_LCTRL = C.SDLK_LCTRL // "Left Ctrl" K_LSHIFT = C.SDLK_LSHIFT // "Left Shift" K_LALT = C.SDLK_LALT // "Left Alt" (alt, option) K_LGUI = C.SDLK_LGUI // "Left GUI" (windows, command (apple), meta) K_RCTRL = C.SDLK_RCTRL // "Right Ctrl" K_RSHIFT = C.SDLK_RSHIFT // "Right Shift" K_RALT = C.SDLK_RALT // "Right Alt" (alt, option) K_RGUI = C.SDLK_RGUI // "Right GUI" (windows, command (apple), meta) K_MODE = C.SDLK_MODE // "ModeSwitch" (I'm not sure if this is really not covered by any of the above, but since there's a special KMOD_MODE for it I'm adding it here) K_AUDIONEXT = C.SDLK_AUDIONEXT // "AudioNext" (the Next Track media key) K_AUDIOPREV = C.SDLK_AUDIOPREV // "AudioPrev" (the Previous Track media key) K_AUDIOSTOP = C.SDLK_AUDIOSTOP // "AudioStop" (the Stop media key) K_AUDIOPLAY = C.SDLK_AUDIOPLAY // "AudioPlay" (the Play media key) K_AUDIOMUTE = C.SDLK_AUDIOMUTE // "AudioMute" (the Mute volume key) K_MEDIASELECT = C.SDLK_MEDIASELECT // "MediaSelect" (the Media Select key) K_WWW = C.SDLK_WWW // "WWW" (the WWW/World Wide Web key) K_MAIL = C.SDLK_MAIL // "Mail" (the Mail/eMail key) K_CALCULATOR = C.SDLK_CALCULATOR // "Calculator" (the Calculator key) K_COMPUTER = C.SDLK_COMPUTER // "Computer" (the My Computer key) K_AC_SEARCH = C.SDLK_AC_SEARCH // "AC Search" (the Search key (application control keypad)) K_AC_HOME = C.SDLK_AC_HOME // "AC Home" (the Home key (application control keypad)) K_AC_BACK = C.SDLK_AC_BACK // "AC Back" (the Back key (application control keypad)) K_AC_FORWARD = C.SDLK_AC_FORWARD // "AC Forward" (the Forward key (application control keypad)) K_AC_STOP = C.SDLK_AC_STOP // "AC Stop" (the Stop key (application control keypad)) K_AC_REFRESH = C.SDLK_AC_REFRESH // "AC Refresh" (the Refresh key (application control keypad)) K_AC_BOOKMARKS = C.SDLK_AC_BOOKMARKS // "AC Bookmarks" (the Bookmarks key (application control keypad)) K_BRIGHTNESSDOWN = C.SDLK_BRIGHTNESSDOWN // "BrightnessDown" (the Brightness Down key) K_BRIGHTNESSUP = C.SDLK_BRIGHTNESSUP // "BrightnessUp" (the Brightness Up key) K_DISPLAYSWITCH = C.SDLK_DISPLAYSWITCH // "DisplaySwitch" (display mirroring/dual display switch, video mode switch) K_KBDILLUMTOGGLE = C.SDLK_KBDILLUMTOGGLE // "KBDIllumToggle" (the Keyboard Illumination Toggle key) K_KBDILLUMDOWN = C.SDLK_KBDILLUMDOWN // "KBDIllumDown" (the Keyboard Illumination Down key) K_KBDILLUMUP = C.SDLK_KBDILLUMUP // "KBDIllumUp" (the Keyboard Illumination Up key) K_EJECT = C.SDLK_EJECT // "Eject" (the Eject key) K_SLEEP = C.SDLK_SLEEP // "Sleep" (the Sleep key) ) // An enumeration of key modifier masks. // (https://wiki.libsdl.org/SDL_Keymod) const ( KMOD_NONE = C.KMOD_NONE // 0 (no modifier is applicable) KMOD_LSHIFT = C.KMOD_LSHIFT // the left Shift key is down KMOD_RSHIFT = C.KMOD_RSHIFT // the right Shift key is down KMOD_LCTRL = C.KMOD_LCTRL // the left Ctrl (Control) key is down KMOD_RCTRL = C.KMOD_RCTRL // the right Ctrl (Control) key is down KMOD_LALT = C.KMOD_LALT // the left Alt key is down KMOD_RALT = C.KMOD_RALT // the right Alt key is down KMOD_LGUI = C.KMOD_LGUI // the left GUI key (often the Windows key) is down KMOD_RGUI = C.KMOD_RGUI // the right GUI key (often the Windows key) is down KMOD_NUM = C.KMOD_NUM // the Num Lock key (may be located on an extended keypad) is down KMOD_CAPS = C.KMOD_CAPS // the Caps Lock key is down KMOD_MODE = C.KMOD_MODE // the AltGr key is down KMOD_CTRL = C.KMOD_CTRL // (KMOD_LCTRL|KMOD_RCTRL) KMOD_SHIFT = C.KMOD_SHIFT // (KMOD_LSHIFT|KMOD_RSHIFT) KMOD_ALT = C.KMOD_ALT // (KMOD_LALT|KMOD_RALT) KMOD_GUI = C.KMOD_GUI // (KMOD_LGUI|KMOD_RGUI) KMOD_RESERVED = C.KMOD_RESERVED // reserved for future use ) // Keycode is the SDL virtual key representation. // (https://wiki.libsdl.org/SDL_Keycode) type Keycode C.SDL_Keycode // Keymod is a key modifier masks. // (https://wiki.libsdl.org/SDL_Keymod) type Keymod C.SDL_Keymod func (code Keycode) c() C.SDL_Keycode { return C.SDL_Keycode(code) } func (mod Keymod) c() C.SDL_Keymod { return C.SDL_Keymod(mod) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/loadso.go ================================================ package sdl // #include "sdl_wrapper.h" import "C" import "unsafe" // SharedObject is a pointer to the object handle. type SharedObject uintptr // LoadObject dynamically loads a shared object and returns a pointer to the object handle. // (https://wiki.libsdl.org/SDL_LoadObject) func LoadObject(sofile string) SharedObject { _sofile := C.CString(sofile) defer C.free(unsafe.Pointer(_sofile)) return (SharedObject)(C.SDL_LoadObject(_sofile)) } // LoadFunction returns a pointer to the named function from the shared object. // (https://wiki.libsdl.org/SDL_LoadFunction) func (handle SharedObject) LoadFunction(name string) unsafe.Pointer { _name := C.CString(name) defer C.free(unsafe.Pointer(_name)) return (unsafe.Pointer)(C.SDL_LoadFunction((unsafe.Pointer)(handle), _name)) } // Unload unloads a shared object from memory. // (https://wiki.libsdl.org/SDL_UnloadObject) func (handle SharedObject) Unload() { C.SDL_UnloadObject((unsafe.Pointer)(handle)) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/log.c ================================================ #include "_cgo_export.h" void LogSetOutputFunction(void *data) { SDL_LogSetOutputFunction((SDL_LogOutputFunction)logOutputFunction, data); } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/log.go ================================================ package sdl /* #include "sdl_wrapper.h" #include "log.h" static inline void _SDL_Log(const char *fmt) { SDL_Log("%s", fmt); } static inline void _SDL_LogVerbose(int category, const char *fmt) { SDL_LogVerbose(category, "%s", fmt); } static inline void _SDL_LogDebug(int category, const char *fmt) { SDL_LogDebug(category, "%s", fmt); } static inline void _SDL_LogInfo(int category, const char *fmt) { SDL_LogInfo(category, "%s", fmt); } static inline void _SDL_LogWarn(int category, const char *fmt) { SDL_LogWarn(category, "%s", fmt); } static inline void _SDL_LogError(int category, const char *fmt) { SDL_LogError(category, "%s", fmt); } static inline void _SDL_LogCritical(int category, const char *fmt) { SDL_LogCritical(category, "%s", fmt); } static inline void _SDL_LogMessage(int category, SDL_LogPriority priority, const char *fmt) { SDL_LogCritical(category, "%s", fmt); } */ import "C" import "fmt" import "unsafe" // An enumeration of the predefined log categories. // (https://wiki.libsdl.org/SDL_LOG_CATEGORY) const ( LOG_CATEGORY_APPLICATION = iota // application log LOG_CATEGORY_ERROR // error log LOG_CATEGORY_ASSERT // assert log LOG_CATEGORY_SYSTEM // system log LOG_CATEGORY_AUDIO // audio log LOG_CATEGORY_VIDEO // video log LOG_CATEGORY_RENDER // render log LOG_CATEGORY_INPUT // input log LOG_CATEGORY_TEST // test log LOG_CATEGORY_RESERVED1 // reserved for future SDL library use LOG_CATEGORY_RESERVED2 // reserved for future SDL library use LOG_CATEGORY_RESERVED3 // reserved for future SDL library use LOG_CATEGORY_RESERVED4 // reserved for future SDL library use LOG_CATEGORY_RESERVED5 // reserved for future SDL library use LOG_CATEGORY_RESERVED6 // reserved for future SDL library use LOG_CATEGORY_RESERVED7 // reserved for future SDL library use LOG_CATEGORY_RESERVED8 // reserved for future SDL library use LOG_CATEGORY_RESERVED9 // reserved for future SDL library use LOG_CATEGORY_RESERVED10 // reserved for future SDL library use LOG_CATEGORY_CUSTOM // reserved for application use ) // An enumeration of the predefined log priorities. // (https://wiki.libsdl.org/SDL_LogPriority) const ( LOG_PRIORITY_VERBOSE = iota + 1 // verbose LOG_PRIORITY_DEBUG // debug LOG_PRIORITY_INFO // info LOG_PRIORITY_WARN // warn LOG_PRIORITY_ERROR // error LOG_PRIORITY_CRITICAL // critical NUM_LOG_PRIORITIES // (internal use) ) // LogPriority is a predefined log priority. // (https://wiki.libsdl.org/SDL_LogPriority) type LogPriority C.SDL_LogPriority func (p LogPriority) c() C.SDL_LogPriority { return C.SDL_LogPriority(p) } // LogSetAllPriority sets the priority of all log categories. // (https://wiki.libsdl.org/SDL_LogSetAllPriority) func LogSetAllPriority(p LogPriority) { C.SDL_LogSetAllPriority(p.c()) } // LogSetPriority sets the priority of a particular log category. // (https://wiki.libsdl.org/SDL_LogSetPriority) func LogSetPriority(category int, p LogPriority) { C.SDL_LogSetPriority(C.int(category), p.c()) } // LogGetPriority returns the priority of a particular log category. // (https://wiki.libsdl.org/SDL_LogGetPriority) func LogGetPriority(category int) LogPriority { return LogPriority(C.SDL_LogGetPriority(C.int(category))) } // LogResetPriorities resets all priorities to default. // (https://wiki.libsdl.org/SDL_LogResetPriorities) func LogResetPriorities() { C.SDL_LogResetPriorities() } // Log logs a message with LOG_CATEGORY_APPLICATION and LOG_PRIORITY_INFO. // (https://wiki.libsdl.org/SDL_Log) func Log(str string, args ...interface{}) { str = fmt.Sprintf(str, args...) cstr := C.CString(str) defer C.free(unsafe.Pointer(cstr)) C._SDL_Log(cstr) } // LogVerbose logs a message with LOG_PRIORITY_VERBOSE. // (https://wiki.libsdl.org/SDL_LogVerbose) func LogVerbose(category int, str string, args ...interface{}) { str = fmt.Sprintf(str, args...) cstr := C.CString(str) defer C.free(unsafe.Pointer(cstr)) C._SDL_LogVerbose(C.int(category), cstr) } // LogDebug logs a message with LOG_PRIORITY_DEBUG. // (https://wiki.libsdl.org/SDL_LogDebug) func LogDebug(category int, str string, args ...interface{}) { str = fmt.Sprintf(str, args...) cstr := C.CString(str) defer C.free(unsafe.Pointer(cstr)) C._SDL_LogDebug(C.int(category), cstr) } // LogInfo logs a message with LOG_PRIORITY_INFO. // (https://wiki.libsdl.org/SDL_LogInfo) func LogInfo(category int, str string, args ...interface{}) { str = fmt.Sprintf(str, args...) cstr := C.CString(str) defer C.free(unsafe.Pointer(cstr)) C._SDL_LogInfo(C.int(category), cstr) } // LogWarn logs a message with LOG_PRIORITY_WARN. // (https://wiki.libsdl.org/SDL_LogWarn) func LogWarn(category int, str string, args ...interface{}) { str = fmt.Sprintf(str, args...) cstr := C.CString(str) defer C.free(unsafe.Pointer(cstr)) C._SDL_LogWarn(C.int(category), cstr) } // LogError logs a message with LOG_PRIORITY_ERROR. // (https://wiki.libsdl.org/SDL_LogError) func LogError(category int, str string, args ...interface{}) { str = fmt.Sprintf(str, args...) cstr := C.CString(str) defer C.free(unsafe.Pointer(cstr)) C._SDL_LogError(C.int(category), cstr) } // LogCritical logs a message with LOG_PRIORITY_CRITICAL. // (https://wiki.libsdl.org/SDL_LogCritical) func LogCritical(category int, str string, args ...interface{}) { str = fmt.Sprintf(str, args...) cstr := C.CString(str) defer C.free(unsafe.Pointer(cstr)) C._SDL_LogCritical(C.int(category), cstr) } // LogMessage logs a message with the specified category and priority. // (https://wiki.libsdl.org/SDL_LogMessage) func LogMessage(category int, pri LogPriority, str string, args ...interface{}) { str = fmt.Sprintf(str, args...) cstr := C.CString(str) defer C.free(unsafe.Pointer(cstr)) C._SDL_LogMessage(C.int(category), C.SDL_LogPriority(pri), cstr) } // LogOutputFunction is the function to call instead of the default type LogOutputFunction func(data interface{}, category int, pri LogPriority, message string) type logOutputFunctionCtx struct { f LogOutputFunction d interface{} } // Yissakhar Z. Beck (DeedleFake)'s implementation // //export logOutputFunction func logOutputFunction(data unsafe.Pointer, category C.int, pri C.SDL_LogPriority, message *C.char) { ctx := (*logOutputFunctionCtx)(data) ctx.f(ctx.d, int(category), LogPriority(pri), C.GoString(message)) } var ( logOutputFunctionCache LogOutputFunction logOutputDataCache interface{} ) // LogGetOutputFunction returns the current log output function. // (https://wiki.libsdl.org/SDL_LogGetOutputFunction) func LogGetOutputFunction() (LogOutputFunction, interface{}) { return logOutputFunctionCache, logOutputDataCache } // LogSetOutputFunction replaces the default log output function with one of your own. // (https://wiki.libsdl.org/SDL_LogSetOutputFunction) func LogSetOutputFunction(f LogOutputFunction, data interface{}) { ctx := &logOutputFunctionCtx{ f: f, d: data, } C.LogSetOutputFunction(unsafe.Pointer(ctx)) logOutputFunctionCache = f logOutputDataCache = data } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/log.h ================================================ void LogSetOutputFunction(void *data); ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/mouse.go ================================================ package sdl /* #include "sdl_wrapper.h" #if defined(__WIN32) #include #else #include #endif #if !(SDL_VERSION_ATLEAST(2,0,4)) #if defined(WARN_OUTDATED) #pragma message("SDL_CaptureMouse is not supported before SDL 2.0.4") #endif static int SDL_CaptureMouse(SDL_bool enabled) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_MOUSEWHEEL_NORMAL is not supported before SDL 2.0.4") #endif #define SDL_MOUSEWHEEL_NORMAL (0) #if defined(WARN_OUTDATED) #pragma message("SDL_MOUSEWHEEL_FLIPPED is not supported before SDL 2.0.4") #endif #define SDL_MOUSEWHEEL_FLIPPED (0) #if defined(WARN_OUTDATED) #pragma message("SDL_WarpMouseGlobal is not supported before SDL 2.0.4") #endif static int SDL_WarpMouseGlobal(int x, int y) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_GetGlobalMouseState is not supported before SDL 2.0.4") #endif static Uint32 SDL_GetGlobalMouseState(int *x, int *y) { return 0; } #endif */ import "C" import "unsafe" // Cursor types for CreateSystemCursor() const ( SYSTEM_CURSOR_ARROW = C.SDL_SYSTEM_CURSOR_ARROW // arrow SYSTEM_CURSOR_IBEAM = C.SDL_SYSTEM_CURSOR_IBEAM // i-beam SYSTEM_CURSOR_WAIT = C.SDL_SYSTEM_CURSOR_WAIT // wait SYSTEM_CURSOR_CROSSHAIR = C.SDL_SYSTEM_CURSOR_CROSSHAIR // crosshair SYSTEM_CURSOR_WAITARROW = C.SDL_SYSTEM_CURSOR_WAITARROW // small wait cursor (or wait if not available) SYSTEM_CURSOR_SIZENWSE = C.SDL_SYSTEM_CURSOR_SIZENWSE // double arrow pointing northwest and southeast SYSTEM_CURSOR_SIZENESW = C.SDL_SYSTEM_CURSOR_SIZENESW // double arrow pointing northeast and southwest SYSTEM_CURSOR_SIZEWE = C.SDL_SYSTEM_CURSOR_SIZEWE // double arrow pointing west and east SYSTEM_CURSOR_SIZENS = C.SDL_SYSTEM_CURSOR_SIZENS // double arrow pointing north and south SYSTEM_CURSOR_SIZEALL = C.SDL_SYSTEM_CURSOR_SIZEALL // four pointed arrow pointing north, south, east, and west SYSTEM_CURSOR_NO = C.SDL_SYSTEM_CURSOR_NO // slashed circle or crossbones SYSTEM_CURSOR_HAND = C.SDL_SYSTEM_CURSOR_HAND // hand NUM_SYSTEM_CURSORS = C.SDL_NUM_SYSTEM_CURSORS // (only for bounding internal arrays) ) // Scroll direction types for the Scroll event const ( MOUSEWHEEL_NORMAL = C.SDL_MOUSEWHEEL_NORMAL // the scroll direction is normal MOUSEWHEEL_FLIPPED = C.SDL_MOUSEWHEEL_FLIPPED // the scroll direction is flipped / natural ) // Used as a mask when testing buttons in buttonstate. const ( BUTTON_LEFT = C.SDL_BUTTON_LEFT // left mouse button BUTTON_MIDDLE = C.SDL_BUTTON_MIDDLE // middle mouse button BUTTON_RIGHT = C.SDL_BUTTON_RIGHT // right mouse button BUTTON_X1 = C.SDL_BUTTON_X1 // x1 mouse button BUTTON_X2 = C.SDL_BUTTON_X2 // x2 mouse button ) // Cursor is a custom cursor created by CreateCursor() or CreateColorCursor(). type Cursor C.SDL_Cursor // SystemCursor is a system cursor created by CreateSystemCursor(). type SystemCursor C.SDL_SystemCursor func (c *Cursor) cptr() *C.SDL_Cursor { return (*C.SDL_Cursor)(unsafe.Pointer(c)) } func (c SystemCursor) c() C.SDL_SystemCursor { return C.SDL_SystemCursor(c) } // GetMouseFocus returns the window which currently has mouse focus. // (https://wiki.libsdl.org/SDL_GetMouseFocus) func GetMouseFocus() *Window { return (*Window)(unsafe.Pointer(C.SDL_GetMouseFocus())) } // GetGlobalMouseState returns the current state of the mouse. // (https://wiki.libsdl.org/SDL_GetGlobalMouseState) func GetGlobalMouseState() (x, y int32, state uint32) { var _x, _y C.int _state := uint32(C.SDL_GetGlobalMouseState(&_x, &_y)) return int32(_x), int32(_y), _state } // GetMouseState returns the current state of the mouse. // (https://wiki.libsdl.org/SDL_GetMouseState) func GetMouseState() (x, y int32, state uint32) { var _x, _y C.int _state := uint32(C.SDL_GetMouseState(&_x, &_y)) return int32(_x), int32(_y), _state } // GetRelativeMouseState returns the relative state of the mouse. // (https://wiki.libsdl.org/SDL_GetRelativeMouseState) func GetRelativeMouseState() (x, y int32, state uint32) { var _x, _y C.int _state := uint32(C.SDL_GetRelativeMouseState(&_x, &_y)) return int32(_x), int32(_y), _state } // WarpMouseInWindow moves the mouse to the given position within the window. // (https://wiki.libsdl.org/SDL_WarpMouseInWindow) func (window *Window) WarpMouseInWindow(x, y int32) { C.SDL_WarpMouseInWindow(window.cptr(), C.int(x), C.int(y)) } // SetRelativeMouseMode sets relative mouse mode. // (https://wiki.libsdl.org/SDL_SetRelativeMouseMode) func SetRelativeMouseMode(enabled bool) int { return int(C.SDL_SetRelativeMouseMode(C.SDL_bool(Btoi(enabled)))) } // GetRelativeMouseMode reports where relative mouse mode is enabled. // (https://wiki.libsdl.org/SDL_GetRelativeMouseMode) func GetRelativeMouseMode() bool { return C.SDL_GetRelativeMouseMode() > 0 } // CreateCursor creates a cursor using the specified bitmap data and mask (in MSB format). // (https://wiki.libsdl.org/SDL_CreateCursor) func CreateCursor(data, mask *uint8, w, h, hotX, hotY int32) *Cursor { _data := (*C.Uint8)(unsafe.Pointer(data)) _mask := (*C.Uint8)(unsafe.Pointer(mask)) return (*Cursor)(C.SDL_CreateCursor(_data, _mask, C.int(w), C.int(h), C.int(hotX), C.int(hotY))) } // CreateColorCursor creates a color cursor. // (https://wiki.libsdl.org/SDL_CreateColorCursor) func CreateColorCursor(surface *Surface, hotX, hotY int32) *Cursor { return (*Cursor)(C.SDL_CreateColorCursor(surface.cptr(), C.int(hotX), C.int(hotY))) } // CreateSystemCursor creates a system cursor. // (https://wiki.libsdl.org/SDL_CreateSystemCursor) func CreateSystemCursor(id SystemCursor) *Cursor { return (*Cursor)(C.SDL_CreateSystemCursor(id.c())) } // SetCursor sets the active cursor. // (https://wiki.libsdl.org/SDL_SetCursor) func SetCursor(cursor *Cursor) { C.SDL_SetCursor(cursor.cptr()) } // GetCursor returns the active cursor. // (https://wiki.libsdl.org/SDL_GetCursor) func GetCursor() *Cursor { return (*Cursor)(C.SDL_GetCursor()) } // GetDefaultCursor returns the default cursor. // (https://wiki.libsdl.org/SDL_GetDefaultCursor) func GetDefaultCursor() *Cursor { return (*Cursor)(C.SDL_GetDefaultCursor()) } // FreeCursor frees a cursor created with CreateCursor(), CreateColorCursor() or CreateSystemCursor(). // (https://wiki.libsdl.org/SDL_FreeCursor) func FreeCursor(cursor *Cursor) { C.SDL_FreeCursor(cursor.cptr()) } // ShowCursor toggles whether or not the cursor is shown. // (https://wiki.libsdl.org/SDL_ShowCursor) func ShowCursor(toggle int) (int, error) { i := int(C.SDL_ShowCursor(C.int(toggle))) return i, errorFromInt(i) } // CaptureMouse captures the mouse and tracks input outside an SDL window. // (https://wiki.libsdl.org/SDL_CaptureMouse) func CaptureMouse(toggle bool) error { var ierr C.int if toggle { ierr = C.SDL_CaptureMouse(C.SDL_TRUE) } else { ierr = C.SDL_CaptureMouse(C.SDL_FALSE) } if ierr != 0 { return GetError() } return nil } // Button is used as a mask when testing buttons in buttonstate. func Button(flag uint32) uint32 { return 1 << (flag - 1) } // ButtonLMask is used as a mask when testing buttons in buttonstate. func ButtonLMask() uint32 { return Button(BUTTON_LEFT) } // ButtonMMask is used as a mask when testing buttons in buttonstate. func ButtonMMask() uint32 { return Button(BUTTON_MIDDLE) } // ButtonRMask is used as a mask when testing buttons in buttonstate. func ButtonRMask() uint32 { return Button(BUTTON_RIGHT) } // ButtonX1Mask is used as a mask when testing buttons in buttonstate. func ButtonX1Mask() uint32 { return Button(BUTTON_X1) } // ButtonX2Mask is used as a mask when testing buttons in buttonstate. func ButtonX2Mask() uint32 { return Button(BUTTON_X2) } // WarpMouseGlobal moves the mouse to the given position in global screen space. // (https://wiki.libsdl.org/SDL_WarpMouseGlobal) func WarpMouseGlobal(x, y int32) error { i := int(C.SDL_WarpMouseGlobal(C.int(x), C.int(y))) return errorFromInt(i) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/mutex.go ================================================ package sdl // #include "sdl_wrapper.h" import "C" import "unsafe" // ThreadID is the thread identifier for a thread. type ThreadID uint64 // Mutex is the SDL mutex structure. type Mutex struct { Recursive int Owner ThreadID Sem *Sem } // Sem is the SDL semaphore structure. type Sem struct { Count uint32 WaitersCount uint32 CountLock *Mutex CountNonzero *Cond } // Cond is the SDL condition variable structure. type Cond struct { Lock *Mutex Waiting int Signals int WaitSem *Sem WaitDone *Sem } func (m *Mutex) cptr() *C.SDL_mutex { return (*C.SDL_mutex)(unsafe.Pointer(m)) } func (s *Sem) cptr() *C.SDL_sem { return (*C.SDL_sem)(unsafe.Pointer(s)) } func (c *Cond) cptr() *C.SDL_cond { return (*C.SDL_cond)(unsafe.Pointer(c)) } // CreateMutex creates a new mutex. // (https://wiki.libsdl.org/SDL_CreateMutex) func CreateMutex() (*Mutex, error) { mutex := C.SDL_CreateMutex() if mutex == nil { return nil, GetError() } return (*Mutex)(unsafe.Pointer(mutex)), nil } // Lock locks a mutex created with CreateMutex(). // (https://wiki.libsdl.org/SDL_LockMutex) func (mutex *Mutex) Lock() error { ret := int(C.SDL_LockMutex(mutex.cptr())) if ret != 0 { return GetError() } return nil } // TryLock tries to lock a mutex without blocking. // (https://wiki.libsdl.org/SDL_TryLockMutex) func (mutex *Mutex) TryLock() error { ret := int(C.SDL_TryLockMutex(mutex.cptr())) if ret != 0 { return GetError() } return nil } // Unlock unlocks a mutex created with CreateMutex(). // (https://wiki.libsdl.org/SDL_UnlockMutex) func (mutex *Mutex) Unlock() error { ret := int(C.SDL_UnlockMutex(mutex.cptr())) if ret != 0 { return GetError() } return nil } // Destroy destroys a mutex created with CreateMutex(). // (https://wiki.libsdl.org/SDL_DestroyMutex) func (mutex *Mutex) Destroy() { C.SDL_DestroyMutex(mutex.cptr()) } // CreateSemaphore creates a semaphore. // (https://wiki.libsdl.org/SDL_CreateSemaphore) func CreateSemaphore(initialValue uint32) (*Sem, error) { sem := C.SDL_CreateSemaphore(C.Uint32(initialValue)) if sem == nil { return nil, GetError() } return (*Sem)(unsafe.Pointer(sem)), nil } // Destroy destroys a semaphore. // (https://wiki.libsdl.org/SDL_DestroySemaphore) func (sem *Sem) Destroy() { C.SDL_DestroySemaphore(sem.cptr()) } // Wait waits until a semaphore has a positive value and then decrements it. // (https://wiki.libsdl.org/SDL_SemWait) func (sem *Sem) Wait() error { ret := int(C.SDL_SemWait(sem.cptr())) if ret != 0 { return GetError() } return nil } // TryWait sees if a semaphore has a positive value and decrement it if it does. // (https://wiki.libsdl.org/SDL_SemTryWait) func (sem *Sem) TryWait() error { ret := int(C.SDL_SemTryWait(sem.cptr())) if ret != 0 { return GetError() } return nil } // WaitTimeout waits until a semaphore has a positive value and then decrements it. // (https://wiki.libsdl.org/SDL_SemWaitTimeout) func (sem *Sem) WaitTimeout(ms uint32) error { ret := int(C.SDL_SemWaitTimeout(sem.cptr(), C.Uint32(ms))) if ret != 0 { return GetError() } return nil } // Post atomically increments a semaphore's value and wake waiting threads. // (https://wiki.libsdl.org/SDL_SemPost) func (sem *Sem) Post() error { ret := int(C.SDL_SemPost(sem.cptr())) if ret != 0 { return GetError() } return nil } // Value returns the current value of a semaphore. // (https://wiki.libsdl.org/SDL_SemValue) func (sem *Sem) Value() uint32 { return uint32(C.SDL_SemValue(sem.cptr())) } // CreateCond (https://wiki.libsdl.org/SDL_CreateCond) func CreateCond() *Cond { return (*Cond)(unsafe.Pointer(C.SDL_CreateCond())) } // Destroy creates a condition variable. // (https://wiki.libsdl.org/SDL_DestroyCond) func (cond *Cond) Destroy() { C.SDL_DestroyCond(cond.cptr()) } // Signal restarts one of the threads that are waiting on the condition variable. // (https://wiki.libsdl.org/SDL_CondSignal) func (cond *Cond) Signal() error { ret := int(C.SDL_CondSignal(cond.cptr())) if ret != 0 { return GetError() } return nil } // Broadcast restarts all threads that are waiting on the condition variable. // (https://wiki.libsdl.org/SDL_CondBroadcast) func (cond *Cond) Broadcast() error { ret := int(C.SDL_CondBroadcast(cond.cptr())) if ret != 0 { return GetError() } return nil } // Wait waits until a condition variable is signaled. // (https://wiki.libsdl.org/SDL_CondWait) func (cond *Cond) Wait(mutex *Mutex) error { ret := int(C.SDL_CondWait(cond.cptr(), mutex.cptr())) if ret != 0 { return GetError() } return nil } // WaitTimeout waits until a condition variable is signaled or a specified amount of time has passed. // (https://wiki.libsdl.org/SDL_CondWaitTimeout) func (cond *Cond) WaitTimeout(mutex *Mutex, ms uint32) error { ret := int(C.SDL_CondWaitTimeout(cond.cptr(), mutex.cptr(), C.Uint32(ms))) if ret != 0 { return GetError() } return nil } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/pixels.go ================================================ package sdl // #include "sdl_wrapper.h" // // #if !(SDL_VERSION_ATLEAST(2,0,5)) // // enum // { // #if SDL_BYTEORDER == SDL_BIG_ENDIAN // SDL_PIXELFORMAT_RGBA32 = SDL_PIXELFORMAT_RGBA8888, // SDL_PIXELFORMAT_ARGB32 = SDL_PIXELFORMAT_ARGB8888, // SDL_PIXELFORMAT_BGRA32 = SDL_PIXELFORMAT_BGRA8888, // SDL_PIXELFORMAT_ABGR32 = SDL_PIXELFORMAT_ABGR8888 // #else // SDL_PIXELFORMAT_RGBA32 = SDL_PIXELFORMAT_ABGR8888, // SDL_PIXELFORMAT_ARGB32 = SDL_PIXELFORMAT_BGRA8888, // SDL_PIXELFORMAT_BGRA32 = SDL_PIXELFORMAT_ARGB8888, // SDL_PIXELFORMAT_ABGR32 = SDL_PIXELFORMAT_RGBA8888 // #endif // }; // // #endif // // int bytesPerPixel(Uint32 format) { // return SDL_BYTESPERPIXEL(format); // } // // int bitsPerPixel(Uint32 format) { // return SDL_BITSPERPIXEL(format); // } import "C" import ( "image/color" "unsafe" ) // PixelFormat contains pixel format information. // (https://wiki.libsdl.org/SDL_PixelFormat) type PixelFormat struct { Format uint32 // one of the PIXELFORMAT values (https://wiki.libsdl.org/SDL_PixelFormatEnum) Palette *Palette // palette structure associated with this pixel format, or nil if the format doesn't have a palette (https://wiki.libsdl.org/SDL_Palette) BitsPerPixel uint8 // the number of significant bits in a pixel value, eg: 8, 15, 16, 24, 32 BytesPerPixel uint8 // the number of bytes required to hold a pixel value, eg: 1, 2, 3, 4 _ [2]uint8 // padding Rmask uint32 // a mask representing the location of the red component of the pixel Gmask uint32 // a mask representing the location of the green component of the pixel Bmask uint32 // a mask representing the location of the blue component of the pixel Amask uint32 // a mask representing the location of the alpha component of the pixel or 0 if the pixel format doesn't have any alpha information rLoss uint8 // (internal use) gLoss uint8 // (internal use) bLoss uint8 // (internal use) aLoss uint8 // (internal use) rShift uint8 // (internal use) gShift uint8 // (internal use) bShift uint8 // (internal use) aShift uint8 // (internal use) refCount int32 // (internal use) next *PixelFormat // (internal use) } type cPixelFormat C.SDL_PixelFormat // Palette contains palette information. // (https://wiki.libsdl.org/SDL_Palette) type Palette struct { Ncolors int32 // the number of colors in the palette Colors *Color // an array of Color structures representing the palette (https://wiki.libsdl.org/SDL_Color) version uint32 // incrementally tracks changes to the palette (internal use) refCount int32 // reference count (internal use) } type cPalette C.SDL_Palette // Color represents a color. This implements image/color.Color interface. // (https://wiki.libsdl.org/SDL_Color) type Color color.NRGBA // Uint32 return uint32 representation of RGBA color. func (c Color) Uint32() uint32 { var v uint32 v |= uint32(c.R) << 24 v |= uint32(c.G) << 16 v |= uint32(c.B) << 8 v |= uint32(c.A) return v } // Pixel types. const ( PIXELTYPE_UNKNOWN = C.SDL_PIXELTYPE_UNKNOWN PIXELTYPE_INDEX1 = C.SDL_PIXELTYPE_INDEX1 PIXELTYPE_INDEX4 = C.SDL_PIXELTYPE_INDEX4 PIXELTYPE_INDEX8 = C.SDL_PIXELTYPE_INDEX8 PIXELTYPE_PACKED8 = C.SDL_PIXELTYPE_PACKED8 PIXELTYPE_PACKED16 = C.SDL_PIXELTYPE_PACKED16 PIXELTYPE_PACKED32 = C.SDL_PIXELTYPE_PACKED32 PIXELTYPE_ARRAYU8 = C.SDL_PIXELTYPE_ARRAYU8 PIXELTYPE_ARRAYU16 = C.SDL_PIXELTYPE_ARRAYU16 PIXELTYPE_ARRAYU32 = C.SDL_PIXELTYPE_ARRAYU32 PIXELTYPE_ARRAYF16 = C.SDL_PIXELTYPE_ARRAYF16 PIXELTYPE_ARRAYF32 = C.SDL_PIXELTYPE_ARRAYF32 ) // Bitmap pixel order high bit -> low bit. const ( BITMAPORDER_NONE = C.SDL_BITMAPORDER_NONE BITMAPORDER_4321 = C.SDL_BITMAPORDER_4321 BITMAPORDER_1234 = C.SDL_BITMAPORDER_1234 ) // Packed component order high bit -> low bit. const ( PACKEDORDER_NONE = C.SDL_PACKEDORDER_NONE PACKEDORDER_XRGB = C.SDL_PACKEDORDER_XRGB PACKEDORDER_RGBX = C.SDL_PACKEDORDER_RGBX PACKEDORDER_ARGB = C.SDL_PACKEDORDER_ARGB PACKEDORDER_RGBA = C.SDL_PACKEDORDER_RGBA PACKEDORDER_XBGR = C.SDL_PACKEDORDER_XBGR PACKEDORDER_BGRX = C.SDL_PACKEDORDER_BGRX PACKEDORDER_ABGR = C.SDL_PACKEDORDER_ABGR PACKEDORDER_BGRA = C.SDL_PACKEDORDER_BGRA ) // Array component order low byte -> high byte. const ( ARRAYORDER_NONE = C.SDL_ARRAYORDER_NONE ARRAYORDER_RGB = C.SDL_ARRAYORDER_RGB ARRAYORDER_RGBA = C.SDL_ARRAYORDER_RGBA ARRAYORDER_ARGB = C.SDL_ARRAYORDER_ARGB ARRAYORDER_BGR = C.SDL_ARRAYORDER_BGR ARRAYORDER_BGRA = C.SDL_ARRAYORDER_BGRA ARRAYORDER_ABGR = C.SDL_ARRAYORDER_ABGR ) // Packed component layout. const ( PACKEDLAYOUT_NONE = C.SDL_PACKEDLAYOUT_NONE PACKEDLAYOUT_332 = C.SDL_PACKEDLAYOUT_332 PACKEDLAYOUT_4444 = C.SDL_PACKEDLAYOUT_4444 PACKEDLAYOUT_1555 = C.SDL_PACKEDLAYOUT_1555 PACKEDLAYOUT_5551 = C.SDL_PACKEDLAYOUT_5551 PACKEDLAYOUT_565 = C.SDL_PACKEDLAYOUT_565 PACKEDLAYOUT_8888 = C.SDL_PACKEDLAYOUT_8888 PACKEDLAYOUT_2101010 = C.SDL_PACKEDLAYOUT_2101010 PACKEDLAYOUT_1010102 = C.SDL_PACKEDLAYOUT_1010102 ) // Pixel format values. const ( PIXELFORMAT_UNKNOWN = C.SDL_PIXELFORMAT_UNKNOWN PIXELFORMAT_INDEX1LSB = C.SDL_PIXELFORMAT_INDEX1LSB PIXELFORMAT_INDEX1MSB = C.SDL_PIXELFORMAT_INDEX1MSB PIXELFORMAT_INDEX4LSB = C.SDL_PIXELFORMAT_INDEX4LSB PIXELFORMAT_INDEX4MSB = C.SDL_PIXELFORMAT_INDEX4MSB PIXELFORMAT_INDEX8 = C.SDL_PIXELFORMAT_INDEX8 PIXELFORMAT_RGB332 = C.SDL_PIXELFORMAT_RGB332 PIXELFORMAT_RGB444 = C.SDL_PIXELFORMAT_RGB444 PIXELFORMAT_RGB555 = C.SDL_PIXELFORMAT_RGB555 PIXELFORMAT_BGR555 = C.SDL_PIXELFORMAT_BGR555 PIXELFORMAT_ARGB4444 = C.SDL_PIXELFORMAT_ARGB4444 PIXELFORMAT_RGBA4444 = C.SDL_PIXELFORMAT_RGBA4444 PIXELFORMAT_ABGR4444 = C.SDL_PIXELFORMAT_ABGR4444 PIXELFORMAT_BGRA4444 = C.SDL_PIXELFORMAT_BGRA4444 PIXELFORMAT_ARGB1555 = C.SDL_PIXELFORMAT_ARGB1555 PIXELFORMAT_RGBA5551 = C.SDL_PIXELFORMAT_RGBA5551 PIXELFORMAT_ABGR1555 = C.SDL_PIXELFORMAT_ABGR1555 PIXELFORMAT_BGRA5551 = C.SDL_PIXELFORMAT_BGRA5551 PIXELFORMAT_RGB565 = C.SDL_PIXELFORMAT_RGB565 PIXELFORMAT_BGR565 = C.SDL_PIXELFORMAT_BGR565 PIXELFORMAT_RGB24 = C.SDL_PIXELFORMAT_RGB24 PIXELFORMAT_BGR24 = C.SDL_PIXELFORMAT_BGR24 PIXELFORMAT_RGB888 = C.SDL_PIXELFORMAT_RGB888 PIXELFORMAT_RGBX8888 = C.SDL_PIXELFORMAT_RGBX8888 PIXELFORMAT_BGR888 = C.SDL_PIXELFORMAT_BGR888 PIXELFORMAT_BGRX8888 = C.SDL_PIXELFORMAT_BGRX8888 PIXELFORMAT_ARGB8888 = C.SDL_PIXELFORMAT_ARGB8888 PIXELFORMAT_RGBA8888 = C.SDL_PIXELFORMAT_RGBA8888 PIXELFORMAT_ABGR8888 = C.SDL_PIXELFORMAT_ABGR8888 PIXELFORMAT_BGRA8888 = C.SDL_PIXELFORMAT_BGRA8888 PIXELFORMAT_ARGB2101010 = C.SDL_PIXELFORMAT_ARGB2101010 PIXELFORMAT_YV12 = C.SDL_PIXELFORMAT_YV12 PIXELFORMAT_IYUV = C.SDL_PIXELFORMAT_IYUV PIXELFORMAT_YUY2 = C.SDL_PIXELFORMAT_YUY2 PIXELFORMAT_UYVY = C.SDL_PIXELFORMAT_UYVY PIXELFORMAT_YVYU = C.SDL_PIXELFORMAT_YVYU ) // Pixel format variables. var ( PIXELFORMAT_RGBA32 = C.SDL_PIXELFORMAT_RGBA32 PIXELFORMAT_ARGB32 = C.SDL_PIXELFORMAT_ARGB32 PIXELFORMAT_BGRA32 = C.SDL_PIXELFORMAT_BGRA32 PIXELFORMAT_ABGR32 = C.SDL_PIXELFORMAT_ABGR32 ) // These define alpha as the opacity of a surface. const ( ALPHA_OPAQUE = C.SDL_ALPHA_OPAQUE ALPHA_TRANSPARENT = C.SDL_ALPHA_TRANSPARENT ) func (format *PixelFormat) cptr() *C.SDL_PixelFormat { return (*C.SDL_PixelFormat)(unsafe.Pointer(format)) } func (palette *Palette) cptr() *C.SDL_Palette { return (*C.SDL_Palette)(unsafe.Pointer(palette)) } /* * the following code is modified version of the code from bitbucket.org/dooots/go-sdl2 */ // GetPixelFormatName returns the human readable name of a pixel format. // (https://wiki.libsdl.org/SDL_GetPixelFormatName) func GetPixelFormatName(format uint) string { return C.GoString(C.SDL_GetPixelFormatName(C.Uint32(format))) } // PixelFormatEnumToMasks converts one of the enumerated pixel formats to a bpp value and RGBA masks. // (https://wiki.libsdl.org/SDL_PixelFormatEnumToMasks) func PixelFormatEnumToMasks(format uint) (bpp int, rmask, gmask, bmask, amask uint32, err error) { result := C.SDL_PixelFormatEnumToMasks(C.Uint32(format), (*C.int)(unsafe.Pointer(&bpp)), (*C.Uint32)(&rmask), (*C.Uint32)(&gmask), (*C.Uint32)(&bmask), (*C.Uint32)(&amask)) if result == C.SDL_FALSE { err = GetError() } return } // MasksToPixelFormatEnum converts a bpp value and RGBA masks to an enumerated pixel format. // (https://wiki.libsdl.org/SDL_MasksToPixelFormatEnum) func MasksToPixelFormatEnum(bpp int, rmask, gmask, bmask, amask uint32) uint { return uint(C.SDL_MasksToPixelFormatEnum(C.int(bpp), C.Uint32(rmask), C.Uint32(gmask), C.Uint32(bmask), C.Uint32(amask))) } // AllocFormat creates a PixelFormat structure corresponding to a pixel format. // (https://wiki.libsdl.org/SDL_AllocFormat) func AllocFormat(format uint) (*PixelFormat, error) { r := (*PixelFormat)(unsafe.Pointer(C.SDL_AllocFormat(C.Uint32(format)))) if r == nil { return nil, GetError() } return r, nil } // Free frees the PixelFormat structure allocated by AllocFormat(). // (https://wiki.libsdl.org/SDL_FreeFormat) func (format *PixelFormat) Free() { C.SDL_FreeFormat((*C.SDL_PixelFormat)(unsafe.Pointer(format))) } // AllocPalette creates a palette structure with the specified number of color entries. // (https://wiki.libsdl.org/SDL_AllocPalette) func AllocPalette(ncolors int) (*Palette, error) { r := (*Palette)(unsafe.Pointer(C.SDL_AllocPalette(C.int(ncolors)))) if r == nil { return nil, GetError() } return r, nil } // SetPalette sets the palette for the pixel format structure. // (https://wiki.libsdl.org/SDL_SetPixelFormatPalette) func (format *PixelFormat) SetPalette(palette *Palette) error { r := C.SDL_SetPixelFormatPalette((*C.SDL_PixelFormat)(unsafe.Pointer(format)), (*C.SDL_Palette)(unsafe.Pointer(palette))) if r != 0 { return GetError() } return nil } // SetColors sets a range of colors in the palette. // (https://wiki.libsdl.org/SDL_SetPaletteColors) func (palette *Palette) SetColors(colors []Color) error { if colors == nil { return nil } var ptr *C.SDL_Color if len(colors) > 0 { ptr = (*C.SDL_Color)(unsafe.Pointer(&colors[0])) } r := C.SDL_SetPaletteColors((*C.SDL_Palette)(unsafe.Pointer(palette)), ptr, 0, C.int(len(colors))) if r != 0 { return GetError() } return nil } // Free frees the palette created with AllocPalette(). // (https://wiki.libsdl.org/SDL_FreePalette) func (palette *Palette) Free() { C.SDL_FreePalette((*C.SDL_Palette)(unsafe.Pointer(palette))) } // MapRGB maps an RGB triple to an opaque pixel value for a given pixel format. // (https://wiki.libsdl.org/SDL_MapRGB) func MapRGB(format *PixelFormat, r, g, b uint8) uint32 { return uint32(C.SDL_MapRGB((*C.SDL_PixelFormat)(unsafe.Pointer(format)), C.Uint8(r), C.Uint8(g), C.Uint8(b))) } // MapRGBA maps an RGBA quadruple to a pixel value for a given pixel format. // (https://wiki.libsdl.org/SDL_MapRGBA) func MapRGBA(format *PixelFormat, r, g, b, a uint8) uint32 { return uint32(C.SDL_MapRGBA((*C.SDL_PixelFormat)(unsafe.Pointer(format)), C.Uint8(r), C.Uint8(g), C.Uint8(b), C.Uint8(a))) } // GetRGB returns RGB values from a pixel in the specified format. // (https://wiki.libsdl.org/SDL_GetRGB) func GetRGB(pixel uint32, format *PixelFormat) (r, g, b uint8) { C.SDL_GetRGB(C.Uint32(pixel), (*C.SDL_PixelFormat)(unsafe.Pointer(format)), (*C.Uint8)(&r), (*C.Uint8)(&g), (*C.Uint8)(&b)) return } // GetRGBA returns RGBA values from a pixel in the specified format. // (https://wiki.libsdl.org/SDL_GetRGBA) func GetRGBA(pixel uint32, format *PixelFormat) (r, g, b, a uint8) { C.SDL_GetRGBA(C.Uint32(pixel), (*C.SDL_PixelFormat)(unsafe.Pointer(format)), (*C.Uint8)(&r), (*C.Uint8)(&g), (*C.Uint8)(&b), (*C.Uint8)(&a)) return } // CalculateGammaRamp calculates a 256 entry gamma ramp for a gamma value. // (https://wiki.libsdl.org/SDL_CalculateGammaRamp) func CalculateGammaRamp(gamma float32, ramp *[256]uint16) { C.SDL_CalculateGammaRamp(C.float(gamma), (*C.Uint16)(unsafe.Pointer(&ramp[0]))) } // BytesPerPixel returns the number of bytes per pixel for the given format func BytesPerPixel(format uint32) int { return int(C.bytesPerPixel(C.Uint32(format))) } // BitsPerPixel returns the number of bits per pixel for the given format func BitsPerPixel(format uint32) int { return int(C.bitsPerPixel(C.Uint32(format))) } var ( RGB444Model color.Model = color.ModelFunc(rgb444Model) RGB332Model color.Model = color.ModelFunc(rgb332Model) RGB565Model color.Model = color.ModelFunc(rgb565Model) RGB555Model color.Model = color.ModelFunc(rgb555Model) BGR565Model color.Model = color.ModelFunc(bgr565Model) BGR555Model color.Model = color.ModelFunc(bgr555Model) ARGB4444Model color.Model = color.ModelFunc(argb4444Model) ABGR4444Model color.Model = color.ModelFunc(abgr4444Model) RGBA4444Model color.Model = color.ModelFunc(rgba4444Model) BGRA4444Model color.Model = color.ModelFunc(bgra4444Model) ARGB1555Model color.Model = color.ModelFunc(argb1555Model) RGBA5551Model color.Model = color.ModelFunc(rgba5551Model) ABGR1555Model color.Model = color.ModelFunc(abgr1555Model) BGRA5551Model color.Model = color.ModelFunc(bgra5551Model) RGBA8888Model color.Model = color.ModelFunc(rgba8888Model) BGRA8888Model color.Model = color.ModelFunc(bgra8888Model) ) type RGB444 struct { R, G, B byte } func (c RGB444) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale4to8bit(c.R), G: upscale4to8bit(c.G), B: upscale4to8bit(c.B), A: 0xFF, } return nrgba.RGBA() } func rgb444Model(c color.Color) color.Color { if _, ok := c.(RGB444); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return RGB444{ R: downscale8to4bit(nrgba.R), G: downscale8to4bit(nrgba.G), B: downscale8to4bit(nrgba.B), } } type RGB332 struct { R, G, B byte } func (c RGB332) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale3to8bit(c.R), G: upscale3to8bit(c.G), B: upscale2to8bit(c.B), A: 0xFF, } return nrgba.RGBA() } func rgb332Model(c color.Color) color.Color { if _, ok := c.(RGB332); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return RGB332{ R: downscale8to3bit(nrgba.R), G: downscale8to3bit(nrgba.G), B: downscale8to2bit(nrgba.B), } } type RGB565 struct { R, G, B byte } func (c RGB565) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale5to8bit(c.R), G: upscale6to8bit(c.G), B: upscale5to8bit(c.B), A: 0xFF, } return nrgba.RGBA() } func rgb565Model(c color.Color) color.Color { if _, ok := c.(RGB565); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return RGB565{ R: downscale8to5bit(nrgba.R), G: downscale8to6bit(nrgba.G), B: downscale8to5bit(nrgba.B), } } type RGB555 struct { R, G, B byte } func (c RGB555) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale5to8bit(c.R), G: upscale5to8bit(c.G), B: upscale5to8bit(c.B), A: 0xFF, } return nrgba.RGBA() } func rgb555Model(c color.Color) color.Color { if _, ok := c.(RGB555); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return RGB555{ R: downscale8to5bit(nrgba.R), G: downscale8to5bit(nrgba.G), B: downscale8to5bit(nrgba.B), } } type BGR565 struct { B, G, R byte } func (c BGR565) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale5to8bit(c.R), G: upscale6to8bit(c.G), B: upscale5to8bit(c.B), A: 0xFF, } return nrgba.RGBA() } func bgr565Model(c color.Color) color.Color { if _, ok := c.(BGR565); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return BGR565{ B: downscale8to5bit(nrgba.B), G: downscale8to6bit(nrgba.G), R: downscale8to5bit(nrgba.R), } } type BGR555 struct { B, G, R byte } func (c BGR555) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale5to8bit(c.R), G: upscale5to8bit(c.G), B: upscale5to8bit(c.B), A: 0xFF, } return nrgba.RGBA() } func bgr555Model(c color.Color) color.Color { if _, ok := c.(BGR555); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return BGR555{ B: downscale8to5bit(nrgba.B), G: downscale8to5bit(nrgba.G), R: downscale8to5bit(nrgba.R), } } type RGB888 struct { R, G, B byte } func (c RGB888) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: c.R, G: c.G, B: c.B, A: 0xFF, } return nrgba.RGBA() } func rgb888Model(c color.Color) color.Color { if _, ok := c.(RGB888); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return RGB888{ R: nrgba.R, G: nrgba.G, B: nrgba.B, } } type BGR888 struct { B, G, R byte } func (c BGR888) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: c.R, G: c.G, B: c.B, A: 0xFF, } return nrgba.RGBA() } func bgr888Model(c color.Color) color.Color { if _, ok := c.(BGR888); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return BGR888{ B: nrgba.B, G: nrgba.G, R: nrgba.R, } } type ARGB4444 struct { A, R, G, B byte } func (c ARGB4444) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale4to8bit(c.R), G: upscale4to8bit(c.G), B: upscale4to8bit(c.B), A: upscale4to8bit(c.A), } return nrgba.RGBA() } func argb4444Model(c color.Color) color.Color { if _, ok := c.(ARGB4444); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return ARGB4444{ A: downscale8to4bit(nrgba.A), R: downscale8to4bit(nrgba.R), G: downscale8to4bit(nrgba.G), B: downscale8to4bit(nrgba.B), } } type ABGR4444 struct { A, B, G, R byte } func (c ABGR4444) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale4to8bit(c.R), G: upscale4to8bit(c.G), B: upscale4to8bit(c.B), A: upscale4to8bit(c.A), } return nrgba.RGBA() } func abgr4444Model(c color.Color) color.Color { if _, ok := c.(ABGR4444); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return ABGR4444{ A: downscale8to4bit(nrgba.A), B: downscale8to4bit(nrgba.B), G: downscale8to4bit(nrgba.G), R: downscale8to4bit(nrgba.R), } } type RGBA4444 struct { R, G, B, A byte } func (c RGBA4444) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale4to8bit(c.R), G: upscale4to8bit(c.G), B: upscale4to8bit(c.B), A: upscale4to8bit(c.A), } return nrgba.RGBA() } func rgba4444Model(c color.Color) color.Color { if _, ok := c.(RGBA4444); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return RGBA4444{ R: downscale8to4bit(nrgba.R), G: downscale8to4bit(nrgba.G), B: downscale8to4bit(nrgba.B), A: downscale8to4bit(nrgba.A), } } type BGRA4444 struct { B, G, R, A byte } func (c BGRA4444) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale4to8bit(c.R), G: upscale4to8bit(c.G), B: upscale4to8bit(c.B), A: upscale4to8bit(c.A), } return nrgba.RGBA() } func bgra4444Model(c color.Color) color.Color { if _, ok := c.(BGRA4444); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return BGRA4444{ B: downscale8to4bit(nrgba.B), G: downscale8to4bit(nrgba.G), R: downscale8to4bit(nrgba.R), A: downscale8to4bit(nrgba.A), } } type ARGB1555 struct { A, R, G, B byte } func (c ARGB1555) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale5to8bit(c.R), G: upscale5to8bit(c.G), B: upscale5to8bit(c.B), A: upscale1to8bit(c.A), } return nrgba.RGBA() } func argb1555Model(c color.Color) color.Color { if _, ok := c.(ARGB1555); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return ARGB1555{ A: downscale8to1bit(nrgba.A), R: downscale8to5bit(nrgba.R), G: downscale8to5bit(nrgba.G), B: downscale8to5bit(nrgba.B), } } type RGBA5551 struct { R, G, B, A byte } func (c RGBA5551) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale5to8bit(c.R), G: upscale5to8bit(c.G), B: upscale5to8bit(c.B), A: upscale1to8bit(c.A), } return nrgba.RGBA() } func rgba5551Model(c color.Color) color.Color { if _, ok := c.(RGBA5551); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return RGBA5551{ R: downscale8to5bit(nrgba.R), G: downscale8to5bit(nrgba.G), B: downscale8to5bit(nrgba.B), A: downscale8to1bit(nrgba.A), } } type ABGR1555 struct { A, R, G, B byte } func (c ABGR1555) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale5to8bit(c.R), G: upscale5to8bit(c.G), B: upscale5to8bit(c.B), A: upscale1to8bit(c.A), } return nrgba.RGBA() } func abgr1555Model(c color.Color) color.Color { if _, ok := c.(ABGR1555); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return ABGR1555{ A: downscale8to1bit(nrgba.A), R: downscale8to5bit(nrgba.R), G: downscale8to5bit(nrgba.G), B: downscale8to5bit(nrgba.B), } } type BGRA5551 struct { B, G, R, A byte } func (c BGRA5551) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale5to8bit(c.R), G: upscale5to8bit(c.G), B: upscale5to8bit(c.B), A: upscale1to8bit(c.A), } return nrgba.RGBA() } func bgra5551Model(c color.Color) color.Color { if _, ok := c.(BGRA5551); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return BGRA5551{ B: downscale8to5bit(nrgba.B), G: downscale8to5bit(nrgba.G), R: downscale8to5bit(nrgba.R), A: downscale8to1bit(nrgba.A), } } type RGBA8888 struct { R, G, B, A byte } func (c RGBA8888) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: c.R, G: c.G, B: c.B, A: c.A, } return nrgba.RGBA() } func rgba8888Model(c color.Color) color.Color { if _, ok := c.(RGBA8888); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return RGBA8888{ R: nrgba.R, G: nrgba.G, B: nrgba.B, A: nrgba.A, } } type BGRA8888 struct { B, G, R, A byte } func (c BGRA8888) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: c.R, G: c.G, B: c.B, A: c.A, } return nrgba.RGBA() } func bgra8888Model(c color.Color) color.Color { if _, ok := c.(BGRA8888); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return BGRA8888{ B: nrgba.B, G: nrgba.G, R: nrgba.R, A: nrgba.A, } } type ARGB8888 struct { A, R, G, B byte } func (c ARGB8888) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: c.R, G: c.G, B: c.B, A: c.A, } return nrgba.RGBA() } func argb8888Model(c color.Color) color.Color { if _, ok := c.(ARGB8888); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return ARGB8888{ A: nrgba.A, R: nrgba.R, G: nrgba.G, B: nrgba.B, } } type ABGR8888 struct { A, B, G, R byte } func (c ABGR8888) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: c.R, G: c.G, B: c.B, A: c.A, } return nrgba.RGBA() } func abgr8888Model(c color.Color) color.Color { if _, ok := c.(ABGR8888); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return ABGR8888{ A: nrgba.A, B: nrgba.B, G: nrgba.G, R: nrgba.R, } } func downscale8to1bit(alpha byte) byte { if alpha == 0 { return 0 } return 1 } func downscale8to2bit(in byte) byte { return in >> 6 } func downscale8to3bit(in byte) byte { return in >> 5 } func downscale8to4bit(in byte) byte { return in >> 4 } func downscale8to5bit(in byte) byte { return in >> 3 } func downscale8to6bit(in byte) byte { return in >> 2 } func upscale1to8bit(alphaBit byte) byte { if alphaBit == 0 { return 0 } return 0xFF } func upscale2to8bit(in byte) byte { return in<<6 | in<<4 | in<<2 | in } func upscale3to8bit(in byte) byte { return in<<5 | in<<2 | (in>>1)&0b11 } func upscale4to8bit(in byte) byte { return in<<4 | in } func upscale5to8bit(in byte) byte { return in<<3 | (in>>2)&0b111 } func upscale6to8bit(in byte) byte { return in<<2 | (in>>4)&0b11 } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/power.go ================================================ package sdl // #include "sdl_wrapper.h" import "C" // An enumeration of the basic state of the system's power supply. // (https://wiki.libsdl.org/SDL_PowerState) const ( POWERSTATE_UNKNOWN = C.SDL_POWERSTATE_UNKNOWN // cannot determine power status POWERSTATE_ON_BATTERY = C.SDL_POWERSTATE_ON_BATTERY // not plugged in, running on the battery POWERSTATE_NO_BATTERY = C.SDL_POWERSTATE_NO_BATTERY // plugged in, no battery available POWERSTATE_CHARGING = C.SDL_POWERSTATE_CHARGING // plugged in, charging battery POWERSTATE_CHARGED = C.SDL_POWERSTATE_CHARGED // plugged in, battery charged ) // PowerState is the basic state for the system's power supply. // (https://wiki.libsdl.org/SDL_PowerState) type PowerState C.SDL_PowerState // GetPowerInfo returns the current power supply details. // (https://wiki.libsdl.org/SDL_GetPowerInfo) func GetPowerInfo() (int, int, int) { _secs := C.int(0) _percent := C.int(0) _state := C.SDL_GetPowerInfo(&_secs, &_percent) return (int)(_state), (int)(_secs), (int)(_percent) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/rect.go ================================================ package sdl // #include "sdl_wrapper.h" import "C" import ( "math" "unsafe" ) // Point defines a two dimensional point. // (https://wiki.libsdl.org/SDL_Point) type Point struct { X int32 // the x coordinate of the point Y int32 // the y coordinate of the point } // Rect contains the definition of a rectangle, with the origin at the upper left. // (https://wiki.libsdl.org/SDL_Rect) type Rect struct { X int32 // the x location of the rectangle's upper left corner Y int32 // the y location of the rectangle's upper left corner W int32 // the width of the rectangle H int32 // the height of the rectangle } // FPoint defines a two dimensional point. // TODO: (https://wiki.libsdl.org/SDL_FPoint) type FPoint struct { X float32 // the x coordinate of the point Y float32 // the y coordinate of the point } // FRect contains the definition of a rectangle, with the origin at the upper left. // TODO: (https://wiki.libsdl.org/SDL_FRect) type FRect struct { X float32 // the x location of the rectangle's upper left corner Y float32 // the y location of the rectangle's upper left corner W float32 // the width of the rectangle H float32 // the height of the rectangle } func (p *Point) cptr() *C.SDL_Point { return (*C.SDL_Point)(unsafe.Pointer(p)) } func (a *Rect) cptr() *C.SDL_Rect { return (*C.SDL_Rect)(unsafe.Pointer(a)) } func (p *FPoint) cptr() *C.SDL_FPoint { return (*C.SDL_FPoint)(unsafe.Pointer(p)) } func (a *FRect) cptr() *C.SDL_FRect { return (*C.SDL_FRect)(unsafe.Pointer(a)) } // InRect reports whether the point resides inside a rectangle. // (https://wiki.libsdl.org/SDL_PointInRect) func (p *Point) InRect(r *Rect) bool { if (p.X >= r.X) && (p.X < (r.X + r.W)) && (p.Y >= r.Y) && (p.Y < (r.Y + r.H)) { return true } return false } // InRect reports whether the point resides inside a rectangle. // (https://wiki.libsdl.org/SDL_PointInRect) func (p *FPoint) InRect(r *FRect) bool { if (p.X >= r.X) && (p.X < (r.X + r.W)) && (p.Y >= r.Y) && (p.Y < (r.Y + r.H)) { return true } return false } // Empty reports whether a rectangle has no area. // (https://wiki.libsdl.org/SDL_RectEmpty) func (a *Rect) Empty() bool { return a == nil || a.W <= 0 || a.H <= 0 } // Equals reports whether two rectangles are equal. // (https://wiki.libsdl.org/SDL_RectEquals) func (a *Rect) Equals(b *Rect) bool { if (a != nil) && (b != nil) && (a.X == b.X) && (a.Y == b.Y) && (a.W == b.W) && (a.H == b.H) { return true } return false } // HasIntersection reports whether two rectangles intersect. // (https://wiki.libsdl.org/SDL_HasIntersection) func (a *Rect) HasIntersection(b *Rect) bool { if a == nil || b == nil { return false } // Special case for empty rects if a.Empty() || b.Empty() { return false } if a.X >= b.X+b.W || a.X+a.W <= b.X || a.Y >= b.Y+b.H || a.Y+a.H <= b.Y { return false } return true } // Intersect calculates the intersection of two rectangles. // (https://wiki.libsdl.org/SDL_IntersectRect) func (a *Rect) Intersect(b *Rect) (Rect, bool) { var result Rect if a == nil || b == nil { return result, false } // Special case for empty rects if a.Empty() || b.Empty() { result.W = 0 result.H = 0 return result, false } aMin := a.X aMax := aMin + a.W bMin := b.X bMax := bMin + b.W if bMin > aMin { aMin = bMin } result.X = aMin if bMax < aMax { aMax = bMax } result.W = aMax - aMin aMin = a.Y aMax = aMin + a.H bMin = b.Y bMax = bMin + b.H if bMin > aMin { aMin = bMin } result.Y = aMin if bMax < aMax { aMax = bMax } result.H = aMax - aMin return result, !result.Empty() } // Union calculates the union of two rectangles. // (https://wiki.libsdl.org/SDL_UnionRect) func (a *Rect) Union(b *Rect) Rect { var result Rect if a == nil || b == nil { return result } // Special case for empty rects if a.Empty() { return *b } else if b.Empty() { return *a } else if a.Empty() && b.Empty() { return result } aMin := a.X aMax := aMin + a.W bMin := b.X bMax := bMin + b.W if bMin < aMin { aMin = bMin } result.X = aMin if bMax > aMax { aMax = bMax } result.W = aMax - aMin aMin = a.Y aMax = aMin + a.H bMin = b.Y bMax = bMin + b.H if bMin < aMin { aMin = bMin } result.Y = aMin if bMax > aMax { aMax = bMax } result.H = aMax - aMin return result } // Empty reports whether a rectangle has no area. // (https://wiki.libsdl.org/SDL_RectEmpty) func (a *FRect) Empty() bool { return a == nil || a.W <= 0 || a.H <= 0 } // Equals reports whether two rectangles are equal. // (https://wiki.libsdl.org/SDL_RectEquals) func (a *FRect) Equals(b *FRect) bool { if (a != nil) && (b != nil) && (a.X == b.X) && (a.Y == b.Y) && (a.W == b.W) && (a.H == b.H) { return true } return false } // EqualsEpsilon returns true if the two rectangles are equal, within some given epsilon. // (https://wiki.libsdl.org/SDL_FRectEqualsEpsilon) func (a *FRect) EqualsEpsilon(b *FRect, epsilon float32) bool { if (a != nil) && (b != nil) && (a == b || (float32(math.Abs(float64(a.X-b.X))) <= epsilon) && (float32(math.Abs(float64(a.Y-b.Y))) <= epsilon) && (float32(math.Abs(float64(a.W-b.W))) <= epsilon) && (float32(math.Abs(float64(a.H-b.H))) <= epsilon)) { return true } return false } // HasIntersection reports whether two rectangles intersect. // (https://wiki.libsdl.org/SDL_HasIntersection) func (a *FRect) HasIntersection(b *FRect) bool { if a == nil || b == nil { return false } // Special case for empty rects if a.Empty() || b.Empty() { return false } if a.X >= b.X+b.W || a.X+a.W <= b.X || a.Y >= b.Y+b.H || a.Y+a.H <= b.Y { return false } return true } // Intersect calculates the intersection of two rectangles. // (https://wiki.libsdl.org/SDL_IntersectRect) func (a *FRect) Intersect(b *FRect) (FRect, bool) { var result FRect if a == nil || b == nil { return result, false } // Special case for empty rects if a.Empty() || b.Empty() { result.W = 0 result.H = 0 return result, false } aMin := a.X aMax := aMin + a.W bMin := b.X bMax := bMin + b.W if bMin > aMin { aMin = bMin } result.X = aMin if bMax < aMax { aMax = bMax } result.W = aMax - aMin aMin = a.Y aMax = aMin + a.H bMin = b.Y bMax = bMin + b.H if bMin > aMin { aMin = bMin } result.Y = aMin if bMax < aMax { aMax = bMax } result.H = aMax - aMin return result, !result.Empty() } // Union calculates the union of two rectangles. // (https://wiki.libsdl.org/SDL_UnionRect) func (a *FRect) Union(b *FRect) FRect { var result FRect if a == nil || b == nil { return result } // Special case for empty rects if a.Empty() { return *b } else if b.Empty() { return *a } else if a.Empty() && b.Empty() { return result } aMin := a.X aMax := aMin + a.W bMin := b.X bMax := bMin + b.W if bMin < aMin { aMin = bMin } result.X = aMin if bMax > aMax { aMax = bMax } result.W = aMax - aMin aMin = a.Y aMax = aMin + a.H bMin = b.Y bMax = bMin + b.H if bMin < aMin { aMin = bMin } result.Y = aMin if bMax > aMax { aMax = bMax } result.H = aMax - aMin return result } // EnclosePoints calculates a minimal rectangle that encloses a set of points. // (https://wiki.libsdl.org/SDL_EnclosePoints) func EnclosePoints(points []Point, clip *Rect) (Rect, bool) { var result Rect if len(points) == 0 { return result, false } var minX, minY, maxX, maxY int32 if clip != nil { added := false clipMinX := clip.X clipMinY := clip.Y clipMaxX := clip.X + clip.W - 1 clipMaxY := clip.Y + clip.H - 1 // If the clip has no size, we're done if clip.Empty() { return result, false } for _, val := range points { // Check if the point is inside the clip rect if val.X < clipMinX || val.X > clipMaxX || val.Y < clipMinY || val.Y > clipMaxY { continue } if !added { // If it's the first point minX = val.X maxX = val.X minY = val.Y maxY = val.Y added = true } // Find mins and maxes if val.X < minX { minX = val.X } else if val.X > maxX { maxX = val.X } if val.Y < minY { minY = val.Y } else if val.Y > maxY { maxY = val.Y } } } else { for i, val := range points { if i == 0 { // Populate the first point minX = val.X maxX = val.X minY = val.Y maxY = val.Y continue } // Find mins and maxes if val.X < minX { minX = val.X } else if val.X > maxX { maxX = val.X } if val.Y < minY { minY = val.Y } else if val.Y > maxY { maxY = val.Y } } } result.X = minX result.Y = minY result.W = (maxX - minX) + 1 result.H = (maxY - minY) + 1 return result, true } // EncloseFPoints calculates a minimal rectangle that encloses a set of points with float precision. // (https://wiki.libsdl.org/SDL_EncloseFPoints) func EncloseFPoints(points []FPoint, clip *FRect) (result FRect, enclosed bool) { if len(points) == 0 { return result, false } var minX, minY, maxX, maxY float32 if clip != nil { added := false clipMinX := clip.X clipMinY := clip.Y clipMaxX := clip.X + clip.W - 1 clipMaxY := clip.Y + clip.H - 1 // If the clip has no size, we're done if clip.Empty() { return result, false } for _, val := range points { // Check if the point is inside the clip rect if val.X < clipMinX || val.X > clipMaxX || val.Y < clipMinY || val.Y > clipMaxY { continue } if !added { // If it's the first point minX = val.X maxX = val.X minY = val.Y maxY = val.Y added = true } // Find mins and maxes if val.X < minX { minX = val.X } else if val.X > maxX { maxX = val.X } if val.Y < minY { minY = val.Y } else if val.Y > maxY { maxY = val.Y } } } else { for i, val := range points { if i == 0 { // Populate the first point minX = val.X maxX = val.X minY = val.Y maxY = val.Y continue } // Find mins and maxes if val.X < minX { minX = val.X } else if val.X > maxX { maxX = val.X } if val.Y < minY { minY = val.Y } else if val.Y > maxY { maxY = val.Y } } } result.X = minX result.Y = minY result.W = (maxX - minX) + 1 result.H = (maxY - minY) + 1 return result, true } const ( codeBottom = 1 codeTop = 2 codeLeft = 4 codeRight = 8 ) func computeOutCode(rect *Rect, x, y int32) int { code := 0 if y < rect.Y { code |= codeTop } else if y >= rect.Y+rect.H { code |= codeBottom } if x < rect.X { code |= codeLeft } else if x >= rect.X+rect.W { code |= codeRight } return code } func computeFOutCode(rect *FRect, x, y float32) int { code := 0 if y < rect.Y { code |= codeTop } else if y >= rect.Y+rect.H { code |= codeBottom } if x < rect.X { code |= codeLeft } else if x >= rect.X+rect.W { code |= codeRight } return code } // IntersectLine calculates the intersection of a rectangle and a line segment. // (https://wiki.libsdl.org/SDL_IntersectRectAndLine) func (a *Rect) IntersectLine(X1, Y1, X2, Y2 *int32) bool { if a.Empty() { return false } x1 := *X1 y1 := *Y1 x2 := *X2 y2 := *Y2 rectX1 := a.X rectY1 := a.Y rectX2 := a.X + a.W - 1 rectY2 := a.Y + a.H - 1 // Check if the line is entirely inside the rect if x1 >= rectX1 && x1 <= rectX2 && x2 >= rectX1 && x2 <= rectX2 && y1 >= rectY1 && y1 <= rectY2 && y2 >= rectY1 && y2 <= rectY2 { return true } // Check if the line is entirely outside the rect if (x1 < rectX1 && x2 < rectX1) || (x1 > rectX2 && x2 > rectX2) || (y1 < rectY1 && y2 < rectY1) || (y1 > rectY2 && y2 > rectY2) { return false } // Check if the line is horizontal if y1 == y2 { if x1 < rectX1 { *X1 = rectX1 } else if x1 > rectX2 { *X1 = rectX2 } if x2 < rectX1 { *X2 = rectX1 } else if x2 > rectX2 { *X2 = rectX2 } return true } // Check if the line is vertical if x1 == x2 { if y1 < rectY1 { *Y1 = rectY1 } else if y1 > rectY2 { *Y1 = rectY2 } if y2 < rectY1 { *Y2 = rectY1 } else if y2 > rectY2 { *Y2 = rectY2 } return true } // Use Cohen-Sutherland algorithm when all shortcuts fail outCode1 := computeOutCode(a, x1, y1) outCode2 := computeOutCode(a, x2, y2) for outCode1 != 0 || outCode2 != 0 { if outCode1&outCode2 != 0 { return false } if outCode1 != 0 { var x, y int32 if outCode1&codeTop != 0 { y = rectY1 x = x1 + ((x2-x1)*(y-y1))/(y2-y1) } else if outCode1&codeBottom != 0 { y = rectY2 x = x1 + ((x2-x1)*(y-y1))/(y2-y1) } else if outCode1&codeLeft != 0 { x = rectX1 y = y1 + ((y2-y1)*(x-x1))/(x2-x1) } else if outCode1&codeRight != 0 { x = rectX2 y = y1 + ((y2-y1)*(x-x1))/(x2-x1) } x1 = x y1 = y outCode1 = computeOutCode(a, x, y) } else { var x, y int32 if outCode2&codeTop != 0 { y = rectY1 x = x1 + ((x2-x1)*(y-y1))/(y2-y1) } else if outCode2&codeBottom != 0 { y = rectY2 x = x1 + ((x2-x1)*(y-y1))/(y2-y1) } else if outCode2&codeLeft != 0 { x = rectX1 y = y1 + ((y2-y1)*(x-x1))/(x2-x1) } else if outCode2&codeRight != 0 { x = rectX2 y = y1 + ((y2-y1)*(x-x1))/(x2-x1) } x2 = x y2 = y outCode2 = computeOutCode(a, x, y) } } *X1 = x1 *Y1 = y1 *X2 = x2 *Y2 = y2 return true } // IntersectLine calculates the intersection of a rectangle and a line segment. // (https://wiki.libsdl.org/SDL_IntersectFRectAndLine) func (a *FRect) IntersectLine(X1, Y1, X2, Y2 *float32) bool { if a.Empty() { return false } x1 := *X1 y1 := *Y1 x2 := *X2 y2 := *Y2 rectX1 := a.X rectY1 := a.Y rectX2 := a.X + a.W - 1 rectY2 := a.Y + a.H - 1 // Check if the line is entirely inside the rect if x1 >= rectX1 && x1 <= rectX2 && x2 >= rectX1 && x2 <= rectX2 && y1 >= rectY1 && y1 <= rectY2 && y2 >= rectY1 && y2 <= rectY2 { return true } // Check if the line is entirely outside the rect if (x1 < rectX1 && x2 < rectX1) || (x1 > rectX2 && x2 > rectX2) || (y1 < rectY1 && y2 < rectY1) || (y1 > rectY2 && y2 > rectY2) { return false } // Check if the line is horizontal if y1 == y2 { if x1 < rectX1 { *X1 = rectX1 } else if x1 > rectX2 { *X1 = rectX2 } if x2 < rectX1 { *X2 = rectX1 } else if x2 > rectX2 { *X2 = rectX2 } return true } // Check if the line is vertical if x1 == x2 { if y1 < rectY1 { *Y1 = rectY1 } else if y1 > rectY2 { *Y1 = rectY2 } if y2 < rectY1 { *Y2 = rectY1 } else if y2 > rectY2 { *Y2 = rectY2 } return true } // Use Cohen-Sutherland algorithm when all shortcuts fail outCode1 := computeFOutCode(a, x1, y1) outCode2 := computeFOutCode(a, x2, y2) for outCode1 != 0 || outCode2 != 0 { if outCode1&outCode2 != 0 { return false } if outCode1 != 0 { var x, y float32 if outCode1&codeTop != 0 { y = rectY1 x = x1 + ((x2-x1)*(y-y1))/(y2-y1) } else if outCode1&codeBottom != 0 { y = rectY2 x = x1 + ((x2-x1)*(y-y1))/(y2-y1) } else if outCode1&codeLeft != 0 { x = rectX1 y = y1 + ((y2-y1)*(x-x1))/(x2-x1) } else if outCode1&codeRight != 0 { x = rectX2 y = y1 + ((y2-y1)*(x-x1))/(x2-x1) } x1 = x y1 = y outCode1 = computeFOutCode(a, x, y) } else { var x, y float32 if outCode2&codeTop != 0 { y = rectY1 x = x1 + ((x2-x1)*(y-y1))/(y2-y1) } else if outCode2&codeBottom != 0 { y = rectY2 x = x1 + ((x2-x1)*(y-y1))/(y2-y1) } else if outCode2&codeLeft != 0 { x = rectX1 y = y1 + ((y2-y1)*(x-x1))/(x2-x1) } else if outCode2&codeRight != 0 { x = rectX2 y = y1 + ((y2-y1)*(x-x1))/(x2-x1) } x2 = x y2 = y outCode2 = computeFOutCode(a, x, y) } } *X1 = x1 *Y1 = y1 *X2 = x2 *Y2 = y2 return true } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/render.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,1)) #if defined(WARN_OUTDATED) #pragma message("SDL_UpdateYUVTexture is not supported before SDL 2.0.1") #endif static inline int SDL_UpdateYUVTexture(SDL_Texture* texture, const SDL_Rect* rect, const Uint8* Yplane, int Ypitch, const Uint8* Uplane, int Upitch, const Uint8* Vplane, int Vpitch) { return -1; } #endif #if !(SDL_VERSION_ATLEAST(2,0,4)) #if defined(WARN_OUTDATED) #pragma message("SDL_RenderIsClipEnabled is not supported before SDL 2.0.4") #endif static inline SDL_bool SDLCALL SDL_RenderIsClipEnabled(SDL_Renderer * renderer) { return SDL_FALSE; } #endif #if !(SDL_VERSION_ATLEAST(2,0,5)) #if defined(WARN_OUTDATED) #pragma message("SDL_RenderSetIntegerScale is not supported before SDL 2.0.5") #endif static inline int SDL_RenderSetIntegerScale(SDL_Renderer* renderer, SDL_bool enable) { SDL_Unsupported(); return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_RenderGetIntegerScale is not supported before SDL 2.0.5") #endif static inline SDL_bool SDL_RenderGetIntegerScale(SDL_Renderer* renderer) { SDL_Unsupported(); return -1; } #endif #if !(SDL_VERSION_ATLEAST(2,0,8)) #if defined(WARN_OUTDATED) #pragma message("SDL_RenderGetMetalLayer is not supported before SDL 2.0.8") #endif static inline void * SDL_RenderGetMetalLayer(SDL_Renderer *renderer) { return NULL; } #if defined(WARN_OUTDATED) #pragma message("SDL_RenderGetMetalCommandEncoder is not supported before SDL 2.0.8") #endif static inline void * SDL_RenderGetMetalCommandEncoder(SDL_Renderer *renderer) { return NULL; } #endif #if !(SDL_VERSION_ATLEAST(2,0,10)) #if defined(WARN_OUTDATED) #pragma message("SDL_RenderDrawPointF is not supported before SDL 2.0.10") #endif static inline int SDL_RenderDrawPointF(SDL_Renderer * renderer, float x, float y) { return SDL_RenderDrawPoint(renderer, (int) x, (int) y); } #if defined(WARN_OUTDATED) #pragma message("SDL_RenderDrawPointsF is not supported before SDL 2.0.10") #endif static inline int SDL_RenderDrawPointsF(SDL_Renderer * renderer, const SDL_FPoint * points, int count) { return SDL_RenderDrawPoints(renderer, (const SDL_Point *) points, count); } #if defined(WARN_OUTDATED) #pragma message("SDL_RenderDrawLineF is not supported before SDL 2.0.10") #endif static inline int SDL_RenderDrawLineF(SDL_Renderer * renderer, float x1, float y1, float x2, float y2) { return SDL_RenderDrawLine(renderer, (int) x1, (int) y1, (int) x2, (int) y2); } #if defined(WARN_OUTDATED) #pragma message("SDL_RenderDrawLinesF is not supported before SDL 2.0.10") #endif static inline int SDL_RenderDrawLinesF(SDL_Renderer * renderer, const SDL_FPoint * points, int count) { return SDL_RenderDrawLines(renderer, (const SDL_Point *) points, count); } #if defined(WARN_OUTDATED) #pragma message("SDL_RenderDrawRectF is not supported before SDL 2.0.10") #endif static inline int SDL_RenderDrawRectF(SDL_Renderer * renderer, const SDL_FRect * rect) { return SDL_RenderDrawRect(renderer, (const SDL_Rect *) rect); } #if defined(WARN_OUTDATED) #pragma message("SDL_RenderDrawRectsF is not supported before SDL 2.0.10") #endif static inline int SDL_RenderDrawRectsF(SDL_Renderer * renderer, const SDL_FRect *rects, int count) { return SDL_RenderDrawRects(renderer, (const SDL_Rect *) rects, count); } #if defined(WARN_OUTDATED) #pragma message("SDL_RenderFillRectF is not supported before SDL 2.0.10") #endif static inline int SDL_RenderFillRectF(SDL_Renderer * renderer, const SDL_FRect * rect) { return SDL_RenderFillRect(renderer, (const SDL_Rect *) rect); } #if defined(WARN_OUTDATED) #pragma message("SDL_RenderFillRectsF is not supported before SDL 2.0.10") #endif static inline int SDL_RenderFillRectsF(SDL_Renderer * renderer, const SDL_FRect * rects, int count) { return SDL_RenderFillRects(renderer, (const SDL_Rect *) rects, count); } #if defined(WARN_OUTDATED) #pragma message("SDL_RenderCopyF is not supported before SDL 2.0.10") #endif static inline int SDL_RenderCopyF(SDL_Renderer * renderer, SDL_Texture * texture, const SDL_Rect * srcrect, const SDL_FRect * dstrect) { return SDL_RenderCopy(renderer, texture, srcrect, (const SDL_Rect *) dstrect); } #if defined(WARN_OUTDATED) #pragma message("SDL_RenderCopyExF is not supported before SDL 2.0.10") #endif static inline int SDL_RenderCopyExF(SDL_Renderer * renderer, SDL_Texture * texture, const SDL_Rect * srcrect, const SDL_FRect * dstrect, const double angle, const SDL_FPoint * center, const SDL_RendererFlip flip) { return SDL_RenderCopyEx(renderer, texture, srcrect, (const SDL_Rect *) dstrect, angle, (const SDL_Point *) center, flip); } #if defined(WARN_OUTDATED) #pragma message("SDL_RenderFlush is not supported before SDL 2.0.10") #endif static inline int SDL_RenderFlush(SDL_Renderer * renderer) { return 0; } #endif #if !(SDL_VERSION_ATLEAST(2,0,12)) typedef enum { SDL_ScaleModeNearest, SDL_ScaleModeLinear, SDL_ScaleModeBest } SDL_ScaleMode; #if defined(WARN_OUTDATED) #pragma message("SDL_SetTextureScaleMode is not supported before SDL 2.0.12") #pragma message("SDL_GetTextureScaleMode is not supported before SDL 2.0.12") #pragma message("SDL_LockTextureToSurface is not supported before SDL 2.0.12") #endif static int SDL_SetTextureScaleMode(SDL_Texture * texture, SDL_ScaleMode scaleMode) { return -1; } static int SDLCALL SDL_GetTextureScaleMode(SDL_Texture * texture, SDL_ScaleMode *scaleMode) { return -1; } static int SDL_LockTextureToSurface(SDL_Texture *texture, const SDL_Rect *rect, SDL_Surface **surface) { return -1; } #endif #if !(SDL_VERSION_ATLEAST(2,0,16)) #if defined(WARN_OUTDATED) #pragma message("SDL_UpdateNVTexture is not supported before SDL 2.0.16") #endif static int SDL_UpdateNVTexture(SDL_Texture * texture, const SDL_Rect * rect, const Uint8 *Yplane, int Ypitch, const Uint8 *UVplane, int UVpitch) { return -1; } #endif #if !(SDL_VERSION_ATLEAST(2,0,18)) #if defined(WARN_OUTDATED) #pragma message("SDL_RenderGeometry is not supported before SDL 2.0.18") #pragma message("SDL_RenderGeometryRaw is not supported before SDL 2.0.18") #pragma message("SDL_SetTextureUserData is not supported before SDL 2.0.18") #pragma message("SDL_GetTextureUserData is not supported before SDL 2.0.18") #pragma message("SDL_RenderWindowToLogical is not supported before SDL 2.0.18") #pragma message("SDL_RenderLogicalToWindow is not supported before SDL 2.0.18") #pragma message("SDL_RenderSetVSync is not supported before SDL 2.0.18") #endif // Vertex structure typedef struct SDL_Vertex { SDL_FPoint position; // Vertex position, in SDL_Renderer coordinates SDL_Color color; // Vertex color SDL_FPoint tex_coord; // Normalized texture coordinates, if needed } SDL_Vertex; static int SDL_RenderGeometry(SDL_Renderer *renderer, SDL_Texture *texture, const SDL_Vertex *vertices, int num_vertices, const int *indices, int num_indices) { return -1; } static int SDL_RenderGeometryRaw(SDL_Renderer *renderer, SDL_Texture *texture, const float *xy, int xy_stride, const SDL_Color *color, int color_stride, const float *uv, int uv_stride, int num_vertices, const void *indices, int num_indices, int size_indices) { return -1; } static int SDL_SetTextureUserData(SDL_Texture * texture, void *userdata) { return -1; } static void * SDLCALL SDL_GetTextureUserData(SDL_Texture * texture) { return NULL; } static void SDL_RenderWindowToLogical(SDL_Renderer * renderer, int windowX, int windowY, float *logicalX, float *logicalY) { } static void SDL_RenderLogicalToWindow(SDL_Renderer * renderer, float logicalX, float logicalY, int *windowX, int *windowY) { } static int SDL_RenderSetVSync(SDL_Renderer* renderer, int vsync) { return -1; } #endif #if SDL_COMPILEDVERSION == SDL_VERSIONNUM(2,0,18) static inline int RenderGeometryRaw(SDL_Renderer *renderer, SDL_Texture *texture, const float *xy, int xy_stride, const SDL_Color *color, int color_stride, const float *uv, int uv_stride, int num_vertices, const void *indices, int num_indices, int size_indices) { return SDL_RenderGeometryRaw(renderer, texture, xy, xy_stride, (int*) color, color_stride, uv, uv_stride, num_vertices, indices, num_indices, size_indices); } #else static inline int RenderGeometryRaw(SDL_Renderer *renderer, SDL_Texture *texture, const float *xy, int xy_stride, const SDL_Color *color, int color_stride, const float *uv, int uv_stride, int num_vertices, const void *indices, int num_indices, int size_indices) { return SDL_RenderGeometryRaw(renderer, texture, xy, xy_stride, color, color_stride, uv, uv_stride, num_vertices, indices, num_indices, size_indices); } #endif #if !(SDL_VERSION_ATLEAST(2,0,22)) #if defined(WARN_OUTDATED) #pragma message("SDL_RenderGetWindow is not supported before SDL 2.0.22") #endif static inline SDL_Window * SDLCALL SDL_RenderGetWindow(SDL_Renderer *renderer) { return NULL; } #endif // WORKAROUND: This prevents audio from seemingly going corrupt when drawing outside the screen bounding box? // It does that by allocating SDL_Rect in the C context instead of Go context. static inline int RenderCopy(SDL_Renderer *renderer, SDL_Texture *texture, SDL_Rect *src, int dst_x, int dst_y, int dst_w, int dst_h) { SDL_Rect dst = {dst_x, dst_y, dst_w, dst_h}; return SDL_RenderCopy(renderer, texture, src, &dst); } */ import "C" import ( "reflect" "unsafe" ) // An enumeration of flags used when creating a rendering context. // (https://wiki.libsdl.org/SDL_RendererFlags) const ( RENDERER_SOFTWARE = C.SDL_RENDERER_SOFTWARE // the renderer is a software fallback RENDERER_ACCELERATED = C.SDL_RENDERER_ACCELERATED // the renderer uses hardware acceleration RENDERER_PRESENTVSYNC = C.SDL_RENDERER_PRESENTVSYNC // present is synchronized with the refresh rate RENDERER_TARGETTEXTURE = C.SDL_RENDERER_TARGETTEXTURE // the renderer supports rendering to texture ) type ScaleMode C.SDL_ScaleMode // The scaling mode for a texture. const ( ScaleModeNearest ScaleMode = C.SDL_ScaleModeNearest // nearest pixel sampling ScaleModeLinear = C.SDL_ScaleModeLinear // linear filtering ScaleModeBest = C.SDL_ScaleModeBest // anisotropic filtering ) // An enumeration of texture access patterns.. // (https://wiki.libsdl.org/SDL_TextureAccess) const ( TEXTUREACCESS_STATIC = C.SDL_TEXTUREACCESS_STATIC // changes rarely, not lockable TEXTUREACCESS_STREAMING = C.SDL_TEXTUREACCESS_STREAMING // changes frequently, lockable TEXTUREACCESS_TARGET = C.SDL_TEXTUREACCESS_TARGET // can be used as a render target ) // An enumeration of the texture channel modulation used in Renderer.Copy(). // (https://wiki.libsdl.org/SDL_TextureModulate) const ( TEXTUREMODULATE_NONE = C.SDL_TEXTUREMODULATE_NONE // no modulation TEXTUREMODULATE_COLOR = C.SDL_TEXTUREMODULATE_COLOR // srcC = srcC * color TEXTUREMODULATE_ALPHA = C.SDL_TEXTUREMODULATE_ALPHA // srcA = srcA * alpha ) // An enumeration of flags that can be used in the flip parameter for Renderer.CopyEx(). // (https://wiki.libsdl.org/SDL_RendererFlip) const ( FLIP_NONE RendererFlip = C.SDL_FLIP_NONE // do not flip FLIP_HORIZONTAL = C.SDL_FLIP_HORIZONTAL // flip horizontally FLIP_VERTICAL = C.SDL_FLIP_VERTICAL // flip vertically ) // RendererInfo contains information on the capabilities of a render driver or the current render context. // (https://wiki.libsdl.org/SDL_RendererInfo) type RendererInfo struct { Name string // the name of the renderer RendererInfoData } type cRendererInfo struct { Name *C.char RendererInfoData } // RendererInfoData contains information on the capabilities of a render driver or the current render context. // (https://wiki.libsdl.org/SDL_RendererInfo) type RendererInfoData struct { Flags uint32 // a mask of supported renderer flags NumTextureFormats uint32 // the number of available texture formats TextureFormats [16]int32 // the available texture formats MaxTextureWidth int32 // the maximum texture width MaxTextureHeight int32 // the maximum texture height } func (info *RendererInfo) cptr() *C.SDL_RendererInfo { return (*C.SDL_RendererInfo)(unsafe.Pointer(info)) } func (info *cRendererInfo) cptr() *C.SDL_RendererInfo { return (*C.SDL_RendererInfo)(unsafe.Pointer(info)) } // RendererFlip is an enumeration of flags that can be used in the flip parameter for Renderer.CopyEx(). // (https://wiki.libsdl.org/SDL_RendererFlip) type RendererFlip uint32 type cRendererFlip C.SDL_RendererFlip // Vertex structure type Vertex struct { Position FPoint // Vertex position, in SDL_Renderer coordinates Color Color // Vertex color TexCoord FPoint // Normalized texture coordinates, if needed } func (flip RendererFlip) c() C.SDL_RendererFlip { return C.SDL_RendererFlip(flip) } // GetNumRenderDrivers returns the number of 2D rendering drivers available for the current display. // (https://wiki.libsdl.org/SDL_GetNumRenderDrivers) func GetNumRenderDrivers() (int, error) { i := int(C.SDL_GetNumRenderDrivers()) return i, errorFromInt(i) } // GetRenderDriverInfo returns information about a specific 2D rendering driver for the current display. // (https://wiki.libsdl.org/SDL_GetRenderDriverInfo) func GetRenderDriverInfo(index int, info *RendererInfo) (int, error) { var cinfo cRendererInfo ret := int(C.SDL_GetRenderDriverInfo(C.int(index), cinfo.cptr())) if ret < 0 { return ret, GetError() } info.RendererInfoData = cinfo.RendererInfoData // No need to free, it's done by DestroyRenderer info.Name = C.GoString(cinfo.Name) return ret, nil } // CreateWindowAndRenderer returns a new window and default renderer. // (https://wiki.libsdl.org/SDL_CreateWindowAndRenderer) func CreateWindowAndRenderer(w, h int32, flags uint32) (*Window, *Renderer, error) { var window *C.SDL_Window var renderer *C.SDL_Renderer ret := C.SDL_CreateWindowAndRenderer( C.int(w), C.int(h), C.Uint32(flags), &window, &renderer) if ret == -1 { return nil, nil, GetError() } return (*Window)(unsafe.Pointer(window)), (*Renderer)(unsafe.Pointer(renderer)), nil } // CreateRenderer returns a new 2D rendering context for a window. // (https://wiki.libsdl.org/SDL_CreateRenderer) func CreateRenderer(window *Window, index int, flags uint32) (*Renderer, error) { renderer := C.SDL_CreateRenderer(window.cptr(), C.int(index), C.Uint32(flags)) if renderer == nil { return nil, GetError() } return (*Renderer)(unsafe.Pointer(renderer)), nil } // CreateSoftwareRenderer returns a new 2D software rendering context for a surface. // (https://wiki.libsdl.org/SDL_CreateSoftwareRenderer) func CreateSoftwareRenderer(surface *Surface) (*Renderer, error) { renderer := C.SDL_CreateSoftwareRenderer(surface.cptr()) if renderer == nil { return nil, GetError() } return (*Renderer)(unsafe.Pointer(renderer)), nil } // GetRenderer returns the renderer associated with a window. // (https://wiki.libsdl.org/SDL_GetRenderer) func (window *Window) GetRenderer() (*Renderer, error) { renderer := C.SDL_GetRenderer(window.cptr()) if renderer == nil { return nil, GetError() } return (*Renderer)(unsafe.Pointer(renderer)), nil } // GetInfo returns information about a rendering context. // (https://wiki.libsdl.org/SDL_GetRendererInfo) func (renderer *Renderer) GetInfo() (RendererInfo, error) { var cinfo cRendererInfo var info RendererInfo ret := int(C.SDL_GetRendererInfo(renderer.cptr(), cinfo.cptr())) if ret < 0 { return info, GetError() } info.RendererInfoData = cinfo.RendererInfoData // No need to free, it's done by DestroyRenderer info.Name = C.GoString(cinfo.Name) return info, nil } // GetOutputSize returns the output size in pixels of a rendering context. // (https://wiki.libsdl.org/SDL_GetRendererOutputSize) func (renderer *Renderer) GetOutputSize() (w, h int32, err error) { ret := C.SDL_GetRendererOutputSize( renderer.cptr(), (*C.int)(unsafe.Pointer(&w)), (*C.int)(unsafe.Pointer(&h))) err = errorFromInt(int(ret)) return } // CreateTexture returns a new texture for a rendering context. // (https://wiki.libsdl.org/SDL_CreateTexture) func (renderer *Renderer) CreateTexture(format uint32, access int, w, h int32) (*Texture, error) { texture := C.SDL_CreateTexture( renderer.cptr(), C.Uint32(format), C.int(access), C.int(w), C.int(h)) if texture == nil { return nil, GetError() } return (*Texture)(unsafe.Pointer(texture)), nil } // CreateTextureFromSurface returns a new texture from an existing surface. // (https://wiki.libsdl.org/SDL_CreateTextureFromSurface) func (renderer *Renderer) CreateTextureFromSurface(surface *Surface) (*Texture, error) { texture := C.SDL_CreateTextureFromSurface(renderer.cptr(), surface.cptr()) if texture == nil { return nil, GetError() } return (*Texture)(unsafe.Pointer(texture)), nil } // Query returns the attributes of a texture. // (https://wiki.libsdl.org/SDL_QueryTexture) func (texture *Texture) Query() (format uint32, access int, width int32, height int32, err error) { var _format C.Uint32 var _access C.int var _width C.int var _height C.int ret := int(C.SDL_QueryTexture(texture.cptr(), &_format, &_access, &_width, &_height)) format = uint32(_format) access = int(_access) width = int32(_width) height = int32(_height) err = errorFromInt(ret) return } // SetColorMod sets an additional color value multiplied into render copy operations. // (https://wiki.libsdl.org/SDL_SetTextureColorMod) func (texture *Texture) SetColorMod(r uint8, g uint8, b uint8) error { return errorFromInt(int( C.SDL_SetTextureColorMod( texture.cptr(), C.Uint8(r), C.Uint8(g), C.Uint8(b)))) } // SetAlphaMod sets an additional alpha value multiplied into render copy operations. // (https://wiki.libsdl.org/SDL_SetTextureAlphaMod) func (texture *Texture) SetAlphaMod(alpha uint8) error { return errorFromInt(int( C.SDL_SetTextureAlphaMod(texture.cptr(), C.Uint8(alpha)))) } // GetAlphaMod returns the additional alpha value multiplied into render copy operations. // (https://wiki.libsdl.org/SDL_GetTextureAlphaMod) func (texture *Texture) GetAlphaMod() (alpha uint8, err error) { ret := C.SDL_GetTextureAlphaMod(texture.cptr(), (*C.Uint8)(unsafe.Pointer(&alpha))) return alpha, errorFromInt(int(ret)) } // SetBlendMode sets the blend mode for a texture, used by Renderer.Copy(). // (https://wiki.libsdl.org/SDL_SetTextureBlendMode) func (texture *Texture) SetBlendMode(bm BlendMode) error { return errorFromInt(int( C.SDL_SetTextureBlendMode(texture.cptr(), bm.c()))) } // GetBlendMode returns the blend mode used for texture copy operations. // (https://wiki.libsdl.org/SDL_GetTextureBlendMode) func (texture *Texture) GetBlendMode() (bm BlendMode, err error) { ret := C.SDL_GetTextureBlendMode(texture.cptr(), bm.cptr()) return bm, errorFromInt(int(ret)) } // Update updates the given texture rectangle with new pixel data. // (https://wiki.libsdl.org/SDL_UpdateTexture) func (texture *Texture) Update(rect *Rect, pixels unsafe.Pointer, pitch int) error { if pixels == nil { return nil } return errorFromInt(int( C.SDL_UpdateTexture( texture.cptr(), rect.cptr(), pixels, C.int(pitch)))) } // UpdateRGBA updates the given texture rectangle with new uint32 pixel data. // (https://wiki.libsdl.org/SDL_UpdateTexture) func (texture *Texture) UpdateRGBA(rect *Rect, pixels []uint32, pitch int) error { if pixels == nil { return nil } return errorFromInt(int( C.SDL_UpdateTexture( texture.cptr(), rect.cptr(), unsafe.Pointer(&pixels[0]), C.int(4*pitch)))) // 4 bytes in one uint32 } // UpdateYUV updates a rectangle within a planar YV12 or IYUV texture with new pixel data. // (https://wiki.libsdl.org/SDL_UpdateYUVTexture) func (texture *Texture) UpdateYUV(rect *Rect, yPlane []byte, yPitch int, uPlane []byte, uPitch int, vPlane []byte, vPitch int) error { var yPlanePtr, uPlanePtr, vPlanePtr *byte if yPlane != nil { yPlanePtr = &yPlane[0] } if uPlane != nil { uPlanePtr = &uPlane[0] } if vPlane != nil { vPlanePtr = &vPlane[0] } return errorFromInt(int( C.SDL_UpdateYUVTexture( texture.cptr(), rect.cptr(), (*C.Uint8)(unsafe.Pointer(yPlanePtr)), C.int(yPitch), (*C.Uint8)(unsafe.Pointer(uPlanePtr)), C.int(uPitch), (*C.Uint8)(unsafe.Pointer(vPlanePtr)), C.int(vPitch)))) } // Lock locks a portion of the texture for write-only pixel access. // (https://wiki.libsdl.org/SDL_LockTexture) func (texture *Texture) Lock(rect *Rect) ([]byte, int, error) { var _pitch C.int var _pixels unsafe.Pointer var b []byte var length int ret := C.SDL_LockTexture(texture.cptr(), rect.cptr(), &_pixels, &_pitch) if ret < 0 { return b, int(_pitch), GetError() } _, _, w, h, err := texture.Query() if err != nil { return b, int(_pitch), GetError() } pitch := int32(_pitch) if rect != nil { bytesPerPixel := pitch / w length = int(bytesPerPixel * (w*rect.H - rect.X - (w - rect.X - rect.W))) } else { length = int(pitch * h) } sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b)) sliceHeader.Cap = int(length) sliceHeader.Len = int(length) sliceHeader.Data = uintptr(_pixels) return b, int(pitch), nil } // Unlock unlocks a texture, uploading the changes to video memory, if needed. // (https://wiki.libsdl.org/SDL_UnlockTexture) func (texture *Texture) Unlock() { C.SDL_UnlockTexture(texture.cptr()) } // RenderTargetSupported reports whether a window supports the use of render targets. // (https://wiki.libsdl.org/SDL_RenderTargetSupported) func (renderer *Renderer) RenderTargetSupported() bool { return C.SDL_RenderTargetSupported(renderer.cptr()) != 0 } // SetRenderTarget sets a texture as the current rendering target. // (https://wiki.libsdl.org/SDL_SetRenderTarget) func (renderer *Renderer) SetRenderTarget(texture *Texture) error { return errorFromInt(int( C.SDL_SetRenderTarget(renderer.cptr(), texture.cptr()))) } // GetRenderTarget returns the current render target. // (https://wiki.libsdl.org/SDL_GetRenderTarget) func (renderer *Renderer) GetRenderTarget() *Texture { return (*Texture)(unsafe.Pointer(C.SDL_GetRenderTarget(renderer.cptr()))) } // SetLogicalSize sets a device independent resolution for rendering. // (https://wiki.libsdl.org/SDL_RenderSetLogicalSize) func (renderer *Renderer) SetLogicalSize(w, h int32) error { return errorFromInt(int( C.SDL_RenderSetLogicalSize(renderer.cptr(), C.int(w), C.int(h)))) } // GetLogicalSize returns device independent resolution for rendering. // (https://wiki.libsdl.org/SDL_RenderGetLogicalSize) func (renderer *Renderer) GetLogicalSize() (w, h int32) { C.SDL_RenderGetLogicalSize( renderer.cptr(), (*C.int)(unsafe.Pointer(&w)), (*C.int)(unsafe.Pointer(&h))) return } // SetViewport sets the drawing area for rendering on the current target. // (https://wiki.libsdl.org/SDL_RenderSetViewport) func (renderer *Renderer) SetViewport(rect *Rect) error { return errorFromInt(int( C.SDL_RenderSetViewport(renderer.cptr(), rect.cptr()))) } // GetViewport returns the drawing area for the current target. // (https://wiki.libsdl.org/SDL_RenderGetViewport) func (renderer *Renderer) GetViewport() (rect Rect) { C.SDL_RenderGetViewport(renderer.cptr(), rect.cptr()) return } // IsClipEnabled returns whether clipping is enabled on the given renderer. // (https://wiki.libsdl.org/SDL_RenderIsClipEnabled) func (renderer *Renderer) IsClipEnabled() bool { return C.SDL_RenderIsClipEnabled(renderer.cptr()) == C.SDL_TRUE } // SetClipRect sets the clip rectangle for rendering on the specified target. // (https://wiki.libsdl.org/SDL_RenderSetClipRect) func (renderer *Renderer) SetClipRect(rect *Rect) error { return errorFromInt(int( C.SDL_RenderSetClipRect(renderer.cptr(), rect.cptr()))) } // GetClipRect returns the clip rectangle for the current target. // (https://wiki.libsdl.org/SDL_RenderGetClipRect) func (renderer *Renderer) GetClipRect() (rect Rect) { C.SDL_RenderGetClipRect(renderer.cptr(), rect.cptr()) return } // SetScale sets the drawing scale for rendering on the current target. // (https://wiki.libsdl.org/SDL_RenderSetScale) func (renderer *Renderer) SetScale(scaleX, scaleY float32) error { return errorFromInt(int( C.SDL_RenderSetScale( renderer.cptr(), C.float(scaleX), C.float(scaleY)))) } // GetScale returns the drawing scale for the current target. // (https://wiki.libsdl.org/SDL_RenderGetScale) func (renderer *Renderer) GetScale() (scaleX, scaleY float32) { C.SDL_RenderGetScale( renderer.cptr(), (*C.float)(unsafe.Pointer(&scaleX)), (*C.float)(unsafe.Pointer(&scaleY))) return } // SetIntegerScale sets whether to force integer scales for // resolution-independent rendering. // // This function restricts the logical viewport to integer values - that is, // when a resolution is between two multiples of a logical size, the viewport // size is rounded down to the lower multiple. // // (https://wiki.libsdl.org/SDL_RenderSetIntegerScale) func (renderer *Renderer) SetIntegerScale(v bool) error { var cv C.SDL_bool = C.SDL_FALSE if v { cv = C.SDL_TRUE } return errorFromInt(int(C.SDL_RenderSetIntegerScale(renderer.cptr(), cv))) } // GetIntegerScale reports whether integer scales are forced for // resolution-independent rendering. // // (https://wiki.libsdl.org/SDL_RenderGetIntegerScale) func (renderer *Renderer) GetIntegerScale() (bool, error) { ClearError() if C.SDL_RenderGetIntegerScale(renderer.cptr()) == C.SDL_TRUE { return true, nil } return false, GetError() } // SetDrawColor sets the color used for drawing operations (Rect, Line and Clear). // (https://wiki.libsdl.org/SDL_SetRenderDrawColor) func (renderer *Renderer) SetDrawColor(r, g, b, a uint8) error { return errorFromInt(int( C.SDL_SetRenderDrawColor( renderer.cptr(), C.Uint8(r), C.Uint8(g), C.Uint8(b), C.Uint8(a)))) } // SetDrawColorArray is a custom variant of SetDrawColor. func (renderer *Renderer) SetDrawColorArray(bs ...uint8) error { _bs := []C.Uint8{0, 0, 0, 255} for i := 0; i < len(_bs) && i < len(bs); i++ { _bs[i] = C.Uint8(bs[i]) } return errorFromInt(int( C.SDL_SetRenderDrawColor( renderer.cptr(), _bs[0], _bs[1], _bs[2], _bs[3]))) } // GetDrawColor returns the color used for drawing operations (Rect, Line and Clear). // (https://wiki.libsdl.org/SDL_GetRenderDrawColor) func (renderer *Renderer) GetDrawColor() (r, g, b, a uint8, err error) { ret := C.SDL_GetRenderDrawColor( renderer.cptr(), (*C.Uint8)(unsafe.Pointer(&r)), (*C.Uint8)(unsafe.Pointer(&g)), (*C.Uint8)(unsafe.Pointer(&b)), (*C.Uint8)(unsafe.Pointer(&a))) return r, g, b, a, errorFromInt(int(ret)) } // SetDrawBlendMode sets the blend mode used for drawing operations (Fill and Line). // (https://wiki.libsdl.org/SDL_SetRenderDrawBlendMode) func (renderer *Renderer) SetDrawBlendMode(bm BlendMode) error { return errorFromInt(int( C.SDL_SetRenderDrawBlendMode(renderer.cptr(), bm.c()))) } // GetDrawBlendMode returns the blend mode used for drawing operations. // (https://wiki.libsdl.org/SDL_GetRenderDrawBlendMode) func (renderer *Renderer) GetDrawBlendMode(bm *BlendMode) error { return errorFromInt(int( C.SDL_GetRenderDrawBlendMode(renderer.cptr(), bm.cptr()))) } // Clear clears the current rendering target with the drawing color. // (https://wiki.libsdl.org/SDL_RenderClear) func (renderer *Renderer) Clear() error { return errorFromInt(int( C.SDL_RenderClear(renderer.cptr()))) } // DrawPoint draws a point on the current rendering target. // (https://wiki.libsdl.org/SDL_RenderDrawPoint) func (renderer *Renderer) DrawPoint(x, y int32) error { return errorFromInt(int( C.SDL_RenderDrawPoint(renderer.cptr(), C.int(x), C.int(y)))) } // DrawPoints draws multiple points on the current rendering target. // (https://wiki.libsdl.org/SDL_RenderDrawPoints) func (renderer *Renderer) DrawPoints(points []Point) error { return errorFromInt(int( C.SDL_RenderDrawPoints( renderer.cptr(), points[0].cptr(), C.int(len(points))))) } // DrawLine draws a line on the current rendering target. // (https://wiki.libsdl.org/SDL_RenderDrawLine) func (renderer *Renderer) DrawLine(x1, y1, x2, y2 int32) error { return errorFromInt(int( C.SDL_RenderDrawLine( renderer.cptr(), C.int(x1), C.int(y1), C.int(x2), C.int(y2)))) } // DrawLines draws a series of connected lines on the current rendering target. // (https://wiki.libsdl.org/SDL_RenderDrawLines) func (renderer *Renderer) DrawLines(points []Point) error { return errorFromInt(int( C.SDL_RenderDrawLines( renderer.cptr(), points[0].cptr(), C.int(len(points))))) } // DrawRect draws a rectangle on the current rendering target. // (https://wiki.libsdl.org/SDL_RenderDrawRect) func (renderer *Renderer) DrawRect(rect *Rect) error { return errorFromInt(int( C.SDL_RenderDrawRect(renderer.cptr(), rect.cptr()))) } // DrawRects draws some number of rectangles on the current rendering target. // (https://wiki.libsdl.org/SDL_RenderDrawRects) func (renderer *Renderer) DrawRects(rects []Rect) error { return errorFromInt(int( C.SDL_RenderDrawRects( renderer.cptr(), rects[0].cptr(), C.int(len(rects))))) } // FillRect fills a rectangle on the current rendering target with the drawing color. // (https://wiki.libsdl.org/SDL_RenderFillRect) func (renderer *Renderer) FillRect(rect *Rect) error { return errorFromInt(int( C.SDL_RenderFillRect(renderer.cptr(), rect.cptr()))) } // FillRects fills some number of rectangles on the current rendering target with the drawing color. // (https://wiki.libsdl.org/SDL_RenderFillRects) func (renderer *Renderer) FillRects(rects []Rect) error { return errorFromInt(int( C.SDL_RenderFillRects( renderer.cptr(), rects[0].cptr(), C.int(len(rects))))) } // Copy copies a portion of the texture to the current rendering target. // (https://wiki.libsdl.org/SDL_RenderCopy) func (renderer *Renderer) Copy(texture *Texture, src, dst *Rect) error { if dst == nil { return errorFromInt(int( C.SDL_RenderCopy( renderer.cptr(), texture.cptr(), src.cptr(), dst.cptr()))) } return errorFromInt(int( C.RenderCopy( renderer.cptr(), texture.cptr(), src.cptr(), C.int(dst.X), C.int(dst.Y), C.int(dst.W), C.int(dst.H)))) } // CopyEx copies a portion of the texture to the current rendering target, optionally rotating it by angle around the given center and also flipping it top-bottom and/or left-right. // (https://wiki.libsdl.org/SDL_RenderCopyEx) func (renderer *Renderer) CopyEx(texture *Texture, src, dst *Rect, angle float64, center *Point, flip RendererFlip) error { return errorFromInt(int( C.SDL_RenderCopyEx( renderer.cptr(), texture.cptr(), src.cptr(), dst.cptr(), C.double(angle), center.cptr(), flip.c()))) } // DrawPointF draws a point on the current rendering target. // TODO: (https://wiki.libsdl.org/SDL_RenderDrawPointF) func (renderer *Renderer) DrawPointF(x, y float32) error { return errorFromInt(int( C.SDL_RenderDrawPointF(renderer.cptr(), C.float(x), C.float(y)))) } // DrawPointsF draws multiple points on the current rendering target. // TODO: (https://wiki.libsdl.org/SDL_RenderDrawPointsF) func (renderer *Renderer) DrawPointsF(points []FPoint) error { return errorFromInt(int( C.SDL_RenderDrawPointsF( renderer.cptr(), points[0].cptr(), C.int(len(points))))) } // DrawLineF draws a line on the current rendering target. // TODO: (https://wiki.libsdl.org/SDL_RenderDrawLineF) func (renderer *Renderer) DrawLineF(x1, y1, x2, y2 float32) error { return errorFromInt(int( C.SDL_RenderDrawLineF( renderer.cptr(), C.float(x1), C.float(y1), C.float(x2), C.float(y2)))) } // DrawLinesF draws a series of connected lines on the current rendering target. // TODO: (https://wiki.libsdl.org/SDL_RenderDrawLinesF) func (renderer *Renderer) DrawLinesF(points []FPoint) error { return errorFromInt(int( C.SDL_RenderDrawLinesF( renderer.cptr(), points[0].cptr(), C.int(len(points))))) } // DrawRectF draws a rectangle on the current rendering target. // TODO: (https://wiki.libsdl.org/SDL_RenderDrawRectF) func (renderer *Renderer) DrawRectF(rect *FRect) error { return errorFromInt(int( C.SDL_RenderDrawRectF(renderer.cptr(), rect.cptr()))) } // DrawRectsF draws some number of rectangles on the current rendering target. // TODO: (https://wiki.libsdl.org/SDL_RenderDrawRectsF) func (renderer *Renderer) DrawRectsF(rects []FRect) error { return errorFromInt(int( C.SDL_RenderDrawRectsF( renderer.cptr(), rects[0].cptr(), C.int(len(rects))))) } // FillRectF fills a rectangle on the current rendering target with the drawing color. // TODO: (https://wiki.libsdl.org/SDL_RenderFillRectF) func (renderer *Renderer) FillRectF(rect *FRect) error { return errorFromInt(int( C.SDL_RenderFillRectF(renderer.cptr(), rect.cptr()))) } // FillRectsF fills some number of rectangles on the current rendering target with the drawing color. // TODO: (https://wiki.libsdl.org/SDL_RenderFillRectsF) func (renderer *Renderer) FillRectsF(rects []FRect) error { return errorFromInt(int( C.SDL_RenderFillRectsF( renderer.cptr(), rects[0].cptr(), C.int(len(rects))))) } // CopyF copies a portion of the texture to the current rendering target. // TODO: (https://wiki.libsdl.org/SDL_RenderCopyF) func (renderer *Renderer) CopyF(texture *Texture, src *Rect, dst *FRect) error { return errorFromInt(int( C.SDL_RenderCopyF( renderer.cptr(), texture.cptr(), src.cptr(), dst.cptr()))) } // CopyExF copies a portion of the texture to the current rendering target, optionally rotating it by angle around the given center and also flipping it top-bottom and/or left-right. // TODO: (https://wiki.libsdl.org/SDL_RenderCopyExF) func (renderer *Renderer) CopyExF(texture *Texture, src *Rect, dst *FRect, angle float64, center *FPoint, flip RendererFlip) error { return errorFromInt(int( C.SDL_RenderCopyExF( renderer.cptr(), texture.cptr(), src.cptr(), dst.cptr(), C.double(angle), center.cptr(), flip.c()))) } // ReadPixels reads pixels from the current rendering target. // (https://wiki.libsdl.org/SDL_RenderReadPixels) func (renderer *Renderer) ReadPixels(rect *Rect, format uint32, pixels unsafe.Pointer, pitch int) error { return errorFromInt(int( C.SDL_RenderReadPixels( renderer.cptr(), rect.cptr(), C.Uint32(format), pixels, C.int(pitch)))) } // Present updates the screen with any rendering performed since the previous call. // (https://wiki.libsdl.org/SDL_RenderPresent) func (renderer *Renderer) Present() { C.SDL_RenderPresent(renderer.cptr()) } // Destroy destroys the specified texture. // (https://wiki.libsdl.org/SDL_DestroyTexture) func (texture *Texture) Destroy() error { lastErr := GetError() ClearError() C.SDL_DestroyTexture(texture.cptr()) err := GetError() if err != nil { return err } SetError(lastErr) return nil } // Destroy destroys the rendering context for a window and free associated textures. // (https://wiki.libsdl.org/SDL_DestroyRenderer) func (renderer *Renderer) Destroy() error { lastErr := GetError() ClearError() C.SDL_DestroyRenderer(renderer.cptr()) err := GetError() if err != nil { return err } SetError(lastErr) return nil } // Flush forces the rendering context to flush any pending commands to the underlying rendering API. // TODO: (https://wiki.libsdl.org/SDL_RenderFlush) func (renderer *Renderer) Flush() error { return errorFromInt(int(C.SDL_RenderFlush(renderer.cptr()))) } // GLBind binds an OpenGL/ES/ES2 texture to the current context for use with OpenGL instructions when rendering OpenGL primitives directly. // (https://wiki.libsdl.org/SDL_GL_BindTexture) func (texture *Texture) GLBind(texw, texh *float32) error { return errorFromInt(int( C.SDL_GL_BindTexture( texture.cptr(), (*C.float)(unsafe.Pointer(texw)), (*C.float)(unsafe.Pointer(texh))))) } // GLUnbind unbinds an OpenGL/ES/ES2 texture from the current context. // (https://wiki.libsdl.org/SDL_GL_UnbindTexture) func (texture *Texture) GLUnbind() error { return errorFromInt(int( C.SDL_GL_UnbindTexture(texture.cptr()))) } // GetMetalLayer gets the CAMetalLayer associated with the given Metal renderer // (https://wiki.libsdl.org/SDL_RenderGetMetalLayer) func (renderer *Renderer) GetMetalLayer() (layer unsafe.Pointer, err error) { layer = C.SDL_RenderGetMetalLayer(renderer.cptr()) if layer == nil { err = GetError() } return } // GetMetalCommandEncoder gets the Metal command encoder for the current frame // (https://wiki.libsdl.org/SDL_RenderGetMetalCommandEncoder) func (renderer *Renderer) GetMetalCommandEncoder() (encoder unsafe.Pointer, err error) { encoder = C.SDL_RenderGetMetalCommandEncoder(renderer.cptr()) if encoder == nil { err = GetError() } return } // UpdateNV updates a rectangle within a planar NV12 or NV21 texture with new pixels. // (https://wiki.libsdl.org/SDL_UpdateNVTexture) func (texture *Texture) UpdateNV(rect *Rect, yPlane []byte, yPitch int, uvPlane []byte, uvPitch int) error { var yPlanePtr, uvPlanePtr *byte if yPlane != nil { yPlanePtr = &yPlane[0] } if uvPlane != nil { uvPlanePtr = &uvPlane[0] } return errorFromInt(int( C.SDL_UpdateNVTexture( texture.cptr(), rect.cptr(), (*C.Uint8)(unsafe.Pointer(yPlanePtr)), C.int(yPitch), (*C.Uint8)(unsafe.Pointer(uvPlanePtr)), C.int(uvPitch)))) } // RenderGeometry renders a list of triangles, optionally using a texture and // indices into the vertex array Color and alpha modulation is done per vertex // (SDL_SetTextureColorMod and SDL_SetTextureAlphaMod are ignored). // (https://wiki.libsdl.org/SDL_RenderGeometry) func (renderer *Renderer) RenderGeometry(texture *Texture, vertices []Vertex, indices []int32) (err error) { _texture := texture.cptr() _vertices := (*C.SDL_Vertex)(unsafe.Pointer(&vertices[0])) _num_vertices := C.int(len(vertices)) var _indices *C.int _num_indices := C.int(0) if indices != nil { _indices = (*C.int)(unsafe.Pointer(&indices[0])) _num_indices = C.int(len(indices)) } err = errorFromInt(int(C.SDL_RenderGeometry(renderer.cptr(), _texture, _vertices, _num_vertices, _indices, _num_indices))) return } // RenderGeomtryRaw renders a list of triangles, optionally using a texture and // indices into the vertex arrays Color and alpha modulation is done per vertex // (SDL_SetTextureColorMod and SDL_SetTextureAlphaMod are ignored). // (https://wiki.libsdl.org/SDL_RenderGeometryRaw) func (renderer *Renderer) RenderGeometryRaw(texture *Texture, xy *float32, xy_stride int, color *Color, color_stride int, uv *float32, uv_stride int, num_vertices int, indices unsafe.Pointer, num_indices int, size_indices int) (err error) { _texture := texture.cptr() _xy := (*C.float)(xy) _xy_stride := C.int(xy_stride) _color := (*C.SDL_Color)(unsafe.Pointer(color)) _color_stride := C.int(color_stride) _uv := (*C.float)(uv) _uv_stride := C.int(uv_stride) _num_vertices := C.int(num_vertices) _num_indices := C.int(num_indices) _size_indices := C.int(size_indices) _indices := indices err = errorFromInt(int(C.RenderGeometryRaw(renderer.cptr(), _texture, _xy, _xy_stride, _color, _color_stride, _uv, _uv_stride, _num_vertices, _indices, _num_indices, _size_indices))) return } // SetTextureUserData associates a user-specified pointer with a texture. // (https://wiki.libsdl.org/SDL_SetTextureUserData) func (texture *Texture) SetTextureUserData(userdata unsafe.Pointer) (err error) { err = errorFromInt(int(C.SDL_SetTextureUserData(texture.cptr(), userdata))) return } // GetTextureUserData gets the user-specified pointer associated with a texture. // (https://wiki.libsdl.org/SDL_GetTextureUserData) func (texture *Texture) GetTextureUserData() (userdata unsafe.Pointer) { userdata = C.SDL_GetTextureUserData(texture.cptr()) return } // RenderWindowToLogical gets logical coordinates of point in renderer when given real coordinates of // point in window. // // Logical coordinates will differ from real coordinates when render is scaled // and logical renderer size set // // (https://wiki.libsdl.org/SDL_RenderWindowToLogical) func (renderer *Renderer) RenderWindowToLogical(windowX, windowY int) (logicalX, logicalY float32) { _windowX := C.int(windowX) _windowY := C.int(windowY) _logicalX := C.float(0) _logicalY := C.float(0) C.SDL_RenderWindowToLogical(renderer.cptr(), _windowX, _windowY, &_logicalX, &_logicalY) logicalX = float32(_logicalX) logicalY = float32(_logicalY) return } // RenderLogicalToWindow gets real coordinates of point in window when given logical coordinates of point in renderer. // Logical coordinates will differ from real coordinates when render is scaled and logical renderer size set. // (https://wiki.libsdl.org/SDL_RenderLogicalToWindow) func (renderer *Renderer) RenderLogicalToWindow(logicalX, logicalY float32) (windowX, windowY int) { _logicalX := C.float(logicalX) _logicalY := C.float(logicalY) _windowX := C.int(0) _windowY := C.int(0) C.SDL_RenderLogicalToWindow(renderer.cptr(), _logicalX, _logicalY, &_windowX, &_windowY) windowX = int(_windowX) windowY = int(_windowY) return } // RenderSetVSync toggles VSync of the given renderer. // (https://wiki.libsdl.org/SDL_RenderSetVSync) func (renderer *Renderer) RenderSetVSync(vsync bool) (err error) { _vsync := C.int(Btoi(vsync)) err = errorFromInt(int(C.SDL_RenderSetVSync(renderer.cptr(), _vsync))) return } // GetWindow gets the window associated with a renderer. // (https://wiki.libsdl.org/SDL_RenderGetWindow) func (renderer *Renderer) GetWindow() (window *Window, err error) { window = (*Window)(unsafe.Pointer(C.SDL_RenderGetWindow(renderer.cptr()))) return } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/rwops.go ================================================ package sdl /* #include "sdl_wrapper.h" static Sint64 RWsize(SDL_RWops *ctx) { return ctx->size(ctx); } static Sint64 RWseek(SDL_RWops *ctx, Sint64 offset, int whence) { return ctx->seek(ctx, offset, whence); } static size_t RWread(SDL_RWops *ctx, void *ptr, size_t size, size_t maxnum) { return ctx->read(ctx, ptr, size, maxnum); } static size_t RWwrite(SDL_RWops *ctx, void *ptr, size_t size, size_t num) { return ctx->write(ctx, ptr, size, num); } static int RWclose(SDL_RWops *ctx) { return ctx->close(ctx); } #if !(SDL_VERSION_ATLEAST(2,0,6)) #if defined(WARN_OUTDATED) #pragma message("SDL_LoadFile_RW is not supported before SDL 2.0.6") #endif static void * SDL_LoadFile_RW(SDL_RWops * src, size_t *datasize, int freesrc) { return 0; } #endif */ import "C" import ( "reflect" "unsafe" ) // RWops types const ( RWOPS_UNKNOWN = 0 // unknown stream type RWOPS_WINFILE = 1 // win32 file RWOPS_STDFILE = 2 // stdio file RWOPS_JNIFILE = 3 // android asset RWOPS_MEMORY = 4 // memory stream RWOPS_MEMORY_RO = 5 // read-only memory stream ) // RWops seek from const ( RW_SEEK_SET = C.RW_SEEK_SET // seek from the beginning of data RW_SEEK_CUR = C.RW_SEEK_CUR // seek relative to current read point RW_SEEK_END = C.RW_SEEK_END // seek relative to the end of data ) // RWops provides an abstract interface to stream I/O. Applications can generally ignore the specifics of this structure's internals and treat them as opaque pointers. The details are important to lower-level code that might need to implement one of these, however. // (https://wiki.libsdl.org/SDL_RWops) type RWops C.SDL_RWops func (rwops *RWops) cptr() *C.SDL_RWops { return (*C.SDL_RWops)(rwops) } // RWFromFile creates a new RWops structure for reading from and/or writing to a named file. // (https://wiki.libsdl.org/SDL_RWFromFile) func RWFromFile(file, mode string) *RWops { _file := C.CString(file) _mode := C.CString(mode) defer C.free(unsafe.Pointer(_file)) defer C.free(unsafe.Pointer(_mode)) return (*RWops)(unsafe.Pointer(C.SDL_RWFromFile(_file, _mode))) } // RWFromMem prepares a read-write memory buffer for use with RWops. // (https://wiki.libsdl.org/SDL_RWFromMem) func RWFromMem(mem []byte) (*RWops, error) { if mem == nil { return nil, ErrInvalidParameters } header := (*reflect.SliceHeader)(unsafe.Pointer(&mem)) _mem := unsafe.Pointer(header.Data) rwops := (*RWops)(unsafe.Pointer(C.SDL_RWFromMem(_mem, C.int(len(mem))))) if rwops == nil { return nil, GetError() } return rwops, nil } // AllocRW allocates an empty, unpopulated RWops structure. // (https://wiki.libsdl.org/SDL_AllocRW) func AllocRW() *RWops { return (*RWops)(unsafe.Pointer(C.SDL_AllocRW())) } // Free frees the RWops structure allocated by AllocRW(). // (https://wiki.libsdl.org/SDL_FreeRW) func (rwops *RWops) Free() error { if rwops == nil { return ErrInvalidParameters } C.SDL_FreeRW(rwops.cptr()) return nil } // Size returns the size of the data stream in the RWops. // (https://wiki.libsdl.org/SDL_RWsize) func (rwops *RWops) Size() (int64, error) { n := int64(C.RWsize(rwops.cptr())) if n < 0 { return n, GetError() } return n, nil } // Seek seeks within the RWops data stream. // (https://wiki.libsdl.org/SDL_RWseek) func (rwops *RWops) Seek(offset int64, whence int) (int64, error) { if rwops == nil { return -1, ErrInvalidParameters } ret := int64(C.RWseek(rwops.cptr(), C.Sint64(offset), C.int(whence))) if ret < 0 { return ret, GetError() } return ret, nil } // Read reads from a data source. // (https://wiki.libsdl.org/SDL_RWread) func (rwops *RWops) Read(buf []byte) (n int, err error) { return rwops.Read2(buf, 1, uint(len(buf))) } // Read2 reads from a data source (native). // (https://wiki.libsdl.org/SDL_RWread) func (rwops *RWops) Read2(buf []byte, size, maxnum uint) (n int, err error) { if rwops == nil || buf == nil { return 0, ErrInvalidParameters } header := (*reflect.SliceHeader)(unsafe.Pointer(&buf)) _data := unsafe.Pointer(header.Data) n = int(C.RWread(rwops.cptr(), _data, C.size_t(size), C.size_t(maxnum))) if n == 0 { err = GetError() } return } // Tell returns the current read/write offset in the RWops data stream. // (https://wiki.libsdl.org/SDL_RWtell) func (rwops *RWops) Tell() (int64, error) { if rwops == nil { return 0, ErrInvalidParameters } ret := int64(C.RWseek(rwops.cptr(), 0, C.int(RW_SEEK_CUR))) if ret < 0 { return ret, GetError() } return ret, nil } // Write writes to the RWops data stream. // (https://wiki.libsdl.org/SDL_RWwrite) func (rwops *RWops) Write(buf []byte) (n int, err error) { return rwops.Write2(buf, 1, uint(len(buf))) } // Write2 writes to the RWops data stream (native). // (https://wiki.libsdl.org/SDL_RWwrite) func (rwops *RWops) Write2(buf []byte, size, num uint) (n int, err error) { if rwops == nil || buf == nil { return 0, ErrInvalidParameters } header := (*reflect.SliceHeader)(unsafe.Pointer(&buf)) _data := unsafe.Pointer(header.Data) n = int(C.RWwrite(rwops.cptr(), _data, C.size_t(size), C.size_t(num))) if n < int(num) { err = GetError() } return } // Close closes and frees the allocated RWops structure. // (https://wiki.libsdl.org/SDL_RWclose) func (rwops *RWops) Close() error { if rwops != nil && C.RWclose(rwops.cptr()) != 0 { return GetError() } return nil } // ReadU8 reads a byte from the RWops. // (https://wiki.libsdl.org/SDL_ReadU8) func (rwops *RWops) ReadU8() uint8 { if rwops == nil { return 0 } return uint8(C.SDL_ReadU8(rwops.cptr())) } // ReadLE16 reads 16 bits of little-endian data from the RWops and returns in native format. // (https://wiki.libsdl.org/SDL_ReadLE16) func (rwops *RWops) ReadLE16() uint16 { if rwops == nil { return 0 } return uint16(C.SDL_ReadLE16(rwops.cptr())) } // ReadBE16 read 16 bits of big-endian data from the RWops and returns in native format. // (https://wiki.libsdl.org/SDL_ReadBE16) func (rwops *RWops) ReadBE16() uint16 { if rwops == nil { return 0 } return uint16(C.SDL_ReadBE16(rwops.cptr())) } // ReadLE32 reads 32 bits of little-endian data from the RWops and returns in native format. // (https://wiki.libsdl.org/SDL_ReadLE32) func (rwops *RWops) ReadLE32() uint32 { if rwops == nil { return 0 } return uint32(C.SDL_ReadLE32(rwops.cptr())) } // ReadBE32 reads 32 bits of big-endian data from the RWops and returns in native format. // (https://wiki.libsdl.org/SDL_ReadBE32) func (rwops *RWops) ReadBE32() uint32 { if rwops == nil { return 0 } return uint32(C.SDL_ReadBE32(rwops.cptr())) } // ReadLE64 reads 64 bits of little-endian data from the RWops and returns in native format. // (https://wiki.libsdl.org/SDL_ReadLE64) func (rwops *RWops) ReadLE64() uint64 { if rwops == nil { return 0 } return uint64(C.SDL_ReadLE64(rwops.cptr())) } // ReadBE64 reads 64 bits of big-endian data from the RWops and returns in native format. // (https://wiki.libsdl.org/SDL_ReadBE64) func (rwops *RWops) ReadBE64() uint64 { if rwops == nil { return 0 } return uint64(C.SDL_ReadBE64(rwops.cptr())) } // LoadFile_RW loads all the data from an SDL data stream. // (https://wiki.libsdl.org/SDL_LoadFile_RW) func (src *RWops) LoadFileRW(freesrc bool) (data []byte, size int) { var _size C.size_t var _freesrc C.int = 0 if freesrc { _freesrc = 1 } _data := C.SDL_LoadFile_RW(src.cptr(), &_size, _freesrc) sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&data)) sliceHeader.Cap = int(_size) sliceHeader.Len = int(_size) sliceHeader.Data = uintptr(_data) size = int(_size) return } // LoadFile loads an entire file // (https://wiki.libsdl.org/SDL_LoadFile) func LoadFile(file string) (data []byte, size int) { return RWFromFile(file, "rb").LoadFileRW(true) } // WriteU8 writes a byte to the RWops. // (https://wiki.libsdl.org/SDL_WriteU8) func (rwops *RWops) WriteU8(value uint8) uint { if rwops == nil { return 0 } return uint(C.SDL_WriteU8(rwops.cptr(), C.Uint8(value))) } // WriteLE16 writes 16 bits in native format to the RWops as little-endian data. // (https://wiki.libsdl.org/SDL_WriteLE16) func (rwops *RWops) WriteLE16(value uint16) uint { if rwops == nil { return 0 } return uint(C.SDL_WriteLE16(rwops.cptr(), C.Uint16(value))) } // WriteBE16 writes 16 bits in native format to the RWops as big-endian data. // (https://wiki.libsdl.org/SDL_WriteBE16) func (rwops *RWops) WriteBE16(value uint16) uint { if rwops == nil { return 0 } return uint(C.SDL_WriteBE16(rwops.cptr(), C.Uint16(value))) } // WriteLE32 writes 32 bits in native format to the RWops as little-endian data. // (https://wiki.libsdl.org/SDL_WriteLE32) func (rwops *RWops) WriteLE32(value uint32) uint { if rwops == nil { return 0 } return uint(C.SDL_WriteLE32(rwops.cptr(), C.Uint32(value))) } // WriteBE32 writes 32 bits in native format to the RWops as big-endian data. // (https://wiki.libsdl.org/SDL_WriteBE32) func (rwops *RWops) WriteBE32(value uint32) uint { if rwops == nil { return 0 } return uint(C.SDL_WriteBE32(rwops.cptr(), C.Uint32(value))) } // WriteLE64 writes 64 bits in native format to the RWops as little-endian data. // (https://wiki.libsdl.org/SDL_WriteLE64) func (rwops *RWops) WriteLE64(value uint64) uint { if rwops == nil { return 0 } return uint(C.SDL_WriteLE64(rwops.cptr(), C.Uint64(value))) } // WriteBE64 writes 64 bits in native format to the RWops as big-endian data. // (https://wiki.libsdl.org/SDL_WriteBE64) func (rwops *RWops) WriteBE64(value uint64) uint { if rwops == nil { return 0 } return uint(C.SDL_WriteBE64(rwops.cptr(), C.Uint64(value))) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/scancode.go ================================================ package sdl // #include "sdl_wrapper.h" import "C" // The SDL keyboard scancode representation. // (https://wiki.libsdl.org/SDL_Scancode) // (https://wiki.libsdl.org/SDLScancodeLookup) const ( SCANCODE_UNKNOWN = 0 // "" (no name, empty string) SCANCODE_A = C.SDL_SCANCODE_A // "A" SCANCODE_B = C.SDL_SCANCODE_B // "B" SCANCODE_C = C.SDL_SCANCODE_C // "C" SCANCODE_D = C.SDL_SCANCODE_D // "D" SCANCODE_E = C.SDL_SCANCODE_E // "E" SCANCODE_F = C.SDL_SCANCODE_F // "F" SCANCODE_G = C.SDL_SCANCODE_G // "G" SCANCODE_H = C.SDL_SCANCODE_H // "H" SCANCODE_I = C.SDL_SCANCODE_I // "I" SCANCODE_J = C.SDL_SCANCODE_J // "J" SCANCODE_K = C.SDL_SCANCODE_K // "K" SCANCODE_L = C.SDL_SCANCODE_L // "L" SCANCODE_M = C.SDL_SCANCODE_M // "M" SCANCODE_N = C.SDL_SCANCODE_N // "N" SCANCODE_O = C.SDL_SCANCODE_O // "O" SCANCODE_P = C.SDL_SCANCODE_P // "P" SCANCODE_Q = C.SDL_SCANCODE_Q // "Q" SCANCODE_R = C.SDL_SCANCODE_R // "R" SCANCODE_S = C.SDL_SCANCODE_S // "S" SCANCODE_T = C.SDL_SCANCODE_T // "T" SCANCODE_U = C.SDL_SCANCODE_U // "U" SCANCODE_V = C.SDL_SCANCODE_V // "V" SCANCODE_W = C.SDL_SCANCODE_W // "W" SCANCODE_X = C.SDL_SCANCODE_X // "X" SCANCODE_Y = C.SDL_SCANCODE_Y // "Y" SCANCODE_Z = C.SDL_SCANCODE_Z // "Z" SCANCODE_1 = C.SDL_SCANCODE_1 // "1" SCANCODE_2 = C.SDL_SCANCODE_2 // "2" SCANCODE_3 = C.SDL_SCANCODE_3 // "3" SCANCODE_4 = C.SDL_SCANCODE_4 // "4" SCANCODE_5 = C.SDL_SCANCODE_5 // "5" SCANCODE_6 = C.SDL_SCANCODE_6 // "6" SCANCODE_7 = C.SDL_SCANCODE_7 // "7" SCANCODE_8 = C.SDL_SCANCODE_8 // "8" SCANCODE_9 = C.SDL_SCANCODE_9 // "9" SCANCODE_0 = C.SDL_SCANCODE_0 // "0" SCANCODE_RETURN = C.SDL_SCANCODE_RETURN // "Return" SCANCODE_ESCAPE = C.SDL_SCANCODE_ESCAPE // "Escape" (the Esc key) SCANCODE_BACKSPACE = C.SDL_SCANCODE_BACKSPACE // "Backspace" SCANCODE_TAB = C.SDL_SCANCODE_TAB // "Tab" (the Tab key) SCANCODE_SPACE = C.SDL_SCANCODE_SPACE // "Space" (the Space Bar key(s)) SCANCODE_MINUS = C.SDL_SCANCODE_MINUS // "-" SCANCODE_EQUALS = C.SDL_SCANCODE_EQUALS // "=" SCANCODE_LEFTBRACKET = C.SDL_SCANCODE_LEFTBRACKET // "[" SCANCODE_RIGHTBRACKET = C.SDL_SCANCODE_RIGHTBRACKET // "]" SCANCODE_BACKSLASH = C.SDL_SCANCODE_BACKSLASH // "\" SCANCODE_NONUSHASH = C.SDL_SCANCODE_NONUSHASH // "#" (ISO USB keyboards actually use this code instead of 49 for the same key, but all OSes I've seen treat the two codes identically. So, as an implementor, unless your keyboard generates both of those codes and your OS treats them differently, you should generate SDL_SCANCODE_BACKSLASH instead of this code. As a user, you should not rely on this code because SDL will never generate it with most (all?) keyboards.) SCANCODE_SEMICOLON = C.SDL_SCANCODE_SEMICOLON // ";" SCANCODE_APOSTROPHE = C.SDL_SCANCODE_APOSTROPHE // "'" SCANCODE_GRAVE = C.SDL_SCANCODE_GRAVE // "`" SCANCODE_COMMA = C.SDL_SCANCODE_COMMA // "," SCANCODE_PERIOD = C.SDL_SCANCODE_PERIOD // "." SCANCODE_SLASH = C.SDL_SCANCODE_SLASH // "/" SCANCODE_CAPSLOCK = C.SDL_SCANCODE_CAPSLOCK // "CapsLock" SCANCODE_F1 = C.SDL_SCANCODE_F1 // "F1" SCANCODE_F2 = C.SDL_SCANCODE_F2 // "F2" SCANCODE_F3 = C.SDL_SCANCODE_F3 // "F3" SCANCODE_F4 = C.SDL_SCANCODE_F4 // "F4" SCANCODE_F5 = C.SDL_SCANCODE_F5 // "F5" SCANCODE_F6 = C.SDL_SCANCODE_F6 // "F6" SCANCODE_F7 = C.SDL_SCANCODE_F7 // "F7" SCANCODE_F8 = C.SDL_SCANCODE_F8 // "F8" SCANCODE_F9 = C.SDL_SCANCODE_F9 // "F9" SCANCODE_F10 = C.SDL_SCANCODE_F10 // "F10" SCANCODE_F11 = C.SDL_SCANCODE_F11 // "F11" SCANCODE_F12 = C.SDL_SCANCODE_F12 // "F12" SCANCODE_PRINTSCREEN = C.SDL_SCANCODE_PRINTSCREEN // "PrintScreen" SCANCODE_SCROLLLOCK = C.SDL_SCANCODE_SCROLLLOCK // "ScrollLock" SCANCODE_PAUSE = C.SDL_SCANCODE_PAUSE // "Pause" (the Pause / Break key) SCANCODE_INSERT = C.SDL_SCANCODE_INSERT // "Insert" (insert on PC, help on some Mac keyboards (but does send code 73, not 117)) SCANCODE_HOME = C.SDL_SCANCODE_HOME // "Home" SCANCODE_PAGEUP = C.SDL_SCANCODE_PAGEUP // "PageUp" SCANCODE_DELETE = C.SDL_SCANCODE_DELETE // "Delete" SCANCODE_END = C.SDL_SCANCODE_END // "End" SCANCODE_PAGEDOWN = C.SDL_SCANCODE_PAGEDOWN // "PageDown" SCANCODE_RIGHT = C.SDL_SCANCODE_RIGHT // "Right" (the Right arrow key (navigation keypad)) SCANCODE_LEFT = C.SDL_SCANCODE_LEFT // "Left" (the Left arrow key (navigation keypad)) SCANCODE_DOWN = C.SDL_SCANCODE_DOWN // "Down" (the Down arrow key (navigation keypad)) SCANCODE_UP = C.SDL_SCANCODE_UP // "Up" (the Up arrow key (navigation keypad)) SCANCODE_NUMLOCKCLEAR = C.SDL_SCANCODE_NUMLOCKCLEAR // "Numlock" (the Num Lock key (PC) / the Clear key (Mac)) SCANCODE_KP_DIVIDE = C.SDL_SCANCODE_KP_DIVIDE // "Keypad /" (the / key (numeric keypad)) SCANCODE_KP_MULTIPLY = C.SDL_SCANCODE_KP_MULTIPLY // "Keypad *" (the * key (numeric keypad)) SCANCODE_KP_MINUS = C.SDL_SCANCODE_KP_MINUS // "Keypad -" (the - key (numeric keypad)) SCANCODE_KP_PLUS = C.SDL_SCANCODE_KP_PLUS // "Keypad +" (the + key (numeric keypad)) SCANCODE_KP_ENTER = C.SDL_SCANCODE_KP_ENTER // "Keypad Enter" (the Enter key (numeric keypad)) SCANCODE_KP_1 = C.SDL_SCANCODE_KP_1 // "Keypad 1" (the 1 key (numeric keypad)) SCANCODE_KP_2 = C.SDL_SCANCODE_KP_2 // "Keypad 2" (the 2 key (numeric keypad)) SCANCODE_KP_3 = C.SDL_SCANCODE_KP_3 // "Keypad 3" (the 3 key (numeric keypad)) SCANCODE_KP_4 = C.SDL_SCANCODE_KP_4 // "Keypad 4" (the 4 key (numeric keypad)) SCANCODE_KP_5 = C.SDL_SCANCODE_KP_5 // "Keypad 5" (the 5 key (numeric keypad)) SCANCODE_KP_6 = C.SDL_SCANCODE_KP_6 // "Keypad 6" (the 6 key (numeric keypad)) SCANCODE_KP_7 = C.SDL_SCANCODE_KP_7 // "Keypad 7" (the 7 key (numeric keypad)) SCANCODE_KP_8 = C.SDL_SCANCODE_KP_8 // "Keypad 8" (the 8 key (numeric keypad)) SCANCODE_KP_9 = C.SDL_SCANCODE_KP_9 // "Keypad 9" (the 9 key (numeric keypad)) SCANCODE_KP_0 = C.SDL_SCANCODE_KP_0 // "Keypad 0" (the 0 key (numeric keypad)) SCANCODE_KP_PERIOD = C.SDL_SCANCODE_KP_PERIOD // "Keypad ." (the . key (numeric keypad)) SCANCODE_NONUSBACKSLASH = C.SDL_SCANCODE_NONUSBACKSLASH // "" (no name, empty string; This is the additional key that ISO keyboards have over ANSI ones, located between left shift and Y. Produces GRAVE ACCENT and TILDE in a US or UK Mac layout, REVERSE SOLIDUS (backslash) and VERTICAL LINE in a US or UK Windows layout, and LESS-THAN SIGN and GREATER-THAN SIGN in a Swiss German, German, or French layout.) SCANCODE_APPLICATION = C.SDL_SCANCODE_APPLICATION // "Application" (the Application / Compose / Context Menu (Windows) key) SCANCODE_POWER = C.SDL_SCANCODE_POWER // "Power" (The USB document says this is a status flag, not a physical key - but some Mac keyboards do have a power key.) SCANCODE_KP_EQUALS = C.SDL_SCANCODE_KP_EQUALS // "Keypad =" (the = key (numeric keypad)) SCANCODE_F13 = C.SDL_SCANCODE_F13 // "F13" SCANCODE_F14 = C.SDL_SCANCODE_F14 // "F14" SCANCODE_F15 = C.SDL_SCANCODE_F15 // "F15" SCANCODE_F16 = C.SDL_SCANCODE_F16 // "F16" SCANCODE_F17 = C.SDL_SCANCODE_F17 // "F17" SCANCODE_F18 = C.SDL_SCANCODE_F18 // "F18" SCANCODE_F19 = C.SDL_SCANCODE_F19 // "F19" SCANCODE_F20 = C.SDL_SCANCODE_F20 // "F20" SCANCODE_F21 = C.SDL_SCANCODE_F21 // "F21" SCANCODE_F22 = C.SDL_SCANCODE_F22 // "F22" SCANCODE_F23 = C.SDL_SCANCODE_F23 // "F23" SCANCODE_F24 = C.SDL_SCANCODE_F24 // "F24" SCANCODE_EXECUTE = C.SDL_SCANCODE_EXECUTE // "Execute" SCANCODE_HELP = C.SDL_SCANCODE_HELP // "Help" SCANCODE_MENU = C.SDL_SCANCODE_MENU // "Menu" SCANCODE_SELECT = C.SDL_SCANCODE_SELECT // "Select" SCANCODE_STOP = C.SDL_SCANCODE_STOP // "Stop" SCANCODE_AGAIN = C.SDL_SCANCODE_AGAIN // "Again" (the Again key (Redo)) SCANCODE_UNDO = C.SDL_SCANCODE_UNDO // "Undo" SCANCODE_CUT = C.SDL_SCANCODE_CUT // "Cut" SCANCODE_COPY = C.SDL_SCANCODE_COPY // "Copy" SCANCODE_PASTE = C.SDL_SCANCODE_PASTE // "Paste" SCANCODE_FIND = C.SDL_SCANCODE_FIND // "Find" SCANCODE_MUTE = C.SDL_SCANCODE_MUTE // "Mute" SCANCODE_VOLUMEUP = C.SDL_SCANCODE_VOLUMEUP // "VolumeUp" SCANCODE_VOLUMEDOWN = C.SDL_SCANCODE_VOLUMEDOWN // "VolumeDown" SCANCODE_KP_COMMA = C.SDL_SCANCODE_KP_COMMA // "Keypad ," (the Comma key (numeric keypad)) SCANCODE_KP_EQUALSAS400 = C.SDL_SCANCODE_KP_EQUALSAS400 // "Keypad = (AS400)" (the Equals AS400 key (numeric keypad)) SCANCODE_INTERNATIONAL1 = C.SDL_SCANCODE_INTERNATIONAL1 // "" (no name, empty string; used on Asian keyboards, see footnotes in USB doc) SCANCODE_INTERNATIONAL2 = C.SDL_SCANCODE_INTERNATIONAL2 // "" (no name, empty string) SCANCODE_INTERNATIONAL3 = C.SDL_SCANCODE_INTERNATIONAL3 // "" (no name, empty string; Yen) SCANCODE_INTERNATIONAL4 = C.SDL_SCANCODE_INTERNATIONAL4 // "" (no name, empty string) SCANCODE_INTERNATIONAL5 = C.SDL_SCANCODE_INTERNATIONAL5 // "" (no name, empty string) SCANCODE_INTERNATIONAL6 = C.SDL_SCANCODE_INTERNATIONAL6 // "" (no name, empty string) SCANCODE_INTERNATIONAL7 = C.SDL_SCANCODE_INTERNATIONAL7 // "" (no name, empty string) SCANCODE_INTERNATIONAL8 = C.SDL_SCANCODE_INTERNATIONAL8 // "" (no name, empty string) SCANCODE_INTERNATIONAL9 = C.SDL_SCANCODE_INTERNATIONAL9 // "" (no name, empty string) SCANCODE_LANG1 = C.SDL_SCANCODE_LANG1 // "" (no name, empty string; Hangul/English toggle) SCANCODE_LANG2 = C.SDL_SCANCODE_LANG2 // "" (no name, empty string; Hanja conversion) SCANCODE_LANG3 = C.SDL_SCANCODE_LANG3 // "" (no name, empty string; Katakana) SCANCODE_LANG4 = C.SDL_SCANCODE_LANG4 // "" (no name, empty string; Hiragana) SCANCODE_LANG5 = C.SDL_SCANCODE_LANG5 // "" (no name, empty string; Zenkaku/Hankaku) SCANCODE_LANG6 = C.SDL_SCANCODE_LANG6 // "" (no name, empty string; reserved) SCANCODE_LANG7 = C.SDL_SCANCODE_LANG7 // "" (no name, empty string; reserved) SCANCODE_LANG8 = C.SDL_SCANCODE_LANG8 // "" (no name, empty string; reserved) SCANCODE_LANG9 = C.SDL_SCANCODE_LANG9 // "" (no name, empty string; reserved) SCANCODE_ALTERASE = C.SDL_SCANCODE_ALTERASE // "AltErase" (Erase-Eaze) SCANCODE_SYSREQ = C.SDL_SCANCODE_SYSREQ // "SysReq" (the SysReq key) SCANCODE_CANCEL = C.SDL_SCANCODE_CANCEL // "Cancel" SCANCODE_CLEAR = C.SDL_SCANCODE_CLEAR // "Clear" SCANCODE_PRIOR = C.SDL_SCANCODE_PRIOR // "Prior" SCANCODE_RETURN2 = C.SDL_SCANCODE_RETURN2 // "Return" SCANCODE_SEPARATOR = C.SDL_SCANCODE_SEPARATOR // "Separator" SCANCODE_OUT = C.SDL_SCANCODE_OUT // "Out" SCANCODE_OPER = C.SDL_SCANCODE_OPER // "Oper" SCANCODE_CLEARAGAIN = C.SDL_SCANCODE_CLEARAGAIN // "Clear / Again" SCANCODE_CRSEL = C.SDL_SCANCODE_CRSEL // "CrSel" SCANCODE_EXSEL = C.SDL_SCANCODE_EXSEL // "ExSel" SCANCODE_KP_00 = C.SDL_SCANCODE_KP_00 // "Keypad 00" (the 00 key (numeric keypad)) SCANCODE_KP_000 = C.SDL_SCANCODE_KP_000 // "Keypad 000" (the 000 key (numeric keypad)) SCANCODE_THOUSANDSSEPARATOR = C.SDL_SCANCODE_THOUSANDSSEPARATOR // "ThousandsSeparator" (the Thousands Separator key) SCANCODE_DECIMALSEPARATOR = C.SDL_SCANCODE_DECIMALSEPARATOR // "DecimalSeparator" (the Decimal Separator key) SCANCODE_CURRENCYUNIT = C.SDL_SCANCODE_CURRENCYUNIT // "CurrencyUnit" (the Currency Unit key) SCANCODE_CURRENCYSUBUNIT = C.SDL_SCANCODE_CURRENCYSUBUNIT // "CurrencySubUnit" (the Currency Subunit key) SCANCODE_KP_LEFTPAREN = C.SDL_SCANCODE_KP_LEFTPAREN // "Keypad (" (the Left Parenthesis key (numeric keypad)) SCANCODE_KP_RIGHTPAREN = C.SDL_SCANCODE_KP_RIGHTPAREN // "Keypad )" (the Right Parenthesis key (numeric keypad)) SCANCODE_KP_LEFTBRACE = C.SDL_SCANCODE_KP_LEFTBRACE // "Keypad {" (the Left Brace key (numeric keypad)) SCANCODE_KP_RIGHTBRACE = C.SDL_SCANCODE_KP_RIGHTBRACE // "Keypad }" (the Right Brace key (numeric keypad)) SCANCODE_KP_TAB = C.SDL_SCANCODE_KP_TAB // "Keypad Tab" (the Tab key (numeric keypad)) SCANCODE_KP_BACKSPACE = C.SDL_SCANCODE_KP_BACKSPACE // "Keypad Backspace" (the Backspace key (numeric keypad)) SCANCODE_KP_A = C.SDL_SCANCODE_KP_A // "Keypad A" (the A key (numeric keypad)) SCANCODE_KP_B = C.SDL_SCANCODE_KP_B // "Keypad B" (the B key (numeric keypad)) SCANCODE_KP_C = C.SDL_SCANCODE_KP_C // "Keypad C" (the C key (numeric keypad)) SCANCODE_KP_D = C.SDL_SCANCODE_KP_D // "Keypad D" (the D key (numeric keypad)) SCANCODE_KP_E = C.SDL_SCANCODE_KP_E // "Keypad E" (the E key (numeric keypad)) SCANCODE_KP_F = C.SDL_SCANCODE_KP_F // "Keypad F" (the F key (numeric keypad)) SCANCODE_KP_XOR = C.SDL_SCANCODE_KP_XOR // "Keypad XOR" (the XOR key (numeric keypad)) SCANCODE_KP_POWER = C.SDL_SCANCODE_KP_POWER // "Keypad ^" (the Power key (numeric keypad)) SCANCODE_KP_PERCENT = C.SDL_SCANCODE_KP_PERCENT // "Keypad %" (the Percent key (numeric keypad)) SCANCODE_KP_LESS = C.SDL_SCANCODE_KP_LESS // "Keypad <" (the Less key (numeric keypad)) SCANCODE_KP_GREATER = C.SDL_SCANCODE_KP_GREATER // "Keypad >" (the Greater key (numeric keypad)) SCANCODE_KP_AMPERSAND = C.SDL_SCANCODE_KP_AMPERSAND // "Keypad &" (the & key (numeric keypad)) SCANCODE_KP_DBLAMPERSAND = C.SDL_SCANCODE_KP_DBLAMPERSAND // "Keypad &&" (the && key (numeric keypad)) SCANCODE_KP_VERTICALBAR = C.SDL_SCANCODE_KP_VERTICALBAR // "Keypad |" (the | key (numeric keypad)) SCANCODE_KP_DBLVERTICALBAR = C.SDL_SCANCODE_KP_DBLVERTICALBAR // "Keypad ||" (the || key (numeric keypad)) SCANCODE_KP_COLON = C.SDL_SCANCODE_KP_COLON // "Keypad :" (the : key (numeric keypad)) SCANCODE_KP_HASH = C.SDL_SCANCODE_KP_HASH // "Keypad #" (the # key (numeric keypad)) SCANCODE_KP_SPACE = C.SDL_SCANCODE_KP_SPACE // "Keypad Space" (the Space key (numeric keypad)) SCANCODE_KP_AT = C.SDL_SCANCODE_KP_AT // "Keypad @" (the @ key (numeric keypad)) SCANCODE_KP_EXCLAM = C.SDL_SCANCODE_KP_EXCLAM // "Keypad !" (the ! key (numeric keypad)) SCANCODE_KP_MEMSTORE = C.SDL_SCANCODE_KP_MEMSTORE // "Keypad MemStore" (the Mem Store key (numeric keypad)) SCANCODE_KP_MEMRECALL = C.SDL_SCANCODE_KP_MEMRECALL // "Keypad MemRecall" (the Mem Recall key (numeric keypad)) SCANCODE_KP_MEMCLEAR = C.SDL_SCANCODE_KP_MEMCLEAR // "Keypad MemClear" (the Mem Clear key (numeric keypad)) SCANCODE_KP_MEMADD = C.SDL_SCANCODE_KP_MEMADD // "Keypad MemAdd" (the Mem Add key (numeric keypad)) SCANCODE_KP_MEMSUBTRACT = C.SDL_SCANCODE_KP_MEMSUBTRACT // "Keypad MemSubtract" (the Mem Subtract key (numeric keypad)) SCANCODE_KP_MEMMULTIPLY = C.SDL_SCANCODE_KP_MEMMULTIPLY // "Keypad MemMultiply" (the Mem Multiply key (numeric keypad)) SCANCODE_KP_MEMDIVIDE = C.SDL_SCANCODE_KP_MEMDIVIDE // "Keypad MemDivide" (the Mem Divide key (numeric keypad)) SCANCODE_KP_PLUSMINUS = C.SDL_SCANCODE_KP_PLUSMINUS // "Keypad +/-" (the +/- key (numeric keypad)) SCANCODE_KP_CLEAR = C.SDL_SCANCODE_KP_CLEAR // "Keypad Clear" (the Clear key (numeric keypad)) SCANCODE_KP_CLEARENTRY = C.SDL_SCANCODE_KP_CLEARENTRY // "Keypad ClearEntry" (the Clear Entry key (numeric keypad)) SCANCODE_KP_BINARY = C.SDL_SCANCODE_KP_BINARY // "Keypad Binary" (the Binary key (numeric keypad)) SCANCODE_KP_OCTAL = C.SDL_SCANCODE_KP_OCTAL // "Keypad Octal" (the Octal key (numeric keypad)) SCANCODE_KP_DECIMAL = C.SDL_SCANCODE_KP_DECIMAL // "Keypad Decimal" (the Decimal key (numeric keypad)) SCANCODE_KP_HEXADECIMAL = C.SDL_SCANCODE_KP_HEXADECIMAL // "Keypad Hexadecimal" (the Hexadecimal key (numeric keypad)) SCANCODE_LCTRL = C.SDL_SCANCODE_LCTRL // "Left Ctrl" SCANCODE_LSHIFT = C.SDL_SCANCODE_LSHIFT // "Left Shift" SCANCODE_LALT = C.SDL_SCANCODE_LALT // "Left Alt" (alt, option) SCANCODE_LGUI = C.SDL_SCANCODE_LGUI // "Left GUI" (windows, command (apple), meta) SCANCODE_RCTRL = C.SDL_SCANCODE_RCTRL // "Right Ctrl" SCANCODE_RSHIFT = C.SDL_SCANCODE_RSHIFT // "Right Shift" SCANCODE_RALT = C.SDL_SCANCODE_RALT // "Right Alt" (alt gr, option) SCANCODE_RGUI = C.SDL_SCANCODE_RGUI // "Right GUI" (windows, command (apple), meta) SCANCODE_MODE = C.SDL_SCANCODE_MODE // "ModeSwitch" (I'm not sure if this is really not covered by any of the above, but since there's a special KMOD_MODE for it I'm adding it here) SCANCODE_AUDIONEXT = C.SDL_SCANCODE_AUDIONEXT // "AudioNext" (the Next Track media key) SCANCODE_AUDIOPREV = C.SDL_SCANCODE_AUDIOPREV // "AudioPrev" (the Previous Track media key) SCANCODE_AUDIOSTOP = C.SDL_SCANCODE_AUDIOSTOP // "AudioStop" (the Stop media key) SCANCODE_AUDIOPLAY = C.SDL_SCANCODE_AUDIOPLAY // "AudioPlay" (the Play media key) SCANCODE_AUDIOMUTE = C.SDL_SCANCODE_AUDIOMUTE // "AudioMute" (the Mute volume key) SCANCODE_MEDIASELECT = C.SDL_SCANCODE_MEDIASELECT // "MediaSelect" (the Media Select key) SCANCODE_WWW = C.SDL_SCANCODE_WWW // "WWW" (the WWW/World Wide Web key) SCANCODE_MAIL = C.SDL_SCANCODE_MAIL // "Mail" (the Mail/eMail key) SCANCODE_CALCULATOR = C.SDL_SCANCODE_CALCULATOR // "Calculator" (the Calculator key) SCANCODE_COMPUTER = C.SDL_SCANCODE_COMPUTER // "Computer" (the My Computer key) SCANCODE_AC_SEARCH = C.SDL_SCANCODE_AC_SEARCH // "AC Search" (the Search key (application control keypad)) SCANCODE_AC_HOME = C.SDL_SCANCODE_AC_HOME // "AC Home" (the Home key (application control keypad)) SCANCODE_AC_BACK = C.SDL_SCANCODE_AC_BACK // "AC Back" (the Back key (application control keypad)) SCANCODE_AC_FORWARD = C.SDL_SCANCODE_AC_FORWARD // "AC Forward" (the Forward key (application control keypad)) SCANCODE_AC_STOP = C.SDL_SCANCODE_AC_STOP // "AC Stop" (the Stop key (application control keypad)) SCANCODE_AC_REFRESH = C.SDL_SCANCODE_AC_REFRESH // "AC Refresh" (the Refresh key (application control keypad)) SCANCODE_AC_BOOKMARKS = C.SDL_SCANCODE_AC_BOOKMARKS // "AC Bookmarks" (the Bookmarks key (application control keypad)) SCANCODE_BRIGHTNESSDOWN = C.SDL_SCANCODE_BRIGHTNESSDOWN // "BrightnessDown" (the Brightness Down key) SCANCODE_BRIGHTNESSUP = C.SDL_SCANCODE_BRIGHTNESSUP // "BrightnessUp" (the Brightness Up key) SCANCODE_DISPLAYSWITCH = C.SDL_SCANCODE_DISPLAYSWITCH // "DisplaySwitch" (display mirroring/dual display switch, video mode switch) SCANCODE_KBDILLUMTOGGLE = C.SDL_SCANCODE_KBDILLUMTOGGLE // "KBDIllumToggle" (the Keyboard Illumination Toggle key) SCANCODE_KBDILLUMDOWN = C.SDL_SCANCODE_KBDILLUMDOWN // "KBDIllumDown" (the Keyboard Illumination Down key) SCANCODE_KBDILLUMUP = C.SDL_SCANCODE_KBDILLUMUP // "KBDIllumUp" (the Keyboard Illumination Up key) SCANCODE_EJECT = C.SDL_SCANCODE_EJECT // "Eject" (the Eject key) SCANCODE_SLEEP = C.SDL_SCANCODE_SLEEP // "Sleep" (the Sleep key) SCANCODE_APP1 = C.SDL_SCANCODE_APP1 SCANCODE_APP2 = C.SDL_SCANCODE_APP2 NUM_SCANCODES = C.SDL_NUM_SCANCODES ) // Scancode is an SDL keyboard scancode representation. // (https://wiki.libsdl.org/SDL_Scancode) type Scancode uint32 func (code Scancode) c() C.SDL_Scancode { return C.SDL_Scancode(code) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/sdl.go ================================================ // Package sdl 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. SDL2 is a cross-platform development library designed to provide low level access to audio, keyboard, mouse, joystick, and graphics hardware via OpenGL and Direct3D. package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,9)) #if defined(WARN_OUTDATED) #pragma message("SDL_INIT_SENSOR is not supported before SDL 2.0.9") #endif #define SDL_INIT_SENSOR (0x00008000u) #endif */ import "C" import ( "runtime" ) // These are the flags which may be passed to SDL_Init(). // (https://wiki.libsdl.org/SDL_Init) const ( INIT_TIMER = C.SDL_INIT_TIMER // timer subsystem INIT_AUDIO = C.SDL_INIT_AUDIO // audio subsystem INIT_VIDEO = C.SDL_INIT_VIDEO // video subsystem; automatically initializes the events subsystem INIT_JOYSTICK = C.SDL_INIT_JOYSTICK // joystick subsystem; automatically initializes the events subsystem INIT_HAPTIC = C.SDL_INIT_HAPTIC // haptic (force feedback) subsystem INIT_GAMECONTROLLER = C.SDL_INIT_GAMECONTROLLER // controller subsystem; automatically initializes the joystick subsystem INIT_EVENTS = C.SDL_INIT_EVENTS // events subsystem INIT_NOPARACHUTE = C.SDL_INIT_NOPARACHUTE // compatibility; this flag is ignored INIT_SENSOR = C.SDL_INIT_SENSOR // sensor subsystem INIT_EVERYTHING = C.SDL_INIT_EVERYTHING // all of the above subsystems ) const ( RELEASED = 0 PRESSED = 1 ) // Calls a function in the main thread. It is only properly initialized inside // sdl.Main(..). As a default, it panics. It is used by sdl.Do(..) below. var callInMain = func(f func()) { panic("sdl.Main(main func()) must be called before sdl.Do(f func())") } func init() { // Make sure the main goroutine is bound to the main thread. runtime.LockOSThread() } // Main entry point. Run this function at the beginning of main(), and pass your // own main body to it as a function. E.g.: // // func main() { // sdl.Main(func() { // // Your code here.... // // [....] // // // Calls to SDL can be made by any goroutine, but always guarded by sdl.Do() // sdl.Do(func() { // sdl.Init(0) // }) // }) // } // // Avoid calling functions like os.Exit(..) within your passed-in function since // they don't respect deferred calls. Instead, do this: // // func main() { // var exitcode int // sdl.Main(func() { // exitcode = run()) // assuming run has signature func() int // }) // os.Exit(exitcode) // } func Main(main func()) { // Queue of functions that are thread-sensitive callQueue := make(chan func()) // Properly initialize callInMain for use by sdl.Do(..) callInMain = func(f func()) { done := make(chan bool, 1) callQueue <- func() { f() done <- true } <-done } go func() { main() // fmt.Println("END") // to check if os.Exit(..) is called by main() above close(callQueue) }() for f := range callQueue { f() } } // Do the specified function in the main thread. // For this function to work, you must have correctly used sdl.Main(..) in your // main() function. Calling this function before/without sdl.Main(..) will cause // a panic. func Do(f func()) { callInMain(f) } // Init initialize the SDL library. This must be called before using most other SDL functions. // (https://wiki.libsdl.org/SDL_Init) func Init(flags uint32) error { if C.SDL_Init(C.Uint32(flags)) != 0 { return GetError() } return nil } // Quit cleans up all initialized subsystems. You should call it upon all exit conditions. // (https://wiki.libsdl.org/SDL_Quit) func Quit() { C.SDL_Quit() eventFilterCache = nil for k := range eventWatches { delete(eventWatches, k) } } // InitSubSystem initializes specific SDL subsystems. // (https://wiki.libsdl.org/SDL_InitSubSystem) func InitSubSystem(flags uint32) error { if C.SDL_InitSubSystem(C.Uint32(flags)) != 0 { return GetError() } return nil } // QuitSubSystem shuts down specific SDL subsystems. // (https://wiki.libsdl.org/SDL_QuitSubSystem) func QuitSubSystem(flags uint32) { C.SDL_QuitSubSystem(C.Uint32(flags)) } // WasInit returns a mask of the specified subsystems which have previously been initialized. // (https://wiki.libsdl.org/SDL_WasInit) func WasInit(flags uint32) uint32 { return uint32(C.SDL_WasInit(C.Uint32(flags))) } // GetPlatform returns the name of the platform. // (https://wiki.libsdl.org/SDL_GetPlatform) func GetPlatform() string { return string(C.GoString(C.SDL_GetPlatform())) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/sdl_cgo.go ================================================ // +build !static package sdl //#cgo windows LDFLAGS: -lSDL2 //#cgo linux freebsd darwin openbsd pkg-config: sdl2 import "C" ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/sdl_cgo_static.go ================================================ // +build static package sdl //#cgo CFLAGS: -I${SRCDIR}/../_libs/include -I${SRCDIR}/../_libs/include/SDL2 //#cgo LDFLAGS: -L${SRCDIR}/../_libs //#cgo linux,386 LDFLAGS: -lSDL2_linux_386 -lm -ldl -lasound -lm -ldl -lpthread -lX11 -lXext -lXcursor -lXinerama -lXi -lXrandr -lXss -lXxf86vm -lpthread -lrt //#cgo linux,amd64 LDFLAGS: -lSDL2_linux_amd64 -lm -ldl -lasound -lm -ldl -lpthread -lX11 -lXext -lXcursor -lXinerama -lXi -lXrandr -lXss -lXxf86vm -lpthread -lrt //#cgo windows,386 LDFLAGS: -lSDL2_windows_386 -lSDL2main_windows_386 -lm -ldinput8 -ldxguid -ldxerr8 -luser32 -lgdi32 -lwinmm -limm32 -lole32 -loleaut32 -lshell32 -lsetupapi -lversion -luuid -static-libgcc //#cgo windows,amd64 LDFLAGS: -lSDL2_windows_amd64 -lSDL2main_windows_amd64 -lm -ldinput8 -ldxguid -ldxerr8 -luser32 -lgdi32 -lwinmm -limm32 -lole32 -loleaut32 -lshell32 -lversion -luuid -lsetupapi -static-libgcc //#cgo darwin,amd64 LDFLAGS: -lSDL2_darwin_amd64 -lm -liconv -Wl,-framework,OpenGL -Wl,-framework,CoreAudio -Wl,-framework,AudioToolbox -Wl,-framework,ForceFeedback -lobjc -Wl,-framework,CoreVideo -Wl,-framework,Cocoa -Wl,-framework,Carbon -Wl,-framework,IOKit -Wl,-framework,Metal //#cgo darwin,arm64 LDFLAGS: -lSDL2_darwin_arm64 -lm -liconv -Wl,-framework,OpenGL -Wl,-framework,CoreAudio -Wl,-framework,AudioToolbox -Wl,-framework,ForceFeedback -lobjc -Wl,-framework,CoreVideo -Wl,-framework,Cocoa -Wl,-framework,Carbon -Wl,-framework,IOKit -Wl,-framework,Metal //#cgo android,arm LDFLAGS: -lSDL2_android_arm -lm -ldl -llog -landroid -lGLESv2 -lGLESv1_CM //#cgo linux,arm,!android LDFLAGS: -L/opt/vc/lib -L/opt/vc/lib64 -lSDL2_linux_arm -lm -ldl -liconv -lbcm_host -lvcos -lvchiq_arm -pthread import "C" import ( _ "github.com/veandco/go-sdl2/_libs" _ "github.com/veandco/go-sdl2/_libs" ) ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/sdl_wrapper.h ================================================ #if defined(_WIN32) #include #include #else #include #endif #if !defined(SDL_2_0_10) #define SDL_2_0_10 #if !(SDL_VERSION_ATLEAST(2,0,10)) #if defined(WARN_OUTDATED) #pragma message("SDL_FPoint is not supported before SDL 2.0.10") #endif typedef struct SDL_FPoint { float x; float y; } SDL_FPoint; #if defined(WARN_OUTDATED) #pragma message("SDL_FRect is not supported before SDL 2.0.10") #endif typedef struct SDL_FRect { float x; float y; float w; float h; } SDL_FRect; #endif #endif ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/sensor.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,9)) typedef struct _SDL_Sensor SDL_Sensor; typedef Sint32 SDL_SensorID; typedef enum { SDL_SENSOR_INVALID = -1, SDL_SENSOR_UNKNOWN, SDL_SENSOR_ACCEL, SDL_SENSOR_GYRO } SDL_SensorType; #if defined(WARN_OUTDATED) #pragma message("SDL_NumSensors is not supported before SDL 2.0.9") #endif static inline int SDL_NumSensors() { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_SensorGetDeviceName is not supported before SDL 2.0.9") #endif static const char * SDL_SensorGetDeviceName(int device_index) { return NULL; } #if defined(WARN_OUTDATED) #pragma message("SDL_SensorGetDeviceType is not supported before SDL 2.0.9") #endif static SDL_SensorType SDL_SensorGetDeviceType(int device_index) { return SDL_SENSOR_INVALID; } #if defined(WARN_OUTDATED) #pragma message("SDL_SensorGetDeviceNonPortableType is not supported before SDL 2.0.9") #endif static int SDL_SensorGetDeviceNonPortableType(int device_index) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_SensorGetDeviceInstanceID is not supported before SDL 2.0.9") #endif static SDL_SensorID SDL_SensorGetDeviceInstanceID(int device_index) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_SensorOpen is not supported before SDL 2.0.9") #endif static SDL_Sensor * SDL_SensorOpen(int device_index) { return NULL; } #if defined(WARN_OUTDATED) #pragma message("SDL_SensorFromInstanceID is not supported before SDL 2.0.9") #endif static SDL_Sensor * SDL_SensorFromInstanceID(SDL_SensorID instance_id) { return NULL; } #if defined(WARN_OUTDATED) #pragma message("SDL_SensorGetName is not supported before SDL 2.0.9") #endif static const char * SDL_SensorGetName(SDL_Sensor *sensor) { return NULL; } #if defined(WARN_OUTDATED) #pragma message("SDL_SensorGetType is not supported before SDL 2.0.9") #endif static SDL_SensorType SDL_SensorGetType(SDL_Sensor *sensor) { return SDL_SENSOR_INVALID; } #if defined(WARN_OUTDATED) #pragma message("SDL_SensorGetNonPortableType is not supported before SDL 2.0.9") #endif static int SDL_SensorGetNonPortableType(SDL_Sensor *sensor) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_SensorGetInstanceID is not supported before SDL 2.0.9") #endif static SDL_SensorID SDL_SensorGetInstanceID(SDL_Sensor *sensor) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_SensorGetData is not supported before SDL 2.0.9") #endif static int SDL_SensorGetData(SDL_Sensor *sensor, float *data, int num_values) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_SensorClose is not supported before SDL 2.0.9") #endif static void SDL_SensorClose(SDL_Sensor *sensor) { } #if defined(WARN_OUTDATED) #pragma message("SDL_SensorUpdate is not supported before SDL 2.0.9") #endif static void SDL_SensorUpdate() { } #endif */ import "C" import "unsafe" const ( STANDARD_GRAVITY = 9.80665 ) // The different sensors defined by SDL // // Additional sensors may be available, using platform dependent semantics. // // Here are the additional Android sensors: // https://developer.android.com/reference/android/hardware/SensorEvent.html#values const ( SENSOR_INVALID SensorType = C.SDL_SENSOR_INVALID // Returned for an invalid sensor SENSOR_UNKNOWN SensorType = C.SDL_SENSOR_UNKNOWN // Unknown sensor type SENSOR_ACCEL SensorType = C.SDL_SENSOR_ACCEL // Accelerometer SENSOR_GYRO SensorType = C.SDL_SENSOR_GYRO // Gyroscope ) type Sensor C.SDL_Sensor type SensorID int32 type SensorType int // NumSensors counts the number of sensors attached to the system right now // (https://wiki.libsdl.org/SDL_NumSensors) func NumSensors() int { return int(C.SDL_NumSensors()) } // SensorGetDeviceName gets the implementation dependent name of a sensor. // // This can be called before any sensors are opened. // // Returns the sensor name, or empty string if deviceIndex is out of range. // (https://wiki.libsdl.org/SDL_SensorGetDeviceName) func SensorGetDeviceName(deviceIndex int) (name string) { name = C.GoString(C.SDL_SensorGetDeviceName(C.int(deviceIndex))) return } // SensorGetDeviceType gets the type of a sensor. // // This can be called before any sensors are opened. // // Returns the sensor type, or SDL_SENSOR_INVALID if deviceIndex is out of range. // (https://wiki.libsdl.org/SDL_SensorGetDeviceType) func SensorGetDeviceType(deviceIndex int) (typ SensorType) { typ = SensorType(C.SDL_SensorGetDeviceType(C.int(deviceIndex))) return } // SensorGetDeviceNonPortableType gets the platform dependent type of a sensor. // // This can be called before any sensors are opened. // // Returns the sensor platform dependent type, or -1 if deviceIndex is out of range. // (https://wiki.libsdl.org/SDL_SensorGetDeviceNonPortableType) func SensorGetDeviceNonPortableType(deviceIndex int) (typ int) { typ = int(C.SDL_SensorGetDeviceNonPortableType(C.int(deviceIndex))) return } // SensorGetDeviceInstanceID gets the instance ID of a sensor. // // This can be called before any sensors are opened. // // Returns the sensor instance ID, or -1 if deviceIndex is out of range. // (https://wiki.libsdl.org/SDL_SensorGetDeviceInstanceID) func SensorGetDeviceInstanceID(deviceIndex int) (id SensorID) { id = SensorID(C.SDL_SensorGetDeviceInstanceID(C.int(deviceIndex))) return } // SensorOpen opens a sensor for use. // // The index passed as an argument refers to the N'th sensor on the system. // // Returns a sensor identifier, or nil if an error occurred. // (https://wiki.libsdl.org/SDL_SensorOpen) func SensorOpen(deviceIndex int) (sensor *Sensor) { sensor = (*Sensor)(unsafe.Pointer(C.SDL_SensorOpen(C.int(deviceIndex)))) return } // SensorFromInstanceID returns the Sensor associated with an instance id. // (https://wiki.libsdl.org/SDL_SensorFromInstanceID) func SensorFromInstanceID(id SensorID) (sensor *Sensor) { sensor = (*Sensor)(unsafe.Pointer(C.SDL_SensorFromInstanceID(C.SDL_SensorID(id)))) return } // GetName gets the implementation dependent name of a sensor. // // Returns the sensor name, or empty string if the sensor is nil. // (https://wiki.libsdl.org/SDL_SensorGetName) func (sensor *Sensor) GetName() (name string) { name = C.GoString(C.SDL_SensorGetName((*C.SDL_Sensor)(sensor))) return } // GetType gets the type of a sensor. // // This can be called before any sensors are opened. // // Returns the sensor type, or SENSOR_INVALID if the sensor is nil. // (https://wiki.libsdl.org/SDL_SensorGetType) func (sensor *Sensor) GetType() (typ SensorType) { typ = SensorType(C.SDL_SensorGetType((*C.SDL_Sensor)(sensor))) return } // GetNonPortableType gets the platform dependent type of a sensor. // // This can be called before any sensors are opened. // // Returns the sensor platform dependent type, or -1 if the sensor is nil. // (https://wiki.libsdl.org/SDL_SensorGetNonPortableType) func (sensor *Sensor) GetNonPortableType() (typ int) { typ = int(C.SDL_SensorGetNonPortableType((*C.SDL_Sensor)(sensor))) return } // GetInstanceID gets the instance ID of a sensor. // // This can be called before any sensors are opened. // // Returns the sensor instance ID, or -1 if the sensor is nil. // (https://wiki.libsdl.org/SDL_SensorGetInstanceID) func (sensor *Sensor) GetInstanceID() (id SensorID) { id = SensorID(C.SDL_SensorGetInstanceID((*C.SDL_Sensor)(sensor))) return } // GetData gets the current state of an opened sensor. // // The number of values and interpretation of the data is sensor dependent. // (https://wiki.libsdl.org/SDL_SensorGetData) func (sensor *Sensor) GetData(data []float32) (err error) { if data == nil { return nil } _data := (*C.float)(unsafe.Pointer(&data[0])) _numValues := C.int(len(data)) err = errorFromInt(int(C.SDL_SensorGetData((*C.SDL_Sensor)(sensor), _data, _numValues))) return } // Close closes a sensor previously opened with SensorOpen() // (https://wiki.libsdl.org/SDL_SensorClose) func (sensor *Sensor) Close() { C.SDL_SensorClose((*C.SDL_Sensor)(sensor)) } // SensorUpdate updates the current state of the open sensors. // // This is called automatically by the event loop if sensor events are enabled. // // This needs to be called from the thread that initialized the sensor subsystem. // (https://wiki.libsdl.org/SDL_SensorUpdate) func SensorUpdate() { C.SDL_SensorUpdate() } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/shape.go ================================================ package sdl /* #include "sdl_wrapper.h" // until SDL 2.0.6 SDL_shape.h was not included in SDL.h #if !(SDL_VERSION_ATLEAST(2,0,6)) #if defined(_WIN32) #include #else #include #endif #endif */ import "C" import "unsafe" const ( NONSHAPEABLE_WINDOW = C.SDL_NONSHAPEABLE_WINDOW INVALID_SHAPE_ARGUMENT = C.SDL_INVALID_SHAPE_ARGUMENT WINDOW_LACKS_SHAPE = C.SDL_WINDOW_LACKS_SHAPE ) type WindowShapeModeKind C.WindowShapeMode const ( ShapeModeDefaultKind WindowShapeModeKind = C.ShapeModeDefault // the default mode, a binarized alpha cutoff of 1 ShapeModeBinarizeAlphaKind WindowShapeModeKind = C.ShapeModeBinarizeAlpha // a binarized alpha cutoff with a given integer value ShapeModeReverseBinarizeAlphaKind WindowShapeModeKind = C.ShapeModeReverseBinarizeAlpha // a binarized alpha cutoff with a given integer value, but with the opposite comparison ShapeModeColorKeyKind WindowShapeModeKind = C.ShapeModeColorKey // a color key is applied ) func SHAPEMODEALPHA(mode WindowShapeModeKind) bool { return (mode == ShapeModeDefaultKind || mode == ShapeModeBinarizeAlphaKind || mode == ShapeModeReverseBinarizeAlphaKind) } // A union containing parameters for shaped windows // uint8 or Color type cWindowShapeParams C.SDL_WindowShapeParams type cWindowShapeMode struct { mode WindowShapeModeKind parameters cWindowShapeParams } type WindowShapeMode interface { Mode() WindowShapeModeKind cWSM() cWindowShapeMode } type ShapeModeDefault struct{} func (smd ShapeModeDefault) Mode() WindowShapeModeKind { return ShapeModeDefaultKind } func (smd ShapeModeDefault) cWSM() cWindowShapeMode { return cWindowShapeMode{ mode: ShapeModeDefaultKind, parameters: [4]uint8{1, 0, 0, 0}, } } type ShapeModeBinarizeAlpha struct { Cutoff uint8 } func (smba ShapeModeBinarizeAlpha) Mode() WindowShapeModeKind { return ShapeModeBinarizeAlphaKind } func (smba ShapeModeBinarizeAlpha) cWSM() cWindowShapeMode { return cWindowShapeMode{ mode: ShapeModeBinarizeAlphaKind, parameters: [4]uint8{smba.Cutoff, 0, 0, 0}, } } type ShapeModeReverseBinarizeAlpha struct { Cutoff uint8 } func (smba ShapeModeReverseBinarizeAlpha) Mode() WindowShapeModeKind { return ShapeModeReverseBinarizeAlphaKind } func (smba ShapeModeReverseBinarizeAlpha) cWSM() cWindowShapeMode { return cWindowShapeMode{ mode: ShapeModeReverseBinarizeAlphaKind, parameters: [4]uint8{smba.Cutoff, 0, 0, 0}, } } type ShapeModeColorKey struct { Color Color } func (smck ShapeModeColorKey) Mode() WindowShapeModeKind { return ShapeModeColorKeyKind } func (smck ShapeModeColorKey) cWSM() cWindowShapeMode { return cWindowShapeMode{ mode: ShapeModeReverseBinarizeAlphaKind, parameters: [4]uint8{smck.Color.R, smck.Color.G, smck.Color.B, smck.Color.A}, } } func (cwsm cWindowShapeMode) goWSM() WindowShapeMode { switch cwsm.mode { case ShapeModeDefaultKind: return ShapeModeDefault{} case ShapeModeBinarizeAlphaKind: return ShapeModeBinarizeAlpha{ Cutoff: ([4]uint8)(cwsm.parameters)[0], } case ShapeModeReverseBinarizeAlphaKind: return ShapeModeReverseBinarizeAlpha{ Cutoff: ([4]uint8)(cwsm.parameters)[0], } case ShapeModeColorKeyKind: return ShapeModeColorKey{ Color: Color{ R: ([4]uint8)(cwsm.parameters)[0], G: ([4]uint8)(cwsm.parameters)[1], B: ([4]uint8)(cwsm.parameters)[2], A: ([4]uint8)(cwsm.parameters)[3], }, } default: panic("Unknown WindowShapeModeKind") } } func (wsm *cWindowShapeMode) cptr() *C.SDL_WindowShapeMode { return (*C.SDL_WindowShapeMode)(unsafe.Pointer(wsm)) } // CreateShapedWindow creates a window that can be shaped with the specified position, dimensions, and flags // (https://wiki.libsdl.org/SDL_CreateShapedWindow) func CreateShapedWindow(title string, x, y, w, h uint32, flags uint32) (*Window, error) { var _window = C.SDL_CreateShapedWindow(C.CString(title), C.uint(x), C.uint(y), C.uint(w), C.uint(h), C.Uint32(flags)) if _window == nil { return nil, GetError() } return (*Window)(unsafe.Pointer(_window)), nil } // IsShapedWindow returns whether the given window is a shaped window. // (https://wiki.libsdl.org/SDL_IsShapedWindow) func (window *Window) IsShaped() bool { return (C.SDL_IsShapedWindow(window.cptr()) & 1) == 1 } // SetShape sets the shape and parameters of a shaped window // (https://wiki.libsdl.org/SDL_SetWindowShape) func (window *Window) SetShape(shape *Surface, shape_mode WindowShapeMode) int32 { if shape_mode == nil { panic("shape_mode can not be nil") } var _cWSM cWindowShapeMode = shape_mode.cWSM() return (int32)(C.SDL_SetWindowShape(window.cptr(), shape.cptr(), _cWSM.cptr())) } // GetShapeMode gets the shape parameters of a shaped window // (https://wiki.libsdl.org/SDL_GetShapedWindowMode) func (window *Window) GetShapeMode() (WindowShapeMode, int32) { var _cWSM cWindowShapeMode var _resInt32 = (int32)(C.SDL_GetShapedWindowMode(window.cptr(), _cWSM.cptr())) if _resInt32 != 0 { return nil, _resInt32 } return _cWSM.goWSM(), _resInt32 } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/surface.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,9)) #if defined(WARN_OUTDATED) #pragma message("SDL_HasColorKey is not supported before SDL 2.0.9") #endif static SDL_bool SDL_HasColorKey(SDL_Surface * surface) { return SDL_FALSE; } #endif #if !(SDL_VERSION_ATLEAST(2,0,8)) typedef enum { SDL_YUV_CONVERSION_JPEG, SDL_YUV_CONVERSION_BT601, SDL_YUV_CONVERSION_BT709, SDL_YUV_CONVERSION_AUTOMATIC } SDL_YUV_CONVERSION_MODE; #if defined(WARN_OUTDATED) #pragma message("SDL_SetYUVConversionMode is not supported before SDL 2.0.8") #endif void SDL_SetYUVConversionMode(SDL_YUV_CONVERSION_MODE mode) { } #if defined(WARN_OUTDATED) #pragma message("SDL_GetYUVConversionMode is not supported before SDL 2.0.8") #endif SDL_YUV_CONVERSION_MODE SDL_GetYUVConversionMode(void) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_GetYUVConversionModeForResolution is not supported before SDL 2.0.8") #endif SDL_YUV_CONVERSION_MODE SDL_GetYUVConversionModeForResolution(int width, int height) { return -1; } #endif #if !(SDL_VERSION_ATLEAST(2,0,6)) #if defined(WARN_OUTDATED) #pragma message("SDL_DuplicateSurface is not supported before SDL 2.0.6") #endif static inline SDL_Surface* SDL_DuplicateSurface(SDL_Surface *surface) { return NULL; } #endif #if !(SDL_VERSION_ATLEAST(2,0,5)) #if defined(WARN_OUTDATED) #pragma message("SDL_CreateRGBSurfaceWithFormat is not supported before SDL 2.0.5") #endif static inline SDL_Surface* SDL_CreateRGBSurfaceWithFormat(Uint32 flags, int width, int height, int depth, Uint32 format) { return NULL; } #if defined(WARN_OUTDATED) #pragma message("SDL_CreateRGBSurfaceWithFormatFrom is not supported before SDL 2.0.5") #endif static inline SDL_Surface* SDL_CreateRGBSurfaceWithFormatFrom(void* pixels, int width, int height, int depth, int pitch, Uint32 format) { return NULL; } #endif #if !(SDL_VERSION_ATLEAST(2,0,16)) #if defined(WARN_OUTDATED) #pragma message("SDL_SoftStretchLinear is not supported before SDL 2.0.16") #endif static int SDL_SoftStretchLinear(SDL_Surface * src, const SDL_Rect * srcrect, SDL_Surface * dst, const SDL_Rect * dstrect) { return -1; } #endif #if !(SDL_VERSION_ATLEAST(2,0,18)) #if defined(WARN_OUTDATED) #pragma message("SDL_PremultiplyAlpha is not supported before SDL 2.0.18") #endif static int SDL_PremultiplyAlpha(int width, int height, Uint32 src_format, const void * src, int src_pitch, Uint32 dst_format, void * dst, int dst_pitch) { return -1; } #endif */ import "C" import ( "image" "image/color" "reflect" "unsafe" ) // Surface flags (internal use) const ( SWSURFACE = C.SDL_SWSURFACE // just here for compatibility PREALLOC = C.SDL_PREALLOC // surface uses preallocated memory RLEACCEL = C.SDL_RLEACCEL // surface is RLE encoded DONTFREE = C.SDL_DONTFREE // surface is referenced internally ) type YUV_CONVERSION_MODE C.SDL_YUV_CONVERSION_MODE // YUV Conversion Modes const ( YUV_CONVERSION_JPEG YUV_CONVERSION_MODE = C.SDL_YUV_CONVERSION_JPEG // Full range JPEG YUV_CONVERSION_BT601 = C.SDL_YUV_CONVERSION_BT601 // BT.601 (the default) YUV_CONVERSION_BT709 = C.SDL_YUV_CONVERSION_BT709 // BT.709 YUV_CONVERSION_AUTOMATIC = C.SDL_YUV_CONVERSION_AUTOMATIC // BT.601 for SD content, BT.709 for HD content ) // Surface contains a collection of pixels used in software blitting. // (https://wiki.libsdl.org/SDL_Surface) type Surface struct { flags uint32 // (internal use) Format *PixelFormat // the format of the pixels stored in the surface (read-only) (https://wiki.libsdl.org/SDL_PixelFormat) W int32 // the width in pixels (read-only) H int32 // the height in pixels (read-only) Pitch int32 // the length of a row of pixels in bytes (read-only) pixels unsafe.Pointer // the pointer to the actual pixel data; use Pixels() for access UserData unsafe.Pointer // an arbitrary pointer you can set locked int32 // used for surfaces that require locking (internal use) lockData unsafe.Pointer // used for surfaces that require locking (internal use) ClipRect Rect // a Rect structure used to clip blits to the surface which can be set by SetClipRect() (read-only) _ unsafe.Pointer // map; info for fast blit mapping to other surfaces (internal use) RefCount int32 // reference count that can be incremented by the application } type cSurface C.SDL_Surface func (surface *Surface) cptr() *C.SDL_Surface { return (*C.SDL_Surface)(unsafe.Pointer(surface)) } // MustLock reports whether the surface must be locked for access. // (https://wiki.libsdl.org/SDL_MUSTLOCK) func (surface *Surface) MustLock() bool { return (surface.flags & RLEACCEL) != 0 } // CreateRGBSurface allocates a new RGB surface. // (https://wiki.libsdl.org/SDL_CreateRGBSurface) func CreateRGBSurface(flags uint32, width, height, depth int32, Rmask, Gmask, Bmask, Amask uint32) (*Surface, error) { surface := (*Surface)(unsafe.Pointer(C.SDL_CreateRGBSurface( C.Uint32(flags), C.int(width), C.int(height), C.int(depth), C.Uint32(Rmask), C.Uint32(Gmask), C.Uint32(Bmask), C.Uint32(Amask)))) if surface == nil { return nil, GetError() } return surface, nil } // CreateRGBSurfaceFrom allocate a new RGB surface with existing pixel data. // (https://wiki.libsdl.org/SDL_CreateRGBSurfaceFrom) func CreateRGBSurfaceFrom(pixels unsafe.Pointer, width, height int32, depth, pitch int, Rmask, Gmask, Bmask, Amask uint32) (*Surface, error) { surface := (*Surface)(unsafe.Pointer(C.SDL_CreateRGBSurfaceFrom( pixels, C.int(width), C.int(height), C.int(depth), C.int(pitch), C.Uint32(Rmask), C.Uint32(Gmask), C.Uint32(Bmask), C.Uint32(Amask)))) if surface == nil { return nil, GetError() } return surface, nil } // CreateRGBSurfaceWithFormat allocates an RGB surface. // (https://wiki.libsdl.org/SDL_CreateRGBSurfaceWithFormat) func CreateRGBSurfaceWithFormat(flags uint32, width, height, depth int32, format uint32) (*Surface, error) { surface := (*Surface)(unsafe.Pointer(C.SDL_CreateRGBSurfaceWithFormat( C.Uint32(flags), C.int(width), C.int(height), C.int(depth), C.Uint32(format)))) if surface == nil { return nil, GetError() } return surface, nil } // CreateRGBSurfaceWithFormatFrom allocates an RGB surface from provided pixel data. // (https://wiki.libsdl.org/SDL_CreateRGBSurfaceWithFormatFrom) func CreateRGBSurfaceWithFormatFrom(pixels unsafe.Pointer, width, height, depth, pitch int32, format uint32) (*Surface, error) { surface := (*Surface)(unsafe.Pointer(C.SDL_CreateRGBSurfaceWithFormatFrom( pixels, C.int(width), C.int(height), C.int(depth), C.int(pitch), C.Uint32(format)))) if surface == nil { return nil, GetError() } return surface, nil } // SetYUVConversionMode sets the YUV conversion mode // TODO: (https://wiki.libsdl.org/SDL_SetYUVConversionMode) func SetYUVConversionMode(mode YUV_CONVERSION_MODE) { _mode := C.SDL_YUV_CONVERSION_MODE(mode) C.SDL_SetYUVConversionMode(_mode) } // GetYUVConversionMode gets the YUV conversion mode // TODO: (https://wiki.libsdl.org/SDL_GetYUVConversionMode) func GetYUVConversionMode() YUV_CONVERSION_MODE { return YUV_CONVERSION_MODE(C.SDL_GetYUVConversionMode()) } // GetYUVConversionModeForResolution gets the YUV conversion mode // TODO: (https://wiki.libsdl.org/SDL_GetYUVConversionModeForResolution) func GetYUVConversionModeForResolution(width, height int) YUV_CONVERSION_MODE { _width := C.int(width) _height := C.int(height) return YUV_CONVERSION_MODE(C.SDL_GetYUVConversionModeForResolution(_width, _height)) } // Free frees the RGB surface. // (https://wiki.libsdl.org/SDL_FreeSurface) func (surface *Surface) Free() { C.SDL_FreeSurface(surface.cptr()) } // SetPalette sets the palette used by the surface. // (https://wiki.libsdl.org/SDL_SetSurfacePalette) func (surface *Surface) SetPalette(palette *Palette) error { if C.SDL_SetSurfacePalette(surface.cptr(), palette.cptr()) != 0 { return GetError() } return nil } // Lock sets up the surface for directly accessing the pixels. // (https://wiki.libsdl.org/SDL_LockSurface) func (surface *Surface) Lock() error { if C.SDL_LockSurface(surface.cptr()) != 0 { return GetError() } return nil } // Unlock releases the surface after directly accessing the pixels. // (https://wiki.libsdl.org/SDL_UnlockSurface) func (surface *Surface) Unlock() { C.SDL_UnlockSurface(surface.cptr()) } // LoadBMPRW loads a BMP image from a seekable SDL data stream (memory or file). // (https://wiki.libsdl.org/SDL_LoadBMP_RW) func LoadBMPRW(src *RWops, freeSrc bool) (*Surface, error) { surface := (*Surface)(unsafe.Pointer(C.SDL_LoadBMP_RW(src.cptr(), C.int(Btoi(freeSrc))))) if surface == nil { return nil, GetError() } return surface, nil } // LoadBMP loads a surface from a BMP file. // (https://wiki.libsdl.org/SDL_LoadBMP) func LoadBMP(file string) (*Surface, error) { return LoadBMPRW(RWFromFile(file, "rb"), true) } // SaveBMPRW save the surface to a seekable SDL data stream (memory or file) in BMP format. // (https://wiki.libsdl.org/SDL_SaveBMP_RW) func (surface *Surface) SaveBMPRW(dst *RWops, freeDst bool) error { if C.SDL_SaveBMP_RW(surface.cptr(), dst.cptr(), C.int(Btoi(freeDst))) != 0 { return GetError() } return nil } // SaveBMP saves the surface to a BMP file. // (https://wiki.libsdl.org/SDL_SaveBMP) func (surface *Surface) SaveBMP(file string) error { return surface.SaveBMPRW(RWFromFile(file, "wb"), true) } // SetRLE sets the RLE acceleration hint for the surface. // (https://wiki.libsdl.org/SDL_SetSurfaceRLE) func (surface *Surface) SetRLE(flag bool) error { if C.SDL_SetSurfaceRLE(surface.cptr(), C.int(Btoi(flag))) != 0 { return GetError() } return nil } // SetColorKey sets the color key (transparent pixel) in the surface. // (https://wiki.libsdl.org/SDL_SetColorKey) func (surface *Surface) SetColorKey(flag bool, key uint32) error { if C.SDL_SetColorKey(surface.cptr(), C.int(Btoi(flag)), C.Uint32(key)) != 0 { return GetError() } return nil } // HasColorKey returns the color key (transparent pixel) for the surface. // TODO: (https://wiki.libsdl.org/SDL_HasColorKey) func (surface *Surface) HasColorKey() bool { return C.SDL_HasColorKey(surface.cptr()) == C.SDL_TRUE } // GetColorKey returns the color key (transparent pixel) for the surface. // (https://wiki.libsdl.org/SDL_GetColorKey) func (surface *Surface) GetColorKey() (key uint32, err error) { _key := (*C.Uint32)(unsafe.Pointer(&key)) if C.SDL_GetColorKey(surface.cptr(), _key) != 0 { return key, GetError() } return key, nil } // SetColorMod sets an additional color value multiplied into blit operations. // (https://wiki.libsdl.org/SDL_SetSurfaceColorMod) func (surface *Surface) SetColorMod(r, g, b uint8) error { if C.SDL_SetSurfaceColorMod(surface.cptr(), C.Uint8(r), C.Uint8(g), C.Uint8(b)) != 0 { return GetError() } return nil } // GetColorMod returns the additional color value multiplied into blit operations. // (https://wiki.libsdl.org/SDL_GetSurfaceColorMod) func (surface *Surface) GetColorMod() (r, g, b uint8, err error) { _r := (*C.Uint8)(unsafe.Pointer(&r)) _g := (*C.Uint8)(unsafe.Pointer(&g)) _b := (*C.Uint8)(unsafe.Pointer(&b)) if C.SDL_GetSurfaceColorMod(surface.cptr(), _r, _g, _b) != 0 { return r, g, b, GetError() } return r, g, b, nil } // SetAlphaMod sets an additional alpha value used in blit operations. // (https://wiki.libsdl.org/SDL_SetSurfaceAlphaMod) func (surface *Surface) SetAlphaMod(alpha uint8) error { if C.SDL_SetSurfaceAlphaMod(surface.cptr(), C.Uint8(alpha)) != 0 { return GetError() } return nil } // GetAlphaMod returns the additional alpha value used in blit operations. // (https://wiki.libsdl.org/SDL_GetSurfaceAlphaMod) func (surface *Surface) GetAlphaMod() (alpha uint8, err error) { _alpha := (*C.Uint8)(unsafe.Pointer(&alpha)) if C.SDL_GetSurfaceAlphaMod(surface.cptr(), _alpha) != 0 { return alpha, GetError() } return alpha, nil } // SetBlendMode sets the blend mode used for blit operations. // (https://wiki.libsdl.org/SDL_SetSurfaceBlendMode) func (surface *Surface) SetBlendMode(bm BlendMode) error { if C.SDL_SetSurfaceBlendMode(surface.cptr(), bm.c()) != 0 { return GetError() } return nil } // GetBlendMode returns the blend mode used for blit operations. // (https://wiki.libsdl.org/SDL_GetSurfaceBlendMode) func (surface *Surface) GetBlendMode() (bm BlendMode, err error) { if C.SDL_GetSurfaceBlendMode(surface.cptr(), bm.cptr()) != 0 { return bm, GetError() } return bm, nil } // SetClipRect sets the clipping rectangle for the surface // (https://wiki.libsdl.org/SDL_SetClipRect) func (surface *Surface) SetClipRect(rect *Rect) bool { return C.SDL_SetClipRect(surface.cptr(), rect.cptr()) > 0 } // GetClipRect returns the clipping rectangle for a surface. // (https://wiki.libsdl.org/SDL_GetClipRect) func (surface *Surface) GetClipRect(rect *Rect) { C.SDL_GetClipRect(surface.cptr(), rect.cptr()) } // Convert copies the existing surface into a new one that is optimized for blitting to a surface of a specified pixel format. // (https://wiki.libsdl.org/SDL_ConvertSurface) func (surface *Surface) Convert(fmt *PixelFormat, flags uint32) (*Surface, error) { _surface := (*Surface)(unsafe.Pointer(C.SDL_ConvertSurface(surface.cptr(), fmt.cptr(), C.Uint32(flags)))) if _surface == nil { return nil, GetError() } return _surface, nil } // ConvertFormat copies the existing surface to a new surface of the specified format. // (https://wiki.libsdl.org/SDL_ConvertSurfaceFormat) func (surface *Surface) ConvertFormat(pixelFormat uint32, flags uint32) (*Surface, error) { _surface := (*Surface)(unsafe.Pointer(C.SDL_ConvertSurfaceFormat(surface.cptr(), C.Uint32(pixelFormat), C.Uint32(flags)))) if _surface == nil { return nil, GetError() } return _surface, nil } // ConvertPixels copies a block of pixels of one format to another format. // (https://wiki.libsdl.org/SDL_ConvertPixels) func ConvertPixels(width, height int32, srcFormat uint32, src unsafe.Pointer, srcPitch int, dstFormat uint32, dst unsafe.Pointer, dstPitch int) error { if C.SDL_ConvertPixels(C.int(width), C.int(height), C.Uint32(srcFormat), src, C.int(srcPitch), C.Uint32(dstFormat), dst, C.int(dstPitch)) != 0 { return GetError() } return nil } // FillRect performs a fast fill of a rectangle with a specific color. // (https://wiki.libsdl.org/SDL_FillRect) func (surface *Surface) FillRect(rect *Rect, color uint32) error { if C.SDL_FillRect(surface.cptr(), rect.cptr(), C.Uint32(color)) != 0 { return GetError() } return nil } // FillRects performs a fast fill of a set of rectangles with a specific color. // (https://wiki.libsdl.org/SDL_FillRects) func (surface *Surface) FillRects(rects []Rect, color uint32) error { if C.SDL_FillRects(surface.cptr(), rects[0].cptr(), C.int(len(rects)), C.Uint32(color)) != 0 { return GetError() } return nil } // Blit performs a fast surface copy to a destination surface. // (https://wiki.libsdl.org/SDL_BlitSurface) func (surface *Surface) Blit(srcRect *Rect, dst *Surface, dstRect *Rect) error { if C.SDL_BlitSurface(surface.cptr(), srcRect.cptr(), dst.cptr(), dstRect.cptr()) != 0 { return GetError() } return nil } // BlitScaled performs a scaled surface copy to a destination surface. // (https://wiki.libsdl.org/SDL_BlitScaled) func (surface *Surface) BlitScaled(srcRect *Rect, dst *Surface, dstRect *Rect) error { if C.SDL_BlitScaled(surface.cptr(), srcRect.cptr(), dst.cptr(), dstRect.cptr()) != 0 { return GetError() } return nil } // UpperBlit has been replaced by Blit(). // (https://wiki.libsdl.org/SDL_UpperBlit) func (surface *Surface) UpperBlit(srcRect *Rect, dst *Surface, dstRect *Rect) error { if C.SDL_UpperBlit(surface.cptr(), srcRect.cptr(), dst.cptr(), dstRect.cptr()) != 0 { return GetError() } return nil } // LowerBlit performs low-level surface blitting only. // (https://wiki.libsdl.org/SDL_LowerBlit) func (surface *Surface) LowerBlit(srcRect *Rect, dst *Surface, dstRect *Rect) error { if C.SDL_LowerBlit(surface.cptr(), srcRect.cptr(), dst.cptr(), dstRect.cptr()) != 0 { return GetError() } return nil } // SoftStretch has been replaced by BlitScaled(). // (https://wiki.libsdl.org/SDL_SoftStretch) func (surface *Surface) SoftStretch(srcRect *Rect, dst *Surface, dstRect *Rect) error { if C.SDL_SoftStretch(surface.cptr(), srcRect.cptr(), dst.cptr(), dstRect.cptr()) != 0 { return GetError() } return nil } // UpperBlitScaled has been replaced by BlitScaled(). // (https://wiki.libsdl.org/SDL_UpperBlitScaled) func (surface *Surface) UpperBlitScaled(srcRect *Rect, dst *Surface, dstRect *Rect) error { if C.SDL_UpperBlitScaled(surface.cptr(), srcRect.cptr(), dst.cptr(), dstRect.cptr()) != 0 { return GetError() } return nil } // LowerBlitScaled performs low-level surface scaled blitting only. // (https://wiki.libsdl.org/SDL_LowerBlitScaled) func (surface *Surface) LowerBlitScaled(srcRect *Rect, dst *Surface, dstRect *Rect) error { if C.SDL_LowerBlitScaled(surface.cptr(), srcRect.cptr(), dst.cptr(), dstRect.cptr()) != 0 { return GetError() } return nil } // PixelNum returns the number of pixels stored in the surface. func (surface *Surface) PixelNum() int { return int(surface.W * surface.H) } // BytesPerPixel return the number of significant bits in a pixel values of the surface. func (surface *Surface) BytesPerPixel() int { return int(surface.Format.BytesPerPixel) } // Pixels returns the actual pixel data of the surface. func (surface *Surface) Pixels() []byte { var b []byte length := int(surface.H) * int(surface.Pitch) sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b)) sliceHeader.Cap = int(length) sliceHeader.Len = int(length) sliceHeader.Data = uintptr(surface.pixels) return b } // Data returns the pointer to the actual pixel data of the surface. func (surface *Surface) Data() unsafe.Pointer { return surface.pixels } // Duplicate creates a new surface identical to the existing surface func (surface *Surface) Duplicate() (newSurface *Surface, err error) { _newSurface := C.SDL_DuplicateSurface(surface.cptr()) if _newSurface == nil { err = GetError() return } newSurface = (*Surface)(unsafe.Pointer(_newSurface)) return } // ColorModel returns the color model used by this Surface. func (surface *Surface) ColorModel() color.Model { switch surface.Format.Format { case PIXELFORMAT_ARGB8888, PIXELFORMAT_ABGR8888: return color.RGBAModel case PIXELFORMAT_RGB888: return color.RGBAModel case PIXELFORMAT_RGB444: return RGB444Model case PIXELFORMAT_RGB332: return RGB332Model case PIXELFORMAT_RGB555: return RGB555Model case PIXELFORMAT_RGB565: return RGB565Model case PIXELFORMAT_BGR555: return BGR555Model case PIXELFORMAT_BGR565: return BGR565Model case PIXELFORMAT_ARGB4444: return ARGB4444Model case PIXELFORMAT_ABGR4444: return ABGR4444Model case PIXELFORMAT_RGBA4444: return RGBA4444Model case PIXELFORMAT_BGRA4444: return BGRA4444Model case PIXELFORMAT_ARGB1555: return ARGB1555Model case PIXELFORMAT_RGBA5551: return RGBA5551Model case PIXELFORMAT_ABGR1555: return ABGR1555Model case PIXELFORMAT_BGRA5551: return BGRA5551Model case PIXELFORMAT_RGBA8888: return RGBA8888Model case PIXELFORMAT_BGRA8888: return BGRA8888Model default: panic("Not implemented yet") } } // Bounds return the bounds of this surface. Currently, it always starts at // (0,0), but this is not guaranteed in the future so don't rely on it. func (surface *Surface) Bounds() image.Rectangle { return image.Rect(0, 0, int(surface.W), int(surface.H)) } // At returns the pixel color at (x, y) func (surface *Surface) At(x, y int) color.Color { pix := surface.Pixels() i := int32(y)*surface.Pitch + int32(x)*int32(surface.Format.BytesPerPixel) r, g, b, a := GetRGBA(*((*uint32)(unsafe.Pointer(&pix[i]))), surface.Format) return color.NRGBA{R: r, G: g, B: b, A: a} } // Set the color of the pixel at (x, y) using this surface's color format to // convert c to the appropriate byte sequence. This method is required for the // draw.Image interface. The surface may require locking before calling Set. func (surface *Surface) Set(x, y int, c color.Color) { // All sdl2 colors are a subset of NRGBA so it is safe precision-wise to // convert to NRGBA and use the color components from there. nrgbaColor := color.NRGBAModel.Convert(c).(color.NRGBA) colR, colG, colB, colA := nrgbaColor.R, nrgbaColor.G, nrgbaColor.B, nrgbaColor.A pix := surface.Pixels() i := int32(y)*surface.Pitch + int32(x)*int32(surface.Format.BytesPerPixel) switch surface.Format.Format { case PIXELFORMAT_ARGB8888: pix[i+3] = colA pix[i+2] = colR pix[i+1] = colG pix[i+0] = colB case PIXELFORMAT_ABGR8888: pix[i+3] = colA pix[i+2] = colB pix[i+1] = colG pix[i+0] = colR case PIXELFORMAT_RGB24, PIXELFORMAT_RGB888: pix[i+2] = colR pix[i+1] = colG pix[i+0] = colB case PIXELFORMAT_BGR24, PIXELFORMAT_BGR888: pix[i+2] = colB pix[i+1] = colG pix[i+0] = colR case PIXELFORMAT_RGB444: buf := (*uint32)(unsafe.Pointer(&pix[i])) r := uint32(colR) >> 4 & 0x0F g := uint32(colG) >> 4 & 0x0F b := uint32(colB) >> 4 & 0x0F *buf = r<<8 | g<<4 | b case PIXELFORMAT_RGB332: buf := (*uint32)(unsafe.Pointer(&pix[i])) r := uint32(colR) >> 5 & 0x0F g := uint32(colG) >> 5 & 0x0F b := uint32(colB) >> 6 & 0x0F *buf = r<<5 | g<<2 | b case PIXELFORMAT_RGB565: buf := (*uint32)(unsafe.Pointer(&pix[i])) r := uint32(colR) >> 3 & 0xFF g := uint32(colG) >> 2 & 0xFF b := uint32(colB) >> 3 & 0xFF *buf = r<<11 | g<<5 | b case PIXELFORMAT_RGB555: buf := (*uint32)(unsafe.Pointer(&pix[i])) r := uint32(colR) >> 3 & 0xFF g := uint32(colG) >> 3 & 0xFF b := uint32(colB) >> 3 & 0xFF *buf = r<<10 | g<<5 | b case PIXELFORMAT_BGR565: buf := (*uint32)(unsafe.Pointer(&pix[i])) r := uint32(colR) >> 3 & 0xFF g := uint32(colG) >> 2 & 0xFF b := uint32(colB) >> 3 & 0xFF *buf = b<<11 | g<<5 | r case PIXELFORMAT_BGR555: buf := (*uint32)(unsafe.Pointer(&pix[i])) r := uint32(colR) >> 3 & 0xFF g := uint32(colG) >> 3 & 0xFF b := uint32(colB) >> 3 & 0xFF *buf = b<<10 | g<<5 | r case PIXELFORMAT_ARGB4444: buf := (*uint32)(unsafe.Pointer(&pix[i])) a := uint32(colA) >> 4 & 0x0F r := uint32(colR) >> 4 & 0x0F g := uint32(colG) >> 4 & 0x0F b := uint32(colB) >> 4 & 0x0F *buf = a<<12 | r<<8 | g<<4 | b case PIXELFORMAT_ABGR4444: buf := (*uint32)(unsafe.Pointer(&pix[i])) a := uint32(colA) >> 4 & 0x0F r := uint32(colR) >> 4 & 0x0F g := uint32(colG) >> 4 & 0x0F b := uint32(colB) >> 4 & 0x0F *buf = a<<12 | b<<8 | g<<4 | r case PIXELFORMAT_RGBA4444: buf := (*uint32)(unsafe.Pointer(&pix[i])) r := uint32(colR) >> 4 & 0x0F g := uint32(colG) >> 4 & 0x0F b := uint32(colB) >> 4 & 0x0F a := uint32(colA) >> 4 & 0x0F *buf = r<<12 | g<<8 | b<<4 | a case PIXELFORMAT_BGRA4444: buf := (*uint32)(unsafe.Pointer(&pix[i])) r := uint32(colR) >> 4 & 0x0F g := uint32(colG) >> 4 & 0x0F b := uint32(colB) >> 4 & 0x0F a := uint32(colA) >> 4 & 0x0F *buf = b<<12 | g<<8 | r<<4 | a case PIXELFORMAT_ARGB1555: buf := (*uint32)(unsafe.Pointer(&pix[i])) r := uint32(colR) >> 3 & 0xFF g := uint32(colG) >> 3 & 0xFF b := uint32(colB) >> 3 & 0xFF a := uint32(0) if colA > 0 { a = 1 } *buf = a<<15 | r<<10 | g<<5 | b case PIXELFORMAT_RGBA5551: buf := (*uint32)(unsafe.Pointer(&pix[i])) r := uint32(colR) >> 3 & 0xFF g := uint32(colG) >> 3 & 0xFF b := uint32(colB) >> 3 & 0xFF a := uint32(0) if colA > 0 { a = 1 } *buf = r<<11 | g<<6 | b<<1 | a case PIXELFORMAT_ABGR1555: buf := (*uint32)(unsafe.Pointer(&pix[i])) r := uint32(colR) >> 3 & 0xFF g := uint32(colG) >> 3 & 0xFF b := uint32(colB) >> 3 & 0xFF a := uint32(0) if colA > 0 { a = 1 } *buf = a<<15 | b<<10 | g<<5 | r case PIXELFORMAT_BGRA5551: buf := (*uint32)(unsafe.Pointer(&pix[i])) r := uint32(colR) >> 3 & 0xFF g := uint32(colG) >> 3 & 0xFF b := uint32(colB) >> 3 & 0xFF a := uint32(0) if colA > 0 { a = 1 } *buf = b<<11 | g<<6 | r<<1 | a case PIXELFORMAT_RGBA8888: pix[i+3] = colR pix[i+2] = colG pix[i+1] = colB pix[i+0] = colA case PIXELFORMAT_BGRA8888: pix[i+3] = colB pix[i+2] = colG pix[i+1] = colR pix[i+0] = colA default: panic("Unknown pixel format!") } } // SoftStretchLinear performs bilinear scaling between two surfaces of the same format, 32BPP. // (https://wiki.libsdl.org/SDL_SoftStretchLinear) func (surface *Surface) SoftStretchLinear(srcRect *Rect, dst *Surface, dstRect *Rect) (err error) { return errorFromInt(int(C.SDL_SoftStretchLinear(surface.cptr(), srcRect.cptr(), dst.cptr(), dstRect.cptr()))) } // PremultiplyAlpha premultiplies the alpha on a block of pixels. // // This is safe to use with src == dst, but not for other overlapping areas. // // This function is currently only implemented for SDL_PIXELFORMAT_ARGB8888. // // (https://wiki.libsdl.org/SDL_PremultiplyAlpha) func PremultiplyAlpha(width, height int, srcFormat uint32, src []byte, srcPitch int, dstFormat uint32, dst []byte, dstPitch int) (err error) { _width := C.int(width) _height := C.int(height) _srcFormat := C.Uint32(srcFormat) _src := unsafe.Pointer(&src[0]) _srcPitch := C.int(srcPitch) _dstFormat := C.Uint32(dstFormat) _dst := unsafe.Pointer(&dst[0]) _dstPitch := C.int(dstPitch) err = errorFromInt(int(C.SDL_PremultiplyAlpha(_width, _height, _srcFormat, _src, _srcPitch, _dstFormat, _dst, _dstPitch))) return } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/sysrender.go ================================================ package sdl // #include "sdl_wrapper.h" import "C" import "unsafe" // Texture contains an efficient, driver-specific representation of pixel data. // (https://wiki.libsdl.org/SDL_Texture) type Texture C.SDL_Texture // Renderer contains a rendering state. // (https://wiki.libsdl.org/SDL_Renderer) type Renderer C.SDL_Renderer func (t *Texture) cptr() *C.SDL_Texture { return (*C.SDL_Texture)(unsafe.Pointer(t)) } func (r *Renderer) cptr() *C.SDL_Renderer { return (*C.SDL_Renderer)(unsafe.Pointer(r)) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/system.c ================================================ #include "_cgo_export.h" #include "system.h" #if defined(_WIN32) void SetWindowsMessageHook() { SDL_SetWindowsMessageHook((SDL_WindowsMessageHook) goWindowsMessageHook, NULL); } #endif ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/system.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,9)) #if defined(WARN_OUTDATED) #pragma message("SDL_IsTablet is not supported before SDL 2.0.9") #endif static inline SDL_bool SDL_IsTablet() { return SDL_FALSE; } #endif */ import "C" // IsTablet returns true if the current device is a tablet // TODO: (https://wiki.libsdl.org/SDL_IsTablet) func IsTablet() bool { return C.SDL_IsTablet() == C.SDL_TRUE } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/system.h ================================================ #ifndef _GO_SDL_SYSTEM_H #define _GO_SDL_SYSTEM_H #if defined(_WIN32) extern void SetWindowsMessageHook(); #endif #endif ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/system_android.go ================================================ // +build go1.4 package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,8)) #if defined(WARN_OUTDATED) #pragma message("SDL_IsAndroidTV is not supported before SDL 2.0.8") #endif static int SDL_IsAndroidTV(void) { return -1; } #endif #if !(SDL_VERSION_ATLEAST(2,0,16)) #if defined(WARN_OUTDATED) #pragma message("SDL_AndroidShowToast is not supported before SDL 2.0.16") #endif static int SDL_AndroidShowToast(const char* message, int duration, int gravity, int xoffset, int yoffset) { return -1; } #endif */ import "C" import "unsafe" // External storage states. See the official Android developer guide for more information. // (http://developer.android.com/guide/topics/data/data-storage.html) const ( ANDROID_EXTERNAL_STORAGE_READ = C.SDL_ANDROID_EXTERNAL_STORAGE_READ ANDROID_EXTERNAL_STORAGE_WRITE = C.SDL_ANDROID_EXTERNAL_STORAGE_WRITE ) // AndroidGetInternalStoragePath returns the path used for internal storage for this application. // (https://wiki.libsdl.org/SDL_AndroidGetInternalStoragePath) func AndroidGetInternalStoragePath() string { return C.GoString(C.SDL_AndroidGetInternalStoragePath()) } // AndroidGetExternalStoragePath returns the path used for external storage for this application. // (https://wiki.libsdl.org/SDL_AndroidGetExternalStoragePath) func AndroidGetExternalStoragePath() string { return C.GoString(C.SDL_AndroidGetExternalStoragePath()) } // AndroidGetExternalStorageState returns the current state of external storage. // (https://wiki.libsdl.org/SDL_AndroidGetExternalStorageState) func AndroidGetExternalStorageState() int { return int(C.SDL_AndroidGetExternalStorageState()) } // AndroidGetJNIEnv returns the Java native interface object (JNIEnv) of the current thread on Android builds. // (https://wiki.libsdl.org/SDL_AndroidGetJNIEnv) func AndroidGetJNIEnv() unsafe.Pointer { return unsafe.Pointer(C.SDL_AndroidGetJNIEnv()) } // AndroidGetActivity returns the Java instance of the activity class in an Android application. // (https://wiki.libsdl.org/SDL_AndroidGetActivity) func AndroidGetActivity() unsafe.Pointer { return unsafe.Pointer(C.SDL_AndroidGetActivity()) } // IsAndroidTV returns true if the application is running on Android TV // (https://wiki.libsdl.org/SDL_IsAndroidTV) func IsAndroidTV() bool { return C.SDL_IsAndroidTV() >= 0 } // AndroidShowToast shows an Android toast notification. // (https://wiki.libsdl.org/SDL_AndroidShowToast) func AndroidShowToast(message string, duration, gravity, xoffset, yoffset int) (err error) { _message := C.CString(message) defer C.free(unsafe.Pointer(_message)) return errorFromInt(int(C.SDL_AndroidShowToast(_message, C.int(duration), C.int(gravity), C.int(xoffset), C.int(yoffset)))) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/system_linux.go ================================================ // +build !android package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,9)) #if defined(WARN_OUTDATED) #pragma message("SDL_LinuxSetThreadPriority is not supported before SDL 2.0.9") #endif static int SDL_LinuxSetThreadPriority(Sint64 threadID, int priority) { return -1; } #endif #if !(SDL_VERSION_ATLEAST(2,0,18)) #if defined(WARN_OUTDATED) #pragma message("SDL_LinuxSetThreadPriorityAndPolicy is not supported before SDL 2.0.18") #endif static int SDL_LinuxSetThreadPriorityAndPolicy(Sint64 threadID, int sdlPriority, int schedPolicy) { return -1; } #endif */ import "C" // LinuxSetThreadPriority sets the UNIX nice value for a thread. // // This uses setpriority() if possible, and RealtimeKit if available. // // (https://wiki.libsdl.org/SDL_LinuxSetThreadPriority) func LinuxSetThreadPriority(threadID int64, priority int) (err error) { _threadID := C.Sint64(threadID) _priority := C.int(priority) return errorFromInt(int(C.SDL_LinuxSetThreadPriority(_threadID, _priority))) } // LinuxSetThreadPriority sets the priority (not nice level) and scheduling policy for a thread. // // This uses setpriority() if possible, and RealtimeKit if available. // // (https://wiki.libsdl.org/SDL_LinuxSetThreadPriorityAndPolicy) func LinuxSetThreadPriorityAndPolicy(threadID int64, sdlPriority, schedPolicy int) (err error) { _threadID := C.Sint64(threadID) _sdlPriority := C.int(sdlPriority) _schedPolicy := C.int(schedPolicy) return errorFromInt(int(C.SDL_LinuxSetThreadPriorityAndPolicy(_threadID, _sdlPriority, _schedPolicy))) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/system_windows.go ================================================ package sdl /* #include "sdl_wrapper.h" #include "system.h" #if !(SDL_VERSION_ATLEAST(2,0,16)) #if defined(WARN_OUTDATED) #pragma message("SDL_RenderGetD3D11Device is not supported before SDL 2.0.16") #endif typedef struct ID3D11Device ID3D11Device; static ID3D11Device* SDL_RenderGetD3D11Device(SDL_Renderer * renderer) { return NULL; } #endif */ import "C" import ( "unsafe" ) type WindowsMessageHook func(userdata interface{}, hWnd unsafe.Pointer, message uint32, wParam uint64, lParam int64) var windowsMessageHook WindowsMessageHook type ID3D11Device C.ID3D11Device; // SetWindowsMessageHook sets a callback for every Windows message, run before TranslateMessage(). // (https://wiki.libsdl.org/SDL_SetWindowsMessageHook) func SetWindowsMessageHook(callback WindowsMessageHook, userdata interface{}) { windowsMessageHook = callback C.SetWindowsMessageHook() } //export goWindowsMessageHook func goWindowsMessageHook(userdata interface{}, hWnd unsafe.Pointer, message uint32, wParam uint64, lParam int64) { if windowsMessageHook == nil { return } windowsMessageHook(userdata, hWnd, message, wParam, lParam) } // SDL_RenderGetD3D11Device gets the D3D11 device associated with a renderer. // (https://wiki.libsdl.org/SDL_RenderGetD3D11Device) func (renderer *Renderer) GetD3D11Device() (device *ID3D11Device, err error) { device = (*ID3D11Device)(C.SDL_RenderGetD3D11Device(renderer.cptr())) if device == nil { err = GetError() } return } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/syswm.go ================================================ package sdl /* #include "sdl_wrapper.h" #if defined(__WIN32) #include #else #include #endif #if !(SDL_VERSION_ATLEAST(2,0,2)) #define SDL_SYSWM_WAYLAND SDL_SYSWM_UNKNOWN #define SDL_SYSWM_MIR SDL_SYSWM_UNKNOWN #endif #if !(SDL_VERSION_ATLEAST(2,0,3)) #if defined(WARN_OUTDATED) #pragma message("SDL_SYSWM_WINRT is not supported before SDL 2.0.3") #endif #define SDL_SYSWM_WINRT (0) #endif #if !(SDL_VERSION_ATLEAST(2,0,4)) #if defined(WARN_OUTDATED) #pragma message("SDL_SYSWM_ANDROID is not supported before SDL 2.0.4") #endif #define SDL_SYSWM_ANDROID (0) #endif #if !(SDL_VERSION_ATLEAST(2,0,5)) #if defined(WARN_OUTDATED) #pragma message("SDL_SYSWM_VIVANTE is not supported before SDL 2.0.5") #endif #define SDL_SYSWM_VIVANTE (0) #endif */ import "C" import "unsafe" // Various supported windowing subsystems. const ( SYSWM_UNKNOWN = C.SDL_SYSWM_UNKNOWN SYSWM_WINDOWS = C.SDL_SYSWM_WINDOWS // Microsoft Windows SYSWM_X11 = C.SDL_SYSWM_X11 // X Window System SYSWM_DIRECTFB = C.SDL_SYSWM_DIRECTFB // DirectFB SYSWM_COCOA = C.SDL_SYSWM_COCOA // Apple Mac OS X SYSWM_UIKIT = C.SDL_SYSWM_UIKIT // Apple iOS SYSWM_WAYLAND = C.SDL_SYSWM_WAYLAND // Wayland (>= SDL 2.0.2) SYSWM_MIR = C.SDL_SYSWM_MIR // Mir (>= SDL 2.0.2) SYSWM_WINRT = C.SDL_SYSWM_WINRT // WinRT (>= SDL 2.0.3) SYSWM_ANDROID = C.SDL_SYSWM_ANDROID // Android (>= SDL 2.0.4) SYSWM_VIVANTE = C.SDL_SYSWM_VIVANTE // Vivante (>= SDL 2.0.5) ) // SysWMInfo contains system-dependent information about a window. // (https://wiki.libsdl.org/SDL_SysWMinfo) type SysWMInfo struct { Version Version // a Version structure that contains the current SDL version Subsystem uint32 // the windowing system type dummy [24]byte // unused (to help compilers when no specific system is available) } // WindowsInfo contains Microsoft Windows window information. type WindowsInfo struct { Window unsafe.Pointer // the window handle DeviceContext unsafe.Pointer // the device context handle Instance unsafe.Pointer // the instance handle } // X11Info contains X Window System window information. type X11Info struct { Display unsafe.Pointer // the X11 display Window uint // the X11 window } // DFBInfo contains DirectFB window information. type DFBInfo struct { Dfb unsafe.Pointer // the DirectFB main interface Window unsafe.Pointer // the DirectFB window handle Surface unsafe.Pointer // the DirectFB client surface } // CocoaInfo contains Apple Mac OS X window information. type CocoaInfo struct { Window unsafe.Pointer // the Cocoa window } // UIKitInfo contains Apple iOS window information. type UIKitInfo struct { Window unsafe.Pointer // the UIKit window } // SysWMmsg contains system-dependent window manager messages. // (https://wiki.libsdl.org/SDL_SysWMmsg) type SysWMmsg struct { Version Version // a Version structure that contains the current SDL version Subsystem uint32 // the windowing system type data [24]byte // internal data } func (info *SysWMInfo) cptr() *C.SDL_SysWMinfo { return (*C.SDL_SysWMinfo)(unsafe.Pointer(info)) } // GetWMInfo returns driver specific information about a window. // (https://wiki.libsdl.org/SDL_GetWindowWMInfo) func (window *Window) GetWMInfo() (*SysWMInfo, error) { var info SysWMInfo VERSION(&info.Version) if C.SDL_GetWindowWMInfo(window.cptr(), info.cptr()) == 0 { return nil, GetError() } return &info, nil } // GetWindowsInfo returns Microsoft Windows window information. func (info *SysWMInfo) GetWindowsInfo() *WindowsInfo { return (*WindowsInfo)(unsafe.Pointer(&info.dummy[0])) } // GetX11Info returns X Window System window information. func (info *SysWMInfo) GetX11Info() *X11Info { return (*X11Info)(unsafe.Pointer(&info.dummy[0])) } // GetDFBInfo returns DirectFB window information. func (info *SysWMInfo) GetDFBInfo() *DFBInfo { return (*DFBInfo)(unsafe.Pointer(&info.dummy[0])) } // GetCocoaInfo returns Apple Mac OS X window information. func (info *SysWMInfo) GetCocoaInfo() *CocoaInfo { return (*CocoaInfo)(unsafe.Pointer(&info.dummy[0])) } // GetUIKitInfo returns Apple iOS window information. func (info *SysWMInfo) GetUIKitInfo() *UIKitInfo { return (*UIKitInfo)(unsafe.Pointer(&info.dummy[0])) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/syswm_cocoa.go ================================================ // +build cocoa OR darwin package sdl import "C" import "unsafe" // CocoaMsg contains Apple Mac OS X window information. type CocoaMsg struct { dummy C.int } // Cocoa() returns Apple Mac OS X message. func (msg *SysWMmsg) Cocoa() *CocoaMsg { return (*CocoaMsg)(unsafe.Pointer(&msg.data[0])) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/syswm_dfb.go ================================================ // +build dfb package sdl import "C" import "unsafe" // DFBMsg contains DirectFB window information. type DFBMsg struct { Event C.DFBEvent } // DFB() returns DirectFB message. func (msg *SysWMmsg) DFB() *DFBMsg { return (*DFBMsg)(unsafe.Pointer(&msg.data[0])) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/syswm_uikit.go ================================================ // +build uikit package sdl import "C" import "unsafe" // UIKitMsg contains Apple iOS window information. type UIKitMsg struct { dummy C.int } // UIKit() returns Apple iOS message. func (msg *SysWMmsg) UIKit() *UIKitMsg { return (*UIKitMsg)(unsafe.Pointer(&msg.data[0])) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/syswm_vivante.go ================================================ // +build vivante package sdl import "C" import "unsafe" // VivanteKitMsg contains Vivante window information. type VivanteKitMsg struct { dummy C.int } // Vivante() returns Vivante message. func (msg *SysWMmsg) Vivante() *VivanteMsg { return (*VivanteMsg)(unsafe.Pointer(&msg.data[0])) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/syswm_windows.go ================================================ // +build windows package sdl /* #include */ import "C" import "unsafe" // WindowsMsg contains Microsoft Windows window information. type WindowsMsg struct { Hwnd C.HWND Msg C.UINT WParam C.WPARAM LParam C.LPARAM } // Windows() returns Microsoft Windows message. func (msg *SysWMmsg) Windows() *WindowsMsg { return (*WindowsMsg)(unsafe.Pointer(&msg.data[0])) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/syswm_x11.go ================================================ // +build x11 package sdl /* #include */ import "C" import "unsafe" // X11Msg contains X Window System window information. type X11Msg struct { Event C.XEvent } // X11() returns X Window System message. func (msg *SysWMmsg) X11() *X11Msg { return (*X11Msg)(unsafe.Pointer(&msg.data[0])) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/thread.go ================================================ package sdl // #include "sdl_wrapper.h" import "C" // CurrentThreadID gets the thread identifier for the current thread. // (https://wiki.libsdl.org/SDL_ThreadID) func CurrentThreadID() uint { return uint(C.SDL_ThreadID()) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/timer.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,18)) #if defined(WARN_OUTDATED) #pragma message("SDL_GetTicks64 is not supported before SDL 2.0.18") #endif static inline Uint64 SDLCALL SDL_GetTicks64(void) { return 0; } #endif */ import "C" // GetTicks returns the number of milliseconds since the SDL library initialization. // // Deprecated: This function is not recommended as of SDL 2.0.18; use GetTicks64() // instead, where the value doesn't wrap every ~49 days. There are places in // SDL where we provide a 32-bit timestamp that can not change without // breaking binary compatibility, though, so this function isn't officially // deprecated. // // (https://wiki.libsdl.org/SDL_GetTicks) func GetTicks() uint32 { return uint32(C.SDL_GetTicks()) } // GetTicks64 returns the number of milliseconds since the SDL library initialization. // (https://wiki.libsdl.org/SDL_GetTicks64) func GetTicks64() uint64 { return uint64(C.SDL_GetTicks64()) } // GetPerformanceCounter returns the current value of the high resolution counter. // (https://wiki.libsdl.org/SDL_GetPerformanceCounter) func GetPerformanceCounter() uint64 { return uint64(C.SDL_GetPerformanceCounter()) } // GetPerformanceFrequency returns the count per second of the high resolution counter. // (https://wiki.libsdl.org/SDL_GetPerformanceFrequency) func GetPerformanceFrequency() uint64 { return uint64(C.SDL_GetPerformanceFrequency()) } // Delay waits a specified number of milliseconds before returning. // (https://wiki.libsdl.org/SDL_Delay) func Delay(ms uint32) { C.SDL_Delay(C.Uint32(ms)) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/touch.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,10)) typedef enum { SDL_TOUCH_DEVICE_INVALID = -1, SDL_TOUCH_DEVICE_DIRECT, // touch screen with window-relative coordinates SDL_TOUCH_DEVICE_INDIRECT_ABSOLUTE, // trackpad with absolute device coordinates SDL_TOUCH_DEVICE_INDIRECT_RELATIVE // trackpad with screen cursor-relative coordinates } SDL_TouchDeviceType; #if defined(WARN_OUTDATED) #pragma message("SDL_GetTouchDeviceType is not supported before SDL 2.0.10") #endif static inline SDL_TouchDeviceType SDL_GetTouchDeviceType(SDL_TouchID touchID) { return SDL_TOUCH_DEVICE_INVALID; } #endif */ import "C" import "unsafe" // TOUCH_MOUSEID is the device ID for mouse events simulated with touch input const TOUCH_MOUSEID = C.SDL_TOUCH_MOUSEID // TouchID is the ID of a touch device. type TouchID C.SDL_TouchID // FingerID is a finger id. type FingerID C.SDL_FingerID // TouchDeviceType is a touch device type. type TouchDeviceType C.SDL_TouchDeviceType const ( TOUCH_DEVICE_INVALID TouchDeviceType = C.SDL_TOUCH_DEVICE_INVALID TOUCH_DEVICE_DIRECT = C.SDL_TOUCH_DEVICE_DIRECT // touch screen with window-relative coordinates TOUCH_DEVICE_INDIRECT_ABSOLUTE = C.SDL_TOUCH_DEVICE_INDIRECT_ABSOLUTE // trackpad with absolute device coordinates TOUCH_DEVICE_INDIRECT_RELATIVE = C.SDL_TOUCH_DEVICE_INDIRECT_RELATIVE // trackpad with screen cursor-relative coordinates ) // Finger contains touch information. type Finger struct { ID FingerID // the finger id X float32 // the x-axis location of the touch event, normalized (0...1) Y float32 // the y-axis location of the touch event, normalized (0...1) Pressure float32 // the quantity of pressure applied, normalized (0...1) } func (t TouchID) c() C.SDL_TouchID { return C.SDL_TouchID(t) } // GetNumTouchDevices returns the number of registered touch devices. // (https://wiki.libsdl.org/SDL_GetNumTouchDevices) func GetNumTouchDevices() int { return int(C.SDL_GetNumTouchDevices()) } // GetTouchDevice returns the touch ID with the given index. // (https://wiki.libsdl.org/SDL_GetTouchDevice) func GetTouchDevice(index int) TouchID { return TouchID(C.SDL_GetTouchDevice(C.int(index))) } // GetTouchDeviceType returns the type of the given touch device. // TODO: (https://wiki.libsdl.org/SDL_GetTouchDeviceType) func GetTouchDeviceType(id TouchID) TouchDeviceType { return TouchDeviceType(C.SDL_GetTouchDeviceType(C.SDL_TouchID(id))) } // GetNumTouchFingers returns the number of active fingers for a given touch device. // (https://wiki.libsdl.org/SDL_GetNumTouchFingers) func GetNumTouchFingers(t TouchID) int { return int(C.SDL_GetNumTouchFingers(t.c())) } // GetTouchFinger returns the finger object for specified touch device ID and finger index. // (https://wiki.libsdl.org/SDL_GetTouchFinger) func GetTouchFinger(t TouchID, index int) *Finger { return (*Finger)(unsafe.Pointer(C.SDL_GetTouchFinger(t.c(), C.int(index)))) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/version.go ================================================ package sdl /* #include "sdl_wrapper.h" #if SDL_VERSION_ATLEAST(2,0,16) static inline int GetRevisionNumber(void) { return 0; } #else static inline int GetRevisionNumber(void) { return SDL_GetRevisionNumber(); } #endif */ import "C" import "unsafe" // The version of SDL in use. const ( MAJOR_VERSION = C.SDL_MAJOR_VERSION // major version MINOR_VERSION = C.SDL_MINOR_VERSION // minor version PATCHLEVEL = C.SDL_PATCHLEVEL // update version (patchlevel) ) // Version contains information about the version of SDL in use. // (https://wiki.libsdl.org/SDL_version) type Version struct { Major uint8 // major version Minor uint8 // minor version Patch uint8 // update version (patchlevel) } type cVersion C.SDL_version func (v *Version) cptr() *C.SDL_version { return (*C.SDL_version)(unsafe.Pointer(v)) } // VERSION fills the selected struct with the version of SDL in use. // (https://wiki.libsdl.org/SDL_VERSION) func VERSION(v *Version) { v.Major = MAJOR_VERSION v.Minor = MINOR_VERSION v.Patch = PATCHLEVEL } // VERSIONNUM converts separate version components into a single numeric value. // (https://wiki.libsdl.org/SDL_VERSIONNUM) func VERSIONNUM(x, y, z int) int { return (x*1000 + y*100 + z) } // COMPILEDVERSION returns the SDL version number that you compiled against. // (https://wiki.libsdl.org/SDL_COMPILEDVERSION) func COMPILEDVERSION() int { return VERSIONNUM(MAJOR_VERSION, MINOR_VERSION, PATCHLEVEL) } // VERSION_ATLEAST reports whether the SDL version compiled against is at least as new as the specified version. // (https://wiki.libsdl.org/SDL_VERSION_ATLEAST) func VERSION_ATLEAST(x, y, z int) bool { return COMPILEDVERSION() >= VERSIONNUM(x, y, z) } // GetVersion returns the version of SDL that is linked against your program. // (https://wiki.libsdl.org/SDL_GetVersion) func GetVersion(v *Version) { C.SDL_GetVersion(v.cptr()) } // GetRevision returns the code revision of SDL that is linked against your program. // (https://wiki.libsdl.org/SDL_GetRevision) func GetRevision() string { return (string)(C.GoString(C.SDL_GetRevision())) } // Deprecated: GetRevisionNumber is deprecated in SDL2 2.0.16 and will return 0. Users should use GetRevision instead. func GetRevisionNumber() int { return (int)(C.GetRevisionNumber()) } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/video.go ================================================ package sdl /* #include "sdl_wrapper.h" static inline Sint32 ShowMessageBox(SDL_MessageBoxData data) { Sint32 buttonid; SDL_ShowMessageBox(&data, &buttonid); return buttonid; } #if !(SDL_VERSION_ATLEAST(2,0,1)) static void SDL_GL_GetDrawableSize(SDL_Window *window, int *w, int *h) { *w = 0; *h = 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_WINDOW_ALLOW_HIGHDPI is not supported before SDL 2.0.1") #endif #define SDL_WINDOW_ALLOW_HIGHDPI (0) #if defined(WARN_OUTDATED) #pragma message("SDL_GL_FRAMEBUFFER_SRGB_CAPABLE is not supported before SDL 2.0.1") #endif #define SDL_GL_FRAMEBUFFER_SRGB_CAPABLE (0) #endif #if !(SDL_VERSION_ATLEAST(2,0,4)) #if defined(WARN_OUTDATED) #pragma message("SDL_WINDOW_MOUSE_CAPTURE is not supported before SDL 2.0.4") #endif #define SDL_WINDOW_MOUSE_CAPTURE (0) #if defined(WARN_OUTDATED) #pragma message("SDL_GL_CONTEXT_RELEASE_BEHAVIOR is not supported before SDL 2.0.4") #endif #define SDL_GL_CONTEXT_RELEASE_BEHAVIOR (0) #if defined(WARN_OUTDATED) #pragma message("SDL_GetDisplayDPI is not supported before SDL 2.0.4") #endif static int SDL_GetDisplayDPI(int displayIndex, float* ddpi, float* hdpi, float* vdpi) { return -1; } #endif #if !(SDL_VERSION_ATLEAST(2,0,5)) #if defined(WARN_OUTDATED) #pragma message("SDL_SetWindowResizable is not supported before SDL 2.0.5") #endif static void SDL_SetWindowResizable(SDL_Window *window, SDL_bool resizable) { } #if defined(WARN_OUTDATED) #pragma message("SDL_SetWindowOpacity is not supported before SDL 2.0.5") #endif static int SDL_SetWindowOpacity(SDL_Window *window, float opacity) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_GetWindowOpacity is not supported before SDL 2.0.5") #endif static int SDL_GetWindowOpacity(SDL_Window *window, float *opacity) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_GetDisplayUsableBounds is not supported before SDL 2.0.5") #endif static int SDL_GetDisplayUsableBounds(int displayIndex, SDL_Rect* rect) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_WINDOW_ALWAYS_ON_TOP is not supported before SDL 2.0.5") #endif #define SDL_WINDOW_ALWAYS_ON_TOP (0) #if defined(WARN_OUTDATED) #pragma message("SDL_WINDOW_SKIP_TASKBAR is not supported before SDL 2.0.5") #endif #define SDL_WINDOW_SKIP_TASKBAR (0) #if defined(WARN_OUTDATED) #pragma message("SDL_WINDOW_UTILITY is not supported before SDL 2.0.5") #endif #define SDL_WINDOW_UTILITY (0) #if defined(WARN_OUTDATED) #pragma message("SDL_WINDOW_TOOLTIP is not supported before SDL 2.0.5") #endif #define SDL_WINDOW_TOOLTIP (0) #if defined(WARN_OUTDATED) #pragma message("SDL_WINDOW_POPUP_MENU is not supported before SDL 2.0.5") #endif #define SDL_WINDOW_POPUP_MENU (0) #if defined(WARN_OUTDATED) #pragma message("SDL_WINDOWEVENT_TAKE_FOCUS is not supported before SDL 2.0.5") #endif #define SDL_WINDOWEVENT_TAKE_FOCUS (0) #if defined(WARN_OUTDATED) #pragma message("SDL_WINDOWEVENT_HIT_TEST is not supported before SDL 2.0.5") #endif #define SDL_WINDOWEVENT_HIT_TEST (0) #endif #if !(SDL_VERSION_ATLEAST(2,0,6)) #if defined(WARN_OUTDATED) #pragma message("SDL_WINDOW_VULKAN is not supported before SDL 2.0.6") #endif #define SDL_WINDOW_VULKAN (0) #if defined(WARN_OUTDATED) #pragma message("SDL_GL_CONTEXT_RESET_NOTIFICATION is not supported before SDL 2.0.6") #endif #define SDL_GL_CONTEXT_RESET_NOTIFICATION (0) #if defined(WARN_OUTDATED) #pragma message("SDL_GL_CONTEXT_NO_ERROR is not supported before SDL 2.0.6") #endif #define SDL_GL_CONTEXT_NO_ERROR (0) #endif #if !(SDL_VERSION_ATLEAST(2,0,16)) #if defined(WARN_OUTDATED) #pragma message("SDL_FlashWindow is not supported before SDL 2.0.16") #pragma message("SDL_SetWindowAlwaysOnTop is not supported before SDL 2.0.16") #pragma message("SDL_SetWindowKeyboardGrab is not supported before SDL 2.0.16") #endif typedef enum { SDL_FLASH_CANCEL, // Cancel any window flash state SDL_FLASH_BRIEFLY, // Flash the window briefly to get attention SDL_FLASH_UNTIL_FOCUSED, // Flash the window until it gets focus } SDL_FlashOperation; static int SDL_FlashWindow(SDL_Window * window, SDL_FlashOperation operation) { return -1; } static void SDL_SetWindowAlwaysOnTop(SDL_Window * window, SDL_bool on_top) { return; } static void SDL_SetWindowKeyboardGrab(SDL_Window * window, SDL_bool grabbed) { return; } #endif #if !(SDL_VERSION_ATLEAST(2,0,18)) #if defined(WARN_OUTDATED) #pragma message("SDL_GetWindowICCProfile is not supported before SDL 2.0.18") #pragma message("SDL_SetWindowMouseRect is not supported before SDL 2.0.18") #pragma message("SDL_GetWindowMouseRect is not supported before SDL 2.0.18") #endif #define SDL_WINDOWEVENT_ICCPROF_CHANGED (17) // The ICC profile of the window's display has changed. #define SDL_WINDOWEVENT_DISPLAY_CHANGED (18) // Window has been moved to display data1. static void* SDLCALL SDL_GetWindowICCProfile(SDL_Window * window, size_t* size) { return NULL; } static int SDL_SetWindowMouseRect(SDL_Window * window, const SDL_Rect * rect) { return -1; } static const SDL_Rect * SDLCALL SDL_GetWindowMouseRect(SDL_Window * window) { return NULL; } #endif */ import "C" import "unsafe" // An enumeration of window states. // (https://wiki.libsdl.org/SDL_WindowFlags) const ( WINDOW_FULLSCREEN = C.SDL_WINDOW_FULLSCREEN // fullscreen window WINDOW_OPENGL = C.SDL_WINDOW_OPENGL // window usable with OpenGL context WINDOW_SHOWN = C.SDL_WINDOW_SHOWN // window is visible WINDOW_HIDDEN = C.SDL_WINDOW_HIDDEN // window is not visible WINDOW_BORDERLESS = C.SDL_WINDOW_BORDERLESS // no window decoration WINDOW_RESIZABLE = C.SDL_WINDOW_RESIZABLE // window can be resized WINDOW_MINIMIZED = C.SDL_WINDOW_MINIMIZED // window is minimized WINDOW_MAXIMIZED = C.SDL_WINDOW_MAXIMIZED // window is maximized WINDOW_INPUT_GRABBED = C.SDL_WINDOW_INPUT_GRABBED // window has grabbed input focus WINDOW_INPUT_FOCUS = C.SDL_WINDOW_INPUT_FOCUS // window has input focus WINDOW_MOUSE_FOCUS = C.SDL_WINDOW_MOUSE_FOCUS // window has mouse focus WINDOW_FULLSCREEN_DESKTOP = C.SDL_WINDOW_FULLSCREEN_DESKTOP // fullscreen window at the current desktop resolution WINDOW_FOREIGN = C.SDL_WINDOW_FOREIGN // window not created by SDL WINDOW_ALLOW_HIGHDPI = C.SDL_WINDOW_ALLOW_HIGHDPI // window should be created in high-DPI mode if supported (>= SDL 2.0.1) WINDOW_MOUSE_CAPTURE = C.SDL_WINDOW_MOUSE_CAPTURE // window has mouse captured (unrelated to INPUT_GRABBED, >= SDL 2.0.4) WINDOW_ALWAYS_ON_TOP = C.SDL_WINDOW_ALWAYS_ON_TOP // window should always be above others (X11 only, >= SDL 2.0.5) WINDOW_SKIP_TASKBAR = C.SDL_WINDOW_SKIP_TASKBAR // window should not be added to the taskbar (X11 only, >= SDL 2.0.5) WINDOW_UTILITY = C.SDL_WINDOW_UTILITY // window should be treated as a utility window (X11 only, >= SDL 2.0.5) WINDOW_TOOLTIP = C.SDL_WINDOW_TOOLTIP // window should be treated as a tooltip (X11 only, >= SDL 2.0.5) WINDOW_POPUP_MENU = C.SDL_WINDOW_POPUP_MENU // window should be treated as a popup menu (X11 only, >= SDL 2.0.5) WINDOW_VULKAN = C.SDL_WINDOW_VULKAN // window usable for Vulkan surface (>= SDL 2.0.6) ) // An enumeration of window events. // (https://wiki.libsdl.org/SDL_WindowEventID) const ( WINDOWEVENT_NONE = C.SDL_WINDOWEVENT_NONE // (never used) WINDOWEVENT_SHOWN = C.SDL_WINDOWEVENT_SHOWN // window has been shown WINDOWEVENT_HIDDEN = C.SDL_WINDOWEVENT_HIDDEN // window has been hidden WINDOWEVENT_EXPOSED = C.SDL_WINDOWEVENT_EXPOSED // window has been exposed and should be redrawn WINDOWEVENT_MOVED = C.SDL_WINDOWEVENT_MOVED // window has been moved to data1, data2 WINDOWEVENT_RESIZED = C.SDL_WINDOWEVENT_RESIZED // window has been resized to data1xdata2; this event is always preceded by WINDOWEVENT_SIZE_CHANGED WINDOWEVENT_SIZE_CHANGED = C.SDL_WINDOWEVENT_SIZE_CHANGED // window size has changed, either as a result of an API call or through the system or user changing the window size; this event is followed by WINDOWEVENT_RESIZED if the size was changed by an external event, i.e. the user or the window manager WINDOWEVENT_MINIMIZED = C.SDL_WINDOWEVENT_MINIMIZED // window has been minimized WINDOWEVENT_MAXIMIZED = C.SDL_WINDOWEVENT_MAXIMIZED // window has been maximized WINDOWEVENT_RESTORED = C.SDL_WINDOWEVENT_RESTORED // window has been restored to normal size and position WINDOWEVENT_ENTER = C.SDL_WINDOWEVENT_ENTER // window has gained mouse focus WINDOWEVENT_LEAVE = C.SDL_WINDOWEVENT_LEAVE // window has lost mouse focus WINDOWEVENT_FOCUS_GAINED = C.SDL_WINDOWEVENT_FOCUS_GAINED // window has gained keyboard focus WINDOWEVENT_FOCUS_LOST = C.SDL_WINDOWEVENT_FOCUS_LOST // window has lost keyboard focus WINDOWEVENT_CLOSE = C.SDL_WINDOWEVENT_CLOSE // the window manager requests that the window be closed WINDOWEVENT_TAKE_FOCUS = C.SDL_WINDOWEVENT_TAKE_FOCUS // window is being offered a focus (should SDL_SetWindowInputFocus() on itself or a subwindow, or ignore) (>= SDL 2.0.5) WINDOWEVENT_HIT_TEST = C.SDL_WINDOWEVENT_HIT_TEST // window had a hit test that wasn't SDL_HITTEST_NORMAL (>= SDL 2.0.5) WINDOWEVENT_ICCPROF_CHANGED = C.SDL_WINDOWEVENT_ICCPROF_CHANGED // the ICC profile of the window's display has changed WINDOWEVENT_DISPLAY_CHANGED = C.SDL_WINDOWEVENT_DISPLAY_CHANGED // window has been moved to display data1 ) // Window position flags. // (https://wiki.libsdl.org/SDL_CreateWindow) const ( WINDOWPOS_UNDEFINED_MASK = C.SDL_WINDOWPOS_UNDEFINED_MASK // used to indicate that you don't care what the window position is WINDOWPOS_UNDEFINED = C.SDL_WINDOWPOS_UNDEFINED // used to indicate that you don't care what the window position is WINDOWPOS_CENTERED_MASK = C.SDL_WINDOWPOS_CENTERED_MASK // used to indicate that the window position should be centered WINDOWPOS_CENTERED = C.SDL_WINDOWPOS_CENTERED // used to indicate that the window position should be centered ) // An enumeration of message box flags (e.g. if supported message box will display warning icon). // (https://wiki.libsdl.org/SDL_MessageBoxFlags) const ( MESSAGEBOX_ERROR = C.SDL_MESSAGEBOX_ERROR // error dialog MESSAGEBOX_WARNING = C.SDL_MESSAGEBOX_WARNING // warning dialog MESSAGEBOX_INFORMATION = C.SDL_MESSAGEBOX_INFORMATION // informational dialog ) // Flags for MessageBoxButtonData. const ( MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT = C.SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT // marks the default button when return is hit MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT = C.SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT // marks the default button when escape is hit ) // OpenGL configuration attributes. // (https://wiki.libsdl.org/SDL_GL_SetAttribute) const ( GL_RED_SIZE = C.SDL_GL_RED_SIZE // the minimum number of bits for the red channel of the color buffer; defaults to 3 GL_GREEN_SIZE = C.SDL_GL_GREEN_SIZE // the minimum number of bits for the green channel of the color buffer; defaults to 3 GL_BLUE_SIZE = C.SDL_GL_BLUE_SIZE // the minimum number of bits for the blue channel of the color buffer; defaults to 2 GL_ALPHA_SIZE = C.SDL_GL_ALPHA_SIZE // the minimum number of bits for the alpha channel of the color buffer; defaults to 0 GL_BUFFER_SIZE = C.SDL_GL_BUFFER_SIZE // the minimum number of bits for frame buffer size; defaults to 0 GL_DOUBLEBUFFER = C.SDL_GL_DOUBLEBUFFER // whether the output is single or double buffered; defaults to double buffering on GL_DEPTH_SIZE = C.SDL_GL_DEPTH_SIZE // the minimum number of bits in the depth buffer; defaults to 16 GL_STENCIL_SIZE = C.SDL_GL_STENCIL_SIZE // the minimum number of bits in the stencil buffer; defaults to 0 GL_ACCUM_RED_SIZE = C.SDL_GL_ACCUM_RED_SIZE // the minimum number of bits for the red channel of the accumulation buffer; defaults to 0 GL_ACCUM_GREEN_SIZE = C.SDL_GL_ACCUM_GREEN_SIZE // the minimum number of bits for the green channel of the accumulation buffer; defaults to 0 GL_ACCUM_BLUE_SIZE = C.SDL_GL_ACCUM_BLUE_SIZE // the minimum number of bits for the blue channel of the accumulation buffer; defaults to 0 GL_ACCUM_ALPHA_SIZE = C.SDL_GL_ALPHA_SIZE // the minimum number of bits for the alpha channel of the accumulation buffer; defaults to 0 GL_STEREO = C.SDL_GL_STEREO // whether the output is stereo 3D; defaults to off GL_MULTISAMPLEBUFFERS = C.SDL_GL_MULTISAMPLEBUFFERS // the number of buffers used for multisample anti-aliasing; defaults to 0; see Remarks for details GL_MULTISAMPLESAMPLES = C.SDL_GL_MULTISAMPLESAMPLES // the number of samples used around the current pixel used for multisample anti-aliasing; defaults to 0; see Remarks for details GL_ACCELERATED_VISUAL = C.SDL_GL_ACCELERATED_VISUAL // set to 1 to require hardware acceleration, set to 0 to force software rendering; defaults to allow either GL_RETAINED_BACKING = C.SDL_GL_RETAINED_BACKING // not used (deprecated) GL_CONTEXT_MAJOR_VERSION = C.SDL_GL_CONTEXT_MAJOR_VERSION // OpenGL context major version GL_CONTEXT_MINOR_VERSION = C.SDL_GL_CONTEXT_MINOR_VERSION // OpenGL context minor version GL_CONTEXT_EGL = C.SDL_GL_CONTEXT_EGL // not used (deprecated) GL_CONTEXT_FLAGS = C.SDL_GL_CONTEXT_FLAGS // some combination of 0 or more of elements of the GLcontextFlag enumeration; defaults to 0 (https://wiki.libsdl.org/SDL_GLcontextFlag) GL_CONTEXT_PROFILE_MASK = C.SDL_GL_CONTEXT_PROFILE_MASK // type of GL context (Core, Compatibility, ES); default value depends on platform (https://wiki.libsdl.org/SDL_GLprofile) GL_SHARE_WITH_CURRENT_CONTEXT = C.SDL_GL_SHARE_WITH_CURRENT_CONTEXT // OpenGL context sharing; defaults to 0 GL_FRAMEBUFFER_SRGB_CAPABLE = C.SDL_GL_FRAMEBUFFER_SRGB_CAPABLE // requests sRGB capable visual; defaults to 0 (>= SDL 2.0.1) GL_CONTEXT_RELEASE_BEHAVIOR = C.SDL_GL_CONTEXT_RELEASE_BEHAVIOR // sets context the release behavior; defaults to 1 (>= SDL 2.0.4) GL_CONTEXT_RESET_NOTIFICATION = C.SDL_GL_CONTEXT_RESET_NOTIFICATION // (>= SDL 2.0.6) GL_CONTEXT_NO_ERROR = C.SDL_GL_CONTEXT_NO_ERROR // (>= SDL 2.0.6) ) // An enumeration of OpenGL profiles. // (https://wiki.libsdl.org/SDL_GLprofile) const ( GL_CONTEXT_PROFILE_CORE = C.SDL_GL_CONTEXT_PROFILE_CORE // OpenGL core profile - deprecated functions are disabled GL_CONTEXT_PROFILE_COMPATIBILITY = C.SDL_GL_CONTEXT_PROFILE_COMPATIBILITY // OpenGL compatibility profile - deprecated functions are allowed GL_CONTEXT_PROFILE_ES = C.SDL_GL_CONTEXT_PROFILE_ES // OpenGL ES profile - only a subset of the base OpenGL functionality is available ) // An enumeration of OpenGL context configuration flags. // (https://wiki.libsdl.org/SDL_GLcontextFlag) const ( GL_CONTEXT_DEBUG_FLAG = C.SDL_GL_CONTEXT_DEBUG_FLAG // intended to put the GL into a "debug" mode which might offer better developer insights, possibly at a loss of performance GL_CONTEXT_FORWARD_COMPATIBLE_FLAG = C.SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG // intended to put the GL into a "forward compatible" mode, which means that no deprecated functionality will be supported, possibly at a gain in performance, and only applies to GL 3.0 and later contexts GL_CONTEXT_ROBUST_ACCESS_FLAG = C.SDL_GL_CONTEXT_ROBUST_ACCESS_FLAG // intended to require a GL context that supports the GL_ARB_robustness extension--a mode that offers a few APIs that are safer than the usual defaults (think snprintf() vs sprintf()) GL_CONTEXT_RESET_ISOLATION_FLAG = C.SDL_GL_CONTEXT_RESET_ISOLATION_FLAG // intended to require the GL to make promises about what to do in the face of driver or hardware failure ) // // Window flash operation // const ( FLASH_CANCEL FlashOperation = C.SDL_FLASH_CANCEL // Cancel any window flash state FLASH_BRIEFLY = C.SDL_FLASH_BRIEFLY // Flash the window briefly to get attention FLASH_UNTIL_FOCUSED = C.SDL_FLASH_UNTIL_FOCUSED // Flash the window until it gets focus ) type FlashOperation C.SDL_FlashOperation // DisplayMode contains the description of a display mode. // (https://wiki.libsdl.org/SDL_DisplayMode) type DisplayMode struct { Format uint32 // one of the PixelFormatEnum values (https://wiki.libsdl.org/SDL_PixelFormatEnum) W int32 // width, in screen coordinates H int32 // height, in screen coordinates RefreshRate int32 // refresh rate (in Hz), or 0 for unspecified DriverData unsafe.Pointer // driver-specific data, initialize to 0 } type cDisplayMode C.SDL_DisplayMode // Window is a type used to identify a window. type Window C.SDL_Window // GLContext is an opaque handle to an OpenGL context. type GLContext C.SDL_GLContext // GLattr is an OpenGL configuration attribute. //(https://wiki.libsdl.org/SDL_GLattr) type GLattr C.SDL_GLattr // MessageBoxColor contains RGB value used in an MessageBoxColorScheme. // (https://wiki.libsdl.org/SDL_MessageBoxColor) type MessageBoxColor struct { R uint8 // the red component in the range 0-255 G uint8 // the green component in the range 0-255 B uint8 // the blue component in the range 0-255 } type cMessageBoxColor C.SDL_MessageBoxColor // MessageBoxColorScheme contains a set of colors to use for message box dialogs. // (https://wiki.libsdl.org/SDL_MessageBoxColorScheme) type MessageBoxColorScheme struct { Colors [5]MessageBoxColor // background, text, button border, button background, button selected } type cMessageBoxColorScheme C.SDL_MessageBoxColorScheme // MessageBoxButtonData contains individual button data for a message box. // (https://wiki.libsdl.org/SDL_MessageBoxButtonData) type MessageBoxButtonData struct { Flags uint32 // MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT, MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT ButtonID int32 // user defined button id (value returned via ShowMessageBox()) Text string // the UTF-8 button text } // MessageBoxData contains title, text, window and other data for a message box. // (https://wiki.libsdl.org/SDL_MessageBoxData) type MessageBoxData struct { Flags uint32 // MESSAGEBOX_ERROR, MESSAGEBOX_WARNING, MESSAGEBOX_INFORMATION Window *Window // parent window or nil Title string Message string Buttons []MessageBoxButtonData ColorScheme *MessageBoxColorScheme // nil to use system settings } func (window *Window) cptr() *C.SDL_Window { return (*C.SDL_Window)(unsafe.Pointer(window)) } func (dm *DisplayMode) cptr() *C.SDL_DisplayMode { return (*C.SDL_DisplayMode)(unsafe.Pointer(dm)) } func (mc *MessageBoxColor) cptr() *C.SDL_MessageBoxColor { return (*C.SDL_MessageBoxColor)(unsafe.Pointer(mc)) } func (mcs *MessageBoxColorScheme) cptr() *C.SDL_MessageBoxColorScheme { return (*C.SDL_MessageBoxColorScheme)(unsafe.Pointer(mcs)) } func (mbd *MessageBoxButtonData) cptr() *C.SDL_MessageBoxButtonData { return (*C.SDL_MessageBoxButtonData)(unsafe.Pointer(mbd)) } func (md *MessageBoxData) cptr() *C.SDL_MessageBoxData { return (*C.SDL_MessageBoxData)(unsafe.Pointer(md)) } func (attr GLattr) c() C.SDL_GLattr { return C.SDL_GLattr(attr) } // GetDisplayName returns the name of a display in UTF-8 encoding. // (https://wiki.libsdl.org/SDL_GetDisplayName) func GetDisplayName(displayIndex int) (string, error) { name := C.SDL_GetDisplayName(C.int(displayIndex)) if name == nil { return "", GetError() } return C.GoString(name), nil } // GetNumVideoDisplays returns the number of available video displays. // (https://wiki.libsdl.org/SDL_GetNumVideoDisplays) func GetNumVideoDisplays() (int, error) { n := int(C.SDL_GetNumVideoDisplays()) return n, errorFromInt(n) } // GetNumVideoDrivers returns the number of video drivers compiled into SDL. // (https://wiki.libsdl.org/SDL_GetNumVideoDrivers) func GetNumVideoDrivers() (int, error) { n := int(C.SDL_GetNumVideoDrivers()) return n, errorFromInt(n) } // GetVideoDriver returns the name of a built in video driver. // (https://wiki.libsdl.org/SDL_GetVideoDriver) func GetVideoDriver(index int) string { return string(C.GoString(C.SDL_GetVideoDriver(C.int(index)))) } // VideoInit initializes the video subsystem, optionally specifying a video driver. // (https://wiki.libsdl.org/SDL_VideoInit) func VideoInit(driverName string) error { return errorFromInt(int( C.SDL_VideoInit(C.CString(driverName)))) } // VideoQuit shuts down the video subsystem, if initialized with VideoInit(). // (https://wiki.libsdl.org/SDL_VideoQuit) func VideoQuit() { C.SDL_VideoQuit() } // GetCurrentVideoDriver returns the name of the currently initialized video driver. // (https://wiki.libsdl.org/SDL_GetCurrentVideoDriver) func GetCurrentVideoDriver() (string, error) { name := C.SDL_GetCurrentVideoDriver() if name == nil { return "", GetError() } return C.GoString(name), nil } // GetNumDisplayModes returns the number of available display modes. // (https://wiki.libsdl.org/SDL_GetNumDisplayModes) func GetNumDisplayModes(displayIndex int) (int, error) { n := int(C.SDL_GetNumDisplayModes(C.int(displayIndex))) return n, errorFromInt(n) } // GetDisplayBounds returns the desktop area represented by a display, with the primary display located at 0,0. // (https://wiki.libsdl.org/SDL_GetDisplayBounds) func GetDisplayBounds(displayIndex int) (rect Rect, err error) { err = errorFromInt(int( C.SDL_GetDisplayBounds(C.int(displayIndex), (&rect).cptr()))) return } // GetDisplayUsableBounds returns the usable desktop area represented by a display, with the primary display located at 0,0. // (https://wiki.libsdl.org/SDL_GetDisplayUsableBounds) func GetDisplayUsableBounds(displayIndex int) (rect Rect, err error) { err = errorFromInt(int( C.SDL_GetDisplayUsableBounds(C.int(displayIndex), rect.cptr()))) return } // GetDisplayMode returns information about a specific display mode. // (https://wiki.libsdl.org/SDL_GetDisplayMode) func GetDisplayMode(displayIndex int, modeIndex int) (mode DisplayMode, err error) { err = errorFromInt(int( C.SDL_GetDisplayMode(C.int(displayIndex), C.int(modeIndex), (&mode).cptr()))) return } // GetDesktopDisplayMode returns information about the desktop display mode. // (https://wiki.libsdl.org/SDL_GetDesktopDisplayMode) func GetDesktopDisplayMode(displayIndex int) (mode DisplayMode, err error) { err = errorFromInt(int( C.SDL_GetDesktopDisplayMode(C.int(displayIndex), (&mode).cptr()))) return } // GetCurrentDisplayMode returns information about the current display mode. // (https://wiki.libsdl.org/SDL_GetCurrentDisplayMode) func GetCurrentDisplayMode(displayIndex int) (mode DisplayMode, err error) { err = errorFromInt(int( C.SDL_GetCurrentDisplayMode(C.int(displayIndex), (&mode).cptr()))) return } // GetClosestDisplayMode returns the closest match to the requested display mode. // (https://wiki.libsdl.org/SDL_GetClosestDisplayMode) func GetClosestDisplayMode(displayIndex int, mode *DisplayMode, closest *DisplayMode) (*DisplayMode, error) { m := (*DisplayMode)(unsafe.Pointer((C.SDL_GetClosestDisplayMode(C.int(displayIndex), mode.cptr(), closest.cptr())))) if m == nil { return nil, GetError() } return m, nil } // GetDisplayDPI returns the dots/pixels-per-inch for a display. // (https://wiki.libsdl.org/SDL_GetDisplayDPI) func GetDisplayDPI(displayIndex int) (ddpi, hdpi, vdpi float32, err error) { err = errorFromInt(int( C.SDL_GetDisplayDPI(C.int(displayIndex), (*C.float)(unsafe.Pointer(&ddpi)), (*C.float)(unsafe.Pointer(&hdpi)), (*C.float)(unsafe.Pointer(&vdpi))))) return } // GetDisplayIndex returns the index of the display associated with the window. // (https://wiki.libsdl.org/SDL_GetWindowDisplayIndex) func (window *Window) GetDisplayIndex() (int, error) { i := int(C.SDL_GetWindowDisplayIndex(window.cptr())) return i, errorFromInt(i) } // SetDisplayMode sets the display mode to use when the window is visible at fullscreen. // (https://wiki.libsdl.org/SDL_SetWindowDisplayMode) func (window *Window) SetDisplayMode(mode *DisplayMode) error { return errorFromInt(int( C.SDL_SetWindowDisplayMode(window.cptr(), mode.cptr()))) } // GetDisplayMode fills in information about the display mode to use when the window is visible at fullscreen. // (https://wiki.libsdl.org/SDL_GetWindowDisplayMode) func (window *Window) GetDisplayMode() (mode DisplayMode, err error) { err = errorFromInt(int( C.SDL_GetWindowDisplayMode(window.cptr(), (&mode).cptr()))) return } // GetPixelFormat returns the pixel format associated with the window. // (https://wiki.libsdl.org/SDL_GetWindowPixelFormat) func (window *Window) GetPixelFormat() (uint32, error) { f := (uint32)(C.SDL_GetWindowPixelFormat(window.cptr())) if f == PIXELFORMAT_UNKNOWN { return f, GetError() } return f, nil } // CreateWindow creates a window with the specified position, dimensions, and flags. // (https://wiki.libsdl.org/SDL_CreateWindow) func CreateWindow(title string, x, y, w, h int32, flags uint32) (*Window, error) { var _window = C.SDL_CreateWindow(C.CString(title), C.int(x), C.int(y), C.int(w), C.int(h), C.Uint32(flags)) if _window == nil { return nil, GetError() } return (*Window)(unsafe.Pointer(_window)), nil } // CreateWindowFrom creates an SDL window from an existing native window. // (https://wiki.libsdl.org/SDL_CreateWindowFrom) func CreateWindowFrom(data unsafe.Pointer) (*Window, error) { _window := C.SDL_CreateWindowFrom(data) if _window == nil { return nil, GetError() } return (*Window)(unsafe.Pointer(_window)), nil } // Destroy destroys the window. // (https://wiki.libsdl.org/SDL_DestroyWindow) func (window *Window) Destroy() error { lastErr := GetError() ClearError() C.SDL_DestroyWindow(window.cptr()) err := GetError() if err != nil { return err } SetError(lastErr) return nil } // GetID returns the numeric ID of the window, for logging purposes. // (https://wiki.libsdl.org/SDL_GetWindowID) func (window *Window) GetID() (uint32, error) { id := uint32(C.SDL_GetWindowID(window.cptr())) if id == 0 { return 0, GetError() } return id, nil } // GetWindowFromID returns a window from a stored ID. // (https://wiki.libsdl.org/SDL_GetWindowFromID) func GetWindowFromID(id uint32) (*Window, error) { _window := C.SDL_GetWindowFromID(C.Uint32(id)) if _window == nil { return nil, GetError() } return (*Window)(unsafe.Pointer((_window))), nil } // GetFlags returns the window flags. // (https://wiki.libsdl.org/SDL_GetWindowFlags) func (window *Window) GetFlags() uint32 { return (uint32)(C.SDL_GetWindowFlags(window.cptr())) } // SetTitle sets the title of the window. // (https://wiki.libsdl.org/SDL_SetWindowTitle) func (window *Window) SetTitle(title string) { C.SDL_SetWindowTitle(window.cptr(), C.CString(title)) } // GetTitle returns the title of the window. // (https://wiki.libsdl.org/SDL_GetWindowTitle) func (window *Window) GetTitle() string { return C.GoString(C.SDL_GetWindowTitle(window.cptr())) } // SetIcon sets the icon for the window. // (https://wiki.libsdl.org/SDL_SetWindowIcon) func (window *Window) SetIcon(icon *Surface) { C.SDL_SetWindowIcon(window.cptr(), icon.cptr()) } // SetData associates an arbitrary named pointer with the window. // (https://wiki.libsdl.org/SDL_SetWindowData) func (window *Window) SetData(name string, userdata unsafe.Pointer) unsafe.Pointer { return unsafe.Pointer(C.SDL_SetWindowData(window.cptr(), C.CString(name), userdata)) } // GetData returns the data pointer associated with the window. // (https://wiki.libsdl.org/SDL_GetWindowData) func (window *Window) GetData(name string) unsafe.Pointer { return unsafe.Pointer(C.SDL_GetWindowData(window.cptr(), C.CString(name))) } // SetPosition sets the position of the window. // (https://wiki.libsdl.org/SDL_SetWindowPosition) func (window *Window) SetPosition(x, y int32) { C.SDL_SetWindowPosition(window.cptr(), C.int(x), C.int(y)) } // GetPosition returns the position of the window. // (https://wiki.libsdl.org/SDL_GetWindowPosition) func (window *Window) GetPosition() (x, y int32) { var _x, _y C.int C.SDL_GetWindowPosition(window.cptr(), &_x, &_y) return int32(_x), int32(_y) } // SetResizable sets the user-resizable state of the window. // (https://wiki.libsdl.org/SDL_SetWindowResizable) func (window *Window) SetResizable(resizable bool) { C.SDL_SetWindowResizable(window.cptr(), C.SDL_bool(Btoi(resizable))) } // SetSize sets the size of the window's client area. // (https://wiki.libsdl.org/SDL_SetWindowSize) func (window *Window) SetSize(w, h int32) { C.SDL_SetWindowSize(window.cptr(), C.int(w), C.int(h)) } // GetSize returns the size of the window's client area. // (https://wiki.libsdl.org/SDL_GetWindowSize) func (window *Window) GetSize() (w, h int32) { var _w, _h C.int C.SDL_GetWindowSize(window.cptr(), &_w, &_h) return int32(_w), int32(_h) } // SetMinimumSize sets the minimum size of the window's client area. // (https://wiki.libsdl.org/SDL_SetWindowMinimumSize) func (window *Window) SetMinimumSize(minW, minH int32) { C.SDL_SetWindowMinimumSize(window.cptr(), C.int(minW), C.int(minH)) } // GetMinimumSize returns the minimum size of the window's client area. // (https://wiki.libsdl.org/SDL_GetWindowMinimumSize) func (window *Window) GetMinimumSize() (w, h int32) { var _w, _h C.int C.SDL_GetWindowMinimumSize(window.cptr(), &_w, &_h) return int32(_w), int32(_h) } // SetMaximumSize sets the maximum size of the window's client area. // (https://wiki.libsdl.org/SDL_SetWindowMaximumSize) func (window *Window) SetMaximumSize(maxW, maxH int32) { C.SDL_SetWindowMaximumSize(window.cptr(), C.int(maxW), C.int(maxH)) } // GetMaximumSize returns the maximum size of the window's client area. // (https://wiki.libsdl.org/SDL_GetWindowMaximumSize) func (window *Window) GetMaximumSize() (w, h int32) { var _w, _h C.int C.SDL_GetWindowMaximumSize(window.cptr(), &_w, &_h) return int32(_w), int32(_h) } // SetBordered sets the border state of the window. // (https://wiki.libsdl.org/SDL_SetWindowBordered) func (window *Window) SetBordered(bordered bool) { C.SDL_SetWindowBordered(window.cptr(), C.SDL_bool(Btoi(bordered))) } // Show shows the window. // (https://wiki.libsdl.org/SDL_ShowWindow) func (window *Window) Show() { C.SDL_ShowWindow(window.cptr()) } // Hide hides the window. // (https://wiki.libsdl.org/SDL_HideWindow) func (window *Window) Hide() { C.SDL_HideWindow(window.cptr()) } // Raise raises the window above other windows and set the input focus. // (https://wiki.libsdl.org/SDL_RaiseWindow) func (window *Window) Raise() { C.SDL_RaiseWindow(window.cptr()) } // Maximize makes the window as large as possible. // (https://wiki.libsdl.org/SDL_MaximizeWindow) func (window *Window) Maximize() { C.SDL_MaximizeWindow(window.cptr()) } // Minimize minimizes the window to an iconic representation. // (https://wiki.libsdl.org/SDL_MinimizeWindow) func (window *Window) Minimize() { C.SDL_MinimizeWindow(window.cptr()) } // Restore restores the size and position of a minimized or maximized window. // (https://wiki.libsdl.org/SDL_RestoreWindow) func (window *Window) Restore() { C.SDL_RestoreWindow(window.cptr()) } // SetFullscreen sets the window's fullscreen state. // (https://wiki.libsdl.org/SDL_SetWindowFullscreen) func (window *Window) SetFullscreen(flags uint32) error { return errorFromInt(int( C.SDL_SetWindowFullscreen(window.cptr(), C.Uint32(flags)))) } // GetSurface returns the SDL surface associated with the window. // (https://wiki.libsdl.org/SDL_GetWindowSurface) func (window *Window) GetSurface() (*Surface, error) { surface := (*Surface)(unsafe.Pointer(C.SDL_GetWindowSurface(window.cptr()))) if surface == nil { return nil, GetError() } return surface, nil } // UpdateSurface copies the window surface to the screen. // (https://wiki.libsdl.org/SDL_UpdateWindowSurface) func (window *Window) UpdateSurface() error { return errorFromInt(int( C.SDL_UpdateWindowSurface(window.cptr()))) } // UpdateSurfaceRects copies areas of the window surface to the screen. // (https://wiki.libsdl.org/SDL_UpdateWindowSurfaceRects) func (window *Window) UpdateSurfaceRects(rects []Rect) error { return errorFromInt(int( C.SDL_UpdateWindowSurfaceRects(window.cptr(), rects[0].cptr(), C.int(len(rects))))) } // SetGrab sets the window's input grab mode. // (https://wiki.libsdl.org/SDL_SetWindowGrab) func (window *Window) SetGrab(grabbed bool) { C.SDL_SetWindowGrab(window.cptr(), C.SDL_bool((Btoi(grabbed)))) } // GetGrab returns the window's input grab mode. // (https://wiki.libsdl.org/SDL_GetWindowGrab) func (window *Window) GetGrab() bool { return C.SDL_GetWindowGrab(window.cptr()) != 0 } // SetBrightness sets the brightness (gamma multiplier) for the display that owns the given window. // (https://wiki.libsdl.org/SDL_SetWindowBrightness) func (window *Window) SetBrightness(brightness float32) error { return errorFromInt(int( C.SDL_SetWindowBrightness(window.cptr(), C.float(brightness)))) } // GetBrightness returns the brightness (gamma multiplier) for the display that owns the given window. // (https://wiki.libsdl.org/SDL_GetWindowBrightness) func (window *Window) GetBrightness() float32 { return float32(C.SDL_GetWindowBrightness(window.cptr())) } // SetGammaRamp sets the gamma ramp for the display that owns the given window. // (https://wiki.libsdl.org/SDL_SetWindowGammaRamp) func (window *Window) SetGammaRamp(red, green, blue *[256]uint16) error { return errorFromInt(int( C.SDL_SetWindowGammaRamp( window.cptr(), (*C.Uint16)(unsafe.Pointer(red)), (*C.Uint16)(unsafe.Pointer(green)), (*C.Uint16)(unsafe.Pointer(blue))))) } // GetGammaRamp returns the gamma ramp for the display that owns a given window. // (https://wiki.libsdl.org/SDL_GetWindowGammaRamp) func (window *Window) GetGammaRamp() (red, green, blue *[256]uint16, err error) { code := int(C.SDL_GetWindowGammaRamp( window.cptr(), (*C.Uint16)(unsafe.Pointer(red)), (*C.Uint16)(unsafe.Pointer(green)), (*C.Uint16)(unsafe.Pointer(blue)))) return red, green, blue, errorFromInt(code) } // SetWindowOpacity sets the opacity of the window. // (https://wiki.libsdl.org/SDL_SetWindowOpacity) func (window *Window) SetWindowOpacity(opacity float32) error { return errorFromInt(int( C.SDL_SetWindowOpacity(window.cptr(), C.float(opacity)))) } // GetWindowOpacity returns the opacity of the window. // (https://wiki.libsdl.org/SDL_GetWindowOpacity) func (window *Window) GetWindowOpacity() (opacity float32, err error) { return opacity, errorFromInt(int( C.SDL_GetWindowOpacity(window.cptr(), (*C.float)(unsafe.Pointer(&opacity))))) } // ShowSimpleMessageBox displays a simple modal message box. // (https://wiki.libsdl.org/SDL_ShowSimpleMessageBox) func ShowSimpleMessageBox(flags uint32, title, message string, window *Window) error { _title := C.CString(title) defer C.free(unsafe.Pointer(_title)) _message := C.CString(message) defer C.free(unsafe.Pointer(_message)) return errorFromInt(int( C.SDL_ShowSimpleMessageBox(C.Uint32(flags), _title, _message, window.cptr()))) } // ShowMessageBox creates a modal message box. // (https://wiki.libsdl.org/SDL_ShowMessageBox) func ShowMessageBox(data *MessageBoxData) (buttonid int32, err error) { _title := C.CString(data.Title) defer C.free(unsafe.Pointer(_title)) _message := C.CString(data.Message) defer C.free(unsafe.Pointer(_message)) var cbuttons []C.SDL_MessageBoxButtonData var cbtntexts []*C.char defer func(texts []*C.char) { for _, t := range texts { C.free(unsafe.Pointer(t)) } }(cbtntexts) for _, btn := range data.Buttons { ctext := C.CString(btn.Text) cbtn := C.SDL_MessageBoxButtonData{ flags: C.Uint32(btn.Flags), buttonid: C.int(btn.ButtonID), text: ctext, } cbuttons = append(cbuttons, cbtn) cbtntexts = append(cbtntexts, ctext) } var buttonPtr *C.SDL_MessageBoxButtonData if len(cbuttons) > 0 { buttonPtr = &cbuttons[0] } cdata := C.SDL_MessageBoxData{ flags: C.Uint32(data.Flags), window: data.Window.cptr(), title: _title, message: _message, numbuttons: C.int(len(data.Buttons)), buttons: buttonPtr, colorScheme: data.ColorScheme.cptr(), } buttonid = int32(C.ShowMessageBox(cdata)) return buttonid, errorFromInt(int(buttonid)) } // IsScreenSaverEnabled reports whether the screensaver is currently enabled. // (https://wiki.libsdl.org/SDL_IsScreenSaverEnabled) func IsScreenSaverEnabled() bool { return C.SDL_IsScreenSaverEnabled() != 0 } // EnableScreenSaver allows the screen to be blanked by a screen saver. // (https://wiki.libsdl.org/SDL_EnableScreenSaver) func EnableScreenSaver() { C.SDL_EnableScreenSaver() } // DisableScreenSaver prevents the screen from being blanked by a screen saver. // (https://wiki.libsdl.org/SDL_DisableScreenSaver) func DisableScreenSaver() { C.SDL_DisableScreenSaver() } // GLLoadLibrary dynamically loads an OpenGL library. // (https://wiki.libsdl.org/SDL_GL_LoadLibrary) func GLLoadLibrary(path string) error { return errorFromInt(int( C.SDL_GL_LoadLibrary(C.CString(path)))) } // GLGetProcAddress returns an OpenGL function by name. // (https://wiki.libsdl.org/SDL_GL_GetProcAddress) func GLGetProcAddress(proc string) unsafe.Pointer { return unsafe.Pointer(C.SDL_GL_GetProcAddress(C.CString(proc))) } // GLUnloadLibrary unloads the OpenGL library previously loaded by GLLoadLibrary(). // (https://wiki.libsdl.org/SDL_GL_UnloadLibrary) func GLUnloadLibrary() { C.SDL_GL_UnloadLibrary() } // GLExtensionSupported reports whether an OpenGL extension is supported for the current context. // (https://wiki.libsdl.org/SDL_GL_ExtensionSupported) func GLExtensionSupported(extension string) bool { return C.SDL_GL_ExtensionSupported(C.CString(extension)) != 0 } // GLSetAttribute sets an OpenGL window attribute before window creation. // (https://wiki.libsdl.org/SDL_GL_SetAttribute) func GLSetAttribute(attr GLattr, value int) error { return errorFromInt(int( C.SDL_GL_SetAttribute(attr.c(), C.int(value)))) } // GLGetAttribute returns the actual value for an attribute from the current context. // (https://wiki.libsdl.org/SDL_GL_GetAttribute) func GLGetAttribute(attr GLattr) (int, error) { var _value C.int if C.SDL_GL_GetAttribute(attr.c(), &_value) != 0 { return int(_value), GetError() } return int(_value), nil } // GLCreateContext creates an OpenGL context for use with an OpenGL window, and make it current. // (https://wiki.libsdl.org/SDL_GL_CreateContext) func (window *Window) GLCreateContext() (GLContext, error) { c := GLContext(C.SDL_GL_CreateContext(window.cptr())) if c == nil { return nil, GetError() } return c, nil } // GLMakeCurrent sets up an OpenGL context for rendering into an OpenGL window. // (https://wiki.libsdl.org/SDL_GL_MakeCurrent) func (window *Window) GLMakeCurrent(glcontext GLContext) error { return errorFromInt(int( C.SDL_GL_MakeCurrent(window.cptr(), C.SDL_GLContext(glcontext)))) } // GLSetSwapInterval sets the swap interval for the current OpenGL context. // (https://wiki.libsdl.org/SDL_GL_SetSwapInterval) func GLSetSwapInterval(interval int) error { return errorFromInt(int( C.SDL_GL_SetSwapInterval(C.int(interval)))) } // GLGetSwapInterval returns the swap interval for the current OpenGL context. // (https://wiki.libsdl.org/SDL_GL_GetSwapInterval) func GLGetSwapInterval() (int, error) { i := int(C.SDL_GL_GetSwapInterval()) // -1 means adaptive vsync, not an error // 0 means vsync off // 1 means vsync on if i == -1 || i == 0 || i == 1 { return i, nil } // any other value should be an error return i, errorFromInt(i) } // GLGetDrawableSize returns the size of a window's underlying drawable in pixels (for use with glViewport). // (https://wiki.libsdl.org/SDL_GL_GetDrawableSize) func (window *Window) GLGetDrawableSize() (w, h int32) { var _w, _h C.int C.SDL_GL_GetDrawableSize(window.cptr(), &_w, &_h) return int32(_w), int32(_h) } // GLSwap updates a window with OpenGL rendering. // (https://wiki.libsdl.org/SDL_GL_SwapWindow) func (window *Window) GLSwap() { C.SDL_GL_SwapWindow(window.cptr()) } // GLDeleteContext deletes an OpenGL context. // (https://wiki.libsdl.org/SDL_GL_DeleteContext) func GLDeleteContext(context GLContext) { C.SDL_GL_DeleteContext(C.SDL_GLContext(context)) } // Flash requests the window to demand attention from the user. // (https://wiki.libsdl.org/SDL_FlashWindow) func (window *Window) Flash(operation FlashOperation) (err error) { return errorFromInt(int(C.SDL_FlashWindow(window.cptr(), C.SDL_FlashOperation(operation)))) } // SetAlwaysOnTop sets the window to always be above the others. // (https://wiki.libsdl.org/SDL_SetWindowAlwaysOnTop) func (window *Window) SetAlwaysOnTop(onTop bool) { C.SDL_SetWindowAlwaysOnTop(window.cptr(), C.SDL_bool(Btoi(onTop))) } // SetKeyboardGrab sets a window's keyboard grab mode. // (https://wiki.libsdl.org/SDL_GetWindowKeyboardGrab) func (window *Window) SetKeyboardGrab(grabbed bool) { C.SDL_SetWindowKeyboardGrab(window.cptr(), C.SDL_bool(Btoi(grabbed))) } // GetICCProfile gets the raw ICC profile data for the screen the window is currently on. // // Data returned should be freed with SDL_free. // // (https://wiki.libsdl.org/SDL_GetWindowICCProfile) func (window *Window) GetICCProfile() (iccProfile unsafe.Pointer, size uintptr, err error) { _size := (*C.size_t)(unsafe.Pointer(&size)) iccProfile = C.SDL_GetWindowICCProfile(window.cptr(), _size) if iccProfile == nil { err = GetError() } return } // SetMouseRect confines the cursor to the specified area of a window. // // Note that this does NOT grab the cursor, it only defines the area a cursor // is restricted to when the window has mouse focus. // // (https://wiki.libsdl.org/SDL_SetWindowMouseRect) func (window *Window) SetMouseRect(rect Rect) (err error) { _rect := (*C.SDL_Rect)(unsafe.Pointer(&rect)) err = errorFromInt(int(C.SDL_SetWindowMouseRect(window.cptr(), _rect))) return } // GetMouseRect gets the mouse confinement rectangle of a window. // (https://wiki.libsdl.org/SDL_GetWindowMouseRect) func (window *Window) GetMouseRect() (rect Rect) { _rect := C.SDL_GetWindowMouseRect(window.cptr()) rect = *((*Rect)(unsafe.Pointer(_rect))) return } ================================================ FILE: gccgo/vendor/github.com/veandco/go-sdl2/sdl/vulkan.go ================================================ package sdl /* #include "sdl_wrapper.h" #if (SDL_VERSION_ATLEAST(2,0,6)) #if defined(_WIN32) #include #else #include #endif #else //!SDL_VERSION_ATLEAST(2,0,6) #define VK_DEFINE_HANDLE(object) typedef struct object##_T* object; #if defined(__LP64__) || defined(_WIN64) || defined(__x86_64__) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__) #define VK_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef struct object##_T *object; #else #define VK_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef uint64_t object; #endif VK_DEFINE_HANDLE(VkInstance) VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkSurfaceKHR) typedef VkInstance SDL_vulkanInstance; typedef VkSurfaceKHR SDL_vulkanSurface; #if defined(WARN_OUTDATED) #pragma message("SDL_Vulkan_LoadLibrary is not supported before SDL 2.0.6") #endif static int SDL_Vulkan_LoadLibrary(const char *path) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_Vulkan_GetVkGetInstanceProcAddr is not supported before SDL 2.0.6") #endif static void* SDL_Vulkan_GetVkGetInstanceProcAddr(void) { return NULL; } #if defined(WARN_OUTDATED) #pragma message("SDL_Vulkan_UnloadLibrary is not supported before SDL 2.0.6") #endif static void SDL_Vulkan_UnloadLibrary(void) {} #if defined(WARN_OUTDATED) #pragma message("SDL_Vulkan_GetInstanceExtensions is not supported before SDL 2.0.6") #endif static int SDL_Vulkan_GetInstanceExtensions(SDL_Window *window, unsigned int *pCount, const char **pNames) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_Vulkan_CreateSurface is not supported before SDL 2.0.6") #endif static int SDL_Vulkan_CreateSurface(SDL_Window *window, VkInstance instance, VkSurfaceKHR *surface) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_Vulkan_GetDrawableSize is not supported before SDL 2.0.6") #endif static void SDL_Vulkan_GetDrawableSize(SDL_Window *window, int *w, int *h) { *w = 0; *h = 0; } #endif */ import "C" import ( "errors" "reflect" "unsafe" ) // VulkanLoadLibrary dynamically loads a Vulkan loader library. // (https://wiki.libsdl.org/SDL_Vulkan_LoadLibrary) func VulkanLoadLibrary(path string) error { var ret C.int if path == "" { ret = C.SDL_Vulkan_LoadLibrary(nil) } else { cpath := C.CString(path) defer C.free(unsafe.Pointer(cpath)) ret = C.SDL_Vulkan_LoadLibrary(cpath) } if int(ret) == -1 { return GetError() } return nil } // VulkanGetVkGetInstanceProcAddr gets the address of the vkGetInstanceProcAddr function. // (https://wiki.libsdl.org/SDL_Vulkan_GetVkInstanceProcAddr) func VulkanGetVkGetInstanceProcAddr() unsafe.Pointer { return C.SDL_Vulkan_GetVkGetInstanceProcAddr() } // VulkanUnloadLibrary unloads the Vulkan loader library previously loaded by VulkanLoadLibrary(). // (https://wiki.libsdl.org/SDL_Vulkan_UnloadLibrary) func VulkanUnloadLibrary() { C.SDL_Vulkan_UnloadLibrary() } // VulkanGetInstanceExtensions gets the names of the Vulkan instance extensions needed to create a surface with VulkanCreateSurface(). // (https://wiki.libsdl.org/SDL_Vulkan_GetInstanceExtensions) func (window *Window) VulkanGetInstanceExtensions() []string { var count C.uint C.SDL_Vulkan_GetInstanceExtensions(window.cptr(), &count, nil) if count == 0 { return nil } strptrs := make([]*C.char, uint(count)) C.SDL_Vulkan_GetInstanceExtensions(window.cptr(), &count, &strptrs[0]) extensions := make([]string, uint(count)) for i := range strptrs { extensions[i] = C.GoString(strptrs[i]) } return extensions } // VulkanCreateSurface creates a Vulkan rendering surface for a window. // (https://wiki.libsdl.org/SDL_Vulkan_CreateSurface) func (window *Window) VulkanCreateSurface(instance interface{}) (surface unsafe.Pointer, err error) { if instance == nil { return nil, errors.New("vulkan: instance is nil") } val := reflect.ValueOf(instance) if val.Kind() != reflect.Ptr { return nil, errors.New("vulkan: instance is not a VkInstance (expected kind Ptr, got " + val.Kind().String() + ")") } var vulkanSurface C.VkSurfaceKHR if C.SDL_Vulkan_CreateSurface(window.cptr(), (C.VkInstance)(unsafe.Pointer(val.Pointer())), (*C.VkSurfaceKHR)(unsafe.Pointer(&vulkanSurface))) == C.SDL_FALSE { return nil, GetError() } return unsafe.Pointer(&vulkanSurface), nil } // VulkanGetDrawableSize gets the size of a window's underlying drawable in pixels (for use with setting viewport, scissor & etc). // (https://wiki.libsdl.org/SDL_Vulkan_GetDrawableSize) func (window *Window) VulkanGetDrawableSize() (w, h int32) { var _w, _h C.int C.SDL_Vulkan_GetDrawableSize(window.cptr(), &_w, &_h) return int32(_w), int32(_h) } ================================================ FILE: gccgo/vendor/modules.txt ================================================ # github.com/veandco/go-sdl2 v0.4.36 ## explicit; go 1.15 github.com/veandco/go-sdl2/_libs github.com/veandco/go-sdl2/img github.com/veandco/go-sdl2/sdl ================================================ FILE: go/Makefile ================================================ .PHONY: all msg clean fullclean all: msg go msg: @echo '--- Go ---' go: main.go go build -mod=vendor -v run: msg go time ./go gorun: main.go go run main.go clean: go clean fullclean: clean ================================================ FILE: go/README.md ================================================ SDL2 and Go =========== Requirements ------------ * The SDL2 library and headers. * The latest version of Go. * The sdl2 package: `go get github.com/veandco/go-sdl2/sdl` An alternative way of fetching the needed dependencies is: `go get -d -t -v` For OS X, remember to install the Development Libraries (place the SDL2 framework in `/Library/Frameworks`) Building -------- go build Running ------- ./go ================================================ FILE: go/go.mod ================================================ module github.com/xyproto/sdl2-examples/go go 1.18 require github.com/veandco/go-sdl2 v0.4.36 ================================================ FILE: go/go.sum ================================================ github.com/veandco/go-sdl2 v0.4.36 h1:Ltydev536rRQodmIrTWFZ3dRp5A+/6t5CYvbi4Kvia0= github.com/veandco/go-sdl2 v0.4.36/go.mod h1:OROqMhHD43nT4/i9crJukyVecjPNYYuCofep6SNiAjY= ================================================ FILE: go/main.go ================================================ package main import ( "log" "path/filepath" "github.com/veandco/go-sdl2/img" "github.com/veandco/go-sdl2/sdl" ) func main() { // Initialize if err := sdl.Init(sdl.INIT_EVERYTHING); err != nil { log.Fatalln("Init Error:", err) } // Make sure to quit when the function returns defer sdl.Quit() // Create the window win, err := sdl.CreateWindow("Hello World!", 100, 100, 620, 387, sdl.WINDOW_SHOWN) if err != nil { log.Fatalln("CreateWindow Error:", err) } defer win.Destroy() // Create a renderer ren, err := sdl.CreateRenderer(win, -1, sdl.RENDERER_ACCELERATED|sdl.RENDERER_PRESENTVSYNC) if err != nil { log.Fatalln("CreateRenderer Error:", err) } defer ren.Destroy() // Load the image as a texture tex, err := img.LoadTexture(ren, filepath.Join("..", "img", "grumpy-cat.png")) if err != nil { log.Fatalln("LoadTexture Error:", err) } defer tex.Destroy() for i := 0; i < 20; i++ { // Clear the renderer and display the image/texture ren.Clear() ren.Copy(tex, nil, nil) ren.Present() // Wait 100 ms sdl.Delay(100) } } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/CONTRIBUTORS.md ================================================ Contributors ============ Here's the list of contributors with their respective Github URLs. * [Jacky Boen](https://github.com/jackyb) * [HardWareGuy](https://github.com/HardWareGuy) * [akovaski](https://github.com/akovaski) * [Jeromy Johnson](https://github.com/whyrusleeping) * [Cai Lei](https://github.com/ccll) * [Arne Döring](https://github.com/krux02) * [Marcus von Appen](https://github.com/marcusva) * [Tom Murray](https://github.com/TomMurray) * [Ian Davis](https://github.com/iand) * [hschendel](https://github.com/hschendel) * [Ingo Oeser](https://github.com/nightlyone) * [nlordell](https://github.com/nlordell) * [Ben Davies](https://github.com/JalfResi) * [Bastien Dejean](https://github.com/baskerville) * [Pirmin Tapken](https://github.com/PirminTapken) * [Robert Lillack](https://github.com/roblillack) * [Marcell Jusztin](https://github.com/morcmarc) * [Stan Schwertly](https://github.com/Stantheman) * [Michael Vetter](https://github.com/jubalh) * [Tom Fogal](https://github.com/tfogal) * [Philipp Meinen](https://github.com/PhiCode) * [Thomas McGrew](https://github.com/mcgrew) * [Geoff Catlin](https://github.com/gcatlin) * [Schobers](https://github.com/Schobers) * [Jan Tuitman](https://github.com/jantuitman) * [Nick Powell](https://github.com/THUNDERGROOVE) * [Steven R. Wiley](https://github.com/srwiley) * [Franco Lazzarino](https://github.com/flazz) * [Jason Alan Palmer](https://github.com/jalan) * [Seuk Won Kang](https://github.com/kasworld) * [Brandon Mulcahy](https://github.com/jangler) * [Tim Anema](https://github.com/tanema) * [Tyler Compton](https://github.com/velovix) * [Nicolas Hess](https://github.com/n0dev) * [Stephen Noonan](https://github.com/tycho) * [Guilherme Freitas Nemeth](https://github.com/glhrmfrts) * [Charney Kaye](https://github.com/charneykaye) * [Lars Scheme](https://github.com/gonutz) * [Emil Laine](https://github.com/emlai) * [Sergey Parshukov](https://github.com/jBugman) * [Casey DeLorme](https://github.com/cdelorme) * [Andreas T. Jonsson](https://github.com/andreas-jonsson) * [Milan Nikolic](https://github.com/gen2brain) * [Mike Gerow](https://github.com/gerow) * [Lilis Iskandar](https://github.com/veeableful) * [tfriedel6](https://github.com/tfriedel6) * [Eric Bronner](https://github.com/MoonWatcher582) * [Julien Castelain](https://github.com/julien) * [Robert Wallis](https://github.com/robert-wallis) * [Chae-Young Song](https://github.com/chaeyoungsong) * [Robert Wallis](https://github.com/robert-wallis) * [Lennart Buhl](https://github.com/r41d) * [Giovanni Bajo](https://github.com/rasky) * [Laurent Vaucher](https://github.com/slowfrog) * [Mike](https://github.com/barbeque) * [Tomas Virgl](https://github.com/tvi) * [Aye Aye Maung](https://github.com/ZeroXLR) * [Anton Malashin](https://github.com/malashin) * [John Perkins](https://github.com/mpath) * [jclc](https://github.com/jclc) * [flga](https://github.com/flga) _if anyone is missing, let me know!.. or you can add yourself in :)_ ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/LICENSE ================================================ Copyright (c) 2013, Go-SDL2 Authors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Go-SDL2 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/_libs/dummy.go ================================================ package dummy ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/img/sdl_image.go ================================================ // Package img is a simple library to load images of various formats as SDL surfaces. package img //#include //#include "sdl_image_wrapper.h" import "C" import "unsafe" import "errors" import "github.com/veandco/go-sdl2/sdl" // Flags which may be passed to img.Init() to load support of image formats, can be bitwise OR'd together. const ( INIT_JPG = 0x00000001 // JPG INIT_PNG = 0x00000002 // PNG INIT_TIF = 0x00000004 // TIF INIT_WEBP = 0x00000008 // WebP ) // LinkedVersion returns the version of the dynamically linked SDL_image library. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_7.html) func LinkedVersion() *sdl.Version { return (*sdl.Version)(unsafe.Pointer(C.IMG_Linked_Version())) } // Init loads dynamic libraries and prepares them for use. Flags should be one or more flags from IMG_InitFlags OR'd together. It returns the flags successfully initialized, or 0 on failure. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_8.html) func Init(flags int) error { _flags := (C.int)(flags) ret := int(C.IMG_Init(_flags)) if ret == 0 { return GetError() } return nil } // Quit unloads libraries loaded with img.Init(). // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_9.html) func Quit() { C.IMG_Quit() } // GetError returns the last error that occurred, or an empty string if there hasn't been an error message set since the last call to sdl.ClearError(). // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_45.html) func GetError() error { e := C.IMG_GetError() if e == nil { return nil } return errors.New(C.GoString(e)) } // LoadTypedRW loads an image from an SDL data source. The 'type' may be one of: "BMP", "GIF", "PNG", etc. If the image format supports a transparent pixel, SDL will set the colorkey for the surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_13.html) func LoadTypedRW(src *sdl.RWops, freesrc bool, type_ string) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _freesrc := (C.int)(sdl.Btoi(freesrc)) _type := C.CString(type_) defer C.free(unsafe.Pointer(_type)) _surface := C.IMG_LoadTyped_RW(_src, _freesrc, _type) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // Load loads a file for use as an image in a new surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_11.html) func Load(file string) (*sdl.Surface, error) { _file := C.CString(file) defer C.free(unsafe.Pointer(_file)) _surface := C.IMG_Load(_file) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadRW loads an image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_12.html) func LoadRW(src *sdl.RWops, freesrc bool) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _freesrc := (C.int)(sdl.Btoi(freesrc)) _surface := C.IMG_Load_RW(_src, _freesrc) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadTexture loads an image directly into a render texture. func LoadTexture(renderer *sdl.Renderer, file string) (*sdl.Texture, error) { _renderer := (*C.SDL_Renderer)(unsafe.Pointer(renderer)) _file := C.CString(file) defer C.free(unsafe.Pointer(_file)) _surface := C.IMG_LoadTexture(_renderer, _file) if _surface == nil { return nil, GetError() } return (*sdl.Texture)(unsafe.Pointer(_surface)), nil } // LoadTextureRW loads an image from an SDL data source directly into a render texture. func LoadTextureRW(renderer *sdl.Renderer, src *sdl.RWops, freesrc bool) (*sdl.Texture, error) { _renderer := (*C.SDL_Renderer)(unsafe.Pointer(renderer)) _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _freesrc := (C.int)(sdl.Btoi(freesrc)) _surface := C.IMG_LoadTexture_RW(_renderer, _src, _freesrc) if _surface == nil { return nil, GetError() } return (*sdl.Texture)(unsafe.Pointer(_surface)), nil } // IsICO reports whether ICO format is supported and image data is readable as an ICO. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_31.html) func IsICO(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isICO(_src)) > 0 } // IsCUR reports whether CUR format is supported and image data is readable as a CUR. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_30.html) func IsCUR(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isCUR(_src)) > 0 } // IsBMP reports whether BMP format is supported and image data is readable as a BMP. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_32.html) func IsBMP(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isBMP(_src)) > 0 } // IsGIF reports whether GIF format is supported and image data is readable as a GIF. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_37.html) func IsGIF(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isGIF(_src)) > 0 } // IsJPG reports whether JPG format is supported and image data is readable as a JPG. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_38.html) func IsJPG(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isJPG(_src)) > 0 } // IsLBM reports whether LBM format is supported and image data is readable as an LBM. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_41.html) func IsLBM(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isLBM(_src)) > 0 } // IsPCX reports whether PCX format is supported and image data is readable as a PCX. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_36.html) func IsPCX(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isPCX(_src)) > 0 } // IsPNG reports whether PNG format is supported and image data is readable as a PNG. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_40.html) func IsPNG(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isPNG(_src)) > 0 } // IsPNM reports whether PNM format is supported and image data is readable as a PNM. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_33.html) func IsPNM(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isPNM(_src)) > 0 } // IsTIF reports whether TIF format is supported and image data is readable as a TIF. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_39.html) func IsTIF(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isTIF(_src)) > 0 } // IsXCF reports whether XCF format is supported and image data is readable as an XCF. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_35.html) func IsXCF(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isXCF(_src)) > 0 } // IsXPM reports whether XPM format is supported and image data is readable as an XPM. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_34.html) func IsXPM(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isXPM(_src)) > 0 } // IsXV reports whether XV format is supported and image data is readable as an XV thumbnail. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_42.html) func IsXV(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isXV(_src)) > 0 } // IsWEBP reports whether WEBP format is supported and image data is readable as a WEBP. func IsWEBP(src *sdl.RWops) bool { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) return int(C.IMG_isWEBP(_src)) > 0 } // LoadICORW loads an ICO image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_15.html) func LoadICORW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadICO_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadCURRW loads a CUR image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_14.html) func LoadCURRW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadCUR_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadBMPRW loads a BMP image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_16.html) func LoadBMPRW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadBMP_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadGIFRW loads a GIF image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_21.html) func LoadGIFRW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadGIF_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadJPGRW loads a JPG image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_22.html) func LoadJPGRW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadJPG_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadLBMRW loads an LBM image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_26.html) func LoadLBMRW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadLBM_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadPCXRW loads a PCX image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_20.html) func LoadPCXRW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadPCX_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadPNGRW loads a PNG image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_24.html) func LoadPNGRW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadPNG_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadPNMRW loads a PNM image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_17.html) func LoadPNMRW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadPNM_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadTGARW loads a TGA image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_25.html) func LoadTGARW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadTGA_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadTIFRW loads a TIF image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_23.html) func LoadTIFRW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadTIF_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadXCFRW loads an XCF image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_19.html) func LoadXCFRW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadXCF_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadXPMRW loads an XPM image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_18.html) func LoadXPMRW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadXPM_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadXVRW loads an XV thumbnail image from an SDL data source for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_27.html) func LoadXVRW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadXV_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // LoadWEBPRW loads a WEBP image from an SDL data source for use as a surface. func LoadWEBPRW(src *sdl.RWops) (*sdl.Surface, error) { _src := (*C.SDL_RWops)(unsafe.Pointer(src)) _surface := C.IMG_LoadWEBP_RW(_src) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // ReadXPMFromArray loads an XPM image from xpm data for use as a surface. // (http://www.libsdl.org/projects/SDL_image/docs/SDL_image_28.html) func ReadXPMFromArray(xpm string) (*sdl.Surface, error) { _xpm := C.CString(xpm) defer C.free(unsafe.Pointer(_xpm)) _surface := C.IMG_ReadXPMFromArray(&_xpm) if _surface == nil { return nil, GetError() } return (*sdl.Surface)(unsafe.Pointer(_surface)), nil } // SavePNG saves a surface as PNG file. func SavePNG(surface *sdl.Surface, file string) error { _surface := (*C.SDL_Surface)(unsafe.Pointer(surface)) _file := C.CString(file) defer C.free(unsafe.Pointer(_file)) _ret := C.IMG_SavePNG(_surface, _file) if _ret < 0 { return GetError() } return nil } // SavePNGRW saves a surface to an SDL data source. func SavePNGRW(surface *sdl.Surface, dst *sdl.RWops, freedst int) error { _surface := (*C.SDL_Surface)(unsafe.Pointer(surface)) _dst := (*C.SDL_RWops)(unsafe.Pointer(dst)) _freedst := (C.int)(freedst) _ret := C.IMG_SavePNG_RW(_surface, _dst, _freedst) if _ret < 0 { return GetError() } return nil } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/img/sdl_image_cgo.go ================================================ // +build !static package img //#cgo linux freebsd darwin pkg-config: sdl2 //#cgo linux freebsd darwin LDFLAGS: -lSDL2_image //#cgo windows LDFLAGS: -lSDL2 -lSDL2_image import "C" ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/img/sdl_image_cgo_static.go ================================================ // +build static package img //#cgo CFLAGS: -I${SRCDIR}/../_libs/include -I${SRCDIR}/../_libs/include/SDL2 //#cgo LDFLAGS: -L${SRCDIR}/../_libs //#cgo linux,386 LDFLAGS: -lSDL2_image_linux_386 -Wl,--no-undefined -lpng_linux_386 -ljpeg_linux_386 -lSDL2_linux_386 -lm -ldl -lz -lasound -lm -ldl -lpthread -lX11 -lXext -lXcursor -lXinerama -lXi -lXrandr -lXss -lXxf86vm -lpthread -lrt //#cgo linux,amd64 LDFLAGS: -lSDL2_image_linux_amd64 -Wl,--no-undefined -lpng_linux_amd64 -ljpeg_linux_amd64 -lSDL2_linux_amd64 -lm -ldl -lz -lasound -lm -ldl -lpthread -lX11 -lXext -lXcursor -lXinerama -lXi -lXrandr -lXss -lXxf86vm -lpthread -lrt //#cgo windows,386 LDFLAGS: -lSDL2_image_windows_386 -Wl,--no-undefined -lpng_windows_386 -ljpeg_windows_386 -lz_windows_386 -lSDL2_windows_386 -lSDL2main_windows_386 -Wl,--no-undefined -lm -ldinput8 -ldxguid -ldxerr8 -luser32 -lgdi32 -lwinmm -limm32 -lole32 -loleaut32 -lshell32 -lversion -luuid -lsetupapi -static-libgcc //#cgo windows,amd64 LDFLAGS: -lSDL2_image_windows_amd64 -Wl,--no-undefined -lpng_windows_amd64 -ljpeg_windows_amd64 -lz_windows_amd64 -lSDL2_windows_amd64 -lSDL2main_windows_amd64 -Wl,--no-undefined -lm -ldinput8 -ldxguid -ldxerr8 -luser32 -lgdi32 -lwinmm -limm32 -lole32 -loleaut32 -lshell32 -lversion -luuid -lsetupapi -static-libgcc //#cgo darwin,amd64 LDFLAGS: -lSDL2_image_darwin_amd64 -lSDL2_darwin_amd64 -lpng_darwin_amd64 -ljpeg_darwin_amd64 -lm -lz -liconv -Wl,-framework,CoreAudio -Wl,-framework,AudioToolbox -Wl,-framework,ForceFeedback -lobjc -Wl,-framework,CoreVideo -Wl,-framework,Cocoa -Wl,-framework,Carbon -Wl,-framework,IOKit -Wl,-framework,Metal //#cgo darwin,arm64 LDFLAGS: -lSDL2_image_darwin_arm64 -lSDL2_darwin_arm64 -lpng_darwin_arm64 -ljpeg_darwin_arm64 -lm -lz -liconv -Wl,-framework,CoreAudio -Wl,-framework,AudioToolbox -Wl,-framework,ForceFeedback -lobjc -Wl,-framework,CoreVideo -Wl,-framework,Cocoa -Wl,-framework,Carbon -Wl,-framework,IOKit -Wl,-framework,Metal //#cgo android,arm LDFLAGS: -lSDL2_image_android_arm -Wl,--no-undefined -lpng_android_arm -ljpeg_android_arm -lSDL2_android_arm -lm -ldl -lz -llog -landroid -lGLESv2 -lGLESv1_CM //#cgo linux,arm,!android LDFLAGS: -L/opt/vc/lib -L/opt/vc/lib64 -lSDL2_image_linux_arm -Wl,--no-undefined -lpng_linux_arm -ljpeg_linux_arm -lSDL2_linux_arm -lm -ldl -lz -liconv -lbcm_host -lvcos -lvchiq_arm -pthread import "C" ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/img/sdl_image_wrapper.h ================================================ #if defined(__WIN32) #include #include #else #include #endif ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/TODO.md ================================================ ## 2.0.16 [x] SDL_FlashWindow() to get a user’s attention [x] SDL_GetAudioDeviceSpec() to get the preferred audio format of a device [x] SDL_SetWindowAlwaysOnTop() to dynamically change the SDL_WINDOW_ALWAYS_ON_TOP flag for a window [x] SDL_SetWindowKeyboardGrab() to support grabbing the keyboard independently of the mouse [x] SDL_SoftStretchLinear() to do bilinear scaling between 32-bit software surfaces [x] SDL_UpdateNVTexture() to update streaming NV12/21 textures [x] SDL_GameControllerSendEffect() and SDL_JoystickSendEffect() to allow sending custom trigger effects to the DualSense controller [x] SDL_GameControllerGetSensorDataRate() to get the sensor data rate for PlayStation and Nintendo Switch controllers ### Windows [?] SDL_SetWindowsMessageHook() to set a function that is called for all Windows messages [?] SDL_RenderGetD3D11Device() to get the D3D11 device used by the SDL renderer ### Linux [x] SDL_HINT_AUDIO_INCLUDE_MONITORS to control whether PulseAudio recording should include monitor devices [x] SDL_HINT_AUDIO_DEVICE_STREAM_ROLE to describe the role of your application for audio control panels ### Android: [?] SDL_AndroidShowToast() to show a lightweight notification ## 2.0.14 [x] SDL_GameControllerGetSerial() [x] SDL_GameControllerHasAxis() [x] SDL_GameControllerHasButton() [x] SDL_GameControllerGetNumTouchpads() [x] SDL_GameControllerGetNumTouchpadFingers() [x] SDL_GameControllerGetTouchpadFinger() [x] SDL_GameControllerHasSensor() [x] SDL_GameControllerSetSensorEnabled() [x] SDL_GameControllerIsSensorEnabled() [x] SDL_GameControllerGetSensorData [x] SDL_GameControllerRumbleTriggers() [x] SDL_GameControllerHasLED() [x] SDL_GameControllerSetLED() [x] SDL_JoystickGetSerial() [x] SDL_JoystickRumbleTriggers() [x] SDL_JoystickHasLED() [x] SDL_JoystickSetLED() [x] SDL_JoystickAttachVirtual() [x] SDL_JoystickDetachVirtual() [x] SDL_JoystickIsVirtual() [x] SDL_JoystickSetVirtualAxis() [x] SDL_JoystickSetVirtualButton() [x] SDL_JoystickSetVirtualHat() [x] SDL_LockSensors() [x] SDL_UnlockSensors() [x] SDL_HAPTIC_STEERING_AXIS [x] SDL_GetPreferredLocales() [x] SDL_OpenURL() [x] SDL_HasSurfaceRLE() [x] SDL_SIMDRealloc() [x] SDL_GetErrorMsg() [x] SDL_Metal_GetLayer() [x] SDL_Metal_GetDrawableSize() [x] SDL_HINT_JOYSTICK_HIDAPI_PS5 [x] SDL_HINT_MOUSE_RELATIVE_SCALING [x] SDL_HINT_PREFERRED_LOCALES [x] SDL_HINT_JOYSTICK_RAWINPUT [x] SDL_HINT_JOYSTICK_HIDAPI_CORRELATE_XINPUT [x] SDL_HINT_AUDIO_DEVICE_APP_NAME [x] SDL_HINT_AUDIO_DEVICE_STREAM_NAME [x] SDL_HINT_LINUX_JOYSTICK_DEADZONES [x] SDL_HINT_THREAD_PRIORITY_POLICY [x] SDL_HINT_THREAD_FORCE_REALTIME_TIME_CRITICAL [x] SDL_HINT_ANDROID_BLOCK_ON_PAUSE_PAUSEAUDIO [x] SDL_HINT_EMSCRIPTEN_ASYNCIFY [x] SDL_PIXELFORMAT_XRGB4444 [x] SDL_PIXELFORMAT_XBGR4444 [x] SDL_PIXELFORMAT_XRGB1555 [x] SDL_PIXELFORMAT_XBGR1555 [x] SDL_PIXELFORMAT_XRGB8888 [x] SDL_PIXELFORMAT_XBGR8888 [x] SDL_WINDOW_METAL [x] SDL_AndroidRequestPermission() ## 2.0.12 [x] SDL_GameControllerTypeForIndex [x] SDL_GameControllerGetType [x] SDL_GameControllerFromPlayerIndex [x] SDL_GameControllerSetPlayerIndex [x] SDL_JoystickFromPlayerIndex [x] SDL_JoystickSetPlayerIndex [x] SDL_GetTextureScaleMode [x] SDL_SetTextureScaleMode [x] SDL_LockTextureToSurface [x] SDL_BLENDMODE_MUL [x] SDL_TouchFingerEvent update [x] SDL_HasARMSIMD [x] SDL_HINT_DISPLAY_USABLE_BOUNDS [x] SDL_HINT_GAMECONTROLLERTYPE [x] SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS [x] SDL_HINT_JOYSTICK_HIDAPI_GAMECUBE [x] SDL_HINT_VIDEO_X11_WINDOW_VISUALID [x] SDL_HINT_VIDEO_X11_FORCE_EGL [x] SDL_Metal_CreateView [x] SDL_Metal_DestroyView [x] SDL_GetAndroidSDKVersion ## 2.0.10 [x] SDL_SIMDGetAlignment [x] SDL_SIMDAlloc [x] SDL_SIMDFree [x] SDL_RenderDrawPointF [x] SDL_RenderDrawPointsF [x] SDL_RenderDrawLineF [x] SDL_RenderDrawLinesF [x] SDL_RenderDrawRectF [x] SDL_RenderDrawRectsF [x] SDL_RenderFillRectF [x] SDL_RenderFillRectsF [x] SDL_RenderCopyF [x] SDL_RenderCopyExF [x] SDL_GetTouchDeviceType [x] SDL_RenderFlush [x] SDL_HINT_RENDER_BATCHING [x] SDL_HINT_EVENT_LOGGING [x] SDL_HINT_GAMECONTROLLERCONFIG_FILE [x] SDL_HINT_MOUSE_TOUCH_EVENTS ## 2.0.9 [x] SDL_SENSORUPDATE [x] SDL_DISPLAYEVENT [x] SDL_JoystickGetDevicePlayerIndex [x] SDL_JoystickGetPlayerIndex [x] SDL_GameControllerGetPlayerIndex [x] SDL_GameControllerRumble [x] SDL_JoystickRumble [x] SDL_GameControllerMappingForDeviceIndex [x] SDL_HINT_MOUSE_DOUBLE_CLICK_TIME [x] SDL_HINT_MOUSE_DOUBLE_CLICK_RADIUS [x] SDL_HasColorKey [x] SDL_HasAVX512F [x] SDL_IsTablet [?] SDL_THREAD_PRIORITY_TIME_CRITICAL ## 2.0.8 ### Hints [x] SDL_HINT_IOS_HIDE_HOME_INDICATOR [x] SDL_HINT_RETURN_KEY_HIDES_IME [x] SDL_HINT_TV_REMOTE_AS_JOYSTICK [x] SDL_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR [x] SDL_HINT_VIDEO_DOUBLE_BUFFER ### Surface [x] SDL_SetYUVConversionMode() [x] SDL_GetYUVConversionMode() ### Android [x] SDL_IsAndroidTV() ### Mac OS X / iOS / tvOS [x] SDL_RenderGetMetalLayer() [x] SDL_RenderGetMetalCommandEncoder() ### Windows UWP [ ] SDL_WinRTGetDeviceFamily() ## 2.0.7 ### General Audio - [x] SDL_NewAudioStream() - [x] SDL_AudioStreamPut() - [x] SDL_AudioStreamGet() - [x] SDL_AudioStreamAvailable() - [x] SDL_AudioStreamFlush() - [x] SDL_AudioStreamClear() - [x] SDL_FreeAudioStream() Joystick - [x] SDL_LockJoysticks() - [x] SDL_UnlockJoysticks() Stdinc - [ ] SDL_GetMemoryFunctions() - [ ] SDL_SetMemoryFunctions() - [ ] SDL_GetNumAllocations() ## 2.0.6 ### General Blend Mode - [x] SDL_ComposeCustomBlendMode() CPU Info - [x] SDL_HasNEON() Game Controller - [x] SDL_GameControllerGetVendor() - [x] SDL_GameControllerGetProduct() - [x] SDL_GameControllerGetProductVersion() - [x] SDL_GameControllerNumMappings() - [x] SDL_GameControllerMappingForIndex() Hints - [x] SDL_HINT_AUDIO_RESAMPLING_MODE - [x] SDL_HINT_RENDER_LOGICAL_SIZE_MODE - [x] SDL_HINT_MOUSE_NORMAL_SPEED_SCALE - [x] SDL_HINT_MOUSE_RELATIVE_SPEED_SCALE - [x] SDL_HINT_TOUCH_MOUSE_EVENTS Joystick - [x] SDL_JoystickGetDeviceVendor() - [x] SDL_JoystickGetDeviceProduct() - [x] SDL_JoystickGetDeviceProductVersion() - [x] SDL_JoystickGetDeviceType() - [x] SDL_JoystickGetDeviceInstanceID() - [x] SDL_JoystickGetVendor() - [x] SDL_JoystickGetProduct() - [x] SDL_JoystickGetProductVersion() - [x] SDL_JoystickGetType() - [x] SDL_JoystickGetAxisInitialState() RW Ops - [x] SDL_LoadFile() - [x] SDL_LoadFile_RW() Surface - [x] SDL_DuplicateSurface() Vulkan - [x] SDL_Vulkan_LoadLibrary() - [x] SDL_Vulkan_GetVkGetInstanceProcAddr() - [x] SDL_Vulkan_GetInstanceExtensions() - [x] SDL_Vulkan_CreateSurface() - [x] SDL_Vulkan_GetDrawableSize() - [x] SDL_Vulkan_UnloadLibrary() ### Windows Hints - [x] SDL_HINT_WINDOWS_INTRESOURCE_ICON - [x] SDL_HINT_WINDOWS_INTRESOURCE_ICON_SMALL ## Miscellaneous - [ ] Add ability to set window title bar color on runtime ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/audio.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,4)) #if defined(WARN_OUTDATED) #pragma message("SDL_QueueAudio is not supported before SDL 2.0.4") #endif static int SDL_QueueAudio(SDL_AudioDeviceID dev, const void *data, Uint32 len) { return -1; } static Uint32 SDL_GetQueuedAudioSize(SDL_AudioDeviceID dev_id) { return 0; } static void SDL_ClearQueuedAudio(SDL_AudioDeviceID dev) { } #endif #if !(SDL_VERSION_ATLEAST(2,0,5)) #if defined(WARN_OUTDATED) #pragma message("SDL_DequeueAudio is not supported before SDL 2.0.5") #endif static int SDL_DequeueAudio(SDL_AudioDeviceID dev, const void *data, Uint32 len) { return -1; } #endif #if !(SDL_VERSION_ATLEAST(2,0,7)) struct _SDL_AudioStream; typedef struct _SDL_AudioStream SDL_AudioStream; #if defined(WARN_OUTDATED) #pragma message("SDL_NewAudioStream is not supported before SDL 2.0.7") #endif static SDL_AudioStream * SDL_NewAudioStream(const SDL_AudioFormat src_format, const Uint8 src_channels, const int src_rate, const SDL_AudioFormat dst_format, const Uint8 dst_channels, const int dst_rate) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_AudioStreamPut is not supported before SDL 2.0.7") #endif static int SDL_AudioStreamPut(SDL_AudioStream *stream, const void *buf, int len) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_AudioStreamGet is not supported before SDL 2.0.7") #endif static int SDL_AudioStreamGet(SDL_AudioStream *stream, void *buf, int len) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_AudioStreamAvailable is not supported before SDL 2.0.7") #endif static int SDL_AudioStreamAvailable(SDL_AudioStream *stream) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_AudioStreamFlush is not supported before SDL 2.0.7") #endif static int SDL_AudioStreamFlush(SDL_AudioStream *stream) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_AudioStreamClear is not supported before SDL 2.0.7") #endif static int SDL_AudioStreamClear(SDL_AudioStream *stream) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_FreeAudioStream is not supported before SDL 2.0.7") #endif static void SDL_FreeAudioStream(SDL_AudioStream *stream) { } #endif #if !(SDL_VERSION_ATLEAST(2,0,16)) #if defined(WARN_OUTDATED) #pragma message("SDL_GetAudioDeviceSpec is not supported before SDL 2.0.16") #endif static int SDL_GetAudioDeviceSpec(int index, int iscapture, SDL_AudioSpec *spec) { return -1; } #endif */ import "C" import ( "reflect" "unsafe" ) // Audio format masks. // (https://wiki.libsdl.org/SDL_AudioFormat) const ( AUDIO_MASK_BITSIZE = C.SDL_AUDIO_MASK_BITSIZE // (0xFF) AUDIO_MASK_DATATYPE = C.SDL_AUDIO_MASK_DATATYPE // (1<<8) AUDIO_MASK_ENDIAN = C.SDL_AUDIO_MASK_ENDIAN // (1<<12) AUDIO_MASK_SIGNED = C.SDL_AUDIO_MASK_SIGNED // (1<<15) ) // Audio format values. // (https://wiki.libsdl.org/SDL_AudioFormat) const ( AUDIO_S8 = C.AUDIO_S8 // signed 8-bit samples AUDIO_U8 = C.AUDIO_U8 // unsigned 8-bit samples AUDIO_S16LSB = C.AUDIO_S16LSB // signed 16-bit samples in little-endian byte order AUDIO_S16MSB = C.AUDIO_S16MSB // signed 16-bit samples in big-endian byte order AUDIO_S16SYS = C.AUDIO_S16SYS // signed 16-bit samples in native byte order AUDIO_S16 = C.AUDIO_S16 // AUDIO_S16LSB AUDIO_U16LSB = C.AUDIO_U16LSB // unsigned 16-bit samples in little-endian byte order AUDIO_U16MSB = C.AUDIO_U16MSB // unsigned 16-bit samples in big-endian byte order AUDIO_U16SYS = C.AUDIO_U16SYS // unsigned 16-bit samples in native byte order AUDIO_U16 = C.AUDIO_U16 // AUDIO_U16LSB AUDIO_S32LSB = C.AUDIO_S32LSB // 32-bit integer samples in little-endian byte order AUDIO_S32MSB = C.AUDIO_S32MSB // 32-bit integer samples in big-endian byte order AUDIO_S32SYS = C.AUDIO_S32SYS // 32-bit integer samples in native byte order AUDIO_S32 = C.AUDIO_S32 // AUDIO_S32LSB AUDIO_F32LSB = C.AUDIO_F32LSB // 32-bit floating point samples in little-endian byte order AUDIO_F32MSB = C.AUDIO_F32MSB // 32-bit floating point samples in big-endian byte order AUDIO_F32SYS = C.AUDIO_F32SYS // 32-bit floating point samples in native byte order AUDIO_F32 = C.AUDIO_F32 // AUDIO_F32LSB ) // AllowedChanges flags specify how SDL should behave when a device cannot offer a specific feature. If the application requests a feature that the hardware doesn't offer, SDL will always try to get the closest equivalent. Used in OpenAudioDevice(). // (https://wiki.libsdl.org/SDL_OpenAudioDevice) const ( AUDIO_ALLOW_FREQUENCY_CHANGE = C.SDL_AUDIO_ALLOW_FREQUENCY_CHANGE AUDIO_ALLOW_FORMAT_CHANGE = C.SDL_AUDIO_ALLOW_FORMAT_CHANGE AUDIO_ALLOW_CHANNELS_CHANGE = C.SDL_AUDIO_ALLOW_CHANNELS_CHANGE AUDIO_ALLOW_ANY_CHANGE = C.SDL_AUDIO_ALLOW_ANY_CHANGE ) // An enumeration of audio device states used in GetAudioDeviceStatus() and GetAudioStatus(). // (https://wiki.libsdl.org/SDL_AudioStatus) const ( AUDIO_STOPPED AudioStatus = C.SDL_AUDIO_STOPPED // audio device is stopped AUDIO_PLAYING = C.SDL_AUDIO_PLAYING // audio device is playing AUDIO_PAUSED = C.SDL_AUDIO_PAUSED // audio device is paused ) // MIX_MAXVOLUME is the full audio volume value used in MixAudioFormat() and AudioFormat(). // (https://wiki.libsdl.org/SDL_MixAudioFormat) const MIX_MAXVOLUME = C.SDL_MIX_MAXVOLUME // full audio volume // AudioFormat is an enumeration of audio formats. // (https://wiki.libsdl.org/SDL_AudioFormat) type AudioFormat uint16 // AudioCallback is a function to call when the audio device needs more data.` // (https://wiki.libsdl.org/SDL_AudioSpec) type AudioCallback C.SDL_AudioCallback // AudioFilter is the filter list used in AudioCVT() (internal use) // (https://wiki.libsdl.org/SDL_AudioCVT) type AudioFilter C.SDL_AudioFilter // AudioDeviceID is ID of an audio device previously opened with OpenAudioDevice(). // (https://wiki.libsdl.org/SDL_OpenAudioDevice) type AudioDeviceID uint32 // AudioStatus is an enumeration of audio device states. // (https://wiki.libsdl.org/SDL_AudioStatus) type AudioStatus uint32 type cAudioStatus C.SDL_AudioStatus // AudioSpec contains the audio output format. It also contains a callback that is called when the audio device needs more data. // (https://wiki.libsdl.org/SDL_AudioSpec) type AudioSpec struct { Freq int32 // DSP frequency (samples per second) Format AudioFormat // audio data format Channels uint8 // number of separate sound channels Silence uint8 // audio buffer silence value (calculated) Samples uint16 // audio buffer size in samples (power of 2) _ uint16 // padding Size uint32 // audio buffer size in bytes (calculated) Callback AudioCallback // the function to call when the audio device needs more data UserData unsafe.Pointer // a pointer that is passed to callback (otherwise ignored by SDL) } type cAudioSpec C.SDL_AudioSpec // AudioCVT contains audio data conversion information. // (https://wiki.libsdl.org/SDL_AudioCVT) type AudioCVT struct { Needed int32 // set to 1 if conversion possible SrcFormat AudioFormat // source audio format DstFormat AudioFormat // target audio format RateIncr float64 // rate conversion increment Buf unsafe.Pointer // the buffer to hold entire audio data. Use AudioCVT.BufAsSlice() for access via a Go slice Len int32 // length of original audio buffer LenCVT int32 // length of converted audio buffer LenMult int32 // buf must be len*len_mult big LenRatio float64 // given len, final size is len*len_ratio filters [10]AudioFilter // filter list (internal use) filterIndex int32 // current audio conversion function (internal use) } type cAudioCVT C.SDL_AudioCVT // AudioStream is a new audio conversion interface. // (https://wiki.libsdl.org/SDL_AudioStream) type AudioStream C.SDL_AudioStream func (fmt AudioFormat) c() C.SDL_AudioFormat { return C.SDL_AudioFormat(fmt) } func (id AudioDeviceID) c() C.SDL_AudioDeviceID { return C.SDL_AudioDeviceID(id) } func (as *AudioSpec) cptr() *C.SDL_AudioSpec { return (*C.SDL_AudioSpec)(unsafe.Pointer(as)) } func (cvt *AudioCVT) cptr() *C.SDL_AudioCVT { return (*C.SDL_AudioCVT)(unsafe.Pointer(cvt)) } func (stream *AudioStream) cptr() *C.SDL_AudioStream { return (*C.SDL_AudioStream)(unsafe.Pointer(stream)) } // BitSize returns audio formats bit size. // (https://wiki.libsdl.org/SDL_AudioFormat) func (fmt AudioFormat) BitSize() uint8 { return uint8(fmt & AUDIO_MASK_BITSIZE) } // IsFloat reports whether audio format is float. // (https://wiki.libsdl.org/SDL_AudioFormat) func (fmt AudioFormat) IsFloat() bool { return (fmt & AUDIO_MASK_DATATYPE) > 0 } // IsBigEndian reports whether audio format is big-endian. // (https://wiki.libsdl.org/SDL_AudioFormat) func (fmt AudioFormat) IsBigEndian() bool { return (fmt & AUDIO_MASK_ENDIAN) > 0 } // IsSigned reports whether audio format is signed. // (https://wiki.libsdl.org/SDL_AudioFormat) func (fmt AudioFormat) IsSigned() bool { return (fmt & AUDIO_MASK_SIGNED) > 0 } // IsInt reports whether audio format is integer. // (https://wiki.libsdl.org/SDL_AudioFormat) func (fmt AudioFormat) IsInt() bool { return !fmt.IsFloat() } // IsLittleEndian reports whether audio format is little-endian. // (https://wiki.libsdl.org/SDL_AudioFormat) func (fmt AudioFormat) IsLittleEndian() bool { return !fmt.IsBigEndian() } // IsUnsigned reports whether audio format is unsigned. // (https://wiki.libsdl.org/SDL_AudioFormat) func (fmt AudioFormat) IsUnsigned() bool { return !fmt.IsSigned() } // AllocBuf allocates the requested memory for AudioCVT buffer. func (cvt *AudioCVT) AllocBuf(size uintptr) { cvt.Buf = C.malloc(C.size_t(size)) } // FreeBuf deallocates the memory previously allocated from AudioCVT buffer. func (cvt *AudioCVT) FreeBuf() { C.free(cvt.Buf) } // BufAsSlice returns AudioCVT.buf as byte slice. // NOTE: Must be used after ConvertAudio() because it uses LenCVT as slice length. func (cvt AudioCVT) BufAsSlice() []byte { var b []byte sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b)) sliceHeader.Len = int(cvt.LenCVT) sliceHeader.Cap = int(cvt.Len * cvt.LenMult) sliceHeader.Data = uintptr(unsafe.Pointer(cvt.Buf)) return b } // GetNumAudioDrivers returns the number of built-in audio drivers. // (https://wiki.libsdl.org/SDL_GetNumAudioDrivers) func GetNumAudioDrivers() int { return int(C.SDL_GetNumAudioDrivers()) } // GetAudioDriver returns the name of a built in audio driver. // (https://wiki.libsdl.org/SDL_GetAudioDriver) func GetAudioDriver(index int) string { return string(C.GoString(C.SDL_GetAudioDriver(C.int(index)))) } // AudioInit initializes a particular audio driver. // (https://wiki.libsdl.org/SDL_AudioInit) func AudioInit(driverName string) error { _driverName := C.CString(driverName) defer C.free(unsafe.Pointer(_driverName)) if C.SDL_AudioInit(_driverName) != 0 { return GetError() } return nil } // AudioQuit shuts down audio if you initialized it with AudioInit(). // (https://wiki.libsdl.org/SDL_AudioQuit) func AudioQuit() { C.SDL_AudioQuit() } // GetCurrentAudioDriver returns the name of the current audio driver. // (https://wiki.libsdl.org/SDL_GetCurrentAudioDriver) func GetCurrentAudioDriver() string { return string(C.GoString(C.SDL_GetCurrentAudioDriver())) } // OpenAudio opens the audio device. New programs might want to use OpenAudioDevice() instead. // (https://wiki.libsdl.org/SDL_OpenAudio) func OpenAudio(desired, obtained *AudioSpec) error { if C.SDL_OpenAudio(desired.cptr(), obtained.cptr()) != 0 { return GetError() } return nil } // GetNumAudioDevices returns the number of built-in audio devices. // (https://wiki.libsdl.org/SDL_GetNumAudioDevices) func GetNumAudioDevices(isCapture bool) int { return int(C.SDL_GetNumAudioDevices(C.int(Btoi(isCapture)))) } // GetAudioDeviceName returns the name of a specific audio device. // (https://wiki.libsdl.org/SDL_GetAudioDeviceName) func GetAudioDeviceName(index int, isCapture bool) string { return string(C.GoString(C.SDL_GetAudioDeviceName(C.int(index), C.int(Btoi(isCapture))))) } // OpenAudioDevice opens a specific audio device. // (https://wiki.libsdl.org/SDL_OpenAudioDevice) func OpenAudioDevice(device string, isCapture bool, desired, obtained *AudioSpec, allowedChanges int) (AudioDeviceID, error) { _device := C.CString(device) if device == "" { _device = nil } defer C.free(unsafe.Pointer(_device)) if id := AudioDeviceID(C.SDL_OpenAudioDevice(_device, C.int(Btoi(isCapture)), desired.cptr(), obtained.cptr(), C.int(allowedChanges))); id > 0 { return id, nil } return 0, GetError() } // GetAudioStatus returns the current audio state of the audio device. New programs might want to use GetAudioDeviceStatus() instead. // (https://wiki.libsdl.org/SDL_GetAudioStatus) func GetAudioStatus() AudioStatus { return (AudioStatus)(C.SDL_GetAudioStatus()) } // GetAudioDeviceStatus returns the current audio state of an audio device. // (https://wiki.libsdl.org/SDL_GetAudioDeviceStatus) func GetAudioDeviceStatus(dev AudioDeviceID) AudioStatus { return (AudioStatus)(C.SDL_GetAudioDeviceStatus(dev.c())) } // PauseAudio pauses and unpauses the audio device. New programs might want to use SDL_PauseAudioDevice() instead. // (https://wiki.libsdl.org/SDL_PauseAudio) func PauseAudio(pauseOn bool) { C.SDL_PauseAudio(C.int(Btoi(pauseOn))) } // PauseAudioDevice pauses and unpauses audio playback on a specified device. // (https://wiki.libsdl.org/SDL_PauseAudioDevice) func PauseAudioDevice(dev AudioDeviceID, pauseOn bool) { C.SDL_PauseAudioDevice(dev.c(), C.int(Btoi(pauseOn))) } // LoadWAVRW loads a WAVE from the data source, automatically freeing that source if freeSrc is true. // (https://wiki.libsdl.org/SDL_LoadWAV_RW) func LoadWAVRW(src *RWops, freeSrc bool) ([]byte, *AudioSpec) { var _audioBuf *C.Uint8 var _audioLen C.Uint32 audioSpec := (*AudioSpec)(unsafe.Pointer(C.SDL_LoadWAV_RW(src.cptr(), C.int(Btoi(freeSrc)), (&AudioSpec{}).cptr(), &_audioBuf, &_audioLen))) var b []byte sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b)) sliceHeader.Len = (int)(_audioLen) sliceHeader.Cap = (int)(_audioLen) sliceHeader.Data = uintptr(unsafe.Pointer(_audioBuf)) return b, audioSpec } // LoadWAV loads a WAVE from a file. // (https://wiki.libsdl.org/SDL_LoadWAV) func LoadWAV(file string) ([]byte, *AudioSpec) { _file := C.CString(file) _rb := C.CString("rb") defer C.free(unsafe.Pointer(_file)) defer C.free(unsafe.Pointer(_rb)) var _audioBuf *C.Uint8 var _audioLen C.Uint32 audioSpec := (*AudioSpec)(unsafe.Pointer(C.SDL_LoadWAV_RW(C.SDL_RWFromFile(_file, _rb), 1, (&AudioSpec{}).cptr(), &_audioBuf, &_audioLen))) var b []byte sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b)) sliceHeader.Len = (int)(_audioLen) sliceHeader.Cap = (int)(_audioLen) sliceHeader.Data = uintptr(unsafe.Pointer(_audioBuf)) return b, audioSpec } // FreeWAV frees data previously allocated with LoadWAV() or LoadWAVRW(). // (https://wiki.libsdl.org/SDL_FreeWAV) func FreeWAV(audioBuf []uint8) { sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&audioBuf)) _audioBuf := (*C.Uint8)(unsafe.Pointer(sliceHeader.Data)) C.SDL_FreeWAV(_audioBuf) } // BuildAudioCVT initializes an AudioCVT structure for conversion. // (https://wiki.libsdl.org/SDL_BuildAudioCVT) func BuildAudioCVT(cvt *AudioCVT, srcFormat AudioFormat, srcChannels uint8, srcRate int, dstFormat AudioFormat, dstChannels uint8, dstRate int) (converted bool, err error) { switch int(C.SDL_BuildAudioCVT(cvt.cptr(), srcFormat.c(), C.Uint8(srcChannels), C.int(srcRate), dstFormat.c(), C.Uint8(dstChannels), C.int(dstRate))) { case 1: return true, nil case 0: return false, nil } return false, GetError() } // ConvertAudio converts audio data to a desired audio format. // (https://wiki.libsdl.org/SDL_ConvertAudio) func ConvertAudio(cvt *AudioCVT) error { _cvt := (*C.SDL_AudioCVT)(unsafe.Pointer(cvt)) if C.SDL_ConvertAudio(_cvt) != 0 { return GetError() } return nil } // QueueAudio queues more audio on non-callback devices. // (https://wiki.libsdl.org/SDL_QueueAudio) func QueueAudio(dev AudioDeviceID, data []byte) error { sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&data)) _data := unsafe.Pointer(sliceHeader.Data) _len := (C.Uint32)(sliceHeader.Len) if C.SDL_QueueAudio(dev.c(), _data, _len) != 0 { return GetError() } return nil } // DequeueAudio dequeues more audio on non-callback devices. Returns the number of bytes dequeued, which could be less than requested // (https://wiki.libsdl.org/SDL_DequeueAudio) func DequeueAudio(dev AudioDeviceID, data []byte) (n int, err error) { sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&data)) _data := unsafe.Pointer(sliceHeader.Data) _len := (C.Uint32)(sliceHeader.Len) if dequeued := int(C.SDL_DequeueAudio(dev.c(), _data, _len)); dequeued > 0 { return dequeued, nil } return 0, GetError() } // GetQueuedAudioSize returns the number of bytes of still-queued audio. // (https://wiki.libsdl.org/SDL_GetQueuedAudioSize) func GetQueuedAudioSize(dev AudioDeviceID) uint32 { return uint32(C.SDL_GetQueuedAudioSize(dev.c())) } // ClearQueuedAudio drops any queued audio data waiting to be sent to the hardware. // (https://wiki.libsdl.org/SDL_ClearQueuedAudio) func ClearQueuedAudio(dev AudioDeviceID) { C.SDL_ClearQueuedAudio(dev.c()) } // MixAudio mixes audio data. New programs might want to use MixAudioFormat() instead. // (https://wiki.libsdl.org/SDL_MixAudio) func MixAudio(dst, src *uint8, len uint32, volume int) { _dst := (*C.Uint8)(unsafe.Pointer(dst)) _src := (*C.Uint8)(unsafe.Pointer(src)) C.SDL_MixAudio(_dst, _src, C.Uint32(len), C.int(volume)) } // MixAudioFormat mixes audio data in a specified format. // (https://wiki.libsdl.org/SDL_MixAudioFormat) func MixAudioFormat(dst, src *uint8, format AudioFormat, len uint32, volume int) { _dst := (*C.Uint8)(unsafe.Pointer(dst)) _src := (*C.Uint8)(unsafe.Pointer(src)) C.SDL_MixAudioFormat(_dst, _src, format.c(), C.Uint32(len), C.int(volume)) } // LockAudio locks the audio device. New programs might want to use LockAudioDevice() instead. // (https://wiki.libsdl.org/SDL_LockAudio) func LockAudio() { C.SDL_LockAudio() } // LockAudioDevice locks out the audio callback function for a specified device. // (https://wiki.libsdl.org/SDL_LockAudioDevice) func LockAudioDevice(dev AudioDeviceID) { C.SDL_LockAudioDevice(dev.c()) } // UnlockAudio unlocks the audio device. New programs might want to use UnlockAudioDevice() instead. // (https://wiki.libsdl.org/SDL_UnlockAudio) func UnlockAudio() { C.SDL_UnlockAudio() } // UnlockAudioDevice unlocks the audio callback function for a specified device. // (https://wiki.libsdl.org/SDL_UnlockAudioDevice) func UnlockAudioDevice(dev AudioDeviceID) { C.SDL_UnlockAudioDevice(dev.c()) } // CloseAudio closes the audio device. New programs might want to use CloseAudioDevice() instead. // (https://wiki.libsdl.org/SDL_CloseAudio) func CloseAudio() { C.SDL_CloseAudio() } // CloseAudioDevice shuts down audio processing and closes the audio device. // (https://wiki.libsdl.org/SDL_CloseAudioDevice) func CloseAudioDevice(dev AudioDeviceID) { C.SDL_CloseAudioDevice(dev.c()) } // NewAudioStream creates a new audio stream // TODO: (https://wiki.libsdl.org/SDL_NewAudioStream) func NewAudioStream(srcFormat AudioFormat, srcChannels uint8, srcRate int, dstFormat AudioFormat, dstChannels uint8, dstRate int) (stream *AudioStream, err error) { _srcFormat := C.SDL_AudioFormat(srcFormat) _srcChannels := C.Uint8(srcChannels) _srcRate := C.int(srcRate) _dstFormat := C.SDL_AudioFormat(dstFormat) _dstChannels := C.Uint8(dstChannels) _dstRate := C.int(dstRate) stream = (*AudioStream)(C.SDL_NewAudioStream(_srcFormat, _srcChannels, _srcRate, _dstFormat, _dstChannels, _dstRate)) if stream == nil { err = GetError() } return } // Put adds data to be converted/resampled to the stream // TODO: (https://wiki.libsdl.org/SDL_AudioStreamPut) func (stream *AudioStream) Put(buf []byte) (err error) { sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&buf)) _buf := unsafe.Pointer(sliceHeader.Data) _len := C.int(len(buf)) ret := int(C.SDL_AudioStreamPut(stream.cptr(), _buf, _len)) err = errorFromInt(ret) return } // Get gets converted/resampled data from the stream. Returns the number of bytes read from the stream. // (https://wiki.libsdl.org/SDL_AudioStreamGet) func (stream *AudioStream) Get(buf []byte) (n int, err error) { sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&buf)) _buf := unsafe.Pointer(sliceHeader.Data) _len := C.int(len(buf)) if ret := int(C.SDL_AudioStreamGet(stream.cptr(), _buf, _len)); ret < 0 { return 0, errorFromInt(ret) } else { return ret, nil } } // Available gets the number of converted/resampled bytes available // TODO: (https://wiki.libsdl.org/SDL_AudioStreamAvailable) func (stream *AudioStream) Available() (err error) { ret := int(C.SDL_AudioStreamAvailable(stream.cptr())) err = errorFromInt(ret) return } // Flush tells the stream that you're done sending data, and anything being buffered // should be converted/resampled and made available immediately. // TODO: (https://wiki.libsdl.org/SDL_AudioStreamFlush) func (stream *AudioStream) Flush() (err error) { ret := int(C.SDL_AudioStreamFlush(stream.cptr())) err = errorFromInt(ret) return } // Clear clears any pending data in the stream without converting it // TODO: (https://wiki.libsdl.org/SDL_AudioStreamClear) func (stream *AudioStream) Clear() { C.SDL_AudioStreamClear(stream.cptr()) } // Free frees the audio stream // TODO: (https://wiki.libsdl.org/SDL_AudoiStreamFree) func (stream *AudioStream) Free() { C.SDL_FreeAudioStream(stream.cptr()) } // GetAudioDeviceSpec returns the preferred audio format of a specific audio device. // (https://wiki.libsdl.org/SDL_GetAudioDeviceSpec) func GetAudioDeviceSpec(index int, isCapture bool) (spec *AudioSpec, err error) { spec = &AudioSpec{} err = errorFromInt(int(C.SDL_GetAudioDeviceSpec(C.int(index), C.int(Btoi(isCapture)), spec.cptr()))) return } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/blendmode.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,6)) #if defined(WARN_OUTDATED) #pragma message("SDL_BLENDMODE_INVALID is not supported before SDL 2.0.6") #endif #define SDL_BLENDMODE_INVALID (0x7FFFFFFF) #if defined(WARN_OUTDATED) #pragma message("SDL_BlendOperation is not supported before SDL 2.0.6") #endif typedef enum { SDL_BLENDOPERATION_ADD = 0x1, SDL_BLENDOPERATION_SUBTRACT = 0x2, SDL_BLENDOPERATION_REV_SUBTRACT = 0x3, SDL_BLENDOPERATION_MINIMUM = 0x4, SDL_BLENDOPERATION_MAXIMUM = 0x5 } SDL_BlendOperation; #if defined(WARN_OUTDATED) #pragma message("SDL_BlendFactor is not supported before SDL 2.0.6") #endif typedef enum { SDL_BLENDFACTOR_ZERO = 0x1, SDL_BLENDFACTOR_ONE = 0x2, SDL_BLENDFACTOR_SRC_COLOR = 0x3, SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR = 0x4, SDL_BLENDFACTOR_SRC_ALPHA = 0x5, SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA = 0x6, SDL_BLENDFACTOR_DST_COLOR = 0x7, SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR = 0x8, SDL_BLENDFACTOR_DST_ALPHA = 0x9, SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA = 0xA } SDL_BlendFactor; #if defined(WARN_OUTDATED) #pragma message("SDL_ComposeCustomBlendMode is not supported before SDL 2.0.6") #endif SDL_BlendMode SDLCALL SDL_ComposeCustomBlendMode(SDL_BlendFactor srcColorFactor, SDL_BlendFactor dstColorFactor, SDL_BlendOperation colorOperation, SDL_BlendFactor srcAlphaFactor, SDL_BlendFactor dstAlphaFactor, SDL_BlendOperation alphaOperation) { return SDL_BLENDMODE_NONE; } #endif */ import "C" import "unsafe" // BlendMode is an enumeration of blend modes used in Render.Copy() and drawing operations. // (https://wiki.libsdl.org/SDL_BlendMode) type BlendMode uint32 const ( BLENDMODE_NONE = C.SDL_BLENDMODE_NONE // no blending BLENDMODE_BLEND = C.SDL_BLENDMODE_BLEND // alpha blending BLENDMODE_ADD = C.SDL_BLENDMODE_ADD // additive blending BLENDMODE_MOD = C.SDL_BLENDMODE_MOD // color modulate BLENDMODE_INVALID = C.SDL_BLENDMODE_INVALID ) func (bm BlendMode) c() C.SDL_BlendMode { return C.SDL_BlendMode(C.Uint32(bm)) } func (bm *BlendMode) cptr() *C.SDL_BlendMode { return (*C.SDL_BlendMode)(unsafe.Pointer(bm)) } // BlendOperation is an enumeration of blend operations used when creating a custom blend mode with ComposeCustomBlendMode(). // (https://wiki.libsdl.org/SDL_BlendOperation) type BlendOperation C.SDL_BlendOperation const ( BLENDOPERATION_ADD = C.SDL_BLENDOPERATION_ADD BLENDOPERATION_SUBTRACT = C.SDL_BLENDOPERATION_SUBTRACT BLENDOPERATION_REV_SUBTRACT = C.SDL_BLENDOPERATION_REV_SUBTRACT BLENDOPERATION_MINIMUM = C.SDL_BLENDOPERATION_MINIMUM BLENDOPERATION_MAXIMUM = C.SDL_BLENDOPERATION_MAXIMUM ) // BlendFactor is an enumeration of blend factors used when creating a custom blend mode with ComposeCustomBlendMode(). // (https://wiki.libsdl.org/SDL_BlendFactor) type BlendFactor C.SDL_BlendFactor const ( BLENDFACTOR_ZERO = C.SDL_BLENDFACTOR_ZERO // 0, 0, 0, 0 BLENDFACTOR_ONE = C.SDL_BLENDFACTOR_ONE // 1, 1, 1, 1 BLENDFACTOR_SRC_COLOR = C.SDL_BLENDFACTOR_SRC_COLOR // srcR, srcG, srcB, srcA BLENDFACTOR_ONE_MINUS_SRC_COLOR = C.SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR // 1-srcR, 1-srcG, 1-srcB, 1-srcA BLENDFACTOR_SRC_ALPHA = C.SDL_BLENDFACTOR_SRC_ALPHA // srcA, srcA, srcA, srcA BLENDFACTOR_ONE_MINUS_SRC_ALPHA = C.SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA // 1-srcA, 1-srcA, 1-srcA, 1-srcA BLENDFACTOR_DST_COLOR = C.SDL_BLENDFACTOR_DST_COLOR // dstR, dstG, dstB, dstA BLENDFACTOR_ONE_MINUS_DST_COLOR = C.SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR // 1-dstR, 1-dstG, 1-dstB, 1-dstA BLENDFACTOR_DST_ALPHA = C.SDL_BLENDFACTOR_DST_ALPHA // dstA, dstA, dstA, dstA BLENDFACTOR_ONE_MINUS_DST_ALPHA = C.SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA // 1-dstA, 1-dstA, 1-dstA, 1-dstA ) // ComposeCustomBlendMode creates a custom blend mode, which may or may not be supported by a given renderer // The result of the blend mode operation will be: // dstRGB = dstRGB * dstColorFactor colorOperation srcRGB * srcColorFactor // and // dstA = dstA * dstAlphaFactor alphaOperation srcA * srcAlphaFactor // (https://wiki.libsdl.org/SDL_ComposeCustomBlendMode) func ComposeCustomBlendMode(srcColorFactor, dstColorFactor BlendFactor, colorOperation BlendOperation, srcAlphaFactor, dstAlphaFactor BlendFactor, alphaOperation BlendOperation) BlendMode { _srcColorFactor := C.SDL_BlendFactor(srcColorFactor) _dstColorFactor := C.SDL_BlendFactor(dstColorFactor) _colorOperation := C.SDL_BlendOperation(colorOperation) _srcAlphaFactor := C.SDL_BlendFactor(srcAlphaFactor) _dstAlphaFactor := C.SDL_BlendFactor(dstAlphaFactor) _alphaOperation := C.SDL_BlendOperation(alphaOperation) return BlendMode(C.SDL_ComposeCustomBlendMode(_srcColorFactor, _dstColorFactor, _colorOperation, _srcAlphaFactor, _dstAlphaFactor, _alphaOperation)) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/clipboard.go ================================================ package sdl // #include "sdl_wrapper.h" import "C" import "unsafe" // SetClipboardText puts UTF-8 text into the clipboard. // (https://wiki.libsdl.org/SDL_SetClipboardText) func SetClipboardText(text string) error { _text := C.CString(text) defer C.free(unsafe.Pointer(_text)) if C.SDL_SetClipboardText(_text) < 0 { return GetError() } return nil } // GetClipboardText returns UTF-8 text from the clipboard. // (https://wiki.libsdl.org/SDL_GetClipboardText) func GetClipboardText() (string, error) { text := C.SDL_GetClipboardText() if text == nil { return "", GetError() } defer C.SDL_free(unsafe.Pointer(text)) _text := C.GoString(text) return _text, nil } // HasClipboardText reports whether the clipboard exists and contains a text string that is non-empty. // (https://wiki.libsdl.org/SDL_HasClipboardText) func HasClipboardText() bool { return C.SDL_HasClipboardText() > 0 } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/cpuinfo.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,9)) #if defined(WARN_OUTDATED) #pragma message("SDL_HasAVX512F is not supported before SDL 2.0.9") #endif static inline SDL_bool SDL_HasAVX512F() { return SDL_FALSE; } #endif #if !(SDL_VERSION_ATLEAST(2,0,1)) #if defined(WARN_OUTDATED) #pragma message("SDL_GetSystemRAM is not supported before SDL 2.0.1") #endif static inline int SDL_GetSystemRAM() { return -1; } #endif #if !(SDL_VERSION_ATLEAST(2,0,2)) #if defined(WARN_OUTDATED) #pragma message("SDL_HasAVX is not supported before SDL 2.0.2") #endif static inline SDL_bool SDL_HasAVX() { return SDL_FALSE; } #endif #if !(SDL_VERSION_ATLEAST(2,0,4)) #if defined(WARN_OUTDATED) #pragma message("SDL_HasAVX2 is not supported before SDL 2.0.4") #endif static inline SDL_bool SDL_HasAVX2() { return SDL_FALSE; } #endif #if !(SDL_VERSION_ATLEAST(2,0,6)) #if defined(WARN_OUTDATED) #pragma message("SDL_HasNEON is not supported before SDL 2.0.4") #endif static inline SDL_bool SDL_HasNEON() { return SDL_FALSE; } #endif #if !(SDL_VERSION_ATLEAST(2,0,10)) #if defined(WARN_OUTDATED) #pragma message("SDL_SIMDGetAlignment is not supported before SDL 2.0.10") #endif static inline size_t SDL_SIMDGetAlignment(void) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_SIMDAlloc is not supported before SDL 2.0.10") #endif static inline void * SDL_SIMDAlloc(const size_t len) { return NULL; } #if defined(WARN_OUTDATED) #pragma message("SDL_SIMDFree is not supported before SDL 2.0.10") #endif static inline void SDL_SIMDFree(void *ptr) { } #endif */ import "C" import "unsafe" // CACHELINE_SIZE is a cacheline size used for padding. const CACHELINE_SIZE = C.SDL_CACHELINE_SIZE // GetCPUCount returns the number of CPU cores available. // (https://wiki.libsdl.org/SDL_GetCPUCount) func GetCPUCount() int { return int(C.SDL_GetCPUCount()) } // GetCPUCacheLineSize returns the L1 cache line size of the CPU. // (https://wiki.libsdl.org/SDL_GetCPUCacheLineSize) func GetCPUCacheLineSize() int { return int(C.SDL_GetCPUCacheLineSize()) } // HasRDTSC reports whether the CPU has the RDTSC instruction. // (https://wiki.libsdl.org/SDL_HasRDTSC) func HasRDTSC() bool { return C.SDL_HasRDTSC() > 0 } // HasAltiVec reports whether the CPU has AltiVec features. // (https://wiki.libsdl.org/SDL_HasAltiVec) func HasAltiVec() bool { return C.SDL_HasAltiVec() > 0 } // HasMMX reports whether the CPU has MMX features. // (https://wiki.libsdl.org/SDL_HasMMX) func HasMMX() bool { return C.SDL_HasMMX() > 0 } // Has3DNow reports whether the CPU has 3DNow! features. // (https://wiki.libsdl.org/SDL_Has3DNow) func Has3DNow() bool { return C.SDL_Has3DNow() > 0 } // HasSSE reports whether the CPU has SSE features. // (https://wiki.libsdl.org/SDL_HasSSE) func HasSSE() bool { return C.SDL_HasSSE() > 0 } // HasSSE2 reports whether the CPU has SSE2 features. // (https://wiki.libsdl.org/SDL_HasSSE2) func HasSSE2() bool { return C.SDL_HasSSE2() > 0 } // HasSSE3 reports whether the CPU has SSE3 features. // (https://wiki.libsdl.org/SDL_HasSSE3) func HasSSE3() bool { return C.SDL_HasSSE3() > 0 } // HasSSE41 reports whether the CPU has SSE4.1 features. // (https://wiki.libsdl.org/SDL_HasSSE41) func HasSSE41() bool { return C.SDL_HasSSE41() > 0 } // HasSSE42 reports whether the CPU has SSE4.2 features. // (https://wiki.libsdl.org/SDL_HasSSE42) func HasSSE42() bool { return C.SDL_HasSSE42() > 0 } // GetSystemRAM returns the amount of RAM configured in the system. // (https://wiki.libsdl.org/SDL_GetSystemRAM) func GetSystemRAM() int { return int(C.SDL_GetSystemRAM()) } // HasAVX reports whether the CPU has AVX features. // (https://wiki.libsdl.org/SDL_HasAVX) func HasAVX() bool { return C.SDL_HasAVX() > 0 } // HasAVX512F reports whether the CPU has AVX-512F (foundation) features. // TODO: (https://wiki.libsdl.org/SDL_HasAVX512F) func HasAVX512F() bool { return C.SDL_HasAVX512F() > 0 } // HasAVX2 reports whether the CPU has AVX2 features. // (https://wiki.libsdl.org/SDL_HasAVX2) func HasAVX2() bool { return C.SDL_HasAVX2() > 0 } // HasNEON reports whether the CPU has NEON features. // (https://wiki.libsdl.org/SDL_HasNEON) func HasNEON() bool { return C.SDL_HasNEON() > 0 } // SIMDGetAlignment reports the alignment this system needs for SIMD allocations. // TODO: (https://wiki.libsdl.org/SDL_SIMDGetAlignment) func SIMDGetAlignment() int { return int(C.SDL_SIMDGetAlignment()) } // SIMDAlloc allocates memory in a SIMD-friendly way. // TODO: (https://wiki.libsdl.org/SDL_SIMDAlloc) func SIMDAlloc(_len int) unsafe.Pointer { return C.SDL_SIMDAlloc(C.size_t(_len)) } // SIMDFree deallocates memory obtained from SDL_SIMDAlloc. // TODO: (https://wiki.libsdl.org/SDL_SIMDFree) func SIMDFree(p unsafe.Pointer) { C.SDL_SIMDFree(p) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/endian.go ================================================ package sdl // #include "sdl_wrapper.h" import "C" // Endian-specific values. // (https://wiki.libsdl.org/CategoryEndian) const ( BYTEORDER = C.SDL_BYTEORDER // macro that corresponds to the byte order used by the processor type it was compiled for LIL_ENDIAN = C.SDL_LIL_ENDIAN // byte order is 1234, where the least significant byte is stored first BIG_ENDIAN = C.SDL_BIG_ENDIAN // byte order is 4321, where the most significant byte is stored first ) ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/error.go ================================================ package sdl /* #include "sdl_wrapper.h" void GoSetError(const char *fmt) { SDL_SetError("%s", fmt); } */ // #include "sdl_wrapper.h" import "C" import "errors" var emptyCString *C.char = C.CString("") var ErrInvalidParameters = errors.New("Invalid Parameters") // SDL error codes with their corresponding predefined strings. const ( ENOMEM ErrorCode = C.SDL_ENOMEM // out of memory EFREAD = C.SDL_EFREAD // error reading from datastream EFWRITE = C.SDL_EFWRITE // error writing to datastream EFSEEK = C.SDL_EFSEEK // error seeking in datastream UNSUPPORTED = C.SDL_UNSUPPORTED // that operation is not supported LASTERROR = C.SDL_LASTERROR // the highest numbered predefined error ) // ErrorCode is an error code used in SDL error messages. type ErrorCode uint32 type cErrorCode C.SDL_errorcode func (ec ErrorCode) c() C.SDL_errorcode { return C.SDL_errorcode(ec) } // GetError returns the last error that occurred, or an empty string if there hasn't been an error message set since the last call to ClearError(). // (https://wiki.libsdl.org/SDL_GetError) func GetError() error { if err := C.SDL_GetError(); err != nil { gostr := C.GoString(err) // SDL_GetError returns "an empty string if there hasn't been an error message" if len(gostr) > 0 { return errors.New(gostr) } } return nil } // SetError set the SDL error message. // (https://wiki.libsdl.org/SDL_SetError) func SetError(err error) { if err != nil { C.GoSetError(C.CString(err.Error())) return } C.GoSetError(emptyCString) } // ClearError clears any previous error message. // (https://wiki.libsdl.org/SDL_ClearError) func ClearError() { C.SDL_ClearError() } // Error sets the SDL error message to the specified error code. func Error(code ErrorCode) { C.SDL_Error(code.c()) } // OutOfMemory sets SDL error message to ENOMEM (out of memory). func OutOfMemory() { Error(ENOMEM) } // Unsupported sets SDL error message to UNSUPPORTED (that operation is not supported). func Unsupported() { Error(UNSUPPORTED) } // errorFromInt returns GetError() if passed negative value, otherwise it returns nil. func errorFromInt(code int) (err error) { if code < 0 { err = GetError() if err == nil { err = errors.New("Unknown error (probably using old version of SDL2 and the function called is not supported?)") } } return } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/events.c ================================================ #include "_cgo_export.h" #include "events.h" SDL_Event event; void setEventFilter() { SDL_SetEventFilter((SDL_EventFilter)goSetEventFilterCallback, NULL); } void clearEventFilter() { SDL_SetEventFilter(NULL, NULL); } void filterEvents(void *userdata) { SDL_FilterEvents((SDL_EventFilter)goEventFilterCallback, userdata); } void addEventWatch(void *userdata) { SDL_AddEventWatch((SDL_EventFilter)goEventFilterCallback, userdata); } void delEventWatch(void *userdata) { SDL_DelEventWatch((SDL_EventFilter)goEventFilterCallback, userdata); } int PollEvent() { return SDL_PollEvent(&event); } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/events.go ================================================ package sdl /* #include "sdl_wrapper.h" #include "events.h" #if !SDL_VERSION_ATLEAST(2,0,9) #define SDL_DISPLAYEVENT (0x150) #endif #if !SDL_VERSION_ATLEAST(2,0,2) #define SDL_RENDER_TARGETS_RESET (0x2000) #endif #if !SDL_VERSION_ATLEAST(2,0,4) #if defined(WARN_OUTDATED) #pragma message("SDL_KEYMAPCHANGED is not supported before SDL 2.0.4") #endif #define SDL_KEYMAPCHANGED (0x304) #if defined(WARN_OUTDATED) #pragma message("SDL_AUDIODEVICEADDED is not supported before SDL 2.0.4") #endif #define SDL_AUDIODEVICEADDED (0x1100) #if defined(WARN_OUTDATED) #pragma message("SDL_AUDIODEVICEREMOVED is not supported before SDL 2.0.4") #endif #define SDL_AUDIODEVICEREMOVED (0x1101) #if defined(WARN_OUTDATED) #pragma message("SDL_RENDER_DEVICE_RESET is not supported before SDL 2.0.4") #endif #define SDL_RENDER_DEVICE_RESET (0x2001) #if defined(WARN_OUTDATED) #pragma message("SDL_AudioDeviceEvent is not supported before SDL 2.0.4") #endif typedef struct SDL_AudioDeviceEvent { Uint32 type; Uint32 timestamp; Uint32 which; Uint8 iscapture; Uint8 padding1; Uint8 padding2; Uint8 padding3; } SDL_AudioDeviceEvent; #endif #if !SDL_VERSION_ATLEAST(2,0,5) #if defined(WARN_OUTDATED) #pragma message("SDL_DROPTEXT is not supported before SDL 2.0.5") #endif #define SDL_DROPTEXT (0x1001) #if defined(WARN_OUTDATED) #pragma message("SDL_DROPBEGIN is not supported before SDL 2.0.5") #endif #define SDL_DROPBEGIN (0x1002) #if defined(WARN_OUTDATED) #pragma message("SDL_DROPCOMPLETE is not supported before SDL 2.0.5") #endif #define SDL_DROPCOMPLETE (0x1003) #endif #if !SDL_VERSION_ATLEAST(2,0,9) #define SDL_SENSORUPDATE (0x1200) typedef struct SDL_SensorEvent { Uint32 type; Uint32 timestamp; Sint32 which; float data[6]; } SDL_SensorEvent; #endif #if !SDL_VERSION_ATLEAST(2,0,22) #if defined(WARN_OUTDATED) #pragma message("SDL_TEXTEDITING_EXT is not supported before SDL 2.0.22") #endif #define SDL_TEXTEDITING_EXT (0x305) #endif // NOTE: To prevent build from failing when using older SDL2, we create a // structure definiton that directly maps to the SDL2 struct definition if // using the latest SDL2. Otherwise, we copy the latest definition and paste // it here. #if SDL_VERSION_ATLEAST(2,0,22) typedef SDL_MouseButtonEvent MouseButtonEvent; typedef SDL_MouseWheelEvent MouseWheelEvent; typedef SDL_TouchFingerEvent TouchFingerEvent; typedef SDL_DropEvent DropEvent; #else typedef struct MouseButtonEvent { Uint32 type; // ::SDL_MOUSEBUTTONDOWN or ::SDL_MOUSEBUTTONUP Uint32 timestamp; Uint32 windowID; // The window with mouse focus, if any Uint32 which; // The mouse instance id, or SDL_TOUCH_MOUSEID Uint8 button; // The mouse button index Uint8 state; // ::SDL_PRESSED or ::SDL_RELEASED Uint8 clicks; // 1 for single-click, 2 for double-click, etc. Uint8 padding1; Sint32 x; // X coordinate, relative to window Sint32 y; // Y coordinate, relative to window } MouseButtonEvent; typedef struct MouseWheelEvent { Uint32 type; // ::SDL_MOUSEWHEEL Uint32 timestamp; // In milliseconds, populated using SDL_GetTicks() Uint32 windowID; // The window with mouse focus, if any Uint32 which; // The mouse instance id, or SDL_TOUCH_MOUSEID Sint32 x; // The amount scrolled horizontally, positive to the right and negative to the left Sint32 y; // The amount scrolled vertically, positive away from the user and negative toward the user Uint32 direction; // Set to one of the SDL_MOUSEWHEEL_* defines. When FLIPPED the values in X and Y will be opposite. Multiply by -1 to change them back float preciseX; // The amount scrolled horizontally, positive to the right and negative to the left, with float precision (added in 2.0.18) float preciseY; // The amount scrolled vertically, positive away from the user and negative toward the user, with float precision (added in 2.0.18) } MouseWheelEvent; typedef struct TouchFingerEvent { Uint32 type; // ::SDL_FINGERMOTION or ::SDL_FINGERDOWN or ::SDL_FINGERUP Uint32 timestamp; // In milliseconds, populated using SDL_GetTicks() SDL_TouchID touchId; // The touch device id SDL_FingerID fingerId; // float x; // Normalized in the range 0...1 float y; // Normalized in the range 0...1 float dx; // Normalized in the range -1...1 float dy; // Normalized in the range -1...1 float pressure; // Normalized in the range 0...1 Uint32 windowID; // The window underneath the finger, if any } TouchFingerEvent; typedef struct DropEvent { Uint32 type; // ::SDL_DROPBEGIN or ::SDL_DROPFILE or ::SDL_DROPTEXT or ::SDL_DROPCOMPLETE Uint32 timestamp; // In milliseconds, populated using SDL_GetTicks() char *file; // The file name, which should be freed with SDL_free(), is NULL on begin/complete Uint32 windowID; // The window that was dropped on, if any } DropEvent; #endif #if !SDL_VERSION_ATLEAST(2,24,0) #if defined(WARN_OUTDATED) #pragma message("SDL_JOYBATTEYUPDATED is not supported before SDL 2.24.0") #endif #define SDL_JOYBATTERYUPDATED (1543) #if !SDL_VERSION_ATLEAST(2,0,4) typedef enum { SDL_JOYSTICK_POWER_UNKNOWN = -1, SDL_JOYSTICK_POWER_EMPTY, SDL_JOYSTICK_POWER_LOW, SDL_JOYSTICK_POWER_MEDIUM, SDL_JOYSTICK_POWER_FULL, SDL_JOYSTICK_POWER_WIRED, SDL_JOYSTICK_POWER_MAX } SDL_JoystickPowerLevel; #endif typedef struct SDL_JoyBatteryEvent { Uint32 type; Uint32 timestamp; SDL_JoystickID which; SDL_JoystickPowerLevel level; } SDL_JoyBatteryEvent; #endif */ import "C" import ( "reflect" "sync" "unsafe" ) var ( eventFilterCache EventFilter eventWatches = make(map[EventWatchHandle]*eventFilterCallbackContext) lastEventWatchHandleMutex sync.Mutex lastEventWatchHandle EventWatchHandle cevent C.SDL_Event ) // Enumeration of the types of events that can be delivered. // (https://wiki.libsdl.org/SDL_EventType) const ( FIRSTEVENT = C.SDL_FIRSTEVENT // do not remove (unused) // Application events QUIT = C.SDL_QUIT // user-requested quit // Android, iOS and WinRT events APP_TERMINATING = C.SDL_APP_TERMINATING // OS is terminating the application APP_LOWMEMORY = C.SDL_APP_LOWMEMORY // OS is low on memory; free some APP_WILLENTERBACKGROUND = C.SDL_APP_WILLENTERBACKGROUND // application is entering background APP_DIDENTERBACKGROUND = C.SDL_APP_DIDENTERBACKGROUND //application entered background APP_WILLENTERFOREGROUND = C.SDL_APP_WILLENTERFOREGROUND // application is entering foreground APP_DIDENTERFOREGROUND = C.SDL_APP_DIDENTERFOREGROUND // application entered foreground // Display events DISPLAYEVENT = C.SDL_DISPLAYEVENT // Display state change // Window events WINDOWEVENT = C.SDL_WINDOWEVENT // window state change SYSWMEVENT = C.SDL_SYSWMEVENT // system specific event // Keyboard events KEYDOWN = C.SDL_KEYDOWN // key pressed KEYUP = C.SDL_KEYUP // key released TEXTEDITING = C.SDL_TEXTEDITING // keyboard text editing (composition) TEXTINPUT = C.SDL_TEXTINPUT // keyboard text input TEXTEDITING_EXT = C.SDL_TEXTEDITING_EXT // keyboard text editing (composition) KEYMAPCHANGED = C.SDL_KEYMAPCHANGED // keymap changed due to a system event such as an input language or keyboard layout change (>= SDL 2.0.4) // Mouse events MOUSEMOTION = C.SDL_MOUSEMOTION // mouse moved MOUSEBUTTONDOWN = C.SDL_MOUSEBUTTONDOWN // mouse button pressed MOUSEBUTTONUP = C.SDL_MOUSEBUTTONUP // mouse button released MOUSEWHEEL = C.SDL_MOUSEWHEEL // mouse wheel motion // Joystick events JOYAXISMOTION = C.SDL_JOYAXISMOTION // joystick axis motion JOYBALLMOTION = C.SDL_JOYBALLMOTION // joystick trackball motion JOYHATMOTION = C.SDL_JOYHATMOTION // joystick hat position change JOYBUTTONDOWN = C.SDL_JOYBUTTONDOWN // joystick button pressed JOYBUTTONUP = C.SDL_JOYBUTTONUP // joystick button released JOYDEVICEADDED = C.SDL_JOYDEVICEADDED // joystick connected JOYDEVICEREMOVED = C.SDL_JOYDEVICEREMOVED // joystick disconnected // Game controller events CONTROLLERAXISMOTION = C.SDL_CONTROLLERAXISMOTION // controller axis motion CONTROLLERBUTTONDOWN = C.SDL_CONTROLLERBUTTONDOWN // controller button pressed CONTROLLERBUTTONUP = C.SDL_CONTROLLERBUTTONUP // controller button released CONTROLLERDEVICEADDED = C.SDL_CONTROLLERDEVICEADDED // controller connected CONTROLLERDEVICEREMOVED = C.SDL_CONTROLLERDEVICEREMOVED // controller disconnected CONTROLLERDEVICEREMAPPED = C.SDL_CONTROLLERDEVICEREMAPPED // controller mapping updated // Touch events FINGERDOWN = C.SDL_FINGERDOWN // user has touched input device FINGERUP = C.SDL_FINGERUP // user stopped touching input device FINGERMOTION = C.SDL_FINGERMOTION // user is dragging finger on input device // Gesture events DOLLARGESTURE = C.SDL_DOLLARGESTURE DOLLARRECORD = C.SDL_DOLLARRECORD MULTIGESTURE = C.SDL_MULTIGESTURE // Clipboard events CLIPBOARDUPDATE = C.SDL_CLIPBOARDUPDATE // the clipboard changed // Drag and drop events DROPFILE = C.SDL_DROPFILE // the system requests a file open DROPTEXT = C.SDL_DROPTEXT // text/plain drag-and-drop event DROPBEGIN = C.SDL_DROPBEGIN // a new set of drops is beginning (NULL filename) DROPCOMPLETE = C.SDL_DROPCOMPLETE // current set of drops is now complete (NULL filename) // Audio hotplug events AUDIODEVICEADDED = C.SDL_AUDIODEVICEADDED // a new audio device is available (>= SDL 2.0.4) AUDIODEVICEREMOVED = C.SDL_AUDIODEVICEREMOVED // an audio device has been removed (>= SDL 2.0.4) // Sensor events SENSORUPDATE = C.SDL_SENSORUPDATE // a sensor was updated // Render events RENDER_TARGETS_RESET = C.SDL_RENDER_TARGETS_RESET // the render targets have been reset and their contents need to be updated (>= SDL 2.0.2) RENDER_DEVICE_RESET = C.SDL_RENDER_DEVICE_RESET // the device has been reset and all textures need to be recreated (>= SDL 2.0.4) // These are for your use, and should be allocated with RegisterEvents() USEREVENT = C.SDL_USEREVENT // a user-specified event LASTEVENT = C.SDL_LASTEVENT // (only for bounding internal arrays) ) // Actions for PeepEvents(). // (https://wiki.libsdl.org/SDL_PeepEvents) const ( ADDEVENT = C.SDL_ADDEVENT // up to numevents events will be added to the back of the event queue PEEKEVENT = C.SDL_PEEKEVENT // up to numevents events at the front of the event queue, within the specified minimum and maximum type, will be returned and will not be removed from the queue GETEVENT = C.SDL_GETEVENT // up to numevents events at the front of the event queue, within the specified minimum and maximum type, will be returned and will be removed from the queue ) // Toggles for different event state functions. const ( QUERY = C.SDL_QUERY IGNORE = C.SDL_IGNORE DISABLE = C.SDL_DISABLE ENABLE = C.SDL_ENABLE ) // Event is a union of all event structures used in SDL. // (https://wiki.libsdl.org/SDL_Event) type Event interface { GetType() uint32 // GetType returns the event type GetTimestamp() uint32 // GetTimestamp returns the timestamp of the event } // CEvent is a union of all event structures used in SDL. // (https://wiki.libsdl.org/SDL_Event) type CEvent struct { Type uint32 _ [52]byte // padding } // CommonEvent contains common event data. // (https://wiki.libsdl.org/SDL_Event) type CommonEvent struct { Type uint32 // the event type Timestamp uint32 // timestamp of the event } // GetType returns the event type. func (e *CommonEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *CommonEvent) GetTimestamp() uint32 { return e.Timestamp } // DisplayEvent contains common event data. // (https://wiki.libsdl.org/SDL_Event) type DisplayEvent struct { Type uint32 // the event type Timestamp uint32 // timestamp of the event Display uint32 // the associated display index Event uint8 // TODO: (https://wiki.libsdl.org/SDL_DisplayEventID) _ uint8 // padding _ uint8 // padding _ uint8 // padding Data1 int32 // event dependent data } // GetType returns the event type. func (e *DisplayEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *DisplayEvent) GetTimestamp() uint32 { return e.Timestamp } // WindowEvent contains window state change event data. // (https://wiki.libsdl.org/SDL_WindowEvent) type WindowEvent struct { Type uint32 // WINDOWEVENT Timestamp uint32 // timestamp of the event WindowID uint32 // the associated window Event uint8 // (https://wiki.libsdl.org/SDL_WindowEventID) _ uint8 // padding _ uint8 // padding _ uint8 // padding Data1 int32 // event dependent data Data2 int32 // event dependent data } type cWindowEvent C.SDL_WindowEvent // GetType returns the event type. func (e *WindowEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *WindowEvent) GetTimestamp() uint32 { return e.Timestamp } // KeyboardEvent contains keyboard key down event information. // (https://wiki.libsdl.org/SDL_KeyboardEvent) type KeyboardEvent struct { Type uint32 // KEYDOWN, KEYUP Timestamp uint32 // timestamp of the event WindowID uint32 // the window with keyboard focus, if any State uint8 // PRESSED, RELEASED Repeat uint8 // non-zero if this is a key repeat _ uint8 // padding _ uint8 // padding Keysym Keysym // Keysym representing the key that was pressed or released } type cKeyboardEvent C.SDL_KeyboardEvent // GetType returns the event type. func (e *KeyboardEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *KeyboardEvent) GetTimestamp() uint32 { return e.Timestamp } // TextEditingEvent contains keyboard text editing event information. // (https://wiki.libsdl.org/SDL_TextEditingEvent) type TextEditingEvent struct { Type uint32 // TEXTEDITING Timestamp uint32 // timestamp of the event WindowID uint32 // the window with keyboard focus, if any Text [C.SDL_TEXTINPUTEVENT_TEXT_SIZE]byte // the null-terminated editing text in UTF-8 encoding Start int32 // the location to begin editing from Length int32 // the number of characters to edit from the start point } type cTextEditingEvent C.SDL_TextEditingEvent // GetType returns the event type. func (e *TextEditingEvent) GetType() uint32 { return e.Type } // GetText returns the text as string func (e *TextEditingEvent) GetText() string { length := func(buf []byte) int { for i := range buf { if buf[i] == 0 { return i } } return 0 }(e.Text[:]) text := e.Text[:length] return string(text) } // GetTimestamp returns the timestamp of the event. func (e *TextEditingEvent) GetTimestamp() uint32 { return e.Timestamp } // TextInputEvent contains keyboard text input event information. // (https://wiki.libsdl.org/SDL_TextInputEvent) type TextInputEvent struct { Type uint32 // TEXTINPUT Timestamp uint32 // timestamp of the event WindowID uint32 // the window with keyboard focus, if any Text [C.SDL_TEXTINPUTEVENT_TEXT_SIZE]byte // the null-terminated input text in UTF-8 encoding } type cTextInputEvent C.SDL_TextInputEvent // GetType returns the event type. func (e *TextInputEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *TextInputEvent) GetTimestamp() uint32 { return e.Timestamp } // GetText returns the text as string func (e *TextInputEvent) GetText() string { length := func(buf []byte) int { for i := range buf { if buf[i] == 0 { return i } } return 0 }(e.Text[:]) text := e.Text[:length] return string(text) } // MouseMotionEvent contains mouse motion event information. // (https://wiki.libsdl.org/SDL_MouseMotionEvent) type MouseMotionEvent struct { Type uint32 // MOUSEMOTION Timestamp uint32 // timestamp of the event WindowID uint32 // the window with mouse focus, if any Which uint32 // the mouse instance id, or TOUCH_MOUSEID State uint32 // BUTTON_LEFT, BUTTON_MIDDLE, BUTTON_RIGHT, BUTTON_X1, BUTTON_X2 X int32 // X coordinate, relative to window Y int32 // Y coordinate, relative to window XRel int32 // relative motion in the X direction YRel int32 // relative motion in the Y direction } type cMouseMotionEvent C.SDL_MouseMotionEvent // GetType returns the event type. func (e *MouseMotionEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *MouseMotionEvent) GetTimestamp() uint32 { return e.Timestamp } // MouseButtonEvent contains mouse button event information. // (https://wiki.libsdl.org/SDL_MouseButtonEvent) type MouseButtonEvent struct { Type uint32 // MOUSEBUTTONDOWN, MOUSEBUTTONUP Timestamp uint32 // timestamp of the event WindowID uint32 // the window with mouse focus, if any Which uint32 // the mouse instance id, or TOUCH_MOUSEID Button uint8 // BUTTON_LEFT, BUTTON_MIDDLE, BUTTON_RIGHT, BUTTON_X1, BUTTON_X2 State uint8 // PRESSED, RELEASED Clicks uint8 // 1 for single-click, 2 for double-click, etc. (>= SDL 2.0.2) _ uint8 // padding X int32 // X coordinate, relative to window Y int32 // Y coordinate, relative to window } type cMouseButtonEvent C.SDL_MouseButtonEvent // GetType returns the event type. func (e *MouseButtonEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *MouseButtonEvent) GetTimestamp() uint32 { return e.Timestamp } // MouseWheelEvent contains mouse wheel event information. // (https://wiki.libsdl.org/SDL_MouseWheelEvent) type MouseWheelEvent struct { Type uint32 // MOUSEWHEEL Timestamp uint32 // timestamp of the event WindowID uint32 // the window with mouse focus, if any Which uint32 // the mouse instance id, or TOUCH_MOUSEID X int32 // the amount scrolled horizontally, positive to the right and negative to the left Y int32 // the amount scrolled vertically, positive away from the user and negative toward the user Direction uint32 // MOUSEWHEEL_NORMAL, MOUSEWHEEL_FLIPPED (>= SDL 2.0.4) PreciseX float32 // The amount scrolled horizontally, positive to the right and negative to the left, with float precision (added in 2.0.18) PreciseY float32 // The amount scrolled vertically, positive away from the user and negative toward the user, with float precision (added in 2.0.18) } type cMouseWheelEvent C.SDL_MouseWheelEvent // GetType returns the event type. func (e *MouseWheelEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *MouseWheelEvent) GetTimestamp() uint32 { return e.Timestamp } // JoyAxisEvent contains joystick axis motion event information. // (https://wiki.libsdl.org/SDL_JoyAxisEvent) type JoyAxisEvent struct { Type uint32 // JOYAXISMOTION Timestamp uint32 // timestamp of the event Which JoystickID // the instance id of the joystick that reported the event Axis uint8 // the index of the axis that changed _ uint8 // padding _ uint8 // padding _ uint8 // padding Value int16 // the current position of the axis (range: -32768 to 32767) _ uint16 // padding } type cJoyAxisEvent C.SDL_JoyAxisEvent // GetType returns the event type. func (e *JoyAxisEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *JoyAxisEvent) GetTimestamp() uint32 { return e.Timestamp } // JoyBallEvent contains joystick trackball motion event information. // (https://wiki.libsdl.org/SDL_JoyBallEvent) type JoyBallEvent struct { Type uint32 // JOYBALLMOTION Timestamp uint32 // timestamp of the event Which JoystickID // the instance id of the joystick that reported the event Ball uint8 // the index of the trackball that changed _ uint8 // padding _ uint8 // padding _ uint8 // padding XRel int16 // the relative motion in the X direction YRel int16 // the relative motion in the Y direction } type cJoyBallEvent C.SDL_JoyBallEvent // GetType returns the event type. func (e *JoyBallEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *JoyBallEvent) GetTimestamp() uint32 { return e.Timestamp } // JoyHatEvent contains joystick hat position change event information. // (https://wiki.libsdl.org/SDL_JoyHatEvent) type JoyHatEvent struct { Type uint32 // JOYHATMOTION Timestamp uint32 // timestamp of the event Which JoystickID // the instance id of the joystick that reported the event Hat uint8 // the index of the hat that changed Value uint8 // HAT_LEFTUP, HAT_UP, HAT_RIGHTUP, HAT_LEFT, HAT_CENTERED, HAT_RIGHT, HAT_LEFTDOWN, HAT_DOWN, HAT_RIGHTDOWN _ uint8 // padding _ uint8 // padding } type cJoyHatEvent C.SDL_JoyHatEvent // GetType returns the event type. func (e *JoyHatEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *JoyHatEvent) GetTimestamp() uint32 { return e.Timestamp } // JoyButtonEvent contains joystick button event information. // (https://wiki.libsdl.org/SDL_JoyButtonEvent) type JoyButtonEvent struct { Type uint32 // JOYBUTTONDOWN, JOYBUTTONUP Timestamp uint32 // timestamp of the event Which JoystickID // the instance id of the joystick that reported the event Button uint8 // the index of the button that changed State uint8 // PRESSED, RELEASED _ uint8 // padding _ uint8 // padding } type cJoyButtonEvent C.SDL_JoyButtonEvent // GetType returns the event type. func (e *JoyButtonEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *JoyButtonEvent) GetTimestamp() uint32 { return e.Timestamp } // JoyDeviceAddedEvent contains joystick device event information. // (https://wiki.libsdl.org/SDL_JoyDeviceEvent) type JoyDeviceAddedEvent struct { Type uint32 // JOYDEVICEADDED Timestamp uint32 // the timestamp of the event Which JoystickID // the joystick device index } // GetType returns the event type. func (e *JoyDeviceAddedEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *JoyDeviceAddedEvent) GetTimestamp() uint32 { return e.Timestamp } // JoyDeviceRemovedEvent contains joystick device event information. // (https://wiki.libsdl.org/SDL_JoyDeviceEvent) type JoyDeviceRemovedEvent struct { Type uint32 // JOYDEVICEREMOVED Timestamp uint32 // the timestamp of the event Which JoystickID // the instance id } // GetType returns the event type. func (e *JoyDeviceRemovedEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *JoyDeviceRemovedEvent) GetTimestamp() uint32 { return e.Timestamp } // ControllerAxisEvent contains game controller axis motion event information. // (https://wiki.libsdl.org/SDL_ControllerAxisEvent) type ControllerAxisEvent struct { Type uint32 // CONTROLLERAXISMOTION Timestamp uint32 // the timestamp of the event Which JoystickID // the joystick instance id Axis uint8 // the controller axis (https://wiki.libsdl.org/SDL_GameControllerAxis) _ uint8 // padding _ uint8 // padding _ uint8 // padding Value int16 // the axis value (range: -32768 to 32767) _ uint16 // padding } type cControllerAxisEvent C.SDL_ControllerAxisEvent // GetType returns the event type. func (e *ControllerAxisEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *ControllerAxisEvent) GetTimestamp() uint32 { return e.Timestamp } // ControllerButtonEvent contains game controller button event information. // (https://wiki.libsdl.org/SDL_ControllerButtonEvent) type ControllerButtonEvent struct { Type uint32 // CONTROLLERBUTTONDOWN, CONTROLLERBUTTONUP Timestamp uint32 // the timestamp of the event Which JoystickID // the joystick instance id Button uint8 // the controller button (https://wiki.libsdl.org/SDL_GameControllerButton) State uint8 // PRESSED, RELEASED _ uint8 // padding _ uint8 // padding } type cControllerButtonEvent C.SDL_ControllerButtonEvent // GetType returns the event type. func (e *ControllerButtonEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *ControllerButtonEvent) GetTimestamp() uint32 { return e.Timestamp } // ControllerDeviceEvent contains controller device event information. // (https://wiki.libsdl.org/SDL_ControllerDeviceEvent) type ControllerDeviceEvent struct { Type uint32 // CONTROLLERDEVICEADDED, CONTROLLERDEVICEREMOVED, SDL_CONTROLLERDEVICEREMAPPED Timestamp uint32 // the timestamp of the event Which JoystickID // the joystick device index for the CONTROLLERDEVICEADDED event or instance id for the CONTROLLERDEVICEREMOVED or CONTROLLERDEVICEREMAPPED event } type cControllerDeviceEvent C.SDL_ControllerDeviceEvent // GetType returns the event type. func (e *ControllerDeviceEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *ControllerDeviceEvent) GetTimestamp() uint32 { return e.Timestamp } // AudioDeviceEvent contains audio device event information. // (https://wiki.libsdl.org/SDL_AudioDeviceEvent) type AudioDeviceEvent struct { Type uint32 // AUDIODEVICEADDED, AUDIODEVICEREMOVED Timestamp uint32 // the timestamp of the event Which uint32 // the audio device index for the AUDIODEVICEADDED event (valid until next GetNumAudioDevices() call), AudioDeviceID for the AUDIODEVICEREMOVED event IsCapture uint8 // zero if an audio output device, non-zero if an audio capture device _ uint8 // padding _ uint8 // padding _ uint8 // padding } type cAudioDeviceEvent C.SDL_AudioDeviceEvent // GetType returns the event type. func (e *AudioDeviceEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *AudioDeviceEvent) GetTimestamp() uint32 { return e.Timestamp } // TouchFingerEvent contains finger touch event information. // (https://wiki.libsdl.org/SDL_TouchFingerEvent) type TouchFingerEvent struct { Type uint32 // FINGERMOTION, FINGERDOWN, FINGERUP Timestamp uint32 // timestamp of the event TouchID TouchID // the touch device id FingerID FingerID // the finger id X float32 // the x-axis location of the touch event, normalized (0...1) Y float32 // the y-axis location of the touch event, normalized (0...1) DX float32 // the distance moved in the x-axis, normalized (-1...1) DY float32 // the distance moved in the y-axis, normalized (-1...1) Pressure float32 // the quantity of pressure applied, normalized (0...1) } type cTouchFingerEvent C.SDL_TouchFingerEvent // GetType returns the event type. func (e *TouchFingerEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *TouchFingerEvent) GetTimestamp() uint32 { return e.Timestamp } // MultiGestureEvent contains multiple finger gesture event information. // (https://wiki.libsdl.org/SDL_MultiGestureEvent) type MultiGestureEvent struct { Type uint32 // MULTIGESTURE Timestamp uint32 // timestamp of the event TouchID TouchID // the touch device id DTheta float32 // the amount that the fingers rotated during this motion DDist float32 // the amount that the fingers pinched during this motion X float32 // the normalized center of gesture Y float32 // the normalized center of gesture NumFingers uint16 // the number of fingers used in the gesture _ uint16 // padding } type cMultiGestureEvent C.SDL_MultiGestureEvent // GetType returns the event type. func (e *MultiGestureEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *MultiGestureEvent) GetTimestamp() uint32 { return e.Timestamp } // DollarGestureEvent contains complex gesture event information. // (https://wiki.libsdl.org/SDL_DollarGestureEvent) type DollarGestureEvent struct { Type uint32 // DOLLARGESTURE, DOLLARRECORD Timestamp uint32 // timestamp of the event TouchID TouchID // the touch device id GestureID GestureID // the unique id of the closest gesture to the performed stroke NumFingers uint32 // the number of fingers used to draw the stroke Error float32 // the difference between the gesture template and the actual performed gesture (lower error is a better match) X float32 // the normalized center of gesture Y float32 // the normalized center of gesture } type cDollarGestureEvent C.SDL_DollarGestureEvent // GetType returns the event type. func (e *DollarGestureEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *DollarGestureEvent) GetTimestamp() uint32 { return e.Timestamp } // DropEvent contains an event used to request a file open by the system. // (https://wiki.libsdl.org/SDL_DropEvent) type DropEvent struct { Type uint32 // DROPFILE, DROPTEXT, DROPBEGIN, DROPCOMPLETE Timestamp uint32 // timestamp of the event File string // the file name WindowID uint32 // the window that was dropped on, if any } type tDropEvent struct { Type uint32 Timestamp uint32 File unsafe.Pointer WindowID uint32 } type cDropEvent C.SDL_DropEvent // GetType returns the event type. func (e *DropEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *DropEvent) GetTimestamp() uint32 { return e.Timestamp } // SensorEvent contains data from sensors such as accelerometer and gyroscope // (https://wiki.libsdl.org/SDL_SensorEvent) type SensorEvent struct { Type uint32 // SDL_SENSORUPDATE Timestamp uint32 // In milliseconds, populated using SDL_GetTicks() Which int32 // The instance ID of the sensor Data [6]float32 // Up to 6 values from the sensor - additional values can be queried using SDL_SensorGetData() } type cSensorEvent C.SDL_SensorEvent // GetType returns the event type. func (e *SensorEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *SensorEvent) GetTimestamp() uint32 { return e.Timestamp } // RenderEvent contains render event information. // (https://wiki.libsdl.org/SDL_EventType) type RenderEvent struct { Type uint32 // the event type Timestamp uint32 // timestamp of the event } // GetType returns the event type. func (e *RenderEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *RenderEvent) GetTimestamp() uint32 { return e.Timestamp } // QuitEvent contains the "quit requested" event. // (https://wiki.libsdl.org/SDL_QuitEvent) type QuitEvent struct { Type uint32 // QUIT Timestamp uint32 // timestamp of the event } // GetType returns the event type. func (e *QuitEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *QuitEvent) GetTimestamp() uint32 { return e.Timestamp } // OSEvent contains OS specific event information. type OSEvent struct { Type uint32 // the event type Timestamp uint32 // timestamp of the event } // GetType returns the event type. func (e *OSEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *OSEvent) GetTimestamp() uint32 { return e.Timestamp } // ClipboardEvent contains clipboard event information. // (https://wiki.libsdl.org/SDL_EventType) type ClipboardEvent struct { Type uint32 // CLIPBOARDUPDATE Timestamp uint32 // timestamp of the event } // GetType returns the event type. func (e *ClipboardEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *ClipboardEvent) GetTimestamp() uint32 { return e.Timestamp } // UserEvent contains an application-defined event type. // (https://wiki.libsdl.org/SDL_UserEvent) type UserEvent struct { Type uint32 // value obtained from RegisterEvents() Timestamp uint32 // timestamp of the event WindowID uint32 // the associated window, if any Code int32 // user defined event code Data1 unsafe.Pointer // user defined data pointer Data2 unsafe.Pointer // user defined data pointer } type cUserEvent C.SDL_UserEvent // GetType returns the event type. func (e *UserEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *UserEvent) GetTimestamp() uint32 { return e.Timestamp } // SysWMEvent contains a video driver dependent system event. // (https://wiki.libsdl.org/SDL_SysWMEvent) type SysWMEvent struct { Type uint32 // SYSWMEVENT Timestamp uint32 // timestamp of the event Msg *SysWMmsg // driver dependent data, defined in SDL_syswm.h } type cSysWMEvent C.SDL_SysWMEvent // GetType returns the event type. func (e *SysWMEvent) GetType() uint32 { return e.Type } // GetTimestamp returns the timestamp of the event. func (e *SysWMEvent) GetTimestamp() uint32 { return e.Timestamp } // EventAction is the action to take in PeepEvents() function. // (https://wiki.libsdl.org/SDL_PeepEvents) type EventAction C.SDL_eventaction // EventFilter is the function to call when an event happens. // (https://wiki.libsdl.org/SDL_SetEventFilter) type EventFilter interface { FilterEvent(e Event, userdata interface{}) bool } type eventFilterFunc func(Event, interface{}) bool type eventFilterCallbackContext struct { filter EventFilter handle EventWatchHandle userdata interface{} } // EventWatchHandle is an event watch callback added with AddEventWatch(). type EventWatchHandle uintptr func (action EventAction) c() C.SDL_eventaction { return C.SDL_eventaction(action) } // PumpEvents pumps the event loop, gathering events from the input devices. // (https://wiki.libsdl.org/SDL_PumpEvents) func PumpEvents() { C.SDL_PumpEvents() } // PeepEvents checks the event queue for messages and optionally return them. // (https://wiki.libsdl.org/SDL_PeepEvents) func PeepEvents(events []Event, action EventAction, minType, maxType uint32) (storedEvents int, err error) { if events == nil { return 0, nil } var _events []CEvent = make([]CEvent, len(events)) if action == ADDEVENT { // the contents of _events matter if they are to be added for i := 0; i < len(events); i++ { _events[i] = *cEvent(events[i]) } } _pevents := (*C.SDL_Event)(unsafe.Pointer(&_events[0])) storedEvents = int(C.SDL_PeepEvents(_pevents, C.int(len(events)), action.c(), C.Uint32(minType), C.Uint32(maxType))) if action != ADDEVENT { // put events into slice, events unchanged if action = ADDEVENT for i := 0; i < storedEvents; i++ { events[i] = goEvent(&_events[i]) } } if storedEvents < 0 { err = GetError() } return } // HasEvent checks for the existence of certain event types in the event queue. // (https://wiki.libsdl.org/SDL_HasEvent) func HasEvent(type_ uint32) bool { return C.SDL_HasEvent(C.Uint32(type_)) != 0 } // HasEvents checks for the existence of a range of event types in the event queue. // (https://wiki.libsdl.org/SDL_HasEvents) func HasEvents(minType, maxType uint32) bool { return C.SDL_HasEvents(C.Uint32(minType), C.Uint32(maxType)) != 0 } // FlushEvent clears events from the event queue. // (https://wiki.libsdl.org/SDL_FlushEvent) func FlushEvent(type_ uint32) { C.SDL_FlushEvent(C.Uint32(type_)) } // FlushEvents clears events from the event queue. // (https://wiki.libsdl.org/SDL_FlushEvents) func FlushEvents(minType, maxType uint32) { C.SDL_FlushEvents(C.Uint32(minType), C.Uint32(maxType)) } // PollEvent polls for currently pending events. // (https://wiki.libsdl.org/SDL_PollEvent) func PollEvent() Event { ret := C.PollEvent() if ret == 0 { return nil } return goEvent((*CEvent)(unsafe.Pointer(&C.event))) } func goEvent(cevent *CEvent) Event { switch cevent.Type { case DISPLAYEVENT: return (*DisplayEvent)(unsafe.Pointer(cevent)) case WINDOWEVENT: return (*WindowEvent)(unsafe.Pointer(cevent)) case SYSWMEVENT: return (*SysWMEvent)(unsafe.Pointer(cevent)) case KEYDOWN, KEYUP: return (*KeyboardEvent)(unsafe.Pointer(cevent)) case TEXTEDITING: return (*TextEditingEvent)(unsafe.Pointer(cevent)) case TEXTINPUT: return (*TextInputEvent)(unsafe.Pointer(cevent)) case MOUSEMOTION: return (*MouseMotionEvent)(unsafe.Pointer(cevent)) case MOUSEBUTTONDOWN, MOUSEBUTTONUP: return (*MouseButtonEvent)(unsafe.Pointer(cevent)) case MOUSEWHEEL: return (*MouseWheelEvent)(unsafe.Pointer(cevent)) case JOYAXISMOTION: return (*JoyAxisEvent)(unsafe.Pointer(cevent)) case JOYBALLMOTION: return (*JoyBallEvent)(unsafe.Pointer(cevent)) case JOYHATMOTION: return (*JoyHatEvent)(unsafe.Pointer(cevent)) case JOYBUTTONDOWN, JOYBUTTONUP: return (*JoyButtonEvent)(unsafe.Pointer(cevent)) case JOYDEVICEADDED: return (*JoyDeviceAddedEvent)(unsafe.Pointer(cevent)) case JOYDEVICEREMOVED: return (*JoyDeviceRemovedEvent)(unsafe.Pointer(cevent)) case CONTROLLERAXISMOTION: return (*ControllerAxisEvent)(unsafe.Pointer(cevent)) case CONTROLLERBUTTONDOWN, CONTROLLERBUTTONUP: return (*ControllerButtonEvent)(unsafe.Pointer(cevent)) case CONTROLLERDEVICEADDED, CONTROLLERDEVICEREMOVED, CONTROLLERDEVICEREMAPPED: return (*ControllerDeviceEvent)(unsafe.Pointer(cevent)) case AUDIODEVICEADDED, AUDIODEVICEREMOVED: return (*AudioDeviceEvent)(unsafe.Pointer(cevent)) case FINGERMOTION, FINGERDOWN, FINGERUP: return (*TouchFingerEvent)(unsafe.Pointer(cevent)) case MULTIGESTURE: return (*MultiGestureEvent)(unsafe.Pointer(cevent)) case DOLLARGESTURE, DOLLARRECORD: return (*DollarGestureEvent)(unsafe.Pointer(cevent)) case DROPFILE, DROPTEXT, DROPBEGIN, DROPCOMPLETE: e := (*tDropEvent)(unsafe.Pointer(cevent)) event := DropEvent{Type: e.Type, Timestamp: e.Timestamp, File: C.GoString((*C.char)(e.File)), WindowID: e.WindowID} C.SDL_free(e.File) return &event case SENSORUPDATE: return (*SensorEvent)(unsafe.Pointer(cevent)) case RENDER_TARGETS_RESET, RENDER_DEVICE_RESET: return (*RenderEvent)(unsafe.Pointer(cevent)) case QUIT: return (*QuitEvent)(unsafe.Pointer(cevent)) case CLIPBOARDUPDATE: return (*ClipboardEvent)(unsafe.Pointer(cevent)) default: if cevent.Type >= USEREVENT { // all events beyond USEREVENT are UserEvents to be registered with RegisterEvents return (*UserEvent)(unsafe.Pointer(cevent)) } return (*CommonEvent)(unsafe.Pointer(cevent)) } } func cEvent(event Event) *CEvent { evv := reflect.ValueOf(event) p := evv.Elem() return (*CEvent)(unsafe.Pointer(p.UnsafeAddr())) } // WaitEventTimeout waits until the specified timeout (in milliseconds) for the next available event. // (https://wiki.libsdl.org/SDL_WaitEventTimeout) func WaitEventTimeout(timeout int) Event { var cevent CEvent _event := (*C.SDL_Event)(unsafe.Pointer(&cevent)) ok := int(C.SDL_WaitEventTimeout(_event, C.int(timeout))) if ok == 0 { return nil } return goEvent(&cevent) } // WaitEvent waits indefinitely for the next available event. // (https://wiki.libsdl.org/SDL_WaitEvent) func WaitEvent() Event { var cevent CEvent _event := (*C.SDL_Event)(unsafe.Pointer(&cevent)) ok := int(C.SDL_WaitEvent(_event)) if ok == 0 { return nil } return goEvent(&cevent) } // PushEvent adds an event to the event queue. // (https://wiki.libsdl.org/SDL_PushEvent) func PushEvent(event Event) (filtered bool, err error) { _event := (*C.SDL_Event)(unsafe.Pointer(cEvent(event))) if ok := int(C.SDL_PushEvent(_event)); ok < 0 { filtered, err = false, GetError() } else if ok == 0 { filtered, err = true, nil } return } func (ef eventFilterFunc) FilterEvent(e Event, userdata interface{}) bool { return ef(e, userdata) } func newEventFilterCallbackContext(filter EventFilter, userdata interface{}) *eventFilterCallbackContext { lastEventWatchHandleMutex.Lock() defer lastEventWatchHandleMutex.Unlock() // Look for the next available watch handle (this should be immediate // unless you're creating a LOT of handlers). for { if _, ok := eventWatches[lastEventWatchHandle]; !ok { break } lastEventWatchHandle++ } e := &eventFilterCallbackContext{filter, lastEventWatchHandle, userdata} eventWatches[lastEventWatchHandle] = e lastEventWatchHandle++ return e } func (e *eventFilterCallbackContext) cptr() unsafe.Pointer { return unsafe.Pointer(e.handle) } //export goSetEventFilterCallback func goSetEventFilterCallback(data unsafe.Pointer, e *C.SDL_Event) C.int { // No check for eventFilterCache != nil. Why? because it should never be // nil since the callback is set/unset based on the last filter being nil // /non-nil. If there is an issue, then it should panic here so we can // figure out why that is. return wrapEventFilterCallback(eventFilterCache, e, nil) } //export goEventFilterCallback func goEventFilterCallback(userdata unsafe.Pointer, e *C.SDL_Event) C.int { // same sort of reasoning with goSetEventFilterCallback, userdata should // always be non-nil and represent a valid eventFilterCallbackContext. If // it doesn't a panic will let us know that there something wrong and the // problem can be fixed. context := eventWatches[EventWatchHandle(userdata)] return wrapEventFilterCallback(context.filter, e, context.userdata) } func wrapEventFilterCallback(filter EventFilter, e *C.SDL_Event, userdata interface{}) C.int { gev := goEvent((*CEvent)(unsafe.Pointer(e))) result := filter.FilterEvent(gev, userdata) if result { return C.SDL_TRUE } return C.SDL_FALSE } // SetEventFilter sets up a filter to process all events before they change internal state and are posted to the internal event queue. // (https://wiki.libsdl.org/SDL_SetEventFilter) func SetEventFilter(filter EventFilter, userdata interface{}) { if eventFilterCache == nil && filter == nil { // nothing to do... return } if eventFilterCache == nil && filter != nil { // We had no event filter before and do now; lets set // goSetEventFilterCallback() as the event filter. C.setEventFilter() } else if eventFilterCache != nil && filter == nil { // We had an event filter before, but no longer do, lets clear the // event filter C.clearEventFilter() } eventFilterCache = filter } // SetEventFilterFunc sets up a function to process all events before they change internal state and are posted to the internal event queue. // (https://wiki.libsdl.org/SDL_SetEventFilter) func SetEventFilterFunc(filterFunc eventFilterFunc, userdata interface{}) { SetEventFilter(filterFunc, userdata) } // GetEventFilter queries the current event filter. // (https://wiki.libsdl.org/SDL_GetEventFilter) func GetEventFilter() EventFilter { return eventFilterCache } func isCEventFilterSet() bool { return C.SDL_GetEventFilter(nil, nil) == C.SDL_TRUE } // FilterEvents run a specific filter function on the current event queue, removing any events for which the filter returns 0. // (https://wiki.libsdl.org/SDL_FilterEvents) func FilterEvents(filter EventFilter, userdata interface{}) { context := newEventFilterCallbackContext(filter, userdata) C.filterEvents(context.cptr()) } // FilterEventsFunc run a specific function on the current event queue, removing any events for which the filter returns 0. // (https://wiki.libsdl.org/SDL_FilterEvents) func FilterEventsFunc(filter eventFilterFunc, userdata interface{}) { FilterEvents(filter, userdata) } // AddEventWatch adds a callback to be triggered when an event is added to the event queue. // (https://wiki.libsdl.org/SDL_AddEventWatch) func AddEventWatch(filter EventFilter, userdata interface{}) EventWatchHandle { context := newEventFilterCallbackContext(filter, userdata) C.addEventWatch(context.cptr()) return context.handle } // AddEventWatchFunc adds a callback function to be triggered when an event is added to the event queue. // (https://wiki.libsdl.org/SDL_AddEventWatch) func AddEventWatchFunc(filterFunc eventFilterFunc, userdata interface{}) EventWatchHandle { return AddEventWatch(filterFunc, userdata) } // DelEventWatch removes an event watch callback added with AddEventWatch(). // (https://wiki.libsdl.org/SDL_DelEventWatch) func DelEventWatch(handle EventWatchHandle) { context, ok := eventWatches[handle] if !ok { return } delete(eventWatches, context.handle) C.delEventWatch(context.cptr()) } // EventState sets the state of processing events by type. // (https://wiki.libsdl.org/SDL_EventState) func EventState(type_ uint32, state int) uint8 { return uint8(C.SDL_EventState(C.Uint32(type_), C.int(state))) } // GetEventState returns the current processing state of the specified event // (https://wiki.libsdl.org/SDL_EventState) func GetEventState(type_ uint32) uint8 { return uint8(C.SDL_EventState(C.Uint32(type_), QUERY)) } // RegisterEvents allocates a set of user-defined events, and return the beginning event number for that set of events. // (https://wiki.libsdl.org/SDL_RegisterEvents) func RegisterEvents(numEvents int) uint32 { return uint32(C.SDL_RegisterEvents(C.int(numEvents))) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/events.h ================================================ #ifndef _GO_SDL_EVENTS_H #define _GO_SDL_EVENTS_H #if defined(_WIN32) #include #else #include #endif extern SDL_Event event; extern void setEventFilter(); extern void clearEventFilter(); extern void filterEvents(void *userdata); extern void addEventWatch(void *userdata); extern void delEventWatch(void *userdata); extern int PollEvent(); #endif ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/filesystem.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,1)) #if defined(WARN_OUTDATED) #pragma message("SDL_GetBasePath is not supported before SDL 2.0.1") #endif static inline char* SDL_GetBasePath() { return NULL; } #if defined(WARN_OUTDATED) #pragma message("SDL_GetPrefPath is not supported before SDL 2.0.1") #endif static inline char* SDL_GetPrefPath(const char *org, const char *app) { return NULL; } #endif */ import "C" import "unsafe" // GetBasePath returns the directory where the application was run from. This is where the application data directory is. // (https://wiki.libsdl.org/SDL_GetBasePath) func GetBasePath() string { _val := C.SDL_GetBasePath() defer C.SDL_free(unsafe.Pointer(_val)) return C.GoString(_val) } // GetPrefPath returns the "pref dir". This is meant to be where the application can write personal files (Preferences and save games, etc.) that are specific to the application. This directory is unique per user and per application. // (https://wiki.libsdl.org/SDL_GetPrefPath) func GetPrefPath(org, app string) string { _org := C.CString(org) _app := C.CString(app) defer C.free(unsafe.Pointer(_org)) defer C.free(unsafe.Pointer(_app)) _val := C.SDL_GetPrefPath(_org, _app) defer C.SDL_free(unsafe.Pointer(_val)) return C.GoString(_val) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/gamecontroller.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,4)) #if defined(WARN_OUTDATED) #pragma message("SDL_GameControllerFromInstanceID is not supported before SDL 2.0.4") #endif static SDL_GameController* SDL_GameControllerFromInstanceID(SDL_JoystickID joyid) { return NULL; } #endif #if !(SDL_VERSION_ATLEAST(2,0,6)) #if defined(WARN_OUTDATED) #pragma message("SDL_GameControllerGetVendor is not supported before SDL 2.0.6") #pragma message("SDL_GameControllerGetProduct is not supported before SDL 2.0.6") #pragma message("SDL_GameControllerGetProductVersion is not supported before SDL 2.0.6") #pragma message("SDL_GameControllerNumMappings is not supported before SDL 2.0.6") #pragma message("SDL_GameControllerMappingForIndex is not supported before SDL 2.0.6") #endif static Uint16 SDL_GameControllerGetVendor(SDL_GameController* gamecontroller) { return 0; } static Uint16 SDL_GameControllerGetProduct(SDL_GameController* gamecontroller) { return 0; } static Uint16 SDL_GameControllerGetProductVersion(SDL_GameController* gamecontroller) { return 0; } static int SDL_GameControllerNumMappings(void) { return 0; } static char* SDL_GameControllerMappingForIndex(int mapping_index) { return NULL; } #endif #if !(SDL_VERSION_ATLEAST(2,0,9)) #if defined(WARN_OUTDATED) #pragma message("SDL_GameControllerGetPlayerIndex is not supported before SDL 2.0.9") #pragma message("SDL_GameControllerRumble is not supported before SDL 2.0.9") #pragma message("SDL_GameControllerMappingForDeviceIndex is not supported before SDL 2.0.9") #endif typedef enum { SDL_SENSOR_INVALID = -1, SDL_SENSOR_UNKNOWN, SDL_SENSOR_ACCEL, SDL_SENSOR_GYRO } SDL_SensorType; static int SDL_GameControllerGetPlayerIndex(SDL_GameController *gamecontroller) { return -1; } static int SDL_GameControllerRumble(SDL_GameController *gamecontroller, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble, Uint32 duration_ms) { return -1; } static char *SDL_GameControllerMappingForDeviceIndex(int joystick_index) { return NULL; } #endif #if !(SDL_VERSION_ATLEAST(2,0,12)) typedef enum { SDL_CONTROLLER_TYPE_UNKNOWN = 0, SDL_CONTROLLER_TYPE_XBOX360, SDL_CONTROLLER_TYPE_XBOXONE, SDL_CONTROLLER_TYPE_PS3, SDL_CONTROLLER_TYPE_PS4, SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO } SDL_GameControllerType; #if defined(WARN_OUTDATED) #pragma message("SDL_GameControllerTypeForIndex is not supported before SDL 2.0.12") #pragma message("SDL_GameControllerGetType is not supported before SDL 2.0.12") #pragma message("SDL_GameControllerFromPlayerIndex is not supported before SDL 2.0.12") #pragma message("SDL_GameControllerSetPlayerIndex is not supported before SDL 2.0.12") #endif static SDL_GameControllerType SDL_GameControllerTypeForIndex(int joystick_index) { return SDL_CONTROLLER_TYPE_UNKNOWN; } static SDL_GameControllerType SDL_GameControllerGetType(SDL_GameController *gamecontroller) { return SDL_CONTROLLER_TYPE_UNKNOWN; } static SDL_GameController * SDL_GameControllerFromPlayerIndex(int player_index) { return NULL; } static void SDL_GameControllerSetPlayerIndex(SDL_GameController *gamecontroller, int player_index) { // do nothing } #endif #if !(SDL_VERSION_ATLEAST(2,0,14)) #define SDL_CONTROLLER_TYPE_VIRTUAL (6) #define SDL_CONTROLLER_TYPE_PS5 (7) #if defined(WARN_OUTDATED) #pragma message("SDL_GameControllerGetSerial is not supported before SDL 2.0.14") #pragma message("SDL_GameControllerHasAxis is not supported before SDL 2.0.14") #pragma message("SDL_GameControllerHasButton is not supported before SDL 2.0.14") #pragma message("SDL_GameControllerGetNumTouchpads is not supported before SDL 2.0.14") #pragma message("SDL_GameControllerGetNumTouchpadFingers is not supported before SDL 2.0.14") #pragma message("SDL_GameControllerGetTouchpadFinger is not supported before SDL 2.0.14") #pragma message("SDL_GameControllerHasSensor is not supported before SDL 2.0.14") #pragma message("SDL_GameControllerSetSensorEnabled is not supported before SDL 2.0.14") #pragma message("SDL_GameControllerIsSensorEnabled is not supported before SDL 2.0.14") #pragma message("SDL_GameControllerGetSensorData is not supported before SDL 2.0.14") #pragma message("SDL_GameControllerRumbleTriggers is not supported before SDL 2.0.14") #pragma message("SDL_GameControllerHasLED is not supported before SDL 2.0.14") #pragma message("SDL_GameControllerSetLED is not supported before SDL 2.0.14") #endif static const char * SDLCALL SDL_GameControllerGetSerial(SDL_GameController *gamecontroller) { return NULL; } static SDL_bool SDL_GameControllerHasAxis(SDL_GameController *gamecontroller, SDL_GameControllerAxis axis) { return SDL_FALSE; } static SDL_bool SDLCALL SDL_GameControllerHasButton(SDL_GameController *gamecontroller, SDL_GameControllerButton button) { return SDL_FALSE; } static int SDLCALL SDL_GameControllerGetNumTouchpads(SDL_GameController *gamecontroller) { return 0; } static int SDL_GameControllerGetNumTouchpadFingers(SDL_GameController *gamecontroller, int touchpad) { return 0; } static int SDL_GameControllerGetTouchpadFinger(SDL_GameController *gamecontroller, int touchpad, int finger, Uint8 *state, float *x, float *y, float *pressure) { return -1; } static SDL_bool SDL_GameControllerHasSensor(SDL_GameController *gamecontroller, SDL_SensorType type) { return SDL_FALSE; } static int SDL_GameControllerSetSensorEnabled(SDL_GameController *gamecontroller, SDL_SensorType type, SDL_bool enabled) { return -1; } static SDL_bool SDL_GameControllerIsSensorEnabled(SDL_GameController *gamecontroller, SDL_SensorType type) { return SDL_FALSE; } static int SDL_GameControllerGetSensorData(SDL_GameController *gamecontroller, SDL_SensorType type, float *data, int num_values) { return -1; } static int SDL_GameControllerRumbleTriggers(SDL_GameController *gamecontroller, Uint16 left_rumble, Uint16 right_rumble, Uint32 duration_ms) { return -1; } static SDL_bool SDL_GameControllerHasLED(SDL_GameController *gamecontroller) { return SDL_FALSE; } static int SDL_GameControllerSetLED(SDL_GameController *gamecontroller, Uint8 red, Uint8 green, Uint8 blue) { return -1; } #endif #if !(SDL_VERSION_ATLEAST(2,0,16)) #if defined(WARN_OUTDATED) #pragma message("SDL_GameControllerSendEffect is not supported before SDL 2.0.16") #pragma message("SDL_GameControllerGetSensorDataRate is not supported before SDL 2.0.16") #endif static int SDL_GameControllerSendEffect(SDL_GameController *gamecontroller, const void *data, int size) { return -1; } static float SDL_GameControllerGetSensorDataRate(SDL_GameController *gamecontroller, SDL_SensorType type) { return 0.0f; } #endif #if !(SDL_VERSION_ATLEAST(2,0,18)) #if defined(WARN_OUTDATED) #pragma message("SDL_GameControllerHasRumble is not supported before SDL 2.0.18") #pragma message("SDL_GameControllerHasRumbleTriggers is not supported before SDL 2.0.18") #pragma message("SDL_GameControllerGetAppleSFSymbolsNameForButton is not supported before SDL 2.0.18") #pragma message("SDL_GameControllerGetAppleSFSymbolsNameForAxis is not supported before SDL 2.0.18") #endif static SDL_bool SDL_GameControllerHasRumble(SDL_GameController *gamecontroller) { return SDL_FALSE; } static SDL_bool SDL_GameControllerHasRumbleTriggers(SDL_GameController *gamecontroller) { return SDL_FALSE; } static const char* SDL_GameControllerGetAppleSFSymbolsNameForButton(SDL_GameController *gamecontroller, SDL_GameControllerButton button) { return NULL; } static const char* SDL_GameControllerGetAppleSFSymbolsNameForAxis(SDL_GameController *gamecontroller, SDL_GameControllerAxis axis) { return NULL; } #endif */ import "C" import ( "encoding/binary" "unsafe" ) // Types of game controller inputs. const ( CONTROLLER_BINDTYPE_NONE = C.SDL_CONTROLLER_BINDTYPE_NONE CONTROLLER_BINDTYPE_BUTTON = C.SDL_CONTROLLER_BINDTYPE_BUTTON CONTROLLER_BINDTYPE_AXIS = C.SDL_CONTROLLER_BINDTYPE_AXIS CONTROLLER_BINDTYPE_HAT = C.SDL_CONTROLLER_BINDTYPE_HAT ) // An enumeration of axes available from a controller. // (https://wiki.libsdl.org/SDL_GameControllerAxis) const ( CONTROLLER_AXIS_INVALID = C.SDL_CONTROLLER_AXIS_INVALID CONTROLLER_AXIS_LEFTX = C.SDL_CONTROLLER_AXIS_LEFTX CONTROLLER_AXIS_LEFTY = C.SDL_CONTROLLER_AXIS_LEFTY CONTROLLER_AXIS_RIGHTX = C.SDL_CONTROLLER_AXIS_RIGHTX CONTROLLER_AXIS_RIGHTY = C.SDL_CONTROLLER_AXIS_RIGHTY CONTROLLER_AXIS_TRIGGERLEFT = C.SDL_CONTROLLER_AXIS_TRIGGERLEFT CONTROLLER_AXIS_TRIGGERRIGHT = C.SDL_CONTROLLER_AXIS_TRIGGERRIGHT CONTROLLER_AXIS_MAX = C.SDL_CONTROLLER_AXIS_MAX ) // An enumeration of buttons available from a controller. // (https://wiki.libsdl.org/SDL_GameControllerButton) const ( CONTROLLER_BUTTON_INVALID = C.SDL_CONTROLLER_BUTTON_INVALID CONTROLLER_BUTTON_A = C.SDL_CONTROLLER_BUTTON_A CONTROLLER_BUTTON_B = C.SDL_CONTROLLER_BUTTON_B CONTROLLER_BUTTON_X = C.SDL_CONTROLLER_BUTTON_X CONTROLLER_BUTTON_Y = C.SDL_CONTROLLER_BUTTON_Y CONTROLLER_BUTTON_BACK = C.SDL_CONTROLLER_BUTTON_BACK CONTROLLER_BUTTON_GUIDE = C.SDL_CONTROLLER_BUTTON_GUIDE CONTROLLER_BUTTON_START = C.SDL_CONTROLLER_BUTTON_START CONTROLLER_BUTTON_LEFTSTICK = C.SDL_CONTROLLER_BUTTON_LEFTSTICK CONTROLLER_BUTTON_RIGHTSTICK = C.SDL_CONTROLLER_BUTTON_RIGHTSTICK CONTROLLER_BUTTON_LEFTSHOULDER = C.SDL_CONTROLLER_BUTTON_LEFTSHOULDER CONTROLLER_BUTTON_RIGHTSHOULDER = C.SDL_CONTROLLER_BUTTON_RIGHTSHOULDER CONTROLLER_BUTTON_DPAD_UP = C.SDL_CONTROLLER_BUTTON_DPAD_UP CONTROLLER_BUTTON_DPAD_DOWN = C.SDL_CONTROLLER_BUTTON_DPAD_DOWN CONTROLLER_BUTTON_DPAD_LEFT = C.SDL_CONTROLLER_BUTTON_DPAD_LEFT CONTROLLER_BUTTON_DPAD_RIGHT = C.SDL_CONTROLLER_BUTTON_DPAD_RIGHT CONTROLLER_BUTTON_MAX = C.SDL_CONTROLLER_BUTTON_MAX ) // GameControllerBindType is a type of game controller input. type GameControllerBindType C.SDL_GameControllerBindType // GameControllerAxis is an axis on a game controller. // (https://wiki.libsdl.org/SDL_GameControllerAxis) type GameControllerAxis C.SDL_GameControllerAxis // GameControllerButton is a button on a game controller. // (https://wiki.libsdl.org/SDL_GameControllerButton) type GameControllerButton C.SDL_GameControllerButton // GameController used to identify an SDL game controller. type GameController C.SDL_GameController // GameControllerButtonBind SDL joystick layer binding for controller button/axis mapping. type GameControllerButtonBind C.SDL_GameControllerButtonBind func (ctrl *GameController) cptr() *C.SDL_GameController { return (*C.SDL_GameController)(unsafe.Pointer(ctrl)) } func (axis GameControllerAxis) c() C.SDL_GameControllerAxis { return C.SDL_GameControllerAxis(axis) } func (btn GameControllerButton) c() C.SDL_GameControllerButton { return C.SDL_GameControllerButton(btn) } // GameControllerAddMapping adds support for controllers that SDL is unaware of or to cause an existing controller to have a different binding. // (https://wiki.libsdl.org/SDL_GameControllerAddMapping) func GameControllerAddMapping(mappingString string) int { _mappingString := C.CString(mappingString) defer C.free(unsafe.Pointer(_mappingString)) return int(C.SDL_GameControllerAddMapping(_mappingString)) } // GameControllerNumMappings returns the number of mappings installed. func GameControllerNumMappings() int { return int(C.SDL_GameControllerNumMappings()) } // GameControllerMappingForIndex returns the game controller mapping string at a particular index. func GameControllerMappingForIndex(index int) string { mappingString := C.SDL_GameControllerMappingForIndex(C.int(index)) defer C.free(unsafe.Pointer(mappingString)) return C.GoString(mappingString) } // GameControllerMappingForGUID returns the game controller mapping string for a given GUID. // (https://wiki.libsdl.org/SDL_GameControllerMappingForGUID) func GameControllerMappingForGUID(guid JoystickGUID) string { mappingString := C.SDL_GameControllerMappingForGUID(guid.c()) defer C.free(unsafe.Pointer(mappingString)) return C.GoString(mappingString) } // IsGameController reports whether the given joystick is supported by the game controller interface. // (https://wiki.libsdl.org/SDL_IsGameController) func IsGameController(index int) bool { return C.SDL_IsGameController(C.int(index)) == C.SDL_TRUE } // GameControllerNameForIndex returns the implementation dependent name for the game controller. // (https://wiki.libsdl.org/SDL_GameControllerNameForIndex) func GameControllerNameForIndex(index int) string { return C.GoString(C.SDL_GameControllerNameForIndex(C.int(index))) } // GameControllerMappingForDeviceIndex returns the game controller mapping string at a particular index. func GameControllerMappingForDeviceIndex(index int) string { mappingString := C.SDL_GameControllerMappingForDeviceIndex(C.int(index)) defer C.free(unsafe.Pointer(mappingString)) return C.GoString(mappingString) } // GameControllerOpen opens a gamecontroller for use. // (https://wiki.libsdl.org/SDL_GameControllerOpen) func GameControllerOpen(index int) *GameController { return (*GameController)(C.SDL_GameControllerOpen(C.int(index))) } // GameControllerFromInstanceID returns the GameController associated with an instance id. // (https://wiki.libsdl.org/SDL_GameControllerFromInstanceID) func GameControllerFromInstanceID(joyid JoystickID) *GameController { return (*GameController)(C.SDL_GameControllerFromInstanceID(joyid.c())) } // Name returns the implementation dependent name for an opened game controller. // (https://wiki.libsdl.org/SDL_GameControllerName) func (ctrl *GameController) Name() string { return C.GoString(C.SDL_GameControllerName(ctrl.cptr())) } // PlayerIndex the player index of an opened game controller, or -1 if it's not available. // TODO: (https://wiki.libsdl.org/SDL_GameControllerGetPlayerIndex) func (ctrl *GameController) PlayerIndex() int { return int(C.SDL_GameControllerGetPlayerIndex(ctrl.cptr())) } // Vendor returns the USB vendor ID of an opened controller, if available, 0 otherwise. func (ctrl *GameController) Vendor() int { return int(C.SDL_GameControllerGetVendor(ctrl.cptr())) } // Product returns the USB product ID of an opened controller, if available, 0 otherwise. func (ctrl *GameController) Product() int { return int(C.SDL_GameControllerGetProduct(ctrl.cptr())) } // ProductVersion returns the product version of an opened controller, if available, 0 otherwise. func (ctrl *GameController) ProductVersion() int { return int(C.SDL_GameControllerGetProductVersion(ctrl.cptr())) } // Attached reports whether a controller has been opened and is currently connected. // (https://wiki.libsdl.org/SDL_GameControllerGetAttached) func (ctrl *GameController) Attached() bool { return C.SDL_GameControllerGetAttached(ctrl.cptr()) == C.SDL_TRUE } // Mapping returns the current mapping of a Game Controller. // (https://wiki.libsdl.org/SDL_GameControllerMapping) func (ctrl *GameController) Mapping() string { mappingString := C.SDL_GameControllerMapping(ctrl.cptr()) defer C.free(unsafe.Pointer(mappingString)) return C.GoString(mappingString) } // Joystick returns the Joystick ID from a Game Controller. The game controller builds on the Joystick API, but to be able to use the Joystick's functions with a gamepad, you need to use this first to get the joystick object. // (https://wiki.libsdl.org/SDL_GameControllerGetJoystick) func (ctrl *GameController) Joystick() *Joystick { return (*Joystick)(unsafe.Pointer(C.SDL_GameControllerGetJoystick(ctrl.cptr()))) } // GameControllerEventState returns the current state of, enable, or disable events dealing with Game Controllers. This will not disable Joystick events, which can also be fired by a controller (see https://wiki.libsdl.org/SDL_JoystickEventState). // (https://wiki.libsdl.org/SDL_GameControllerEventState) func GameControllerEventState(state int) int { return int(C.SDL_GameControllerEventState(C.int(state))) } // GameControllerUpdate manually pumps game controller updates if not using the loop. // (https://wiki.libsdl.org/SDL_GameControllerUpdate) func GameControllerUpdate() { C.SDL_GameControllerUpdate() } // GameControllerGetAxisFromString converts a string into an enum representation for a GameControllerAxis. // (https://wiki.libsdl.org/SDL_GameControllerGetAxisFromString) func GameControllerGetAxisFromString(pchString string) GameControllerAxis { _pchString := C.CString(pchString) defer C.free(unsafe.Pointer(_pchString)) return GameControllerAxis(C.SDL_GameControllerGetAxisFromString(_pchString)) } // GameControllerGetStringForAxis converts from an axis enum to a string. // (https://wiki.libsdl.org/SDL_GameControllerGetStringForAxis) func GameControllerGetStringForAxis(axis GameControllerAxis) string { return C.GoString(C.SDL_GameControllerGetStringForAxis(axis.c())) } // BindForAxis returns the SDL joystick layer binding for a controller button mapping. // (https://wiki.libsdl.org/SDL_GameControllerGetBindForAxis) func (ctrl *GameController) BindForAxis(axis GameControllerAxis) GameControllerButtonBind { return GameControllerButtonBind(C.SDL_GameControllerGetBindForAxis(ctrl.cptr(), axis.c())) } // Axis returns the current state of an axis control on a game controller. // (https://wiki.libsdl.org/SDL_GameControllerGetAxis) func (ctrl *GameController) Axis(axis GameControllerAxis) int16 { return int16(C.SDL_GameControllerGetAxis(ctrl.cptr(), axis.c())) } // GameControllerGetButtonFromString turns a string into a button mapping. // (https://wiki.libsdl.org/SDL_GameControllerGetButtonFromString) func GameControllerGetButtonFromString(pchString string) GameControllerButton { _pchString := C.CString(pchString) defer C.free(unsafe.Pointer(_pchString)) return GameControllerButton(C.SDL_GameControllerGetButtonFromString(_pchString)) } // GameControllerGetStringForButton turns a button enum into a string mapping. // (https://wiki.libsdl.org/SDL_GameControllerGetStringForButton) func GameControllerGetStringForButton(btn GameControllerButton) string { return C.GoString(C.SDL_GameControllerGetStringForButton(btn.c())) } // BindForButton returns the SDL joystick layer binding for this controller button mapping. // (https://wiki.libsdl.org/SDL_GameControllerGetBindForButton) func (ctrl *GameController) BindForButton(btn GameControllerButton) GameControllerButtonBind { return GameControllerButtonBind(C.SDL_GameControllerGetBindForButton(ctrl.cptr(), btn.c())) } // Rumble triggers a rumble effect // Each call to this function cancels any previous rumble effect, and calling it with 0 intensity stops any rumbling. // // lowFrequencyRumble - The intensity of the low frequency (left) rumble motor, from 0 to 0xFFFF // highFrequencyRumble - The intensity of the high frequency (right) rumble motor, from 0 to 0xFFFF // durationMS - The duration of the rumble effect, in milliseconds // // Returns error if rumble isn't supported on this joystick. // // TODO: (https://wiki.libsdl.org/SDL_GameControllerRumble) func (ctrl *GameController) Rumble(lowFrequencyRumble, highFrequencyRumble uint16, durationMS uint32) error { return errorFromInt(int(C.SDL_GameControllerRumble(ctrl.cptr(), C.Uint16(lowFrequencyRumble), C.Uint16(highFrequencyRumble), C.Uint32(durationMS)))) } // Button returns the current state of a button on a game controller. // (https://wiki.libsdl.org/SDL_GameControllerGetButton) func (ctrl *GameController) Button(btn GameControllerButton) byte { return byte(C.SDL_GameControllerGetButton(ctrl.cptr(), btn.c())) } // Close closes a game controller previously opened with GameControllerOpen(). // (https://wiki.libsdl.org/SDL_GameControllerClose) func (ctrl *GameController) Close() { C.SDL_GameControllerClose(ctrl.cptr()) } // Type returns the type of game controller input for this SDL joystick layer binding. func (bind *GameControllerButtonBind) Type() int { return int(bind.bindType) } // Button returns button mapped for this SDL joystick layer binding. func (bind *GameControllerButtonBind) Button() int { val, _ := binary.Varint(bind.value[:4]) return int(val) } // Axis returns axis mapped for this SDL joystick layer binding. func (bind *GameControllerButtonBind) Axis() int { val, _ := binary.Varint(bind.value[:4]) return int(val) } // Hat returns hat mapped for this SDL joystick layer binding. func (bind *GameControllerButtonBind) Hat() int { val, _ := binary.Varint(bind.value[:4]) return int(val) } // HatMask returns hat mask for this SDL joystick layer binding. func (bind *GameControllerButtonBind) HatMask() int { val, _ := binary.Varint(bind.value[4:8]) return int(val) } // SendEffect sends a controller specific effect packet. // (https://wiki.libsdl.org/SDL_GameControllerSendEffect) func (ctrl *GameController) SendEffect(data []byte) (err error) { _size := C.int(len(data)) return errorFromInt(int(C.SDL_GameControllerSendEffect(ctrl.cptr(), unsafe.Pointer(&data[0]), _size))) } // GetSensorDataRate gets the data rate (number of events per second) of a game controller sensor. // (https://wiki.libsdl.org/SDL_GameControllerGetSensorDataRate) func (ctrl *GameController) SensorDataRate(typ SensorType) (rate float32) { return float32(C.SDL_GameControllerGetSensorDataRate(ctrl.cptr(), C.SDL_SensorType(typ))) } // HasRumble queries whether a game controller has rumble support. // (https://wiki.libsdl.org/SDL_GameControllerHasRumble) func (ctrl *GameController) HasRumble() bool { return C.SDL_GameControllerHasRumble(ctrl.cptr()) == C.SDL_TRUE } // HasRumbleTriggers queries whether a game controller has rumble support on triggers. // (https://wiki.libsdl.org/SDL_GameControllerHasRumbleTriggers) func (ctrl *GameController) HasRumbleTriggers() bool { return C.SDL_GameControllerHasRumbleTriggers(ctrl.cptr()) == C.SDL_TRUE } // GetAppleSFSymbolsNameForButton returns the sfSymbolsName for a given button on a game controller on Apple platforms. // (https://wiki.libsdl.org/SDL_GameControllerGetAppleSFSymbolsNameForButton) func (ctrl *GameController) GetAppleSFSymbolsNameForButton(button GameControllerButton) (sfSymbolsName string) { _button := C.SDL_GameControllerButton(button) _sfSymbolsName := C.SDL_GameControllerGetAppleSFSymbolsNameForButton(ctrl.cptr(), _button) sfSymbolsName = C.GoString(_sfSymbolsName) return } // GetAppleSFSymbolsNameForAxis returns the sfSymbolsName for a given axis on a game controller on Apple platforms. // (https://wiki.libsdl.org/SDL_GameControllerGetAppleSFSymbolsNameForAxis) func (ctrl *GameController) SDL_GameControllerGetAppleSFSymbolsNameForAxis(axis GameControllerAxis) (sfSymbolsName string) { _axis := C.SDL_GameControllerAxis(axis) _sfSymbolsName := C.SDL_GameControllerGetAppleSFSymbolsNameForAxis(ctrl.cptr(), _axis) sfSymbolsName = C.GoString(_sfSymbolsName) return } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/gesture.go ================================================ package sdl // #include "sdl_wrapper.h" import "C" // GestureID is the unique id of the closest gesture to the performed stroke. type GestureID C.SDL_GestureID func (g GestureID) c() C.SDL_GestureID { return C.SDL_GestureID(g) } // RecordGesture begins recording a gesture on a specified touch device or all touch devices. // (https://wiki.libsdl.org/SDL_RecordGesture) func RecordGesture(t TouchID) int { return int(C.SDL_RecordGesture(t.c())) } // SaveAllDollarTemplates saves all currently loaded Dollar Gesture templates. // (https://wiki.libsdl.org/SDL_SaveAllDollarTemplates) func SaveAllDollarTemplates(src *RWops) int { return int(C.SDL_SaveAllDollarTemplates(src.cptr())) } // SaveDollarTemplate saves a currently loaded Dollar Gesture template. // (https://wiki.libsdl.org/SDL_SaveDollarTemplate) func SaveDollarTemplate(g GestureID, src *RWops) int { return int(C.SDL_SaveDollarTemplate(g.c(), src.cptr())) } // LoadDollarTemplates loads Dollar Gesture templates from a file. // (https://wiki.libsdl.org/SDL_LoadDollarTemplates) func LoadDollarTemplates(t TouchID, src *RWops) int { return int(C.SDL_LoadDollarTemplates(t.c(), src.cptr())) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/guid.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !SDL_VERSION_ATLEAST(2,24,0) #if defined(WARN_OUTDATED) #pragma message("SDL_GUIDToString is not supported before SDL 2.24.0") #pragma message("SDL_GUIDFromString is not supported before SDL 2.24.0") #endif typedef struct { Uint8 data[16]; } SDL_GUID; static inline void SDL_GUIDToString(SDL_GUID guid, char *pszGUID, int cbGUID) { return; } static inline SDL_GUID SDL_GUIDFromString(const char *pchGUID) { SDL_GUID guid; return guid; } #endif */ import "C" import ( "unsafe" ) type GUID C.SDL_GUID // ToString returns an ASCII string representation for a given GUID. func (guid GUID) ToString() (ascii string) { _cap := C.size_t(33) _buf := (*C.char)(C.SDL_malloc(_cap)) defer C.SDL_free(unsafe.Pointer(_buf)) C.SDL_GUIDToString(C.SDL_GUID(guid), _buf, C.int(_cap)) return C.GoString(_buf) } // GUIDFromString converts a GUID string into a GUID structure. func GUIDFromString(ascii string) (guid GUID) { _ascii := C.CString(ascii) return GUID(C.SDL_GUIDFromString(_ascii)) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/haptic.go ================================================ package sdl // #include "sdl_wrapper.h" import "C" import "unsafe" // Haptic effects. // (https://wiki.libsdl.org/SDL_HapticEffect) const ( HAPTIC_CONSTANT = C.SDL_HAPTIC_CONSTANT // constant haptic effect HAPTIC_SINE = C.SDL_HAPTIC_SINE // periodic haptic effect that simulates sine waves HAPTIC_LEFTRIGHT = C.SDL_HAPTIC_LEFTRIGHT // haptic effect for direct control over high/low frequency motors HAPTIC_TRIANGLE = C.SDL_HAPTIC_TRIANGLE // periodic haptic effect that simulates triangular waves HAPTIC_SAWTOOTHUP = C.SDL_HAPTIC_SAWTOOTHUP // periodic haptic effect that simulates saw tooth up waves HAPTIC_SAWTOOTHDOWN = C.SDL_HAPTIC_SAWTOOTHDOWN // periodic haptic effect that simulates saw tooth down waves HAPTIC_RAMP = C.SDL_HAPTIC_RAMP // ramp haptic effect HAPTIC_SPRING = C.SDL_HAPTIC_SPRING // condition haptic effect that simulates a spring. Effect is based on the axes position HAPTIC_DAMPER = C.SDL_HAPTIC_DAMPER // condition haptic effect that simulates dampening. Effect is based on the axes velocity HAPTIC_INERTIA = C.SDL_HAPTIC_INERTIA // condition haptic effect that simulates inertia. Effect is based on the axes acceleration HAPTIC_FRICTION = C.SDL_HAPTIC_FRICTION // condition haptic effect that simulates friction. Effect is based on the axes movement HAPTIC_CUSTOM = C.SDL_HAPTIC_CUSTOM // user defined custom haptic effect HAPTIC_GAIN = C.SDL_HAPTIC_GAIN // device supports setting the global gain HAPTIC_AUTOCENTER = C.SDL_HAPTIC_AUTOCENTER // device supports setting autocenter HAPTIC_STATUS = C.SDL_HAPTIC_STATUS // device can be queried for effect status HAPTIC_PAUSE = C.SDL_HAPTIC_PAUSE // device can be paused //HAPTIC_SQUARE = C.SDL_HAPTIC_SQUARE (back in SDL 2.1) ) // Direction encodings. // (https://wiki.libsdl.org/SDL_HapticDirection) const ( HAPTIC_POLAR = C.SDL_HAPTIC_POLAR // uses polar coordinates for the direction HAPTIC_CARTESIAN = C.SDL_HAPTIC_CARTESIAN // uses cartesian coordinates for the direction HAPTIC_SPHERICAL = C.SDL_HAPTIC_SPHERICAL // uses spherical coordinates for the direction HAPTIC_INFINITY = C.SDL_HAPTIC_INFINITY // used to play a device an infinite number of times ) // Haptic identifies an SDL haptic. // (https://wiki.libsdl.org/CategoryForceFeedback) type Haptic C.SDL_Haptic // HapticDirection contains a haptic direction. // (https://wiki.libsdl.org/SDL_HapticDirection) type HapticDirection struct { Type byte // the type of encoding Dir [3]int32 // the encoded direction } // HapticConstant contains a template for a constant effect. // (https://wiki.libsdl.org/SDL_HapticConstant) type HapticConstant struct { Type uint16 // HAPTIC_CONSTANT Direction HapticDirection // direction of the effect Length uint32 // duration of the effect Delay uint16 // delay before starting the effect Button uint16 // button that triggers the effect Interval uint16 // how soon it can be triggered again after button Level int16 // strength of the constant effect AttackLength uint16 // duration of the attack AttackLevel uint16 // level at the start of the attack FadeLength uint16 // duration of the fade FadeLevel uint16 // level at the end of the fade } func (he *HapticConstant) cHapticEffect() *C.SDL_HapticEffect { return (*C.SDL_HapticEffect)(unsafe.Pointer(he)) } // HapticPeriodic contains a template for a periodic effect. // (https://wiki.libsdl.org/SDL_HapticPeriodic) type HapticPeriodic struct { Type uint16 // HAPTIC_SINE, HAPTIC_LEFTRIGHT, HAPTIC_TRIANGLE, HAPTIC_SAWTOOTHUP, HAPTIC_SAWTOOTHDOWN Direction HapticDirection // direction of the effect Length uint32 // duration of the effect Delay uint16 // delay before starting the effect Button uint16 // button that triggers the effect Interval uint16 // how soon it can be triggered again after button Period uint16 // period of the wave Magnitude int16 // peak value; if negative, equivalent to 180 degrees extra phase shift Offset int16 // mean value of the wave Phase uint16 // positive phase shift given by hundredth of a degree AttackLength uint16 // duration of the attack AttackLevel uint16 // level at the start of the attack FadeLength uint16 // duration of the fade FadeLevel uint16 // level at the end of the fade } func (he *HapticPeriodic) cHapticEffect() *C.SDL_HapticEffect { return (*C.SDL_HapticEffect)(unsafe.Pointer(he)) } // HapticCondition contains a template for a condition effect. // (https://wiki.libsdl.org/SDL_HapticCondition) type HapticCondition struct { Type uint16 // HAPTIC_SPRING, HAPTIC_DAMPER, HAPTIC_INERTIA, HAPTIC_FRICTION Direction HapticDirection // direction of the effect - not used at the moment Length uint32 // duration of the effect Delay uint16 // delay before starting the effect Button uint16 // button that triggers the effect Interval uint16 // how soon it can be triggered again after button RightSat [3]uint16 // level when joystick is to the positive side; max 0xFFFF LeftSat [3]uint16 // level when joystick is to the negative side; max 0xFFFF RightCoeff [3]int16 // how fast to increase the force towards the positive side LeftCoeff [3]int16 // how fast to increase the force towards the negative side Deadband [3]uint16 // size of the dead zone; max 0xFFFF: whole axis-range when 0-centered Center [3]int16 // position of the dead zone } func (he *HapticCondition) cHapticEffect() *C.SDL_HapticEffect { return (*C.SDL_HapticEffect)(unsafe.Pointer(he)) } // HapticRamp contains a template for a ramp effect. // (https://wiki.libsdl.org/SDL_HapticRamp) type HapticRamp struct { Type uint16 // HAPTIC_RAMP Direction HapticDirection // direction of the effect Length uint32 // duration of the effect Delay uint16 // delay before starting the effect Button uint16 // button that triggers the effect Interval uint16 // how soon it can be triggered again after button Start int16 // beginning strength level End int16 // ending strength level AttackLength uint16 // duration of the attack AttackLevel uint16 // level at the start of the attack FadeLength uint16 // duration of the fade FadeLevel uint16 // level at the end of the fade } func (he *HapticRamp) cHapticEffect() *C.SDL_HapticEffect { return (*C.SDL_HapticEffect)(unsafe.Pointer(he)) } // HapticLeftRight contains a template for a left/right effect. // (https://wiki.libsdl.org/SDL_HapticLeftRight) type HapticLeftRight struct { Type uint16 // HAPTIC_LEFTRIGHT Length uint32 // duration of the effect LargeMagnitude uint16 // control of the large controller motor SmallMagnitude uint16 // control of the small controller motor } func (he *HapticLeftRight) cHapticEffect() *C.SDL_HapticEffect { return (*C.SDL_HapticEffect)(unsafe.Pointer(he)) } // HapticCustom contains a template for a custom effect. // (https://wiki.libsdl.org/SDL_HapticCustom) type HapticCustom struct { Type uint16 // SDL_HAPTIC_CUSTOM Direction HapticDirection // direction of the effect Length uint32 // duration of the effect Delay uint16 // delay before starting the effect Button uint16 // button that triggers the effect Interval uint16 // how soon it can be triggered again after button Channels uint8 // axes to use, minimum of 1 Period uint16 // sample periods Samples uint16 // amount of samples Data *uint16 // should contain channels*samples items AttackLength uint16 // duration of the attack AttackLevel uint16 // level at the start of the attack FadeLength uint16 // duration of the fade FadeLevel uint16 // level at the end of the fade } func (he *HapticCustom) cHapticEffect() *C.SDL_HapticEffect { return (*C.SDL_HapticEffect)(unsafe.Pointer(he)) } // HapticEffect union that contains the generic template for any haptic effect. // (https://wiki.libsdl.org/SDL_HapticEffect) type HapticEffect interface { cHapticEffect() *C.SDL_HapticEffect } func (h *Haptic) cptr() *C.SDL_Haptic { return (*C.SDL_Haptic)(unsafe.Pointer(h)) } // NumHaptics returns the number of haptic devices attached to the system. // (https://wiki.libsdl.org/SDL_NumHaptics) func NumHaptics() (int, error) { i := int(C.SDL_NumHaptics()) return i, errorFromInt(i) } // HapticName returns the implementation dependent name of a haptic device. // (https://wiki.libsdl.org/SDL_HapticName) func HapticName(index int) (string, error) { name := C.SDL_HapticName(C.int(index)) if name == nil { return "", GetError() } return C.GoString(name), nil } // HapticOpen opens a haptic device for use. // (https://wiki.libsdl.org/SDL_HapticOpen) func HapticOpen(index int) (*Haptic, error) { haptic := (*Haptic)(unsafe.Pointer(C.SDL_HapticOpen(C.int(index)))) if haptic == nil { return nil, GetError() } return haptic, nil } // HapticOpened reports whether the haptic device at the designated index has been opened. // (https://wiki.libsdl.org/SDL_HapticOpened) func HapticOpened(index int) (bool, error) { ret := int(C.SDL_HapticOpened(C.int(index))) if ret == 0 { return false, GetError() } return ret == 1, nil } // HapticIndex returns the index of a haptic device. // (https://wiki.libsdl.org/SDL_HapticIndex) func HapticIndex(h *Haptic) (int, error) { i := int(C.SDL_HapticIndex(h.cptr())) return i, errorFromInt(i) } // MouseIsHaptic reports whether or not the current mouse has haptic capabilities. // (https://wiki.libsdl.org/SDL_MouseIsHaptic) func MouseIsHaptic() (bool, error) { ret := int(C.SDL_MouseIsHaptic()) return ret == C.SDL_TRUE, errorFromInt(ret) } // HapticOpenFromMouse open a haptic device from the current mouse. // (https://wiki.libsdl.org/SDL_HapticOpenFromMouse) func HapticOpenFromMouse() (*Haptic, error) { haptic := (*Haptic)(unsafe.Pointer(C.SDL_HapticOpenFromMouse())) if haptic == nil { return nil, GetError() } return haptic, nil } // JoystickIsHaptic reports whether a joystick has haptic features. // (https://wiki.libsdl.org/SDL_JoystickIsHaptic) func JoystickIsHaptic(joy *Joystick) (bool, error) { ret := int(C.SDL_JoystickIsHaptic(joy.cptr())) return ret == C.SDL_TRUE, errorFromInt(ret) } // HapticOpenFromJoystick opens a haptic device for use from a joystick device. // (https://wiki.libsdl.org/SDL_HapticOpenFromJoystick) func HapticOpenFromJoystick(joy *Joystick) (*Haptic, error) { haptic := (*Haptic)(unsafe.Pointer(C.SDL_HapticOpenFromJoystick(joy.cptr()))) if haptic == nil { return nil, GetError() } return haptic, nil } // Close closes a haptic device previously opened with HapticOpen(). // (https://wiki.libsdl.org/SDL_HapticClose) func (h *Haptic) Close() { C.SDL_HapticClose(h.cptr()) } // NumAxes returns the number of haptic axes the device has. // (https://wiki.libsdl.org/SDL_HapticNumAxes) func (h *Haptic) NumAxes() (int, error) { i := int(C.SDL_HapticNumAxes(h.cptr())) return i, errorFromInt(i) } // NumEffects returns the number of effects a haptic device can store. // (https://wiki.libsdl.org/SDL_HapticNumEffects) func (h *Haptic) NumEffects() (int, error) { i := int(C.SDL_HapticNumEffects(h.cptr())) return i, errorFromInt(i) } // NumEffectsPlaying returns the number of effects a haptic device can play at the same time. // (https://wiki.libsdl.org/SDL_HapticNumEffectsPlaying) func (h *Haptic) NumEffectsPlaying() (int, error) { i := int(C.SDL_HapticNumEffectsPlaying(h.cptr())) return i, errorFromInt(i) } // Query returns haptic device's supported features in bitwise manner. // (https://wiki.libsdl.org/SDL_HapticQuery) func (h *Haptic) Query() (uint32, error) { i := uint32(C.SDL_HapticQuery(h.cptr())) if i == 0 { return 0, GetError() } return i, nil } // EffectSupported reports whether an effect is supported by a haptic device. // Pass pointer to a Haptic struct (Constant|Periodic|Condition|Ramp|LeftRight|Custom) instead of HapticEffect union. // (https://wiki.libsdl.org/SDL_HapticEffectSupported) func (h *Haptic) EffectSupported(he HapticEffect) (bool, error) { ret := int(C.SDL_HapticEffectSupported( h.cptr(), he.cHapticEffect())) return ret == C.SDL_TRUE, errorFromInt(ret) } // NewEffect creates a new haptic effect on a specified device. // Pass pointer to a Haptic struct (Constant|Periodic|Condition|Ramp|LeftRight|Custom) instead of HapticEffect union. // (https://wiki.libsdl.org/SDL_HapticNewEffect) func (h *Haptic) NewEffect(he HapticEffect) (int, error) { ret := int(C.SDL_HapticNewEffect( h.cptr(), he.cHapticEffect())) return ret, errorFromInt(ret) } // UpdateEffect updates the properties of an effect. // Pass pointer to a Haptic struct (Constant|Periodic|Condition|Ramp|LeftRight|Custom) instead of HapticEffect union. // (https://wiki.libsdl.org/SDL_HapticUpdateEffect) func (h *Haptic) UpdateEffect(effect int, data HapticEffect) error { return errorFromInt(int( C.SDL_HapticUpdateEffect( h.cptr(), C.int(effect), data.cHapticEffect()))) } // RunEffect runs the haptic effect on its associated haptic device. // (https://wiki.libsdl.org/SDL_HapticRunEffect) func (h *Haptic) RunEffect(effect int, iterations uint32) error { return errorFromInt(int( C.SDL_HapticRunEffect( h.cptr(), C.int(effect), C.Uint32(iterations)))) } // StopEffect stops the haptic effect on its associated haptic device. // (https://wiki.libsdl.org/SDL_HapticStopEffect) func (h *Haptic) StopEffect(effect int) error { return errorFromInt(int( C.SDL_HapticStopEffect(h.cptr(), C.int(effect)))) } // DestroyEffect destroys a haptic effect on the device. // (https://wiki.libsdl.org/SDL_HapticDestroyEffect) func (h *Haptic) DestroyEffect(effect int) { C.SDL_HapticDestroyEffect(h.cptr(), C.int(effect)) } // GetEffectStatus returns the status of the current effect on the specified haptic device. // (https://wiki.libsdl.org/SDL_HapticGetEffectStatus) func (h *Haptic) GetEffectStatus(effect int) (int, error) { i := int(C.SDL_HapticGetEffectStatus(h.cptr(), C.int(effect))) return i, errorFromInt(i) } // SetGain sets the global gain of the specified haptic device. // (https://wiki.libsdl.org/SDL_HapticSetGain) func (h *Haptic) SetGain(gain int) error { return errorFromInt(int( C.SDL_HapticSetGain(h.cptr(), C.int(gain)))) } // SetAutocenter sets the global autocenter of the device. // (https://wiki.libsdl.org/SDL_HapticSetAutocenter) func (h *Haptic) SetAutocenter(autocenter int) error { return errorFromInt(int( C.SDL_HapticSetAutocenter(h.cptr(), C.int(autocenter)))) } // Pause pauses a haptic device. // (https://wiki.libsdl.org/SDL_HapticPause) func (h *Haptic) Pause() error { return errorFromInt(int( C.SDL_HapticPause(h.cptr()))) } // Unpause unpauses a haptic device. // (https://wiki.libsdl.org/SDL_HapticUnpause) func (h *Haptic) Unpause() error { return errorFromInt(int( C.SDL_HapticUnpause(h.cptr()))) } // StopAll stops all the currently playing effects on a haptic device. // (https://wiki.libsdl.org/SDL_HapticStopAll) func (h *Haptic) StopAll() error { return errorFromInt(int( C.SDL_HapticStopAll(h.cptr()))) } // RumbleSupported reports whether rumble is supported on a haptic device. // (https://wiki.libsdl.org/SDL_HapticRumbleSupported) func (h *Haptic) RumbleSupported() (bool, error) { ret := int(C.SDL_HapticRumbleSupported(h.cptr())) return ret == C.SDL_TRUE, errorFromInt(ret) } // RumbleInit initializes the haptic device for simple rumble playback. // (https://wiki.libsdl.org/SDL_HapticRumbleInit) func (h *Haptic) RumbleInit() error { return errorFromInt(int( C.SDL_HapticRumbleInit(h.cptr()))) } // RumblePlay runs a simple rumble effect on a haptic device. // (https://wiki.libsdl.org/SDL_HapticRumblePlay) func (h *Haptic) RumblePlay(strength float32, length uint32) error { return errorFromInt(int( C.SDL_HapticRumblePlay(h.cptr(), C.float(strength), C.Uint32(length)))) } // RumbleStop stops the simple rumble on a haptic device. // (https://wiki.libsdl.org/SDL_HapticRumbleStop) func (h *Haptic) RumbleStop() error { return errorFromInt(int( C.SDL_HapticRumbleStop(h.cptr()))) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/helpers.go ================================================ package sdl // Btoi returns 0 or 1 according to the value of b. func Btoi(b bool) int { if b == true { return 1 } return 0 } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/hidapi.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,18)) #if defined(WARN_OUTDATED) #pragma message("SDL_hid_init is not supported before SDL 2.0.18") #pragma message("SDL_hid_exit is not supported before SDL 2.0.18") #pragma message("SDL_hid_device_change_count is not supported before SDL 2.0.18") #pragma message("SDL_hid_enumerate is not supported before SDL 2.0.18") #pragma message("SDL_hid_free_enumeration is not supported before SDL 2.0.18") #pragma message("SDL_hid_open is not supported before SDL 2.0.18") #pragma message("SDL_hid_open_path is not supported before SDL 2.0.18") #pragma message("SDL_hid_write is not supported before SDL 2.0.18") #pragma message("SDL_hid_read_timeout is not supported before SDL 2.0.18") #pragma message("SDL_hid_read is not supported before SDL 2.0.18") #pragma message("SDL_hid_set_nonblocking is not supported before SDL 2.0.18") #pragma message("SDL_hid_send_feature_report is not supported before SDL 2.0.18") #pragma message("SDL_hid_get_feature_report is not supported before SDL 2.0.18") #pragma message("SDL_hid_close is not supported before SDL 2.0.18") #pragma message("SDL_hid_get_manufacturer_string is not supported before SDL 2.0.18") #pragma message("SDL_hid_get_product_string is not supported before SDL 2.0.18") #pragma message("SDL_hid_get_serial_number_string is not supported before SDL 2.0.18") #pragma message("SDL_hid_get_indexed_string is not supported before SDL 2.0.18") #pragma message("SDL_hid_ble_scan is not supported before SDL 2.0.18") #endif struct SDL_hid_device_; typedef struct SDL_hid_device_ SDL_hid_device; // opaque hidapi structure // hidapi info structure // Information about a connected HID device typedef struct SDL_hid_device_info { // Platform-specific device path char *path; // Device Vendor ID unsigned short vendor_id; // Device Product ID unsigned short product_id; // Serial Number wchar_t *serial_number; // Device Release Number in binary-coded decimal, also known as Device Version Number unsigned short release_number; // Manufacturer String wchar_t *manufacturer_string; // Product string wchar_t *product_string; // Usage Page for this Device/Interface (Windows/Mac only). unsigned short usage_page; // Usage for this Device/Interface (Windows/Mac only). unsigned short usage; // The USB interface which this logical device represents. // Valid on both Linux implementations in all cases. // Valid on the Windows implementation only if the device // contains more than one interface. int interface_number; // Additional information about the USB interface. // Valid on libusb and Android implementations. int interface_class; int interface_subclass; int interface_protocol; // Pointer to the next device struct SDL_hid_device_info *next; } SDL_hid_device_info; static int SDL_hid_init(void) { return -1; } static int SDL_hid_exit(void) { return -1; } static Uint32 SDL_hid_device_change_count(void) { return 0; } static SDL_hid_device_info * SDL_hid_enumerate(unsigned short vendor_id, unsigned short product_id) { return NULL; } static void SDL_hid_free_enumeration(SDL_hid_device_info *devs) { } static SDL_hid_device * SDL_hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number) { return NULL; } static SDL_hid_device * SDL_hid_open_path(const char *path, int bExclusive) { return NULL; } static int SDL_hid_write(SDL_hid_device *dev, const unsigned char *data, size_t length) { return -1; } static int SDL_hid_read_timeout(SDL_hid_device *dev, unsigned char *data, size_t length, int milliseconds) { return -1; } static int SDL_hid_read(SDL_hid_device *dev, unsigned char *data, size_t length) { return -1; } static int SDL_hid_set_nonblocking(SDL_hid_device *dev, int nonblock) { return -1; } static int SDL_hid_send_feature_report(SDL_hid_device *dev, const unsigned char *data, size_t length) { return -1; } static int SDL_hid_get_feature_report(SDL_hid_device *dev, unsigned char *data, size_t length) { return -1; } static void SDL_hid_close(SDL_hid_device *dev) { } static int SDL_hid_get_manufacturer_string(SDL_hid_device *dev, wchar_t *string, size_t maxlen) { return -1; } static int SDL_hid_get_product_string(SDL_hid_device *dev, wchar_t *string, size_t maxlen) { return -1; } static int SDL_hid_get_serial_number_string(SDL_hid_device *dev, wchar_t *string, size_t maxlen) { return -1; } static int SDL_hid_get_indexed_string(SDL_hid_device *dev, int string_index, wchar_t *string, size_t maxlen) { return -1; } static void SDL_hid_ble_scan(SDL_bool active) { } #endif */ import "C" import "unsafe" type HIDDevice C.SDL_hid_device type HIDDeviceInfo struct { path *C.char VendorID uint16 ProductID uint16 SerialNumber *C.wchar_t ReleaseNumber uint16 ManufacturerString *C.wchar_t ProductString *C.wchar_t UsagePage uint16 Usage uint16 InterfaceNumber int32 InterfaceClass int32 InterfaceSubclass int32 InterfaceProtocol int32 next *HIDDeviceInfo } func (info *HIDDeviceInfo) Path() string { return C.GoString(info.path) } // HIDInit initializes the HIDAPI library. // (https://wiki.libsdl.org/SDL_hid_init) func HIDInit() (err error) { ret := C.SDL_hid_init() return errorFromInt(int(ret)) } // HIDExit finalizes the HIDAPI library. // (https://wiki.libsdl.org/SDL_hid_exit) func HIDExit() (err error) { ret := C.SDL_hid_exit() return errorFromInt(int(ret)) } // HIDDeviceChangeCount checks to see if devices may have been added or removed. // (https://wiki.libsdl.org/SDL_hid_device_change_count) func HIDDeviceChangeCount() (n uint32) { return uint32(C.SDL_hid_device_change_count()) } // HIDEnumerate enumerates the HID devices. // (https://wiki.libsdl.org/SDL_hid_enumerate) func HIDEnumerate(vendorID, productID uint16) (info *HIDDeviceInfo) { _vendorID := C.Uint16(vendorID) _productID := C.Uint16(productID) info = (*HIDDeviceInfo)(unsafe.Pointer(C.SDL_hid_enumerate(_vendorID, _productID))) return } // HIDFreeEnumeration frees an enumeration Linked List. // (https://wiki.libsdl.org/SDL_hid_free_enumeration) func HIDFreeEnumeration(info *HIDDeviceInfo) { _info := (*C.SDL_hid_device_info)(unsafe.Pointer(info)) C.SDL_hid_free_enumeration(_info) } // HIDOpen opens a HID device using a Vendor ID (VID), Product ID (PID) and optionally a serial number. // (https://wiki.libsdl.org/SDL_hid_open) func HIDOpen(vendorID, productID uint16, _serialNumber *C.wchar_t) (device *HIDDevice) { _vendorID := C.Uint16(vendorID) _productID := C.Uint16(productID) _device := C.SDL_hid_open(_vendorID, _productID, _serialNumber) return (*HIDDevice)(_device) } // HIDOpenPath opens a HID device by its path name. // (https://wiki.libsdl.org/SDL_hid_open_path) func HIDOpenPath(path string, exclusive bool) (device *HIDDevice) { _path := C.CString(path) defer C.free(unsafe.Pointer(_path)) _exclusive := C.int(0) if exclusive { _exclusive = C.int(1) } _device := C.SDL_hid_open_path(_path, _exclusive) return (*HIDDevice)(_device) } // Write writes an Output report to a HID device. // (https://wiki.libsdl.org/SDL_hid_write) func (device *HIDDevice) Write(data []byte) (n int, err error) { _length := C.size_t(len(data)) _data := (*C.uchar)(unsafe.Pointer(&data[0])) _device := (*C.SDL_hid_device)(device) n = int(C.SDL_hid_write(_device, _data, _length)) return n, errorFromInt(n) } // ReadTimeout reads an Input report from a HID device with timeout. // (https://wiki.libsdl.org/SDL_hid_read_timeout) func (device *HIDDevice) ReadTimeout(data []byte, milliseconds int) (n int, err error) { _length := C.size_t(len(data)) _data := (*C.uchar)(unsafe.Pointer(&data[0])) _device := (*C.SDL_hid_device)(device) _milliseconds := C.int(milliseconds) n = int(C.SDL_hid_read_timeout(_device, _data, _length, _milliseconds)) return n, errorFromInt(n) } // Read an Input report from a HID device. // (https://wiki.libsdl.org/SDL_hid_read) func (device *HIDDevice) Read(data []byte) (n int, err error) { _length := C.size_t(len(data)) _data := (*C.uchar)(unsafe.Pointer(&data[0])) _device := (*C.SDL_hid_device)(device) n = int(C.SDL_hid_read(_device, _data, _length)) return n, errorFromInt(n) } // SetNonBlocking sets the device handle to be non-blocking. // (https://wiki.libsdl.org/SDL_hid_set_nonblocking) func (device *HIDDevice) SetNonBlocking(nonblock bool) (err error) { _device := (*C.SDL_hid_device)(device) _nonblock := C.int(Btoi(nonblock)) return errorFromInt(int(C.SDL_hid_set_nonblocking(_device, _nonblock))) } // SendFeatureReport sends a Feature report to the device. // (https://wiki.libsdl.org/SDL_hid_send_feature_report) func (device *HIDDevice) SendFeatureReport(data []byte) (n int, err error) { _length := C.size_t(len(data)) _data := (*C.uchar)(unsafe.Pointer(&data[0])) _device := (*C.SDL_hid_device)(device) n = int(C.SDL_hid_send_feature_report(_device, _data, _length)) return n, errorFromInt(n) } // GetFeatureReport gets a feature report from a HID device. // (https://wiki.libsdl.org/SDL_hid_get_feature_report) func (device *HIDDevice) GetFeatureReport(data []byte) (n int, err error) { _length := C.size_t(len(data)) _data := (*C.uchar)(unsafe.Pointer(&data[0])) _device := (*C.SDL_hid_device)(device) n = int(C.SDL_hid_get_feature_report(_device, _data, _length)) return n, errorFromInt(n) } // Close closes a HID device. // (https://wiki.libsdl.org/SDL_hid_close) func (device *HIDDevice) Close() { _device := (*C.SDL_hid_device)(device) C.SDL_hid_close(_device) } // GetManufacturerString gets The Manufacturer String from a HID device. // (https://wiki.libsdl.org/SDL_hid_get_manufacturer_string) func (device *HIDDevice) GetManufacturerString(_str *C.wchar_t, _maxlen C.size_t) (err error) { _device := (*C.SDL_hid_device)(device) return errorFromInt(int(C.SDL_hid_get_manufacturer_string(_device, _str, _maxlen))) } // GetProductString gets The Product String from a HID device. // (https://wiki.libsdl.org/SDL_hid_get_product_string) func (device *HIDDevice) GetProductString(_str *C.wchar_t, _maxlen C.size_t) (err error) { _device := (*C.SDL_hid_device)(device) return errorFromInt(int(C.SDL_hid_get_product_string(_device, _str, _maxlen))) } // GetSerialNumberString gets The SerialNumber String from a HID device. // (https://wiki.libsdl.org/SDL_hid_get_serial_number_string) func (device *HIDDevice) GetSerialNumberString(_str *C.wchar_t, _maxlen C.size_t) (err error) { _device := (*C.SDL_hid_device)(device) return errorFromInt(int(C.SDL_hid_get_serial_number_string(_device, _str, _maxlen))) } // GetIndexedString gets a string from a HID device, based on its string index. // (https://wiki.libsdl.org/SDL_hid_get_indexed_string) func (device *HIDDevice) GetIndexedString(index int, _str *C.wchar_t, _maxlen C.size_t) (err error) { _device := (*C.SDL_hid_device)(device) _index := C.int(index) return errorFromInt(int(C.SDL_hid_get_indexed_string(_device, _index, _str, _maxlen))) } // HIDBLEScan starts or stops a BLE scan on iOS and tvOS to pair Steam Controllers. // (https://wiki.libsdl.org/SDL_hid_ble_scan) func (device *HIDDevice) HIDBLEScan(active bool) { _active := C.SDL_bool(Btoi(active)) C.SDL_hid_ble_scan(_active) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/hints.c ================================================ #include "_cgo_export.h" #include "sdl_wrapper.h" #include "hints.h" void hintCallback(void *userdata, const char *name, const char *oldValue, const char *newValue) { goHintCallback((char *) name, (char *) oldValue, (char *) newValue); } void addHintCallback(const char *name) { SDL_AddHintCallback(name, hintCallback, NULL); } void delHintCallback(const char *name) { SDL_DelHintCallback(name, hintCallback, NULL);} ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/hints.go ================================================ package sdl /* #include "sdl_wrapper.h" #include "hints.h" #if !(SDL_VERSION_ATLEAST(2,0,20)) #define SDL_HINT_RENDER_LINE_METHOD "" #endif #if !(SDL_VERSION_ATLEAST(2,0,18)) #define SDL_HINT_APP_NAME "" #endif #if !(SDL_VERSION_ATLEAST(2,0,16)) #define SDL_HINT_JOYSTICK_RAWINPUT_CORRELATE_XINPUT "" #define SDL_HINT_AUDIO_INCLUDE_MONITORS "" #define SDL_HINT_AUDIO_DEVICE_STREAM_ROLE "" #endif #if !(SDL_VERSION_ATLEAST(2,0,14)) #define SDL_HINT_JOYSTICK_HIDAPI_PS5 "" #define SDL_HINT_MOUSE_RELATIVE_SCALING "" #define SDL_HINT_PREFERRED_LOCALES "" #define SDL_HINT_JOYSTICK_RAWINPUT "" #define SDL_HINT_JOYSTICK_HIDAPI_CORRELATE_XINPUT "" #define SDL_HINT_AUDIO_DEVICE_APP_NAME "" #define SDL_HINT_AUDIO_DEVICE_STREAM_NAME "" #define SDL_HINT_LINUX_JOYSTICK_DEADZONES "" #define SDL_HINT_THREAD_PRIORITY_POLICY "" #define SDL_HINT_THREAD_FORCE_REALTIME_TIME_CRITICAL "" #define SDL_HINT_ANDROID_BLOCK_ON_PAUSE_PAUSEAUDIO "" #define SDL_HINT_EMSCRIPTEN_ASYNCIFY "" #endif #if !(SDL_VERSION_ATLEAST(2,0,12)) #define SDL_HINT_DISPLAY_USABLE_BOUNDS "" #define SDL_HINT_GAMECONTROLLERTYPE "" #define SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS "" #define SDL_HINT_JOYSTICK_HIDAPI_GAMECUBE "" #define SDL_HINT_VIDEO_X11_WINDOW_VISUALID "" #define SDL_HINT_VIDEO_X11_FORCE_EGL "" #endif #if !(SDL_VERSION_ATLEAST(2,0,9)) #define SDL_HINT_MOUSE_DOUBLE_CLICK_TIME "" #define SDL_HINT_MOUSE_DOUBLE_CLICK_RADIUS "" #define SDL_HINT_JOYSTICK_HIDAPI_STEAM "" #endif #if !(SDL_VERSION_ATLEAST(2,0,8)) #define SDL_HINT_IOS_HIDE_HOME_INDICATOR "" #define SDL_HINT_RETURN_KEY_HIDES_IME "" #define SDL_HINT_TV_REMOTE_AS_JOYSTICK "" #define SDL_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR "" #define SDL_HINT_VIDEO_DOUBLE_BUFFER "" #endif #if !(SDL_VERSION_ATLEAST(2,0,6)) #define SDL_HINT_AUDIO_RESAMPLING_MODE "" #define SDL_HINT_RENDER_LOGICAL_SIZE_MODE "" #define SDL_HINT_MOUSE_NORMAL_SPEED_SCALE "" #define SDL_HINT_MOUSE_RELATIVE_SPEED_SCALE "" #define SDL_HINT_TOUCH_MOUSE_EVENTS "" #define SDL_HINT_WINDOWS_INTRESOURCE_ICON "" #define SDL_HINT_WINDOWS_INTRESOURCE_ICON_SMALL "" #endif #if !(SDL_VERSION_ATLEAST(2,0,4)) #define SDL_HINT_NO_SIGNAL_HANDLERS "" #define SDL_HINT_THREAD_STACK_SIZE "" #define SDL_HINT_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN "" #define SDL_HINT_WINDOWS_ENABLE_MESSAGELOOP "" #define SDL_HINT_WINDOWS_NO_CLOSE_ON_ALT_F4 "" #define SDL_HINT_XINPUT_USE_OLD_JOYSTICK_MAPPING "" #define SDL_HINT_MAC_BACKGROUND_APP "" #define SDL_HINT_IME_INTERNAL_EDITING "" #define SDL_HINT_VIDEO_X11_NET_WM_PING "" #define SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH "" #define SDL_HINT_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION "" #define SDL_HINT_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION "" #endif #if !(SDL_VERSION_ATLEAST(2,0,3)) #define SDL_HINT_WINRT_PRIVACY_POLICY_URL "" #define SDL_HINT_WINRT_PRIVACY_POLICY_LABEL "" #define SDL_HINT_WINRT_HANDLE_BACK_BUTTON "" #define SDL_HINT_RENDER_DIRECT3D11_DEBUG "" #endif #if !(SDL_VERSION_ATLEAST(2,0,2)) #define SDL_HINT_ACCELEROMETER_AS_JOYSTICK "" #define SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK "" #define SDL_HINT_VIDEO_ALLOW_SCREENSAVER "" #define SDL_HINT_MOUSE_RELATIVE_MODE_WARP "" #define SDL_HINT_VIDEO_WIN_D3DCOMPILER "" #define SDL_HINT_VIDEO_WINDOW_SHARE_PIXEL_FORMAT "" #define SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES "" #endif #if !(SDL_VERSION_ATLEAST(2,0,1)) #define SDL_HINT_RENDER_DIRECT3D_THREADSAFE "" #define SDL_HINT_VIDEO_HIGHDPI_DISABLED "" #endif #if !(SDL_VERSION_ATLEAST(2,0,10)) #if defined(WARN_OUTDATED) #pragma message("SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH has been removed in SDL 2.0.10") #endif #define SDL_HINT_RENDER_BATCHING "" #define SDL_HINT_EVENT_LOGGING "" #define SDL_HINT_GAMECONTROLLERCONFIG_FILE "" #define SDL_HINT_ANDROID_BLOCK_ON_PAUSE "" #define SDL_HINT_MOUSE_TOUCH_EVENTS "" #else #define SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH "" // For compatibility #endif #if SDL_VERSION_ATLEAST(2,0,16) #if defined(WARN_OUTDATED) #pragma message("SDL_HINT_JOYSTICK_HIDAPI_CORRELATE_XINPUT has been replaced by SDL_HINT_JOYSTICK_RAWINPUT_CORRELATE_XINPUT in SDL 2.0.16") #endif #define SDL_HINT_JOYSTICK_HIDAPI_CORRELATE_XINPUT (SDL_HINT_JOYSTICK_RAWINPUT_CORRELATE_XINPUT) #endif #if !SDL_VERSION_ATLEAST(2,0,18) #define SDL_HINT_IME_SHOW_UI "" #define SDL_HINT_JOYSTICK_DEVICE "" #define SDL_HINT_LINUX_JOYSTICK_CLASSIC "" #define SDL_HINT_SCREENSAVER_INHIBIT_ACTIVITY_NAME "" #define SDL_HINT_VIDEO_EGL_ALLOW_TRANSPARENCY "" #endif #if !SDL_VERSION_ATLEAST(2,0,22) #define SDL_HINT_IME_SUPPORT_EXTENDED_TEXT "" #define SDL_HINT_MOUSE_RELATIVE_MODE_CENTER "" #define SDL_HINT_MOUSE_AUTO_CAPTURE "" #define SDL_HINT_VIDEO_FOREIGN_WINDOW_OPENGL "" #define SDL_HINT_VIDEO_FOREIGN_WINDOW_VULKAN "" #define SDL_HINT_QUIT_ON_LAST_WINDOW_CLOSE "" #define SDL_HINT_JOYSTICK_ROG_CHAKRAM "" #define SDL_HINT_X11_WINDOW_TYPE "" #define SDL_HINT_VIDEO_WAYLAND_PREFER_LIBDECOR "" #endif */ import "C" import "unsafe" // Configuration hints // (https://wiki.libsdl.org/CategoryHints) const ( HINT_FRAMEBUFFER_ACCELERATION = C.SDL_HINT_FRAMEBUFFER_ACCELERATION // specifies how 3D acceleration is used with Window.GetSurface() HINT_RENDER_DRIVER = C.SDL_HINT_RENDER_DRIVER // specifies which render driver to use HINT_RENDER_OPENGL_SHADERS = C.SDL_HINT_RENDER_OPENGL_SHADERS // specifies whether the OpenGL render driver uses shaders HINT_RENDER_DIRECT3D_THREADSAFE = C.SDL_HINT_RENDER_DIRECT3D_THREADSAFE // specifies whether the Direct3D device is initialized for thread-safe operations HINT_RENDER_DIRECT3D11_DEBUG = C.SDL_HINT_RENDER_DIRECT3D11_DEBUG // specifies a variable controlling whether to enable Direct3D 11+'s Debug Layer HINT_RENDER_SCALE_QUALITY = C.SDL_HINT_RENDER_SCALE_QUALITY // specifies scaling quality HINT_RENDER_VSYNC = C.SDL_HINT_RENDER_VSYNC // specifies whether sync to vertical refresh is enabled or disabled in CreateRenderer() to avoid tearing HINT_VIDEO_ALLOW_SCREENSAVER = C.SDL_HINT_VIDEO_ALLOW_SCREENSAVER // specifies whether the screensaver is enabled HINT_VIDEO_X11_NET_WM_PING = C.SDL_HINT_VIDEO_X11_NET_WM_PING // specifies whether the X11 _NET_WM_PING protocol should be supported HINT_VIDEO_X11_XVIDMODE = C.SDL_HINT_VIDEO_X11_XVIDMODE // specifies whether the X11 VidMode extension should be used HINT_VIDEO_X11_XINERAMA = C.SDL_HINT_VIDEO_X11_XINERAMA // specifies whether the X11 Xinerama extension should be used HINT_VIDEO_X11_XRANDR = C.SDL_HINT_VIDEO_X11_XRANDR // specifies whether the X11 XRandR extension should be used HINT_GRAB_KEYBOARD = C.SDL_HINT_GRAB_KEYBOARD // specifies whether grabbing input grabs the keyboard HINT_MOUSE_DOUBLE_CLICK_TIME = C.SDL_HINT_MOUSE_DOUBLE_CLICK_TIME // specifies the double click time, in milliseconds HINT_MOUSE_DOUBLE_CLICK_RADIUS = C.SDL_HINT_MOUSE_DOUBLE_CLICK_RADIUS // specifies the double click radius, in pixels. HINT_MOUSE_RELATIVE_MODE_WARP = C.SDL_HINT_MOUSE_RELATIVE_MODE_WARP // specifies whether relative mouse mode is implemented using mouse warping HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS = C.SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS // specifies if a Window is minimized if it loses key focus when in fullscreen mode HINT_IDLE_TIMER_DISABLED = C.SDL_HINT_IDLE_TIMER_DISABLED // specifies a variable controlling whether the idle timer is disabled on iOS HINT_IME_INTERNAL_EDITING = C.SDL_HINT_IME_INTERNAL_EDITING // specifies whether certain IMEs should handle text editing internally instead of sending TextEditingEvents HINT_ORIENTATIONS = C.SDL_HINT_ORIENTATIONS // specifies a variable controlling which orientations are allowed on iOS HINT_ACCELEROMETER_AS_JOYSTICK = C.SDL_HINT_ACCELEROMETER_AS_JOYSTICK // specifies whether the Android / iOS built-in accelerometer should be listed as a joystick device, rather than listing actual joysticks only HINT_XINPUT_ENABLED = C.SDL_HINT_XINPUT_ENABLED // specifies if Xinput gamepad devices are detected HINT_XINPUT_USE_OLD_JOYSTICK_MAPPING = C.SDL_HINT_XINPUT_USE_OLD_JOYSTICK_MAPPING // specifies that SDL should use the old axis and button mapping for XInput devices HINT_GAMECONTROLLERCONFIG = C.SDL_HINT_GAMECONTROLLERCONFIG // specifies extra gamecontroller db entries HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS = C.SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS // specifies if joystick (and gamecontroller) events are enabled even when the application is in the background HINT_ALLOW_TOPMOST = C.SDL_HINT_ALLOW_TOPMOST // specifies if top most bit on an SDL Window can be set HINT_THREAD_STACK_SIZE = C.SDL_HINT_THREAD_STACK_SIZE // specifies a variable specifying SDL's threads stack size in bytes or "0" for the backend's default size HINT_TIMER_RESOLUTION = C.SDL_HINT_TIMER_RESOLUTION // specifies the timer resolution in milliseconds HINT_VIDEO_HIGHDPI_DISABLED = C.SDL_HINT_VIDEO_HIGHDPI_DISABLED // specifies if high-DPI windows ("Retina" on Mac and iOS) are not allowed HINT_MAC_BACKGROUND_APP = C.SDL_HINT_MAC_BACKGROUND_APP // specifies if the SDL app should not be forced to become a foreground process on Mac OS X HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK = C.SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK // specifies whether ctrl+click should generate a right-click event on Mac HINT_VIDEO_WIN_D3DCOMPILER = C.SDL_HINT_VIDEO_WIN_D3DCOMPILER // specifies which shader compiler to preload when using the Chrome ANGLE binaries HINT_VIDEO_WINDOW_SHARE_PIXEL_FORMAT = C.SDL_HINT_VIDEO_WINDOW_SHARE_PIXEL_FORMAT // specifies the address of another Window* (as a hex string formatted with "%p") HINT_WINRT_PRIVACY_POLICY_URL = C.SDL_HINT_WINRT_PRIVACY_POLICY_URL // specifies a URL to a WinRT app's privacy policy HINT_WINRT_PRIVACY_POLICY_LABEL = C.SDL_HINT_WINRT_PRIVACY_POLICY_LABEL // specifies a label text for a WinRT app's privacy policy link HINT_WINRT_HANDLE_BACK_BUTTON = C.SDL_HINT_WINRT_HANDLE_BACK_BUTTON // specifies a variable to allow back-button-press events on Windows Phone to be marked as handled HINT_VIDEO_MAC_FULLSCREEN_SPACES = C.SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES // specifies policy for fullscreen Spaces on Mac OS X HINT_NO_SIGNAL_HANDLERS = C.SDL_HINT_NO_SIGNAL_HANDLERS // specifies not to catch the SIGINT or SIGTERM signals HINT_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN = C.SDL_HINT_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN // specifies whether the window frame and title bar are interactive when the cursor is hidden HINT_WINDOWS_ENABLE_MESSAGELOOP = C.SDL_HINT_WINDOWS_ENABLE_MESSAGELOOP // specifies whether the windows message loop is processed by SDL HINT_WINDOWS_NO_CLOSE_ON_ALT_F4 = C.SDL_HINT_WINDOWS_NO_CLOSE_ON_ALT_F4 // specifies that SDL should not to generate WINDOWEVENT_CLOSE events for Alt+F4 on Microsoft Windows HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH = C.SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH // specifies a variable to control whether mouse and touch events are to be treated together or separately HINT_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION = C.SDL_HINT_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION // specifies the Android APK expansion main file version HINT_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION = C.SDL_HINT_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION // specifies the Android APK expansion patch file version HINT_AUDIO_RESAMPLING_MODE = C.SDL_HINT_AUDIO_RESAMPLING_MODE // specifies a variable controlling speed/quality tradeoff of audio resampling HINT_RENDER_LOGICAL_SIZE_MODE = C.SDL_HINT_RENDER_LOGICAL_SIZE_MODE // specifies a variable controlling the scaling policy for SDL_RenderSetLogicalSize HINT_MOUSE_NORMAL_SPEED_SCALE = C.SDL_HINT_MOUSE_NORMAL_SPEED_SCALE // specifies a variable setting the speed scale for mouse motion, in floating point, when the mouse is not in relative mode HINT_MOUSE_RELATIVE_SPEED_SCALE = C.SDL_HINT_MOUSE_RELATIVE_SPEED_SCALE // specifies a variable setting the scale for mouse motion, in floating point, when the mouse is in relative mode HINT_MOUSE_TOUCH_EVENTS = C.SDL_HINT_MOUSE_TOUCH_EVENTS // specifies a variable to control whether mouse events should generate synthetic touch events HINT_TOUCH_MOUSE_EVENTS = C.SDL_HINT_TOUCH_MOUSE_EVENTS // specifies a variable controlling whether touch events should generate synthetic mouse events HINT_WINDOWS_INTRESOURCE_ICON = C.SDL_HINT_WINDOWS_INTRESOURCE_ICON // specifies a variable to specify custom icon resource id from RC file on Windows platform HINT_WINDOWS_INTRESOURCE_ICON_SMALL = C.SDL_HINT_WINDOWS_INTRESOURCE_ICON_SMALL // specifies a variable to specify custom icon resource id from RC file on Windows platform HINT_IOS_HIDE_HOME_INDICATOR = C.SDL_HINT_IOS_HIDE_HOME_INDICATOR // specifies a variable controlling whether the home indicator bar on iPhone X should be hidden. HINT_RETURN_KEY_HIDES_IME = C.SDL_HINT_RETURN_KEY_HIDES_IME // specifies a variable to control whether the return key on the soft keyboard should hide the soft keyboard on Android and iOS. HINT_TV_REMOTE_AS_JOYSTICK = C.SDL_HINT_TV_REMOTE_AS_JOYSTICK // specifies a variable controlling whether the Android / tvOS remotes should be listed as joystick devices, instead of sending keyboard events. HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR = C.SDL_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR // specifies a variable controlling whether the X11 _NET_WM_BYPASS_COMPOSITOR hint should be used. HINT_VIDEO_DOUBLE_BUFFER = C.SDL_HINT_VIDEO_DOUBLE_BUFFER // specifies a variable that tells the video driver that we only want a double buffer. HINT_RENDER_BATCHING = C.SDL_HINT_RENDER_BATCHING // specifies a variable controlling whether the 2D render API is compatible or efficient. HINT_EVENT_LOGGING = C.SDL_HINT_EVENT_LOGGING // specifies a variable controlling whether SDL logs all events pushed onto its internal queue. HINT_GAMECONTROLLERCONFIG_FILE = C.SDL_HINT_GAMECONTROLLERCONFIG_FILE // specifies a variable that lets you provide a file with extra gamecontroller db entries. HINT_ANDROID_BLOCK_ON_PAUSE = C.SDL_HINT_ANDROID_BLOCK_ON_PAUSE // specifies a variable to control whether the event loop will block itself when the app is paused. HINT_DISPLAY_USABLE_BOUNDS = C.SDL_HINT_DISPLAY_USABLE_BOUNDS // Override for SDL_GetDisplayUsableBounds(). HINT_GAMECONTROLLERTYPE = C.SDL_HINT_GAMECONTROLLERTYPE // Overrides the automatic controller type detection. HINT_GAMECONTROLLER_USE_BUTTON_LABELS = C.SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS // If set, game controller face buttons report their values according to their labels instead of their positional layout. HINT_JOYSTICK_HIDAPI_GAMECUBE = C.SDL_HINT_JOYSTICK_HIDAPI_GAMECUBE // A variable controlling whether the HIDAPI driver for Nintendo GameCube controllers should be used. HINT_VIDEO_X11_WINDOW_VISUALID = C.SDL_HINT_VIDEO_X11_WINDOW_VISUALID // A variable forcing the visual ID chosen for new X11 windows. HINT_VIDEO_X11_FORCE_EGL = C.SDL_HINT_VIDEO_X11_FORCE_EGL // A variable controlling whether X11 should use GLX or EGL by default. HINT_JOYSTICK_HIDAPI_PS5 = C.SDL_HINT_JOYSTICK_HIDAPI_PS5 // A variable controlling whether the HIDAPI driver for PS5 controllers should be used. HINT_MOUSE_RELATIVE_SCALING = C.SDL_HINT_MOUSE_RELATIVE_SCALING // A variable controlling whether relative mouse motion is affected by renderer scaling. HINT_PREFERRED_LOCALES = C.SDL_HINT_PREFERRED_LOCALES // Override for SDL_GetPreferredLocales(). HINT_JOYSTICK_RAWINPUT = C.SDL_HINT_JOYSTICK_RAWINPUT // A variable controlling whether the RAWINPUT joystick drivers should be used for better handling XInput-capable devices. HINT_JOYSTICK_RAWINPUT_CORRELATE_XINPUT = C.SDL_HINT_JOYSTICK_RAWINPUT_CORRELATE_XINPUT // A variable controlling whether the HIDAPI driver for XBox controllers on Windows should pull correlated data from XInput. HINT_JOYSTICK_HIDAPI_CORRELATE_XINPUT = C.SDL_HINT_JOYSTICK_HIDAPI_CORRELATE_XINPUT // A variable controlling whether the HIDAPI driver for XBox controllers on Windows should pull correlated data from XInput. HINT_AUDIO_DEVICE_APP_NAME = C.SDL_HINT_AUDIO_DEVICE_APP_NAME // Specify an application name for an audio device. HINT_AUDIO_DEVICE_STREAM_NAME = C.SDL_HINT_AUDIO_DEVICE_STREAM_NAME // Specify an application name for an audio device. HINT_LINUX_JOYSTICK_DEADZONES = C.SDL_HINT_LINUX_JOYSTICK_DEADZONES // A variable controlling whether joysticks on Linux adhere to their HID-defined deadzones or return unfiltered values. HINT_THREAD_PRIORITY_POLICY = C.SDL_HINT_THREAD_PRIORITY_POLICY // A string specifying additional information to use with SDL_SetThreadPriority. HINT_THREAD_FORCE_REALTIME_TIME_CRITICAL = C.SDL_HINT_THREAD_FORCE_REALTIME_TIME_CRITICAL // Specifies whether SDL_THREAD_PRIORITY_TIME_CRITICAL should be treated as realtime. HINT_ANDROID_BLOCK_ON_PAUSE_PAUSEAUDIO = C.SDL_HINT_ANDROID_BLOCK_ON_PAUSE_PAUSEAUDIO // A variable to control whether SDL will pause audio in background (Requires SDL_ANDROID_BLOCK_ON_PAUSE as "Non blocking"). HINT_EMSCRIPTEN_ASYNCIFY = C.SDL_HINT_EMSCRIPTEN_ASYNCIFY // Disable giving back control to the browser automatically when running with asyncify. HINT_AUDIO_INCLUDE_MONITORS = C.SDL_HINT_AUDIO_INCLUDE_MONITORS // Control whether PulseAudio recording should include monitor devices HINT_AUDIO_DEVICE_STREAM_ROLE = C.SDL_HINT_AUDIO_DEVICE_STREAM_ROLE // Describe the role of your application for audio control panels HINT_APP_NAME = C.SDL_HINT_APP_NAME // Lets you specify the application name sent to the OS when required HINT_VIDEO_EGL_ALLOW_TRANSPARENCY = C.SDL_HINT_VIDEO_EGL_ALLOW_TRANSPARENCY // A variable controlling whether the EGL window is allowed to be composited as transparent, rather than opaque HINT_IME_SHOW_UI = C.SDL_HINT_IME_SHOW_UI // A variable to control whether certain IMEs should show native UI components (such as the Candidate List) instead of suppressing them HINT_IME_SUPPORT_EXTENDED_TEXT = C.SDL_HINT_IME_SUPPORT_EXTENDED_TEXT // A variable to control if extended IME text support is enabled. HINT_SCREENSAVER_INHIBIT_ACTIVITY_NAME = C.SDL_HINT_SCREENSAVER_INHIBIT_ACTIVITY_NAME // This hint lets you specify the "activity name" sent to the OS when SDL_DisableScreenSaver() is used (or the screensaver is automatically disabled) HINT_LINUX_JOYSTICK_CLASSIC = C.SDL_HINT_LINUX_JOYSTICK_CLASSIC // A variable controlling whether to use the classic /dev/input/js* joystick interface or the newer /dev/input/event* joystick interface on Linux HINT_JOYSTICK_DEVICE = C.SDL_HINT_JOYSTICK_DEVICE // This variable is currently only used by the Linux joystick driver HINT_JOYSTICK_HIDAPI_STEAM = C.SDL_HINT_JOYSTICK_HIDAPI_STEAM // A variable controlling whether the HIDAPI driver for Steam Controllers should be used HINT_RENDER_LINE_METHOD = C.SDL_HINT_RENDER_LINE_METHOD // A variable controlling how the 2D render API renders lines HINT_MOUSE_RELATIVE_MODE_CENTER = C.SDL_HINT_MOUSE_RELATIVE_MODE_CENTER // A variable controlling whether relative mouse mode constrains the mouse to the center of the window HINT_MOUSE_AUTO_CAPTURE = C.SDL_HINT_MOUSE_AUTO_CAPTURE // A variable controlling whether the mouse is captured while mouse buttons are pressed HINT_VIDEO_FOREIGN_WINDOW_OPENGL = C.SDL_HINT_VIDEO_FOREIGN_WINDOW_OPENGL // When calling SDL_CreateWindowFrom(), make the window compatible with OpenGL HINT_VIDEO_FOREIGN_WINDOW_VULKAN = C.SDL_HINT_VIDEO_FOREIGN_WINDOW_VULKAN // When calling SDL_CreateWindowFrom(), make the window compatible with Vulkan HINT_QUIT_ON_LAST_WINDOW_CLOSE = C.SDL_HINT_QUIT_ON_LAST_WINDOW_CLOSE // A variable that decides whether to send SDL_QUIT when closing the final window HINT_JOYSTICK_ROG_CHAKRAM = C.SDL_HINT_JOYSTICK_ROG_CHAKRAM // A variable controlling whether the ROG Chakram mice should show up as joysticks HINT_X11_WINDOW_TYPE = C.SDL_HINT_X11_WINDOW_TYPE // A variable that forces X11 windows to create as a custom type HINT_VIDEO_WAYLAND_PREFER_LIBDECOR = C.SDL_HINT_VIDEO_WAYLAND_PREFER_LIBDECOR // A variable controlling whether the libdecor Wayland backend is preferred over native decrations ) // An enumeration of hint priorities. // (https://wiki.libsdl.org/SDL_HintPriority) const ( HINT_DEFAULT = C.SDL_HINT_DEFAULT // low priority, used for default values HINT_NORMAL = C.SDL_HINT_NORMAL // medium priority HINT_OVERRIDE = C.SDL_HINT_OVERRIDE // high priority ) // HintCallback is the function to call when the hint value changes. type HintCallback func(data interface{}, name, oldValue, newValue string) // HintCallbackAndData contains a callback function and userdata. type HintCallbackAndData struct { callback HintCallback // the function to call when the hint value changes data interface{} // data to pass to the callback function } var hintCallbacks = make(map[string]HintCallbackAndData) // HintPriority is a hint priority used in SetHintWithPriority(). // (https://wiki.libsdl.org/SDL_HintPriority) type HintPriority C.SDL_HintPriority func (hp HintPriority) c() C.SDL_HintPriority { return C.SDL_HintPriority(hp) } // SetHintWithPriority sets a hint with a specific priority. // (https://wiki.libsdl.org/SDL_SetHintWithPriority) func SetHintWithPriority(name, value string, hp HintPriority) bool { _name := C.CString(name) _value := C.CString(value) defer C.free(unsafe.Pointer(_name)) defer C.free(unsafe.Pointer(_value)) return C.SDL_SetHintWithPriority(_name, _value, hp.c()) > 0 } // SetHint sets a hint with normal priority. // (https://wiki.libsdl.org/SDL_SetHint) func SetHint(name, value string) bool { _name := C.CString(name) _value := C.CString(value) defer C.free(unsafe.Pointer(_name)) defer C.free(unsafe.Pointer(_value)) return C.SDL_SetHint(_name, _value) > 0 } // GetHint returns the value of a hint. // (https://wiki.libsdl.org/SDL_GetHint) func GetHint(name string) string { _name := C.CString(name) defer C.free(unsafe.Pointer(_name)) return C.GoString(C.SDL_GetHint(_name)) } // ClearHints clears all hints. // (https://wiki.libsdl.org/SDL_ClearHints) func ClearHints() { C.SDL_ClearHints() } // AddHintCallback adds a function to watch a particular hint. // (https://wiki.libsdl.org/SDL_AddHintCallback) func AddHintCallback(name string, fn HintCallback, data interface{}) { _name := C.CString(name) hintCallbacks[name] = HintCallbackAndData{ callback: fn, data: data, } C.addHintCallback(_name) } // DelHintCallback removes a function watching a particular hint. // (https://wiki.libsdl.org/SDL_DelHintCallback) func DelHintCallback(name string) { _name := C.CString(name) delete(hintCallbacks, name) C.delHintCallback(_name) } //export goHintCallback func goHintCallback(_name, _oldValue, _newValue *C.char) { name := C.GoString(_name) oldValue := C.GoString(_oldValue) newValue := C.GoString(_newValue) if cb, ok := hintCallbacks[name]; ok { cb.callback(cb.data, name, oldValue, newValue) } } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/hints.h ================================================ void hintCallback(void *userdata, const char *name, const char *oldValue, const char *newValue); void addHintCallback(const char *name); void delHintCallback(const char *name); ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/joystick.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,4)) #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickPowerLevel is not supported before SDL 2.0.4") #endif typedef enum { SDL_JOYSTICK_POWER_UNKNOWN = -1, SDL_JOYSTICK_POWER_EMPTY, SDL_JOYSTICK_POWER_LOW, SDL_JOYSTICK_POWER_MEDIUM, SDL_JOYSTICK_POWER_FULL, SDL_JOYSTICK_POWER_WIRED, SDL_JOYSTICK_POWER_MAX } SDL_JoystickPowerLevel; #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickCurrentPowerLevel is not supported before SDL 2.0.4") #endif static SDL_JoystickPowerLevel SDL_JoystickCurrentPowerLevel(SDL_Joystick* joystick) { return SDL_JOYSTICK_POWER_UNKNOWN; } #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickFromInstanceID is not supported before SDL 2.0.4") #endif static SDL_Joystick* SDL_JoystickFromInstanceID(SDL_JoystickID joyid) { return NULL; } #endif #if !(SDL_VERSION_ATLEAST(2,0,6)) #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickType is not supported before SDL 2.0.6") #endif typedef enum { SDL_JOYSTICK_TYPE_UNKNOWN, SDL_JOYSTICK_TYPE_GAMECONTROLLER, SDL_JOYSTICK_TYPE_WHEEL, SDL_JOYSTICK_TYPE_ARCADE_STICK, SDL_JOYSTICK_TYPE_FLIGHT_STICK, SDL_JOYSTICK_TYPE_DANCE_PAD, SDL_JOYSTICK_TYPE_GUITAR, SDL_JOYSTICK_TYPE_DRUM_KIT, SDL_JOYSTICK_TYPE_ARCADE_PAD, SDL_JOYSTICK_TYPE_THROTTLE } SDL_JoystickType; #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickGetDeviceVendor is not supported before SDL 2.0.6") #endif static Uint16 SDL_JoystickGetDeviceVendor(int device_index) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickGetDeviceProduct is not supported before SDL 2.0.6") #endif static Uint16 SDL_JoystickGetDeviceProduct(int device_index) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickGetDeviceProductVersion is not supported before SDL 2.0.6") #endif static Uint16 SDL_JoystickGetDeviceProductVersion(int device_index) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickGetDeviceType is not supported before SDL 2.0.6") #endif static SDL_JoystickType SDL_JoystickGetDeviceType(int device_index) { return SDL_JOYSTICK_TYPE_UNKNOWN; } #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickGetDeviceInstanceID is not supported before SDL 2.0.6") #endif static SDL_JoystickID SDL_JoystickGetDeviceInstanceID(int device_index) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickGetVendor is not supported before SDL 2.0.6") #endif static Uint16 SDL_JoystickGetVendor(SDL_Joystick* joystick) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickGetProduct is not supported before SDL 2.0.6") #endif static Uint16 SDL_JoystickGetProduct(SDL_Joystick* joystick) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickGetProductVersion is not supported before SDL 2.0.6") #endif static Uint16 SDL_JoystickGetProductVersion(SDL_Joystick* joystick) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickGetType is not supported before SDL 2.0.6") #endif static SDL_JoystickType SDL_JoystickGetType(SDL_Joystick* joystick) { return SDL_JOYSTICK_TYPE_UNKNOWN; } #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickGetAxisInitialState is not supported before SDL 2.0.6") #endif static SDL_bool SDL_JoystickGetAxisInitialState(SDL_Joystick* joystick, int axis, Sint16* state) { return SDL_FALSE; } #endif #if !(SDL_VERSION_ATLEAST(2,0,7)) #if defined(WARN_OUTDATED) #pragma message("SDL_LockJoysticks is not supported before SDL 2.0.7") #endif static void SDL_LockJoysticks() { } #if defined(WARN_OUTDATED) #pragma message("SDL_UnlockJoysticks is not supported before SDL 2.0.7") #endif static void SDL_UnlockJoysticks() { } #endif #if !(SDL_VERSION_ATLEAST(2,0,9)) #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickGetDevicePlayerIndex is not supported before SDL 2.0.9") #endif static int SDL_JoystickGetDevicePlayerIndex(int device_index) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickGetPlayerIndex is not supported before SDL 2.0.9") #endif static int SDL_JoystickGetPlayerIndex(SDL_Joystick *joystick) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickRumble is not supported before SDL 2.0.9") #endif static int SDL_JoystickRumble(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble, Uint32 duration_ms) { return -1; } #endif #if !(SDL_VERSION_ATLEAST(2,0,18)) #if defined(WARN_OUTDATED) #pragma message("SDL_JoystickHasRumble is not supported before SDL 2.0.18") #pragma message("SDL_JoystickHasRumbleTriggers is not supported before SDL 2.0.18") #endif static SDL_bool SDL_JoystickHasRumble(SDL_Joystick *joystick) { return SDL_FALSE; } static SDL_bool SDL_JoystickHasRumbleTriggers(SDL_Joystick *joystick) { return SDL_FALSE; } #endif */ import "C" import "unsafe" // Hat positions. // (https://wiki.libsdl.org/SDL_JoystickGetHat) const ( HAT_CENTERED = C.SDL_HAT_CENTERED HAT_UP = C.SDL_HAT_UP HAT_RIGHT = C.SDL_HAT_RIGHT HAT_DOWN = C.SDL_HAT_DOWN HAT_LEFT = C.SDL_HAT_LEFT HAT_RIGHTUP = C.SDL_HAT_RIGHTUP HAT_RIGHTDOWN = C.SDL_HAT_RIGHTDOWN HAT_LEFTUP = C.SDL_HAT_LEFTUP HAT_LEFTDOWN = C.SDL_HAT_LEFTDOWN ) // Types of a joystick. const ( JOYSTICK_TYPE_UNKNOWN = C.SDL_JOYSTICK_TYPE_UNKNOWN JOYSTICK_TYPE_GAMECONTROLLER = C.SDL_JOYSTICK_TYPE_GAMECONTROLLER JOYSTICK_TYPE_WHEEL = C.SDL_JOYSTICK_TYPE_WHEEL JOYSTICK_TYPE_ARCADE_STICK = C.SDL_JOYSTICK_TYPE_ARCADE_STICK JOYSTICK_TYPE_FLIGHT_STICK = C.SDL_JOYSTICK_TYPE_FLIGHT_STICK JOYSTICK_TYPE_DANCE_PAD = C.SDL_JOYSTICK_TYPE_DANCE_PAD JOYSTICK_TYPE_GUITAR = C.SDL_JOYSTICK_TYPE_GUITAR JOYSTICK_TYPE_DRUM_KIT = C.SDL_JOYSTICK_TYPE_DRUM_KIT JOYSTICK_TYPE_ARCADE_PAD = C.SDL_JOYSTICK_TYPE_ARCADE_PAD JOYSTICK_TYPE_THROTTLE = C.SDL_JOYSTICK_TYPE_THROTTLE ) // An enumeration of battery levels of a joystick. // (https://wiki.libsdl.org/SDL_JoystickPowerLevel) const ( JOYSTICK_POWER_UNKNOWN = C.SDL_JOYSTICK_POWER_UNKNOWN JOYSTICK_POWER_EMPTY = C.SDL_JOYSTICK_POWER_EMPTY JOYSTICK_POWER_LOW = C.SDL_JOYSTICK_POWER_LOW JOYSTICK_POWER_MEDIUM = C.SDL_JOYSTICK_POWER_MEDIUM JOYSTICK_POWER_FULL = C.SDL_JOYSTICK_POWER_FULL JOYSTICK_POWER_WIRED = C.SDL_JOYSTICK_POWER_WIRED JOYSTICK_POWER_MAX = C.SDL_JOYSTICK_POWER_MAX ) // Joystick is an SDL joystick. type Joystick C.SDL_Joystick // JoystickGUID is a stable unique id for a joystick device. type JoystickGUID C.SDL_JoystickGUID // JoystickID is joystick's instance id. type JoystickID C.SDL_JoystickID // JoystickType is a type of a joystick. type JoystickType C.SDL_JoystickType // JoystickPowerLevel is a battery level of a joystick. type JoystickPowerLevel C.SDL_JoystickPowerLevel func (joy *Joystick) cptr() *C.SDL_Joystick { return (*C.SDL_Joystick)(unsafe.Pointer(joy)) } func (guid JoystickGUID) c() C.SDL_JoystickGUID { return C.SDL_JoystickGUID(guid) } func (joyid JoystickID) c() C.SDL_JoystickID { return C.SDL_JoystickID(joyid) } // NumJoysticks returns the number of joysticks attached to the system. // (https://wiki.libsdl.org/SDL_NumJoysticks) func NumJoysticks() int { return (int)(C.SDL_NumJoysticks()) } // JoystickNameForIndex returns the implementation dependent name of a joystick. // (https://wiki.libsdl.org/SDL_JoystickNameForIndex) func JoystickNameForIndex(index int) string { return (C.GoString)(C.SDL_JoystickNameForIndex(C.int(index))) } // JoystickGetDevicePlayerIndex returns the player index of a joystick, or -1 if it's not available // TODO: (https://wiki.libsdl.org/SDL_JoystickGetDevicePlayerIndex) func JoystickGetDevicePlayerIndex(index int) int { return int(C.SDL_JoystickGetDevicePlayerIndex(C.int(index))) } // JoystickGetDeviceGUID returns the implementation dependent GUID for the joystick at a given device index. // (https://wiki.libsdl.org/SDL_JoystickGetDeviceGUID) func JoystickGetDeviceGUID(index int) JoystickGUID { return (JoystickGUID)(C.SDL_JoystickGetDeviceGUID(C.int(index))) } // JoystickGetDeviceVendor returns the USB vendor ID of a joystick, if available, 0 otherwise. func JoystickGetDeviceVendor(index int) int { return int(C.SDL_JoystickGetDeviceVendor(C.int(index))) } // JoystickGetDeviceProduct returns the USB product ID of a joystick, if available, 0 otherwise. func JoystickGetDeviceProduct(index int) int { return int(C.SDL_JoystickGetDeviceProduct(C.int(index))) } // JoystickGetDeviceProductVersion returns the product version of a joystick, if available, 0 otherwise. func JoystickGetDeviceProductVersion(index int) int { return int(C.SDL_JoystickGetDeviceProductVersion(C.int(index))) } // JoystickGetDeviceType returns the type of a joystick. func JoystickGetDeviceType(index int) JoystickType { return JoystickType(C.SDL_JoystickGetDeviceType(C.int(index))) } // JoystickGetDeviceInstanceID returns the instance ID of a joystick. func JoystickGetDeviceInstanceID(index int) JoystickID { return JoystickID(C.SDL_JoystickGetDeviceInstanceID(C.int(index))) } // JoystickGetGUIDString returns an ASCII string representation for a given JoystickGUID. // (https://wiki.libsdl.org/SDL_JoystickGetGUIDString) func JoystickGetGUIDString(guid JoystickGUID) string { _pszGUID := make([]rune, 1024) pszGUID := C.CString(string(_pszGUID[:])) defer C.free(unsafe.Pointer(pszGUID)) C.SDL_JoystickGetGUIDString(guid.c(), pszGUID, C.int(unsafe.Sizeof(_pszGUID))) return C.GoString(pszGUID) } // JoystickGetGUIDFromString converts a GUID string into a JoystickGUID structure. // (https://wiki.libsdl.org/SDL_JoystickGetGUIDFromString) func JoystickGetGUIDFromString(pchGUID string) JoystickGUID { _pchGUID := C.CString(pchGUID) defer C.free(unsafe.Pointer(_pchGUID)) return (JoystickGUID)(C.SDL_JoystickGetGUIDFromString(_pchGUID)) } // JoystickUpdate updates the current state of the open joysticks. // (https://wiki.libsdl.org/SDL_JoystickUpdate) func JoystickUpdate() { C.SDL_JoystickUpdate() } // JoystickEventState enables or disables joystick event polling. // (https://wiki.libsdl.org/SDL_JoystickEventState) func JoystickEventState(state int) int { return (int)(C.SDL_JoystickEventState(C.int(state))) } // JoystickOpen opens a joystick for use. // (https://wiki.libsdl.org/SDL_JoystickOpen) func JoystickOpen(index int) *Joystick { return (*Joystick)(C.SDL_JoystickOpen(C.int(index))) } // JoystickFromInstanceID returns the Joystick associated with an instance id. // (https://wiki.libsdl.org/SDL_JoystickFromInstanceID) func JoystickFromInstanceID(joyid JoystickID) *Joystick { return (*Joystick)(C.SDL_JoystickFromInstanceID(joyid.c())) } // LockJoysticks locks joysticks for multi-threaded access to the joystick API // TODO: (https://wiki.libsdl.org/SDL_LockJoysticks) func LockJoysticks() { C.SDL_LockJoysticks() } // UnlockJoysticks unlocks joysticks for multi-threaded access to the joystick API // TODO: (https://wiki.libsdl.org/SDL_UnlockJoysticks) func UnlockJoysticks() { C.SDL_UnlockJoysticks() } // Name returns the implementation dependent name of a joystick. // (https://wiki.libsdl.org/SDL_JoystickName) func (joy *Joystick) Name() string { return (C.GoString)(C.SDL_JoystickName(joy.cptr())) } // PlayerIndex returns the player index of an opened joystick, or -1 if it's not available. // (https://wiki.libsdl.org/SDL_JoystickGetPlayerIndex) func (joy *Joystick) PlayerIndex() int { return int(C.SDL_JoystickGetPlayerIndex(joy.cptr())) } // GUID returns the implementation-dependent GUID for the joystick. // (https://wiki.libsdl.org/SDL_JoystickGetGUID) func (joy *Joystick) GUID() JoystickGUID { return (JoystickGUID)(C.SDL_JoystickGetGUID(joy.cptr())) } // Vendor returns the USB vendor ID of an opened joystick, if available, 0 otherwise. func (joy *Joystick) Vendor() int { return int(C.SDL_JoystickGetVendor(joy.cptr())) } // Product returns the USB product ID of an opened joystick, if available, 0 otherwise. func (joy *Joystick) Product() int { return int(C.SDL_JoystickGetProduct(joy.cptr())) } // ProductVersion returns the product version of an opened joystick, if available, 0 otherwise. func (joy *Joystick) ProductVersion() int { return int(C.SDL_JoystickGetProductVersion(joy.cptr())) } // Type returns the the type of an opened joystick. func (joy *Joystick) Type() JoystickType { return JoystickType(C.SDL_JoystickGetType(joy.cptr())) } // Attached returns the status of a specified joystick. // (https://wiki.libsdl.org/SDL_JoystickGetAttached) func (joy *Joystick) Attached() bool { return C.SDL_JoystickGetAttached(joy.cptr()) == C.SDL_TRUE } // InstanceID returns the instance ID of an opened joystick. // (https://wiki.libsdl.org/SDL_JoystickInstanceID) func (joy *Joystick) InstanceID() JoystickID { return (JoystickID)(C.SDL_JoystickInstanceID(joy.cptr())) } // NumAxes returns the number of general axis controls on a joystick. // (https://wiki.libsdl.org/SDL_JoystickNumAxes) func (joy *Joystick) NumAxes() int { return (int)(C.SDL_JoystickNumAxes(joy.cptr())) } // NumBalls returns the number of trackballs on a joystick. // (https://wiki.libsdl.org/SDL_JoystickNumBalls) func (joy *Joystick) NumBalls() int { return (int)(C.SDL_JoystickNumBalls(joy.cptr())) } // NumHats returns the number of POV hats on a joystick. // (https://wiki.libsdl.org/SDL_JoystickNumHats) func (joy *Joystick) NumHats() int { return (int)(C.SDL_JoystickNumHats(joy.cptr())) } // NumButtons returns the number of buttons on a joystick. // (https://wiki.libsdl.org/SDL_JoystickNumButtons) func (joy *Joystick) NumButtons() int { return (int)(C.SDL_JoystickNumButtons(joy.cptr())) } // Axis returns the current state of an axis control on a joystick. // (https://wiki.libsdl.org/SDL_JoystickGetAxis) func (joy *Joystick) Axis(axis int) int16 { return (int16)(C.SDL_JoystickGetAxis(joy.cptr(), C.int(axis))) } // AxisInitialState returns the initial state of an axis control on a joystick, ok is true if this axis has any initial value. func (joy *Joystick) AxisInitialState(axis int) (state int16, ok bool) { ok = C.SDL_JoystickGetAxisInitialState(joy.cptr(), C.int(axis), (*C.Sint16)(&state)) == C.SDL_TRUE return } // Hat returns the current state of a POV hat on a joystick. // (https://wiki.libsdl.org/SDL_JoystickGetHat) func (joy *Joystick) Hat(hat int) byte { return (byte)(C.SDL_JoystickGetHat(joy.cptr(), C.int(hat))) } // Ball returns the ball axis change since the last poll. // (https://wiki.libsdl.org/SDL_JoystickGetBall) func (joy *Joystick) Ball(ball int, dx, dy *int32) int { _dx := (*C.int)(unsafe.Pointer(dx)) _dy := (*C.int)(unsafe.Pointer(dy)) return (int)(C.SDL_JoystickGetBall(joy.cptr(), C.int(ball), _dx, _dy)) } // Button the current state of a button on a joystick. // (https://wiki.libsdl.org/SDL_JoystickGetButton) func (joy *Joystick) Button(button int) byte { return (byte)(C.SDL_JoystickGetButton(joy.cptr(), C.int(button))) } // Rumble triggers a rumble effect // Each call to this function cancels any previous rumble effect, and calling it with 0 intensity stops any rumbling. // // lowFrequencyRumble - The intensity of the low frequency (left) rumble motor, from 0 to 0xFFFF // highFrequencyRumble - The intensity of the high frequency (right) rumble motor, from 0 to 0xFFFF // durationMS - The duration of the rumble effect, in milliseconds // // Returns error if rumble isn't supported on this joystick. // // TODO: (https://wiki.libsdl.org/SDL_JoystickRumble) func (joy *Joystick) Rumble(lowFrequencyRumble, highFrequencyRumble uint16, durationMS uint32) error { return errorFromInt(int(C.SDL_JoystickRumble(joy.cptr(), C.Uint16(lowFrequencyRumble), C.Uint16(highFrequencyRumble), C.Uint32(durationMS)))) } // Close closes a joystick previously opened with JoystickOpen(). // (https://wiki.libsdl.org/SDL_JoystickClose) func (joy *Joystick) Close() { C.SDL_JoystickClose(joy.cptr()) } // CurrentPowerLevel returns the battery level of a joystick as JoystickPowerLevel. // (https://wiki.libsdl.org/SDL_JoystickCurrentPowerLevel) func (joy *Joystick) CurrentPowerLevel() JoystickPowerLevel { return JoystickPowerLevel(C.SDL_JoystickCurrentPowerLevel(joy.cptr())) } // HasRumble queries whether a game controller has rumble support. // (https://wiki.libsdl.org/SDL_JoystickHasRumble) func (ctrl *Joystick) HasRumble() bool { return C.SDL_JoystickHasRumble(ctrl.cptr()) == C.SDL_TRUE } // HasRumbleTriggers queries whether a game controller has rumble support on triggers. // (https://wiki.libsdl.org/SDL_JoystickHasRumbleTriggers) func (ctrl *Joystick) HasRumbleTriggers() bool { return C.SDL_JoystickHasRumbleTriggers(ctrl.cptr()) == C.SDL_TRUE } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/keyboard.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,22)) #if defined(WARN_OUTDATED) #pragma message("SDL_IsTextInputShown is not supported before SDL 2.0.22") #pragma message("SDL_ClearComposition is not supported before SDL 2.0.22") #endif static inline SDL_bool SDL_IsTextInputShown(void) { return SDL_FALSE; } static inline void SDL_ClearComposition(void) { } #endif */ import "C" import ( "reflect" "unsafe" ) // Keysym contains key information used in key events. // (https://wiki.libsdl.org/SDL_Keysym) type Keysym struct { Scancode Scancode // SDL physical key code Sym Keycode // SDL virtual key code Mod uint16 // current key modifiers unused uint32 // unused } // GetKeyboardFocus returns the window which currently has keyboard focus. // (https://wiki.libsdl.org/SDL_GetKeyboardFocus) func GetKeyboardFocus() *Window { return (*Window)(unsafe.Pointer(C.SDL_GetKeyboardFocus())) } // GetKeyboardState returns a snapshot of the current state of the keyboard. // (https://wiki.libsdl.org/SDL_GetKeyboardState) func GetKeyboardState() []uint8 { var numkeys C.int start := C.SDL_GetKeyboardState(&numkeys) sh := reflect.SliceHeader{} sh.Len = int(numkeys) sh.Cap = int(numkeys) sh.Data = uintptr(unsafe.Pointer(start)) return *(*[]uint8)(unsafe.Pointer(&sh)) } // GetModState returns the current key modifier state for the keyboard. // (https://wiki.libsdl.org/SDL_GetModState) func GetModState() Keymod { return (Keymod)(C.SDL_GetModState()) } // SetModState sets the current key modifier state for the keyboard. // (https://wiki.libsdl.org/SDL_SetModState) func SetModState(mod Keymod) { C.SDL_SetModState(mod.c()) } // GetKeyFromScancode returns the key code corresponding to the given scancode according to the current keyboard layout. // (https://wiki.libsdl.org/SDL_GetKeyFromScancode) func GetKeyFromScancode(code Scancode) Keycode { return (Keycode)(C.SDL_GetKeyFromScancode(code.c())) } // GetScancodeFromKey returns the scancode corresponding to the given key code according to the current keyboard layout. // (https://wiki.libsdl.org/SDL_GetScancodeFromKey) func GetScancodeFromKey(code Keycode) Scancode { return (Scancode)(C.SDL_GetScancodeFromKey(code.c())) } // GetScancodeName returns a human-readable name for a scancode // (https://wiki.libsdl.org/SDL_GetScancodeName) func GetScancodeName(code Scancode) string { return (C.GoString)(C.SDL_GetScancodeName(code.c())) } // GetScancodeFromName returns a scancode from a human-readable name. // (https://wiki.libsdl.org/SDL_GetScancodeFromName) func GetScancodeFromName(name string) Scancode { _name := C.CString(name) defer C.free(unsafe.Pointer(_name)) return (Scancode)(C.SDL_GetScancodeFromName(_name)) } // GetKeyName returns a human-readable name for a key. // (https://wiki.libsdl.org/SDL_GetKeyName) func GetKeyName(code Keycode) string { return (C.GoString)(C.SDL_GetKeyName(code.c())) } // GetKeyFromName returns a key code from a human-readable name. // (https://wiki.libsdl.org/SDL_GetKeyFromName) func GetKeyFromName(name string) Keycode { _name := C.CString(name) defer C.free(unsafe.Pointer(_name)) return (Keycode)(C.SDL_GetKeyFromName(_name)) } // StartTextInput starts accepting Unicode text input events. // (https://wiki.libsdl.org/SDL_StartTextInput) func StartTextInput() { C.SDL_StartTextInput() } // IsTextInputActive checks whether or not Unicode text input events are enabled. // (https://wiki.libsdl.org/SDL_IsTextInputActive) func IsTextInputActive() bool { return C.SDL_IsTextInputActive() > 0 } // StopTextInput stops receiving any text input events. // (https://wiki.libsdl.org/SDL_StopTextInput) func StopTextInput() { C.SDL_StopTextInput() } // SetTextInputRect sets the rectangle used to type Unicode text inputs. // (https://wiki.libsdl.org/SDL_SetTextInputRect) func SetTextInputRect(rect *Rect) { C.SDL_SetTextInputRect(rect.cptr()) } // HasScreenKeyboardSupport reports whether the platform has some screen keyboard support. // (https://wiki.libsdl.org/SDL_HasScreenKeyboardSupport) func HasScreenKeyboardSupport() bool { return C.SDL_HasScreenKeyboardSupport() > 0 } // IsScreenKeyboardShown reports whether the screen keyboard is shown for given window. // (https://wiki.libsdl.org/SDL_IsScreenKeyboardShown) func IsScreenKeyboardShown(window *Window) bool { return C.SDL_IsScreenKeyboardShown(window.cptr()) > 0 } // IsTextInputShown returns if an IME Composite or Candidate window is currently shown. // (https://wiki.libsdl.org/SDL_IsTextInputShown) func IsTextInputShown() bool { return C.SDL_IsTextInputShown() > 0 } // ClearComposition dismisses the composition window/IME without disabling the subsystem. // (https://wiki.libsdl.org/SDL_ClearComposition) func ClearComposition() { C.SDL_ClearComposition() } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/keycode.go ================================================ package sdl // #include "sdl_wrapper.h" import "C" const K_SCANCODE_MASK = 1 << 30 // The SDL virtual key representation. // (https://wiki.libsdl.org/SDL_Keycode) // (https://wiki.libsdl.org/SDLKeycodeLookup) const ( K_UNKNOWN = C.SDLK_UNKNOWN // "" (no name, empty string) K_RETURN = C.SDLK_RETURN // "Return" (the Enter key (main keyboard)) K_ESCAPE = C.SDLK_ESCAPE // "Escape" (the Esc key) K_BACKSPACE = C.SDLK_BACKSPACE // "Backspace" K_TAB = C.SDLK_TAB // "Tab" (the Tab key) K_SPACE = C.SDLK_SPACE // "Space" (the Space Bar key(s)) K_EXCLAIM = C.SDLK_EXCLAIM // "!" K_QUOTEDBL = C.SDLK_QUOTEDBL // """ K_HASH = C.SDLK_HASH // "#" K_PERCENT = C.SDLK_PERCENT // "%" K_DOLLAR = C.SDLK_DOLLAR // "$" K_AMPERSAND = C.SDLK_AMPERSAND // "&" K_QUOTE = C.SDLK_QUOTE // "'" K_LEFTPAREN = C.SDLK_LEFTPAREN // "(" K_RIGHTPAREN = C.SDLK_RIGHTPAREN // ")" K_ASTERISK = C.SDLK_ASTERISK // "*" K_PLUS = C.SDLK_PLUS // "+" K_COMMA = C.SDLK_COMMA // "," K_MINUS = C.SDLK_MINUS // "-" K_PERIOD = C.SDLK_PERIOD // "." K_SLASH = C.SDLK_SLASH // "/" K_0 = C.SDLK_0 // "0" K_1 = C.SDLK_1 // "1" K_2 = C.SDLK_2 // "2" K_3 = C.SDLK_3 // "3" K_4 = C.SDLK_4 // "4" K_5 = C.SDLK_5 // "5" K_6 = C.SDLK_6 // "6" K_7 = C.SDLK_7 // "7" K_8 = C.SDLK_8 // "8" K_9 = C.SDLK_9 // "9" K_COLON = C.SDLK_COLON // ":" K_SEMICOLON = C.SDLK_SEMICOLON // ";" K_LESS = C.SDLK_LESS // "<" K_EQUALS = C.SDLK_EQUALS // "=" K_GREATER = C.SDLK_GREATER // ">" K_QUESTION = C.SDLK_QUESTION // "?" K_AT = C.SDLK_AT // "@" /* Skip uppercase letters */ K_LEFTBRACKET = C.SDLK_LEFTBRACKET // "[" K_BACKSLASH = C.SDLK_BACKSLASH // "\" K_RIGHTBRACKET = C.SDLK_RIGHTBRACKET // "]" K_CARET = C.SDLK_CARET // "^" K_UNDERSCORE = C.SDLK_UNDERSCORE // "_" K_BACKQUOTE = C.SDLK_BACKQUOTE // "`" K_a = C.SDLK_a // "A" K_b = C.SDLK_b // "B" K_c = C.SDLK_c // "C" K_d = C.SDLK_d // "D" K_e = C.SDLK_e // "E" K_f = C.SDLK_f // "F" K_g = C.SDLK_g // "G" K_h = C.SDLK_h // "H" K_i = C.SDLK_i // "I" K_j = C.SDLK_j // "J" K_k = C.SDLK_k // "K" K_l = C.SDLK_l // "L" K_m = C.SDLK_m // "M" K_n = C.SDLK_n // "N" K_o = C.SDLK_o // "O" K_p = C.SDLK_p // "P" K_q = C.SDLK_q // "Q" K_r = C.SDLK_r // "R" K_s = C.SDLK_s // "S" K_t = C.SDLK_t // "T" K_u = C.SDLK_u // "U" K_v = C.SDLK_v // "V" K_w = C.SDLK_w // "W" K_x = C.SDLK_x // "X" K_y = C.SDLK_y // "Y" K_z = C.SDLK_z // "Z" K_CAPSLOCK = C.SDLK_CAPSLOCK // "CapsLock" K_F1 = C.SDLK_F1 // "F1" K_F2 = C.SDLK_F2 // "F2" K_F3 = C.SDLK_F3 // "F3" K_F4 = C.SDLK_F4 // "F4" K_F5 = C.SDLK_F5 // "F5" K_F6 = C.SDLK_F6 // "F6" K_F7 = C.SDLK_F7 // "F7" K_F8 = C.SDLK_F8 // "F8" K_F9 = C.SDLK_F9 // "F9" K_F10 = C.SDLK_F10 // "F10" K_F11 = C.SDLK_F11 // "F11" K_F12 = C.SDLK_F12 // "F12" K_PRINTSCREEN = C.SDLK_PRINTSCREEN // "PrintScreen" K_SCROLLLOCK = C.SDLK_SCROLLLOCK // "ScrollLock" K_PAUSE = C.SDLK_PAUSE // "Pause" (the Pause / Break key) K_INSERT = C.SDLK_INSERT // "Insert" (insert on PC, help on some Mac keyboards (but does send code 73, not 117)) K_HOME = C.SDLK_HOME // "Home" K_PAGEUP = C.SDLK_PAGEUP // "PageUp" K_DELETE = C.SDLK_DELETE // "Delete" K_END = C.SDLK_END // "End" K_PAGEDOWN = C.SDLK_PAGEDOWN // "PageDown" K_RIGHT = C.SDLK_RIGHT // "Right" (the Right arrow key (navigation keypad)) K_LEFT = C.SDLK_LEFT // "Left" (the Left arrow key (navigation keypad)) K_DOWN = C.SDLK_DOWN // "Down" (the Down arrow key (navigation keypad)) K_UP = C.SDLK_UP // "Up" (the Up arrow key (navigation keypad)) K_NUMLOCKCLEAR = C.SDLK_NUMLOCKCLEAR // "Numlock" (the Num Lock key (PC) / the Clear key (Mac)) K_KP_DIVIDE = C.SDLK_KP_DIVIDE // "Keypad /" (the / key (numeric keypad)) K_KP_MULTIPLY = C.SDLK_KP_MULTIPLY // "Keypad *" (the * key (numeric keypad)) K_KP_MINUS = C.SDLK_KP_MINUS // "Keypad -" (the - key (numeric keypad)) K_KP_PLUS = C.SDLK_KP_PLUS // "Keypad +" (the + key (numeric keypad)) K_KP_ENTER = C.SDLK_KP_ENTER // "Keypad Enter" (the Enter key (numeric keypad)) K_KP_1 = C.SDLK_KP_1 // "Keypad 1" (the 1 key (numeric keypad)) K_KP_2 = C.SDLK_KP_2 // "Keypad 2" (the 2 key (numeric keypad)) K_KP_3 = C.SDLK_KP_3 // "Keypad 3" (the 3 key (numeric keypad)) K_KP_4 = C.SDLK_KP_4 // "Keypad 4" (the 4 key (numeric keypad)) K_KP_5 = C.SDLK_KP_5 // "Keypad 5" (the 5 key (numeric keypad)) K_KP_6 = C.SDLK_KP_6 // "Keypad 6" (the 6 key (numeric keypad)) K_KP_7 = C.SDLK_KP_7 // "Keypad 7" (the 7 key (numeric keypad)) K_KP_8 = C.SDLK_KP_8 // "Keypad 8" (the 8 key (numeric keypad)) K_KP_9 = C.SDLK_KP_9 // "Keypad 9" (the 9 key (numeric keypad)) K_KP_0 = C.SDLK_KP_0 // "Keypad 0" (the 0 key (numeric keypad)) K_KP_PERIOD = C.SDLK_KP_PERIOD // "Keypad ." (the . key (numeric keypad)) K_APPLICATION = C.SDLK_APPLICATION // "Application" (the Application / Compose / Context Menu (Windows) key) K_POWER = C.SDLK_POWER // "Power" (The USB document says this is a status flag, not a physical key - but some Mac keyboards do have a power key.) K_KP_EQUALS = C.SDLK_KP_EQUALS // "Keypad =" (the = key (numeric keypad)) K_F13 = C.SDLK_F13 // "F13" K_F14 = C.SDLK_F14 // "F14" K_F15 = C.SDLK_F15 // "F15" K_F16 = C.SDLK_F16 // "F16" K_F17 = C.SDLK_F17 // "F17" K_F18 = C.SDLK_F18 // "F18" K_F19 = C.SDLK_F19 // "F19" K_F20 = C.SDLK_F20 // "F20" K_F21 = C.SDLK_F21 // "F21" K_F22 = C.SDLK_F22 // "F22" K_F23 = C.SDLK_F23 // "F23" K_F24 = C.SDLK_F24 // "F24" K_EXECUTE = C.SDLK_EXECUTE // "Execute" K_HELP = C.SDLK_HELP // "Help" K_MENU = C.SDLK_MENU // "Menu" K_SELECT = C.SDLK_SELECT // "Select" K_STOP = C.SDLK_STOP // "Stop" K_AGAIN = C.SDLK_AGAIN // "Again" (the Again key (Redo)) K_UNDO = C.SDLK_UNDO // "Undo" K_CUT = C.SDLK_CUT // "Cut" K_COPY = C.SDLK_COPY // "Copy" K_PASTE = C.SDLK_PASTE // "Paste" K_FIND = C.SDLK_FIND // "Find" K_MUTE = C.SDLK_MUTE // "Mute" K_VOLUMEUP = C.SDLK_VOLUMEUP // "VolumeUp" K_VOLUMEDOWN = C.SDLK_VOLUMEDOWN // "VolumeDown" K_KP_COMMA = C.SDLK_KP_COMMA // "Keypad ," (the Comma key (numeric keypad)) K_KP_EQUALSAS400 = C.SDLK_KP_EQUALSAS400 // "Keypad = (AS400)" (the Equals AS400 key (numeric keypad)) K_ALTERASE = C.SDLK_ALTERASE // "AltErase" (Erase-Eaze) K_SYSREQ = C.SDLK_SYSREQ // "SysReq" (the SysReq key) K_CANCEL = C.SDLK_CANCEL // "Cancel" K_CLEAR = C.SDLK_CLEAR // "Clear" K_PRIOR = C.SDLK_PRIOR // "Prior" K_RETURN2 = C.SDLK_RETURN2 // "Return" K_SEPARATOR = C.SDLK_SEPARATOR // "Separator" K_OUT = C.SDLK_OUT // "Out" K_OPER = C.SDLK_OPER // "Oper" K_CLEARAGAIN = C.SDLK_CLEARAGAIN // "Clear / Again" K_CRSEL = C.SDLK_CRSEL // "CrSel" K_EXSEL = C.SDLK_EXSEL // "ExSel" K_KP_00 = C.SDLK_KP_00 // "Keypad 00" (the 00 key (numeric keypad)) K_KP_000 = C.SDLK_KP_000 // "Keypad 000" (the 000 key (numeric keypad)) K_THOUSANDSSEPARATOR = C.SDLK_THOUSANDSSEPARATOR // "ThousandsSeparator" (the Thousands Separator key) K_DECIMALSEPARATOR = C.SDLK_DECIMALSEPARATOR // "DecimalSeparator" (the Decimal Separator key) K_CURRENCYUNIT = C.SDLK_CURRENCYUNIT // "CurrencyUnit" (the Currency Unit key) K_CURRENCYSUBUNIT = C.SDLK_CURRENCYSUBUNIT // "CurrencySubUnit" (the Currency Subunit key) K_KP_LEFTPAREN = C.SDLK_KP_LEFTPAREN // "Keypad (" (the Left Parenthesis key (numeric keypad)) K_KP_RIGHTPAREN = C.SDLK_KP_RIGHTPAREN // "Keypad )" (the Right Parenthesis key (numeric keypad)) K_KP_LEFTBRACE = C.SDLK_KP_LEFTBRACE // "Keypad {" (the Left Brace key (numeric keypad)) K_KP_RIGHTBRACE = C.SDLK_KP_RIGHTBRACE // "Keypad }" (the Right Brace key (numeric keypad)) K_KP_TAB = C.SDLK_KP_TAB // "Keypad Tab" (the Tab key (numeric keypad)) K_KP_BACKSPACE = C.SDLK_KP_BACKSPACE // "Keypad Backspace" (the Backspace key (numeric keypad)) K_KP_A = C.SDLK_KP_A // "Keypad A" (the A key (numeric keypad)) K_KP_B = C.SDLK_KP_B // "Keypad B" (the B key (numeric keypad)) K_KP_C = C.SDLK_KP_C // "Keypad C" (the C key (numeric keypad)) K_KP_D = C.SDLK_KP_D // "Keypad D" (the D key (numeric keypad)) K_KP_E = C.SDLK_KP_E // "Keypad E" (the E key (numeric keypad)) K_KP_F = C.SDLK_KP_F // "Keypad F" (the F key (numeric keypad)) K_KP_XOR = C.SDLK_KP_XOR // "Keypad XOR" (the XOR key (numeric keypad)) K_KP_POWER = C.SDLK_KP_POWER // "Keypad ^" (the Power key (numeric keypad)) K_KP_PERCENT = C.SDLK_KP_PERCENT // "Keypad %" (the Percent key (numeric keypad)) K_KP_LESS = C.SDLK_KP_LESS // "Keypad <" (the Less key (numeric keypad)) K_KP_GREATER = C.SDLK_KP_GREATER // "Keypad >" (the Greater key (numeric keypad)) K_KP_AMPERSAND = C.SDLK_KP_AMPERSAND // "Keypad &" (the & key (numeric keypad)) K_KP_DBLAMPERSAND = C.SDLK_KP_DBLAMPERSAND // "Keypad &&" (the && key (numeric keypad)) K_KP_VERTICALBAR = C.SDLK_KP_VERTICALBAR // "Keypad |" (the | key (numeric keypad)) K_KP_DBLVERTICALBAR = C.SDLK_KP_DBLVERTICALBAR // "Keypad ||" (the || key (numeric keypad)) K_KP_COLON = C.SDLK_KP_COLON // "Keypad :" (the : key (numeric keypad)) K_KP_HASH = C.SDLK_KP_HASH // "Keypad #" (the # key (numeric keypad)) K_KP_SPACE = C.SDLK_KP_SPACE // "Keypad Space" (the Space key (numeric keypad)) K_KP_AT = C.SDLK_KP_AT // "Keypad @" (the @ key (numeric keypad)) K_KP_EXCLAM = C.SDLK_KP_EXCLAM // "Keypad !" (the ! key (numeric keypad)) K_KP_MEMSTORE = C.SDLK_KP_MEMSTORE // "Keypad MemStore" (the Mem Store key (numeric keypad)) K_KP_MEMRECALL = C.SDLK_KP_MEMRECALL // "Keypad MemRecall" (the Mem Recall key (numeric keypad)) K_KP_MEMCLEAR = C.SDLK_KP_MEMCLEAR // "Keypad MemClear" (the Mem Clear key (numeric keypad)) K_KP_MEMADD = C.SDLK_KP_MEMADD // "Keypad MemAdd" (the Mem Add key (numeric keypad)) K_KP_MEMSUBTRACT = C.SDLK_KP_MEMSUBTRACT // "Keypad MemSubtract" (the Mem Subtract key (numeric keypad)) K_KP_MEMMULTIPLY = C.SDLK_KP_MEMMULTIPLY // "Keypad MemMultiply" (the Mem Multiply key (numeric keypad)) K_KP_MEMDIVIDE = C.SDLK_KP_MEMDIVIDE // "Keypad MemDivide" (the Mem Divide key (numeric keypad)) K_KP_PLUSMINUS = C.SDLK_KP_PLUSMINUS // "Keypad +/-" (the +/- key (numeric keypad)) K_KP_CLEAR = C.SDLK_KP_CLEAR // "Keypad Clear" (the Clear key (numeric keypad)) K_KP_CLEARENTRY = C.SDLK_KP_CLEARENTRY // "Keypad ClearEntry" (the Clear Entry key (numeric keypad)) K_KP_BINARY = C.SDLK_KP_BINARY // "Keypad Binary" (the Binary key (numeric keypad)) K_KP_OCTAL = C.SDLK_KP_OCTAL // "Keypad Octal" (the Octal key (numeric keypad)) K_KP_DECIMAL = C.SDLK_KP_DECIMAL // "Keypad Decimal" (the Decimal key (numeric keypad)) K_KP_HEXADECIMAL = C.SDLK_KP_HEXADECIMAL // "Keypad Hexadecimal" (the Hexadecimal key (numeric keypad)) K_LCTRL = C.SDLK_LCTRL // "Left Ctrl" K_LSHIFT = C.SDLK_LSHIFT // "Left Shift" K_LALT = C.SDLK_LALT // "Left Alt" (alt, option) K_LGUI = C.SDLK_LGUI // "Left GUI" (windows, command (apple), meta) K_RCTRL = C.SDLK_RCTRL // "Right Ctrl" K_RSHIFT = C.SDLK_RSHIFT // "Right Shift" K_RALT = C.SDLK_RALT // "Right Alt" (alt, option) K_RGUI = C.SDLK_RGUI // "Right GUI" (windows, command (apple), meta) K_MODE = C.SDLK_MODE // "ModeSwitch" (I'm not sure if this is really not covered by any of the above, but since there's a special KMOD_MODE for it I'm adding it here) K_AUDIONEXT = C.SDLK_AUDIONEXT // "AudioNext" (the Next Track media key) K_AUDIOPREV = C.SDLK_AUDIOPREV // "AudioPrev" (the Previous Track media key) K_AUDIOSTOP = C.SDLK_AUDIOSTOP // "AudioStop" (the Stop media key) K_AUDIOPLAY = C.SDLK_AUDIOPLAY // "AudioPlay" (the Play media key) K_AUDIOMUTE = C.SDLK_AUDIOMUTE // "AudioMute" (the Mute volume key) K_MEDIASELECT = C.SDLK_MEDIASELECT // "MediaSelect" (the Media Select key) K_WWW = C.SDLK_WWW // "WWW" (the WWW/World Wide Web key) K_MAIL = C.SDLK_MAIL // "Mail" (the Mail/eMail key) K_CALCULATOR = C.SDLK_CALCULATOR // "Calculator" (the Calculator key) K_COMPUTER = C.SDLK_COMPUTER // "Computer" (the My Computer key) K_AC_SEARCH = C.SDLK_AC_SEARCH // "AC Search" (the Search key (application control keypad)) K_AC_HOME = C.SDLK_AC_HOME // "AC Home" (the Home key (application control keypad)) K_AC_BACK = C.SDLK_AC_BACK // "AC Back" (the Back key (application control keypad)) K_AC_FORWARD = C.SDLK_AC_FORWARD // "AC Forward" (the Forward key (application control keypad)) K_AC_STOP = C.SDLK_AC_STOP // "AC Stop" (the Stop key (application control keypad)) K_AC_REFRESH = C.SDLK_AC_REFRESH // "AC Refresh" (the Refresh key (application control keypad)) K_AC_BOOKMARKS = C.SDLK_AC_BOOKMARKS // "AC Bookmarks" (the Bookmarks key (application control keypad)) K_BRIGHTNESSDOWN = C.SDLK_BRIGHTNESSDOWN // "BrightnessDown" (the Brightness Down key) K_BRIGHTNESSUP = C.SDLK_BRIGHTNESSUP // "BrightnessUp" (the Brightness Up key) K_DISPLAYSWITCH = C.SDLK_DISPLAYSWITCH // "DisplaySwitch" (display mirroring/dual display switch, video mode switch) K_KBDILLUMTOGGLE = C.SDLK_KBDILLUMTOGGLE // "KBDIllumToggle" (the Keyboard Illumination Toggle key) K_KBDILLUMDOWN = C.SDLK_KBDILLUMDOWN // "KBDIllumDown" (the Keyboard Illumination Down key) K_KBDILLUMUP = C.SDLK_KBDILLUMUP // "KBDIllumUp" (the Keyboard Illumination Up key) K_EJECT = C.SDLK_EJECT // "Eject" (the Eject key) K_SLEEP = C.SDLK_SLEEP // "Sleep" (the Sleep key) ) // An enumeration of key modifier masks. // (https://wiki.libsdl.org/SDL_Keymod) const ( KMOD_NONE = C.KMOD_NONE // 0 (no modifier is applicable) KMOD_LSHIFT = C.KMOD_LSHIFT // the left Shift key is down KMOD_RSHIFT = C.KMOD_RSHIFT // the right Shift key is down KMOD_LCTRL = C.KMOD_LCTRL // the left Ctrl (Control) key is down KMOD_RCTRL = C.KMOD_RCTRL // the right Ctrl (Control) key is down KMOD_LALT = C.KMOD_LALT // the left Alt key is down KMOD_RALT = C.KMOD_RALT // the right Alt key is down KMOD_LGUI = C.KMOD_LGUI // the left GUI key (often the Windows key) is down KMOD_RGUI = C.KMOD_RGUI // the right GUI key (often the Windows key) is down KMOD_NUM = C.KMOD_NUM // the Num Lock key (may be located on an extended keypad) is down KMOD_CAPS = C.KMOD_CAPS // the Caps Lock key is down KMOD_MODE = C.KMOD_MODE // the AltGr key is down KMOD_CTRL = C.KMOD_CTRL // (KMOD_LCTRL|KMOD_RCTRL) KMOD_SHIFT = C.KMOD_SHIFT // (KMOD_LSHIFT|KMOD_RSHIFT) KMOD_ALT = C.KMOD_ALT // (KMOD_LALT|KMOD_RALT) KMOD_GUI = C.KMOD_GUI // (KMOD_LGUI|KMOD_RGUI) KMOD_RESERVED = C.KMOD_RESERVED // reserved for future use ) // Keycode is the SDL virtual key representation. // (https://wiki.libsdl.org/SDL_Keycode) type Keycode C.SDL_Keycode // Keymod is a key modifier masks. // (https://wiki.libsdl.org/SDL_Keymod) type Keymod C.SDL_Keymod func (code Keycode) c() C.SDL_Keycode { return C.SDL_Keycode(code) } func (mod Keymod) c() C.SDL_Keymod { return C.SDL_Keymod(mod) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/loadso.go ================================================ package sdl // #include "sdl_wrapper.h" import "C" import "unsafe" // SharedObject is a pointer to the object handle. type SharedObject uintptr // LoadObject dynamically loads a shared object and returns a pointer to the object handle. // (https://wiki.libsdl.org/SDL_LoadObject) func LoadObject(sofile string) SharedObject { _sofile := C.CString(sofile) defer C.free(unsafe.Pointer(_sofile)) return (SharedObject)(C.SDL_LoadObject(_sofile)) } // LoadFunction returns a pointer to the named function from the shared object. // (https://wiki.libsdl.org/SDL_LoadFunction) func (handle SharedObject) LoadFunction(name string) unsafe.Pointer { _name := C.CString(name) defer C.free(unsafe.Pointer(_name)) return (unsafe.Pointer)(C.SDL_LoadFunction((unsafe.Pointer)(handle), _name)) } // Unload unloads a shared object from memory. // (https://wiki.libsdl.org/SDL_UnloadObject) func (handle SharedObject) Unload() { C.SDL_UnloadObject((unsafe.Pointer)(handle)) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/log.c ================================================ #include "_cgo_export.h" void LogSetOutputFunction(void *data) { SDL_LogSetOutputFunction((SDL_LogOutputFunction)logOutputFunction, data); } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/log.go ================================================ package sdl /* #include "sdl_wrapper.h" #include "log.h" static inline void _SDL_Log(const char *fmt) { SDL_Log("%s", fmt); } static inline void _SDL_LogVerbose(int category, const char *fmt) { SDL_LogVerbose(category, "%s", fmt); } static inline void _SDL_LogDebug(int category, const char *fmt) { SDL_LogDebug(category, "%s", fmt); } static inline void _SDL_LogInfo(int category, const char *fmt) { SDL_LogInfo(category, "%s", fmt); } static inline void _SDL_LogWarn(int category, const char *fmt) { SDL_LogWarn(category, "%s", fmt); } static inline void _SDL_LogError(int category, const char *fmt) { SDL_LogError(category, "%s", fmt); } static inline void _SDL_LogCritical(int category, const char *fmt) { SDL_LogCritical(category, "%s", fmt); } static inline void _SDL_LogMessage(int category, SDL_LogPriority priority, const char *fmt) { SDL_LogCritical(category, "%s", fmt); } */ import "C" import "fmt" import "unsafe" // An enumeration of the predefined log categories. // (https://wiki.libsdl.org/SDL_LOG_CATEGORY) const ( LOG_CATEGORY_APPLICATION = iota // application log LOG_CATEGORY_ERROR // error log LOG_CATEGORY_ASSERT // assert log LOG_CATEGORY_SYSTEM // system log LOG_CATEGORY_AUDIO // audio log LOG_CATEGORY_VIDEO // video log LOG_CATEGORY_RENDER // render log LOG_CATEGORY_INPUT // input log LOG_CATEGORY_TEST // test log LOG_CATEGORY_RESERVED1 // reserved for future SDL library use LOG_CATEGORY_RESERVED2 // reserved for future SDL library use LOG_CATEGORY_RESERVED3 // reserved for future SDL library use LOG_CATEGORY_RESERVED4 // reserved for future SDL library use LOG_CATEGORY_RESERVED5 // reserved for future SDL library use LOG_CATEGORY_RESERVED6 // reserved for future SDL library use LOG_CATEGORY_RESERVED7 // reserved for future SDL library use LOG_CATEGORY_RESERVED8 // reserved for future SDL library use LOG_CATEGORY_RESERVED9 // reserved for future SDL library use LOG_CATEGORY_RESERVED10 // reserved for future SDL library use LOG_CATEGORY_CUSTOM // reserved for application use ) // An enumeration of the predefined log priorities. // (https://wiki.libsdl.org/SDL_LogPriority) const ( LOG_PRIORITY_VERBOSE = iota + 1 // verbose LOG_PRIORITY_DEBUG // debug LOG_PRIORITY_INFO // info LOG_PRIORITY_WARN // warn LOG_PRIORITY_ERROR // error LOG_PRIORITY_CRITICAL // critical NUM_LOG_PRIORITIES // (internal use) ) // LogPriority is a predefined log priority. // (https://wiki.libsdl.org/SDL_LogPriority) type LogPriority C.SDL_LogPriority func (p LogPriority) c() C.SDL_LogPriority { return C.SDL_LogPriority(p) } // LogSetAllPriority sets the priority of all log categories. // (https://wiki.libsdl.org/SDL_LogSetAllPriority) func LogSetAllPriority(p LogPriority) { C.SDL_LogSetAllPriority(p.c()) } // LogSetPriority sets the priority of a particular log category. // (https://wiki.libsdl.org/SDL_LogSetPriority) func LogSetPriority(category int, p LogPriority) { C.SDL_LogSetPriority(C.int(category), p.c()) } // LogGetPriority returns the priority of a particular log category. // (https://wiki.libsdl.org/SDL_LogGetPriority) func LogGetPriority(category int) LogPriority { return LogPriority(C.SDL_LogGetPriority(C.int(category))) } // LogResetPriorities resets all priorities to default. // (https://wiki.libsdl.org/SDL_LogResetPriorities) func LogResetPriorities() { C.SDL_LogResetPriorities() } // Log logs a message with LOG_CATEGORY_APPLICATION and LOG_PRIORITY_INFO. // (https://wiki.libsdl.org/SDL_Log) func Log(str string, args ...interface{}) { str = fmt.Sprintf(str, args...) cstr := C.CString(str) defer C.free(unsafe.Pointer(cstr)) C._SDL_Log(cstr) } // LogVerbose logs a message with LOG_PRIORITY_VERBOSE. // (https://wiki.libsdl.org/SDL_LogVerbose) func LogVerbose(category int, str string, args ...interface{}) { str = fmt.Sprintf(str, args...) cstr := C.CString(str) defer C.free(unsafe.Pointer(cstr)) C._SDL_LogVerbose(C.int(category), cstr) } // LogDebug logs a message with LOG_PRIORITY_DEBUG. // (https://wiki.libsdl.org/SDL_LogDebug) func LogDebug(category int, str string, args ...interface{}) { str = fmt.Sprintf(str, args...) cstr := C.CString(str) defer C.free(unsafe.Pointer(cstr)) C._SDL_LogDebug(C.int(category), cstr) } // LogInfo logs a message with LOG_PRIORITY_INFO. // (https://wiki.libsdl.org/SDL_LogInfo) func LogInfo(category int, str string, args ...interface{}) { str = fmt.Sprintf(str, args...) cstr := C.CString(str) defer C.free(unsafe.Pointer(cstr)) C._SDL_LogInfo(C.int(category), cstr) } // LogWarn logs a message with LOG_PRIORITY_WARN. // (https://wiki.libsdl.org/SDL_LogWarn) func LogWarn(category int, str string, args ...interface{}) { str = fmt.Sprintf(str, args...) cstr := C.CString(str) defer C.free(unsafe.Pointer(cstr)) C._SDL_LogWarn(C.int(category), cstr) } // LogError logs a message with LOG_PRIORITY_ERROR. // (https://wiki.libsdl.org/SDL_LogError) func LogError(category int, str string, args ...interface{}) { str = fmt.Sprintf(str, args...) cstr := C.CString(str) defer C.free(unsafe.Pointer(cstr)) C._SDL_LogError(C.int(category), cstr) } // LogCritical logs a message with LOG_PRIORITY_CRITICAL. // (https://wiki.libsdl.org/SDL_LogCritical) func LogCritical(category int, str string, args ...interface{}) { str = fmt.Sprintf(str, args...) cstr := C.CString(str) defer C.free(unsafe.Pointer(cstr)) C._SDL_LogCritical(C.int(category), cstr) } // LogMessage logs a message with the specified category and priority. // (https://wiki.libsdl.org/SDL_LogMessage) func LogMessage(category int, pri LogPriority, str string, args ...interface{}) { str = fmt.Sprintf(str, args...) cstr := C.CString(str) defer C.free(unsafe.Pointer(cstr)) C._SDL_LogMessage(C.int(category), C.SDL_LogPriority(pri), cstr) } // LogOutputFunction is the function to call instead of the default type LogOutputFunction func(data interface{}, category int, pri LogPriority, message string) type logOutputFunctionCtx struct { f LogOutputFunction d interface{} } // Yissakhar Z. Beck (DeedleFake)'s implementation // //export logOutputFunction func logOutputFunction(data unsafe.Pointer, category C.int, pri C.SDL_LogPriority, message *C.char) { ctx := (*logOutputFunctionCtx)(data) ctx.f(ctx.d, int(category), LogPriority(pri), C.GoString(message)) } var ( logOutputFunctionCache LogOutputFunction logOutputDataCache interface{} ) // LogGetOutputFunction returns the current log output function. // (https://wiki.libsdl.org/SDL_LogGetOutputFunction) func LogGetOutputFunction() (LogOutputFunction, interface{}) { return logOutputFunctionCache, logOutputDataCache } // LogSetOutputFunction replaces the default log output function with one of your own. // (https://wiki.libsdl.org/SDL_LogSetOutputFunction) func LogSetOutputFunction(f LogOutputFunction, data interface{}) { ctx := &logOutputFunctionCtx{ f: f, d: data, } C.LogSetOutputFunction(unsafe.Pointer(ctx)) logOutputFunctionCache = f logOutputDataCache = data } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/log.h ================================================ void LogSetOutputFunction(void *data); ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/mouse.go ================================================ package sdl /* #include "sdl_wrapper.h" #if defined(__WIN32) #include #else #include #endif #if !(SDL_VERSION_ATLEAST(2,0,4)) #if defined(WARN_OUTDATED) #pragma message("SDL_CaptureMouse is not supported before SDL 2.0.4") #endif static int SDL_CaptureMouse(SDL_bool enabled) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_MOUSEWHEEL_NORMAL is not supported before SDL 2.0.4") #endif #define SDL_MOUSEWHEEL_NORMAL (0) #if defined(WARN_OUTDATED) #pragma message("SDL_MOUSEWHEEL_FLIPPED is not supported before SDL 2.0.4") #endif #define SDL_MOUSEWHEEL_FLIPPED (0) #if defined(WARN_OUTDATED) #pragma message("SDL_WarpMouseGlobal is not supported before SDL 2.0.4") #endif static int SDL_WarpMouseGlobal(int x, int y) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_GetGlobalMouseState is not supported before SDL 2.0.4") #endif static Uint32 SDL_GetGlobalMouseState(int *x, int *y) { return 0; } #endif */ import "C" import "unsafe" // Cursor types for CreateSystemCursor() const ( SYSTEM_CURSOR_ARROW = C.SDL_SYSTEM_CURSOR_ARROW // arrow SYSTEM_CURSOR_IBEAM = C.SDL_SYSTEM_CURSOR_IBEAM // i-beam SYSTEM_CURSOR_WAIT = C.SDL_SYSTEM_CURSOR_WAIT // wait SYSTEM_CURSOR_CROSSHAIR = C.SDL_SYSTEM_CURSOR_CROSSHAIR // crosshair SYSTEM_CURSOR_WAITARROW = C.SDL_SYSTEM_CURSOR_WAITARROW // small wait cursor (or wait if not available) SYSTEM_CURSOR_SIZENWSE = C.SDL_SYSTEM_CURSOR_SIZENWSE // double arrow pointing northwest and southeast SYSTEM_CURSOR_SIZENESW = C.SDL_SYSTEM_CURSOR_SIZENESW // double arrow pointing northeast and southwest SYSTEM_CURSOR_SIZEWE = C.SDL_SYSTEM_CURSOR_SIZEWE // double arrow pointing west and east SYSTEM_CURSOR_SIZENS = C.SDL_SYSTEM_CURSOR_SIZENS // double arrow pointing north and south SYSTEM_CURSOR_SIZEALL = C.SDL_SYSTEM_CURSOR_SIZEALL // four pointed arrow pointing north, south, east, and west SYSTEM_CURSOR_NO = C.SDL_SYSTEM_CURSOR_NO // slashed circle or crossbones SYSTEM_CURSOR_HAND = C.SDL_SYSTEM_CURSOR_HAND // hand NUM_SYSTEM_CURSORS = C.SDL_NUM_SYSTEM_CURSORS // (only for bounding internal arrays) ) // Scroll direction types for the Scroll event const ( MOUSEWHEEL_NORMAL = C.SDL_MOUSEWHEEL_NORMAL // the scroll direction is normal MOUSEWHEEL_FLIPPED = C.SDL_MOUSEWHEEL_FLIPPED // the scroll direction is flipped / natural ) // Used as a mask when testing buttons in buttonstate. const ( BUTTON_LEFT = C.SDL_BUTTON_LEFT // left mouse button BUTTON_MIDDLE = C.SDL_BUTTON_MIDDLE // middle mouse button BUTTON_RIGHT = C.SDL_BUTTON_RIGHT // right mouse button BUTTON_X1 = C.SDL_BUTTON_X1 // x1 mouse button BUTTON_X2 = C.SDL_BUTTON_X2 // x2 mouse button ) // Cursor is a custom cursor created by CreateCursor() or CreateColorCursor(). type Cursor C.SDL_Cursor // SystemCursor is a system cursor created by CreateSystemCursor(). type SystemCursor C.SDL_SystemCursor func (c *Cursor) cptr() *C.SDL_Cursor { return (*C.SDL_Cursor)(unsafe.Pointer(c)) } func (c SystemCursor) c() C.SDL_SystemCursor { return C.SDL_SystemCursor(c) } // GetMouseFocus returns the window which currently has mouse focus. // (https://wiki.libsdl.org/SDL_GetMouseFocus) func GetMouseFocus() *Window { return (*Window)(unsafe.Pointer(C.SDL_GetMouseFocus())) } // GetGlobalMouseState returns the current state of the mouse. // (https://wiki.libsdl.org/SDL_GetGlobalMouseState) func GetGlobalMouseState() (x, y int32, state uint32) { var _x, _y C.int _state := uint32(C.SDL_GetGlobalMouseState(&_x, &_y)) return int32(_x), int32(_y), _state } // GetMouseState returns the current state of the mouse. // (https://wiki.libsdl.org/SDL_GetMouseState) func GetMouseState() (x, y int32, state uint32) { var _x, _y C.int _state := uint32(C.SDL_GetMouseState(&_x, &_y)) return int32(_x), int32(_y), _state } // GetRelativeMouseState returns the relative state of the mouse. // (https://wiki.libsdl.org/SDL_GetRelativeMouseState) func GetRelativeMouseState() (x, y int32, state uint32) { var _x, _y C.int _state := uint32(C.SDL_GetRelativeMouseState(&_x, &_y)) return int32(_x), int32(_y), _state } // WarpMouseInWindow moves the mouse to the given position within the window. // (https://wiki.libsdl.org/SDL_WarpMouseInWindow) func (window *Window) WarpMouseInWindow(x, y int32) { C.SDL_WarpMouseInWindow(window.cptr(), C.int(x), C.int(y)) } // SetRelativeMouseMode sets relative mouse mode. // (https://wiki.libsdl.org/SDL_SetRelativeMouseMode) func SetRelativeMouseMode(enabled bool) int { return int(C.SDL_SetRelativeMouseMode(C.SDL_bool(Btoi(enabled)))) } // GetRelativeMouseMode reports where relative mouse mode is enabled. // (https://wiki.libsdl.org/SDL_GetRelativeMouseMode) func GetRelativeMouseMode() bool { return C.SDL_GetRelativeMouseMode() > 0 } // CreateCursor creates a cursor using the specified bitmap data and mask (in MSB format). // (https://wiki.libsdl.org/SDL_CreateCursor) func CreateCursor(data, mask *uint8, w, h, hotX, hotY int32) *Cursor { _data := (*C.Uint8)(unsafe.Pointer(data)) _mask := (*C.Uint8)(unsafe.Pointer(mask)) return (*Cursor)(C.SDL_CreateCursor(_data, _mask, C.int(w), C.int(h), C.int(hotX), C.int(hotY))) } // CreateColorCursor creates a color cursor. // (https://wiki.libsdl.org/SDL_CreateColorCursor) func CreateColorCursor(surface *Surface, hotX, hotY int32) *Cursor { return (*Cursor)(C.SDL_CreateColorCursor(surface.cptr(), C.int(hotX), C.int(hotY))) } // CreateSystemCursor creates a system cursor. // (https://wiki.libsdl.org/SDL_CreateSystemCursor) func CreateSystemCursor(id SystemCursor) *Cursor { return (*Cursor)(C.SDL_CreateSystemCursor(id.c())) } // SetCursor sets the active cursor. // (https://wiki.libsdl.org/SDL_SetCursor) func SetCursor(cursor *Cursor) { C.SDL_SetCursor(cursor.cptr()) } // GetCursor returns the active cursor. // (https://wiki.libsdl.org/SDL_GetCursor) func GetCursor() *Cursor { return (*Cursor)(C.SDL_GetCursor()) } // GetDefaultCursor returns the default cursor. // (https://wiki.libsdl.org/SDL_GetDefaultCursor) func GetDefaultCursor() *Cursor { return (*Cursor)(C.SDL_GetDefaultCursor()) } // FreeCursor frees a cursor created with CreateCursor(), CreateColorCursor() or CreateSystemCursor(). // (https://wiki.libsdl.org/SDL_FreeCursor) func FreeCursor(cursor *Cursor) { C.SDL_FreeCursor(cursor.cptr()) } // ShowCursor toggles whether or not the cursor is shown. // (https://wiki.libsdl.org/SDL_ShowCursor) func ShowCursor(toggle int) (int, error) { i := int(C.SDL_ShowCursor(C.int(toggle))) return i, errorFromInt(i) } // CaptureMouse captures the mouse and tracks input outside an SDL window. // (https://wiki.libsdl.org/SDL_CaptureMouse) func CaptureMouse(toggle bool) error { var ierr C.int if toggle { ierr = C.SDL_CaptureMouse(C.SDL_TRUE) } else { ierr = C.SDL_CaptureMouse(C.SDL_FALSE) } if ierr != 0 { return GetError() } return nil } // Button is used as a mask when testing buttons in buttonstate. func Button(flag uint32) uint32 { return 1 << (flag - 1) } // ButtonLMask is used as a mask when testing buttons in buttonstate. func ButtonLMask() uint32 { return Button(BUTTON_LEFT) } // ButtonMMask is used as a mask when testing buttons in buttonstate. func ButtonMMask() uint32 { return Button(BUTTON_MIDDLE) } // ButtonRMask is used as a mask when testing buttons in buttonstate. func ButtonRMask() uint32 { return Button(BUTTON_RIGHT) } // ButtonX1Mask is used as a mask when testing buttons in buttonstate. func ButtonX1Mask() uint32 { return Button(BUTTON_X1) } // ButtonX2Mask is used as a mask when testing buttons in buttonstate. func ButtonX2Mask() uint32 { return Button(BUTTON_X2) } // WarpMouseGlobal moves the mouse to the given position in global screen space. // (https://wiki.libsdl.org/SDL_WarpMouseGlobal) func WarpMouseGlobal(x, y int32) error { i := int(C.SDL_WarpMouseGlobal(C.int(x), C.int(y))) return errorFromInt(i) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/mutex.go ================================================ package sdl // #include "sdl_wrapper.h" import "C" import "unsafe" // ThreadID is the thread identifier for a thread. type ThreadID uint64 // Mutex is the SDL mutex structure. type Mutex struct { Recursive int Owner ThreadID Sem *Sem } // Sem is the SDL semaphore structure. type Sem struct { Count uint32 WaitersCount uint32 CountLock *Mutex CountNonzero *Cond } // Cond is the SDL condition variable structure. type Cond struct { Lock *Mutex Waiting int Signals int WaitSem *Sem WaitDone *Sem } func (m *Mutex) cptr() *C.SDL_mutex { return (*C.SDL_mutex)(unsafe.Pointer(m)) } func (s *Sem) cptr() *C.SDL_sem { return (*C.SDL_sem)(unsafe.Pointer(s)) } func (c *Cond) cptr() *C.SDL_cond { return (*C.SDL_cond)(unsafe.Pointer(c)) } // CreateMutex creates a new mutex. // (https://wiki.libsdl.org/SDL_CreateMutex) func CreateMutex() (*Mutex, error) { mutex := C.SDL_CreateMutex() if mutex == nil { return nil, GetError() } return (*Mutex)(unsafe.Pointer(mutex)), nil } // Lock locks a mutex created with CreateMutex(). // (https://wiki.libsdl.org/SDL_LockMutex) func (mutex *Mutex) Lock() error { ret := int(C.SDL_LockMutex(mutex.cptr())) if ret != 0 { return GetError() } return nil } // TryLock tries to lock a mutex without blocking. // (https://wiki.libsdl.org/SDL_TryLockMutex) func (mutex *Mutex) TryLock() error { ret := int(C.SDL_TryLockMutex(mutex.cptr())) if ret != 0 { return GetError() } return nil } // Unlock unlocks a mutex created with CreateMutex(). // (https://wiki.libsdl.org/SDL_UnlockMutex) func (mutex *Mutex) Unlock() error { ret := int(C.SDL_UnlockMutex(mutex.cptr())) if ret != 0 { return GetError() } return nil } // Destroy destroys a mutex created with CreateMutex(). // (https://wiki.libsdl.org/SDL_DestroyMutex) func (mutex *Mutex) Destroy() { C.SDL_DestroyMutex(mutex.cptr()) } // CreateSemaphore creates a semaphore. // (https://wiki.libsdl.org/SDL_CreateSemaphore) func CreateSemaphore(initialValue uint32) (*Sem, error) { sem := C.SDL_CreateSemaphore(C.Uint32(initialValue)) if sem == nil { return nil, GetError() } return (*Sem)(unsafe.Pointer(sem)), nil } // Destroy destroys a semaphore. // (https://wiki.libsdl.org/SDL_DestroySemaphore) func (sem *Sem) Destroy() { C.SDL_DestroySemaphore(sem.cptr()) } // Wait waits until a semaphore has a positive value and then decrements it. // (https://wiki.libsdl.org/SDL_SemWait) func (sem *Sem) Wait() error { ret := int(C.SDL_SemWait(sem.cptr())) if ret != 0 { return GetError() } return nil } // TryWait sees if a semaphore has a positive value and decrement it if it does. // (https://wiki.libsdl.org/SDL_SemTryWait) func (sem *Sem) TryWait() error { ret := int(C.SDL_SemTryWait(sem.cptr())) if ret != 0 { return GetError() } return nil } // WaitTimeout waits until a semaphore has a positive value and then decrements it. // (https://wiki.libsdl.org/SDL_SemWaitTimeout) func (sem *Sem) WaitTimeout(ms uint32) error { ret := int(C.SDL_SemWaitTimeout(sem.cptr(), C.Uint32(ms))) if ret != 0 { return GetError() } return nil } // Post atomically increments a semaphore's value and wake waiting threads. // (https://wiki.libsdl.org/SDL_SemPost) func (sem *Sem) Post() error { ret := int(C.SDL_SemPost(sem.cptr())) if ret != 0 { return GetError() } return nil } // Value returns the current value of a semaphore. // (https://wiki.libsdl.org/SDL_SemValue) func (sem *Sem) Value() uint32 { return uint32(C.SDL_SemValue(sem.cptr())) } // CreateCond (https://wiki.libsdl.org/SDL_CreateCond) func CreateCond() *Cond { return (*Cond)(unsafe.Pointer(C.SDL_CreateCond())) } // Destroy creates a condition variable. // (https://wiki.libsdl.org/SDL_DestroyCond) func (cond *Cond) Destroy() { C.SDL_DestroyCond(cond.cptr()) } // Signal restarts one of the threads that are waiting on the condition variable. // (https://wiki.libsdl.org/SDL_CondSignal) func (cond *Cond) Signal() error { ret := int(C.SDL_CondSignal(cond.cptr())) if ret != 0 { return GetError() } return nil } // Broadcast restarts all threads that are waiting on the condition variable. // (https://wiki.libsdl.org/SDL_CondBroadcast) func (cond *Cond) Broadcast() error { ret := int(C.SDL_CondBroadcast(cond.cptr())) if ret != 0 { return GetError() } return nil } // Wait waits until a condition variable is signaled. // (https://wiki.libsdl.org/SDL_CondWait) func (cond *Cond) Wait(mutex *Mutex) error { ret := int(C.SDL_CondWait(cond.cptr(), mutex.cptr())) if ret != 0 { return GetError() } return nil } // WaitTimeout waits until a condition variable is signaled or a specified amount of time has passed. // (https://wiki.libsdl.org/SDL_CondWaitTimeout) func (cond *Cond) WaitTimeout(mutex *Mutex, ms uint32) error { ret := int(C.SDL_CondWaitTimeout(cond.cptr(), mutex.cptr(), C.Uint32(ms))) if ret != 0 { return GetError() } return nil } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/pixels.go ================================================ package sdl // #include "sdl_wrapper.h" // // #if !(SDL_VERSION_ATLEAST(2,0,5)) // // enum // { // #if SDL_BYTEORDER == SDL_BIG_ENDIAN // SDL_PIXELFORMAT_RGBA32 = SDL_PIXELFORMAT_RGBA8888, // SDL_PIXELFORMAT_ARGB32 = SDL_PIXELFORMAT_ARGB8888, // SDL_PIXELFORMAT_BGRA32 = SDL_PIXELFORMAT_BGRA8888, // SDL_PIXELFORMAT_ABGR32 = SDL_PIXELFORMAT_ABGR8888 // #else // SDL_PIXELFORMAT_RGBA32 = SDL_PIXELFORMAT_ABGR8888, // SDL_PIXELFORMAT_ARGB32 = SDL_PIXELFORMAT_BGRA8888, // SDL_PIXELFORMAT_BGRA32 = SDL_PIXELFORMAT_ARGB8888, // SDL_PIXELFORMAT_ABGR32 = SDL_PIXELFORMAT_RGBA8888 // #endif // }; // // #endif // // int bytesPerPixel(Uint32 format) { // return SDL_BYTESPERPIXEL(format); // } // // int bitsPerPixel(Uint32 format) { // return SDL_BITSPERPIXEL(format); // } import "C" import ( "image/color" "unsafe" ) // PixelFormat contains pixel format information. // (https://wiki.libsdl.org/SDL_PixelFormat) type PixelFormat struct { Format uint32 // one of the PIXELFORMAT values (https://wiki.libsdl.org/SDL_PixelFormatEnum) Palette *Palette // palette structure associated with this pixel format, or nil if the format doesn't have a palette (https://wiki.libsdl.org/SDL_Palette) BitsPerPixel uint8 // the number of significant bits in a pixel value, eg: 8, 15, 16, 24, 32 BytesPerPixel uint8 // the number of bytes required to hold a pixel value, eg: 1, 2, 3, 4 _ [2]uint8 // padding Rmask uint32 // a mask representing the location of the red component of the pixel Gmask uint32 // a mask representing the location of the green component of the pixel Bmask uint32 // a mask representing the location of the blue component of the pixel Amask uint32 // a mask representing the location of the alpha component of the pixel or 0 if the pixel format doesn't have any alpha information rLoss uint8 // (internal use) gLoss uint8 // (internal use) bLoss uint8 // (internal use) aLoss uint8 // (internal use) rShift uint8 // (internal use) gShift uint8 // (internal use) bShift uint8 // (internal use) aShift uint8 // (internal use) refCount int32 // (internal use) next *PixelFormat // (internal use) } type cPixelFormat C.SDL_PixelFormat // Palette contains palette information. // (https://wiki.libsdl.org/SDL_Palette) type Palette struct { Ncolors int32 // the number of colors in the palette Colors *Color // an array of Color structures representing the palette (https://wiki.libsdl.org/SDL_Color) version uint32 // incrementally tracks changes to the palette (internal use) refCount int32 // reference count (internal use) } type cPalette C.SDL_Palette // Color represents a color. This implements image/color.Color interface. // (https://wiki.libsdl.org/SDL_Color) type Color color.NRGBA // Uint32 return uint32 representation of RGBA color. func (c Color) Uint32() uint32 { var v uint32 v |= uint32(c.R) << 24 v |= uint32(c.G) << 16 v |= uint32(c.B) << 8 v |= uint32(c.A) return v } // Pixel types. const ( PIXELTYPE_UNKNOWN = C.SDL_PIXELTYPE_UNKNOWN PIXELTYPE_INDEX1 = C.SDL_PIXELTYPE_INDEX1 PIXELTYPE_INDEX4 = C.SDL_PIXELTYPE_INDEX4 PIXELTYPE_INDEX8 = C.SDL_PIXELTYPE_INDEX8 PIXELTYPE_PACKED8 = C.SDL_PIXELTYPE_PACKED8 PIXELTYPE_PACKED16 = C.SDL_PIXELTYPE_PACKED16 PIXELTYPE_PACKED32 = C.SDL_PIXELTYPE_PACKED32 PIXELTYPE_ARRAYU8 = C.SDL_PIXELTYPE_ARRAYU8 PIXELTYPE_ARRAYU16 = C.SDL_PIXELTYPE_ARRAYU16 PIXELTYPE_ARRAYU32 = C.SDL_PIXELTYPE_ARRAYU32 PIXELTYPE_ARRAYF16 = C.SDL_PIXELTYPE_ARRAYF16 PIXELTYPE_ARRAYF32 = C.SDL_PIXELTYPE_ARRAYF32 ) // Bitmap pixel order high bit -> low bit. const ( BITMAPORDER_NONE = C.SDL_BITMAPORDER_NONE BITMAPORDER_4321 = C.SDL_BITMAPORDER_4321 BITMAPORDER_1234 = C.SDL_BITMAPORDER_1234 ) // Packed component order high bit -> low bit. const ( PACKEDORDER_NONE = C.SDL_PACKEDORDER_NONE PACKEDORDER_XRGB = C.SDL_PACKEDORDER_XRGB PACKEDORDER_RGBX = C.SDL_PACKEDORDER_RGBX PACKEDORDER_ARGB = C.SDL_PACKEDORDER_ARGB PACKEDORDER_RGBA = C.SDL_PACKEDORDER_RGBA PACKEDORDER_XBGR = C.SDL_PACKEDORDER_XBGR PACKEDORDER_BGRX = C.SDL_PACKEDORDER_BGRX PACKEDORDER_ABGR = C.SDL_PACKEDORDER_ABGR PACKEDORDER_BGRA = C.SDL_PACKEDORDER_BGRA ) // Array component order low byte -> high byte. const ( ARRAYORDER_NONE = C.SDL_ARRAYORDER_NONE ARRAYORDER_RGB = C.SDL_ARRAYORDER_RGB ARRAYORDER_RGBA = C.SDL_ARRAYORDER_RGBA ARRAYORDER_ARGB = C.SDL_ARRAYORDER_ARGB ARRAYORDER_BGR = C.SDL_ARRAYORDER_BGR ARRAYORDER_BGRA = C.SDL_ARRAYORDER_BGRA ARRAYORDER_ABGR = C.SDL_ARRAYORDER_ABGR ) // Packed component layout. const ( PACKEDLAYOUT_NONE = C.SDL_PACKEDLAYOUT_NONE PACKEDLAYOUT_332 = C.SDL_PACKEDLAYOUT_332 PACKEDLAYOUT_4444 = C.SDL_PACKEDLAYOUT_4444 PACKEDLAYOUT_1555 = C.SDL_PACKEDLAYOUT_1555 PACKEDLAYOUT_5551 = C.SDL_PACKEDLAYOUT_5551 PACKEDLAYOUT_565 = C.SDL_PACKEDLAYOUT_565 PACKEDLAYOUT_8888 = C.SDL_PACKEDLAYOUT_8888 PACKEDLAYOUT_2101010 = C.SDL_PACKEDLAYOUT_2101010 PACKEDLAYOUT_1010102 = C.SDL_PACKEDLAYOUT_1010102 ) // Pixel format values. const ( PIXELFORMAT_UNKNOWN = C.SDL_PIXELFORMAT_UNKNOWN PIXELFORMAT_INDEX1LSB = C.SDL_PIXELFORMAT_INDEX1LSB PIXELFORMAT_INDEX1MSB = C.SDL_PIXELFORMAT_INDEX1MSB PIXELFORMAT_INDEX4LSB = C.SDL_PIXELFORMAT_INDEX4LSB PIXELFORMAT_INDEX4MSB = C.SDL_PIXELFORMAT_INDEX4MSB PIXELFORMAT_INDEX8 = C.SDL_PIXELFORMAT_INDEX8 PIXELFORMAT_RGB332 = C.SDL_PIXELFORMAT_RGB332 PIXELFORMAT_RGB444 = C.SDL_PIXELFORMAT_RGB444 PIXELFORMAT_RGB555 = C.SDL_PIXELFORMAT_RGB555 PIXELFORMAT_BGR555 = C.SDL_PIXELFORMAT_BGR555 PIXELFORMAT_ARGB4444 = C.SDL_PIXELFORMAT_ARGB4444 PIXELFORMAT_RGBA4444 = C.SDL_PIXELFORMAT_RGBA4444 PIXELFORMAT_ABGR4444 = C.SDL_PIXELFORMAT_ABGR4444 PIXELFORMAT_BGRA4444 = C.SDL_PIXELFORMAT_BGRA4444 PIXELFORMAT_ARGB1555 = C.SDL_PIXELFORMAT_ARGB1555 PIXELFORMAT_RGBA5551 = C.SDL_PIXELFORMAT_RGBA5551 PIXELFORMAT_ABGR1555 = C.SDL_PIXELFORMAT_ABGR1555 PIXELFORMAT_BGRA5551 = C.SDL_PIXELFORMAT_BGRA5551 PIXELFORMAT_RGB565 = C.SDL_PIXELFORMAT_RGB565 PIXELFORMAT_BGR565 = C.SDL_PIXELFORMAT_BGR565 PIXELFORMAT_RGB24 = C.SDL_PIXELFORMAT_RGB24 PIXELFORMAT_BGR24 = C.SDL_PIXELFORMAT_BGR24 PIXELFORMAT_RGB888 = C.SDL_PIXELFORMAT_RGB888 PIXELFORMAT_RGBX8888 = C.SDL_PIXELFORMAT_RGBX8888 PIXELFORMAT_BGR888 = C.SDL_PIXELFORMAT_BGR888 PIXELFORMAT_BGRX8888 = C.SDL_PIXELFORMAT_BGRX8888 PIXELFORMAT_ARGB8888 = C.SDL_PIXELFORMAT_ARGB8888 PIXELFORMAT_RGBA8888 = C.SDL_PIXELFORMAT_RGBA8888 PIXELFORMAT_ABGR8888 = C.SDL_PIXELFORMAT_ABGR8888 PIXELFORMAT_BGRA8888 = C.SDL_PIXELFORMAT_BGRA8888 PIXELFORMAT_ARGB2101010 = C.SDL_PIXELFORMAT_ARGB2101010 PIXELFORMAT_YV12 = C.SDL_PIXELFORMAT_YV12 PIXELFORMAT_IYUV = C.SDL_PIXELFORMAT_IYUV PIXELFORMAT_YUY2 = C.SDL_PIXELFORMAT_YUY2 PIXELFORMAT_UYVY = C.SDL_PIXELFORMAT_UYVY PIXELFORMAT_YVYU = C.SDL_PIXELFORMAT_YVYU ) // Pixel format variables. var ( PIXELFORMAT_RGBA32 = C.SDL_PIXELFORMAT_RGBA32 PIXELFORMAT_ARGB32 = C.SDL_PIXELFORMAT_ARGB32 PIXELFORMAT_BGRA32 = C.SDL_PIXELFORMAT_BGRA32 PIXELFORMAT_ABGR32 = C.SDL_PIXELFORMAT_ABGR32 ) // These define alpha as the opacity of a surface. const ( ALPHA_OPAQUE = C.SDL_ALPHA_OPAQUE ALPHA_TRANSPARENT = C.SDL_ALPHA_TRANSPARENT ) func (format *PixelFormat) cptr() *C.SDL_PixelFormat { return (*C.SDL_PixelFormat)(unsafe.Pointer(format)) } func (palette *Palette) cptr() *C.SDL_Palette { return (*C.SDL_Palette)(unsafe.Pointer(palette)) } /* * the following code is modified version of the code from bitbucket.org/dooots/go-sdl2 */ // GetPixelFormatName returns the human readable name of a pixel format. // (https://wiki.libsdl.org/SDL_GetPixelFormatName) func GetPixelFormatName(format uint) string { return C.GoString(C.SDL_GetPixelFormatName(C.Uint32(format))) } // PixelFormatEnumToMasks converts one of the enumerated pixel formats to a bpp value and RGBA masks. // (https://wiki.libsdl.org/SDL_PixelFormatEnumToMasks) func PixelFormatEnumToMasks(format uint) (bpp int, rmask, gmask, bmask, amask uint32, err error) { result := C.SDL_PixelFormatEnumToMasks(C.Uint32(format), (*C.int)(unsafe.Pointer(&bpp)), (*C.Uint32)(&rmask), (*C.Uint32)(&gmask), (*C.Uint32)(&bmask), (*C.Uint32)(&amask)) if result == C.SDL_FALSE { err = GetError() } return } // MasksToPixelFormatEnum converts a bpp value and RGBA masks to an enumerated pixel format. // (https://wiki.libsdl.org/SDL_MasksToPixelFormatEnum) func MasksToPixelFormatEnum(bpp int, rmask, gmask, bmask, amask uint32) uint { return uint(C.SDL_MasksToPixelFormatEnum(C.int(bpp), C.Uint32(rmask), C.Uint32(gmask), C.Uint32(bmask), C.Uint32(amask))) } // AllocFormat creates a PixelFormat structure corresponding to a pixel format. // (https://wiki.libsdl.org/SDL_AllocFormat) func AllocFormat(format uint) (*PixelFormat, error) { r := (*PixelFormat)(unsafe.Pointer(C.SDL_AllocFormat(C.Uint32(format)))) if r == nil { return nil, GetError() } return r, nil } // Free frees the PixelFormat structure allocated by AllocFormat(). // (https://wiki.libsdl.org/SDL_FreeFormat) func (format *PixelFormat) Free() { C.SDL_FreeFormat((*C.SDL_PixelFormat)(unsafe.Pointer(format))) } // AllocPalette creates a palette structure with the specified number of color entries. // (https://wiki.libsdl.org/SDL_AllocPalette) func AllocPalette(ncolors int) (*Palette, error) { r := (*Palette)(unsafe.Pointer(C.SDL_AllocPalette(C.int(ncolors)))) if r == nil { return nil, GetError() } return r, nil } // SetPalette sets the palette for the pixel format structure. // (https://wiki.libsdl.org/SDL_SetPixelFormatPalette) func (format *PixelFormat) SetPalette(palette *Palette) error { r := C.SDL_SetPixelFormatPalette((*C.SDL_PixelFormat)(unsafe.Pointer(format)), (*C.SDL_Palette)(unsafe.Pointer(palette))) if r != 0 { return GetError() } return nil } // SetColors sets a range of colors in the palette. // (https://wiki.libsdl.org/SDL_SetPaletteColors) func (palette *Palette) SetColors(colors []Color) error { if colors == nil { return nil } var ptr *C.SDL_Color if len(colors) > 0 { ptr = (*C.SDL_Color)(unsafe.Pointer(&colors[0])) } r := C.SDL_SetPaletteColors((*C.SDL_Palette)(unsafe.Pointer(palette)), ptr, 0, C.int(len(colors))) if r != 0 { return GetError() } return nil } // Free frees the palette created with AllocPalette(). // (https://wiki.libsdl.org/SDL_FreePalette) func (palette *Palette) Free() { C.SDL_FreePalette((*C.SDL_Palette)(unsafe.Pointer(palette))) } // MapRGB maps an RGB triple to an opaque pixel value for a given pixel format. // (https://wiki.libsdl.org/SDL_MapRGB) func MapRGB(format *PixelFormat, r, g, b uint8) uint32 { return uint32(C.SDL_MapRGB((*C.SDL_PixelFormat)(unsafe.Pointer(format)), C.Uint8(r), C.Uint8(g), C.Uint8(b))) } // MapRGBA maps an RGBA quadruple to a pixel value for a given pixel format. // (https://wiki.libsdl.org/SDL_MapRGBA) func MapRGBA(format *PixelFormat, r, g, b, a uint8) uint32 { return uint32(C.SDL_MapRGBA((*C.SDL_PixelFormat)(unsafe.Pointer(format)), C.Uint8(r), C.Uint8(g), C.Uint8(b), C.Uint8(a))) } // GetRGB returns RGB values from a pixel in the specified format. // (https://wiki.libsdl.org/SDL_GetRGB) func GetRGB(pixel uint32, format *PixelFormat) (r, g, b uint8) { C.SDL_GetRGB(C.Uint32(pixel), (*C.SDL_PixelFormat)(unsafe.Pointer(format)), (*C.Uint8)(&r), (*C.Uint8)(&g), (*C.Uint8)(&b)) return } // GetRGBA returns RGBA values from a pixel in the specified format. // (https://wiki.libsdl.org/SDL_GetRGBA) func GetRGBA(pixel uint32, format *PixelFormat) (r, g, b, a uint8) { C.SDL_GetRGBA(C.Uint32(pixel), (*C.SDL_PixelFormat)(unsafe.Pointer(format)), (*C.Uint8)(&r), (*C.Uint8)(&g), (*C.Uint8)(&b), (*C.Uint8)(&a)) return } // CalculateGammaRamp calculates a 256 entry gamma ramp for a gamma value. // (https://wiki.libsdl.org/SDL_CalculateGammaRamp) func CalculateGammaRamp(gamma float32, ramp *[256]uint16) { C.SDL_CalculateGammaRamp(C.float(gamma), (*C.Uint16)(unsafe.Pointer(&ramp[0]))) } // BytesPerPixel returns the number of bytes per pixel for the given format func BytesPerPixel(format uint32) int { return int(C.bytesPerPixel(C.Uint32(format))) } // BitsPerPixel returns the number of bits per pixel for the given format func BitsPerPixel(format uint32) int { return int(C.bitsPerPixel(C.Uint32(format))) } var ( RGB444Model color.Model = color.ModelFunc(rgb444Model) RGB332Model color.Model = color.ModelFunc(rgb332Model) RGB565Model color.Model = color.ModelFunc(rgb565Model) RGB555Model color.Model = color.ModelFunc(rgb555Model) BGR565Model color.Model = color.ModelFunc(bgr565Model) BGR555Model color.Model = color.ModelFunc(bgr555Model) ARGB4444Model color.Model = color.ModelFunc(argb4444Model) ABGR4444Model color.Model = color.ModelFunc(abgr4444Model) RGBA4444Model color.Model = color.ModelFunc(rgba4444Model) BGRA4444Model color.Model = color.ModelFunc(bgra4444Model) ARGB1555Model color.Model = color.ModelFunc(argb1555Model) RGBA5551Model color.Model = color.ModelFunc(rgba5551Model) ABGR1555Model color.Model = color.ModelFunc(abgr1555Model) BGRA5551Model color.Model = color.ModelFunc(bgra5551Model) RGBA8888Model color.Model = color.ModelFunc(rgba8888Model) BGRA8888Model color.Model = color.ModelFunc(bgra8888Model) ) type RGB444 struct { R, G, B byte } func (c RGB444) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale4to8bit(c.R), G: upscale4to8bit(c.G), B: upscale4to8bit(c.B), A: 0xFF, } return nrgba.RGBA() } func rgb444Model(c color.Color) color.Color { if _, ok := c.(RGB444); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return RGB444{ R: downscale8to4bit(nrgba.R), G: downscale8to4bit(nrgba.G), B: downscale8to4bit(nrgba.B), } } type RGB332 struct { R, G, B byte } func (c RGB332) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale3to8bit(c.R), G: upscale3to8bit(c.G), B: upscale2to8bit(c.B), A: 0xFF, } return nrgba.RGBA() } func rgb332Model(c color.Color) color.Color { if _, ok := c.(RGB332); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return RGB332{ R: downscale8to3bit(nrgba.R), G: downscale8to3bit(nrgba.G), B: downscale8to2bit(nrgba.B), } } type RGB565 struct { R, G, B byte } func (c RGB565) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale5to8bit(c.R), G: upscale6to8bit(c.G), B: upscale5to8bit(c.B), A: 0xFF, } return nrgba.RGBA() } func rgb565Model(c color.Color) color.Color { if _, ok := c.(RGB565); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return RGB565{ R: downscale8to5bit(nrgba.R), G: downscale8to6bit(nrgba.G), B: downscale8to5bit(nrgba.B), } } type RGB555 struct { R, G, B byte } func (c RGB555) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale5to8bit(c.R), G: upscale5to8bit(c.G), B: upscale5to8bit(c.B), A: 0xFF, } return nrgba.RGBA() } func rgb555Model(c color.Color) color.Color { if _, ok := c.(RGB555); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return RGB555{ R: downscale8to5bit(nrgba.R), G: downscale8to5bit(nrgba.G), B: downscale8to5bit(nrgba.B), } } type BGR565 struct { B, G, R byte } func (c BGR565) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale5to8bit(c.R), G: upscale6to8bit(c.G), B: upscale5to8bit(c.B), A: 0xFF, } return nrgba.RGBA() } func bgr565Model(c color.Color) color.Color { if _, ok := c.(BGR565); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return BGR565{ B: downscale8to5bit(nrgba.B), G: downscale8to6bit(nrgba.G), R: downscale8to5bit(nrgba.R), } } type BGR555 struct { B, G, R byte } func (c BGR555) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale5to8bit(c.R), G: upscale5to8bit(c.G), B: upscale5to8bit(c.B), A: 0xFF, } return nrgba.RGBA() } func bgr555Model(c color.Color) color.Color { if _, ok := c.(BGR555); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return BGR555{ B: downscale8to5bit(nrgba.B), G: downscale8to5bit(nrgba.G), R: downscale8to5bit(nrgba.R), } } type RGB888 struct { R, G, B byte } func (c RGB888) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: c.R, G: c.G, B: c.B, A: 0xFF, } return nrgba.RGBA() } func rgb888Model(c color.Color) color.Color { if _, ok := c.(RGB888); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return RGB888{ R: nrgba.R, G: nrgba.G, B: nrgba.B, } } type BGR888 struct { B, G, R byte } func (c BGR888) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: c.R, G: c.G, B: c.B, A: 0xFF, } return nrgba.RGBA() } func bgr888Model(c color.Color) color.Color { if _, ok := c.(BGR888); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return BGR888{ B: nrgba.B, G: nrgba.G, R: nrgba.R, } } type ARGB4444 struct { A, R, G, B byte } func (c ARGB4444) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale4to8bit(c.R), G: upscale4to8bit(c.G), B: upscale4to8bit(c.B), A: upscale4to8bit(c.A), } return nrgba.RGBA() } func argb4444Model(c color.Color) color.Color { if _, ok := c.(ARGB4444); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return ARGB4444{ A: downscale8to4bit(nrgba.A), R: downscale8to4bit(nrgba.R), G: downscale8to4bit(nrgba.G), B: downscale8to4bit(nrgba.B), } } type ABGR4444 struct { A, B, G, R byte } func (c ABGR4444) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale4to8bit(c.R), G: upscale4to8bit(c.G), B: upscale4to8bit(c.B), A: upscale4to8bit(c.A), } return nrgba.RGBA() } func abgr4444Model(c color.Color) color.Color { if _, ok := c.(ABGR4444); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return ABGR4444{ A: downscale8to4bit(nrgba.A), B: downscale8to4bit(nrgba.B), G: downscale8to4bit(nrgba.G), R: downscale8to4bit(nrgba.R), } } type RGBA4444 struct { R, G, B, A byte } func (c RGBA4444) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale4to8bit(c.R), G: upscale4to8bit(c.G), B: upscale4to8bit(c.B), A: upscale4to8bit(c.A), } return nrgba.RGBA() } func rgba4444Model(c color.Color) color.Color { if _, ok := c.(RGBA4444); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return RGBA4444{ R: downscale8to4bit(nrgba.R), G: downscale8to4bit(nrgba.G), B: downscale8to4bit(nrgba.B), A: downscale8to4bit(nrgba.A), } } type BGRA4444 struct { B, G, R, A byte } func (c BGRA4444) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale4to8bit(c.R), G: upscale4to8bit(c.G), B: upscale4to8bit(c.B), A: upscale4to8bit(c.A), } return nrgba.RGBA() } func bgra4444Model(c color.Color) color.Color { if _, ok := c.(BGRA4444); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return BGRA4444{ B: downscale8to4bit(nrgba.B), G: downscale8to4bit(nrgba.G), R: downscale8to4bit(nrgba.R), A: downscale8to4bit(nrgba.A), } } type ARGB1555 struct { A, R, G, B byte } func (c ARGB1555) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale5to8bit(c.R), G: upscale5to8bit(c.G), B: upscale5to8bit(c.B), A: upscale1to8bit(c.A), } return nrgba.RGBA() } func argb1555Model(c color.Color) color.Color { if _, ok := c.(ARGB1555); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return ARGB1555{ A: downscale8to1bit(nrgba.A), R: downscale8to5bit(nrgba.R), G: downscale8to5bit(nrgba.G), B: downscale8to5bit(nrgba.B), } } type RGBA5551 struct { R, G, B, A byte } func (c RGBA5551) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale5to8bit(c.R), G: upscale5to8bit(c.G), B: upscale5to8bit(c.B), A: upscale1to8bit(c.A), } return nrgba.RGBA() } func rgba5551Model(c color.Color) color.Color { if _, ok := c.(RGBA5551); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return RGBA5551{ R: downscale8to5bit(nrgba.R), G: downscale8to5bit(nrgba.G), B: downscale8to5bit(nrgba.B), A: downscale8to1bit(nrgba.A), } } type ABGR1555 struct { A, R, G, B byte } func (c ABGR1555) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale5to8bit(c.R), G: upscale5to8bit(c.G), B: upscale5to8bit(c.B), A: upscale1to8bit(c.A), } return nrgba.RGBA() } func abgr1555Model(c color.Color) color.Color { if _, ok := c.(ABGR1555); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return ABGR1555{ A: downscale8to1bit(nrgba.A), R: downscale8to5bit(nrgba.R), G: downscale8to5bit(nrgba.G), B: downscale8to5bit(nrgba.B), } } type BGRA5551 struct { B, G, R, A byte } func (c BGRA5551) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: upscale5to8bit(c.R), G: upscale5to8bit(c.G), B: upscale5to8bit(c.B), A: upscale1to8bit(c.A), } return nrgba.RGBA() } func bgra5551Model(c color.Color) color.Color { if _, ok := c.(BGRA5551); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return BGRA5551{ B: downscale8to5bit(nrgba.B), G: downscale8to5bit(nrgba.G), R: downscale8to5bit(nrgba.R), A: downscale8to1bit(nrgba.A), } } type RGBA8888 struct { R, G, B, A byte } func (c RGBA8888) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: c.R, G: c.G, B: c.B, A: c.A, } return nrgba.RGBA() } func rgba8888Model(c color.Color) color.Color { if _, ok := c.(RGBA8888); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return RGBA8888{ R: nrgba.R, G: nrgba.G, B: nrgba.B, A: nrgba.A, } } type BGRA8888 struct { B, G, R, A byte } func (c BGRA8888) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: c.R, G: c.G, B: c.B, A: c.A, } return nrgba.RGBA() } func bgra8888Model(c color.Color) color.Color { if _, ok := c.(BGRA8888); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return BGRA8888{ B: nrgba.B, G: nrgba.G, R: nrgba.R, A: nrgba.A, } } type ARGB8888 struct { A, R, G, B byte } func (c ARGB8888) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: c.R, G: c.G, B: c.B, A: c.A, } return nrgba.RGBA() } func argb8888Model(c color.Color) color.Color { if _, ok := c.(ARGB8888); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return ARGB8888{ A: nrgba.A, R: nrgba.R, G: nrgba.G, B: nrgba.B, } } type ABGR8888 struct { A, B, G, R byte } func (c ABGR8888) RGBA() (r, g, b, a uint32) { nrgba := color.NRGBA{ R: c.R, G: c.G, B: c.B, A: c.A, } return nrgba.RGBA() } func abgr8888Model(c color.Color) color.Color { if _, ok := c.(ABGR8888); ok { return c } nrgba := color.NRGBAModel.Convert(c).(color.NRGBA) return ABGR8888{ A: nrgba.A, B: nrgba.B, G: nrgba.G, R: nrgba.R, } } func downscale8to1bit(alpha byte) byte { if alpha == 0 { return 0 } return 1 } func downscale8to2bit(in byte) byte { return in >> 6 } func downscale8to3bit(in byte) byte { return in >> 5 } func downscale8to4bit(in byte) byte { return in >> 4 } func downscale8to5bit(in byte) byte { return in >> 3 } func downscale8to6bit(in byte) byte { return in >> 2 } func upscale1to8bit(alphaBit byte) byte { if alphaBit == 0 { return 0 } return 0xFF } func upscale2to8bit(in byte) byte { return in<<6 | in<<4 | in<<2 | in } func upscale3to8bit(in byte) byte { return in<<5 | in<<2 | (in>>1)&0b11 } func upscale4to8bit(in byte) byte { return in<<4 | in } func upscale5to8bit(in byte) byte { return in<<3 | (in>>2)&0b111 } func upscale6to8bit(in byte) byte { return in<<2 | (in>>4)&0b11 } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/power.go ================================================ package sdl // #include "sdl_wrapper.h" import "C" // An enumeration of the basic state of the system's power supply. // (https://wiki.libsdl.org/SDL_PowerState) const ( POWERSTATE_UNKNOWN = C.SDL_POWERSTATE_UNKNOWN // cannot determine power status POWERSTATE_ON_BATTERY = C.SDL_POWERSTATE_ON_BATTERY // not plugged in, running on the battery POWERSTATE_NO_BATTERY = C.SDL_POWERSTATE_NO_BATTERY // plugged in, no battery available POWERSTATE_CHARGING = C.SDL_POWERSTATE_CHARGING // plugged in, charging battery POWERSTATE_CHARGED = C.SDL_POWERSTATE_CHARGED // plugged in, battery charged ) // PowerState is the basic state for the system's power supply. // (https://wiki.libsdl.org/SDL_PowerState) type PowerState C.SDL_PowerState // GetPowerInfo returns the current power supply details. // (https://wiki.libsdl.org/SDL_GetPowerInfo) func GetPowerInfo() (int, int, int) { _secs := C.int(0) _percent := C.int(0) _state := C.SDL_GetPowerInfo(&_secs, &_percent) return (int)(_state), (int)(_secs), (int)(_percent) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/rect.go ================================================ package sdl // #include "sdl_wrapper.h" import "C" import ( "math" "unsafe" ) // Point defines a two dimensional point. // (https://wiki.libsdl.org/SDL_Point) type Point struct { X int32 // the x coordinate of the point Y int32 // the y coordinate of the point } // Rect contains the definition of a rectangle, with the origin at the upper left. // (https://wiki.libsdl.org/SDL_Rect) type Rect struct { X int32 // the x location of the rectangle's upper left corner Y int32 // the y location of the rectangle's upper left corner W int32 // the width of the rectangle H int32 // the height of the rectangle } // FPoint defines a two dimensional point. // TODO: (https://wiki.libsdl.org/SDL_FPoint) type FPoint struct { X float32 // the x coordinate of the point Y float32 // the y coordinate of the point } // FRect contains the definition of a rectangle, with the origin at the upper left. // TODO: (https://wiki.libsdl.org/SDL_FRect) type FRect struct { X float32 // the x location of the rectangle's upper left corner Y float32 // the y location of the rectangle's upper left corner W float32 // the width of the rectangle H float32 // the height of the rectangle } func (p *Point) cptr() *C.SDL_Point { return (*C.SDL_Point)(unsafe.Pointer(p)) } func (a *Rect) cptr() *C.SDL_Rect { return (*C.SDL_Rect)(unsafe.Pointer(a)) } func (p *FPoint) cptr() *C.SDL_FPoint { return (*C.SDL_FPoint)(unsafe.Pointer(p)) } func (a *FRect) cptr() *C.SDL_FRect { return (*C.SDL_FRect)(unsafe.Pointer(a)) } // InRect reports whether the point resides inside a rectangle. // (https://wiki.libsdl.org/SDL_PointInRect) func (p *Point) InRect(r *Rect) bool { if (p.X >= r.X) && (p.X < (r.X + r.W)) && (p.Y >= r.Y) && (p.Y < (r.Y + r.H)) { return true } return false } // InRect reports whether the point resides inside a rectangle. // (https://wiki.libsdl.org/SDL_PointInRect) func (p *FPoint) InRect(r *FRect) bool { if (p.X >= r.X) && (p.X < (r.X + r.W)) && (p.Y >= r.Y) && (p.Y < (r.Y + r.H)) { return true } return false } // Empty reports whether a rectangle has no area. // (https://wiki.libsdl.org/SDL_RectEmpty) func (a *Rect) Empty() bool { return a == nil || a.W <= 0 || a.H <= 0 } // Equals reports whether two rectangles are equal. // (https://wiki.libsdl.org/SDL_RectEquals) func (a *Rect) Equals(b *Rect) bool { if (a != nil) && (b != nil) && (a.X == b.X) && (a.Y == b.Y) && (a.W == b.W) && (a.H == b.H) { return true } return false } // HasIntersection reports whether two rectangles intersect. // (https://wiki.libsdl.org/SDL_HasIntersection) func (a *Rect) HasIntersection(b *Rect) bool { if a == nil || b == nil { return false } // Special case for empty rects if a.Empty() || b.Empty() { return false } if a.X >= b.X+b.W || a.X+a.W <= b.X || a.Y >= b.Y+b.H || a.Y+a.H <= b.Y { return false } return true } // Intersect calculates the intersection of two rectangles. // (https://wiki.libsdl.org/SDL_IntersectRect) func (a *Rect) Intersect(b *Rect) (Rect, bool) { var result Rect if a == nil || b == nil { return result, false } // Special case for empty rects if a.Empty() || b.Empty() { result.W = 0 result.H = 0 return result, false } aMin := a.X aMax := aMin + a.W bMin := b.X bMax := bMin + b.W if bMin > aMin { aMin = bMin } result.X = aMin if bMax < aMax { aMax = bMax } result.W = aMax - aMin aMin = a.Y aMax = aMin + a.H bMin = b.Y bMax = bMin + b.H if bMin > aMin { aMin = bMin } result.Y = aMin if bMax < aMax { aMax = bMax } result.H = aMax - aMin return result, !result.Empty() } // Union calculates the union of two rectangles. // (https://wiki.libsdl.org/SDL_UnionRect) func (a *Rect) Union(b *Rect) Rect { var result Rect if a == nil || b == nil { return result } // Special case for empty rects if a.Empty() { return *b } else if b.Empty() { return *a } else if a.Empty() && b.Empty() { return result } aMin := a.X aMax := aMin + a.W bMin := b.X bMax := bMin + b.W if bMin < aMin { aMin = bMin } result.X = aMin if bMax > aMax { aMax = bMax } result.W = aMax - aMin aMin = a.Y aMax = aMin + a.H bMin = b.Y bMax = bMin + b.H if bMin < aMin { aMin = bMin } result.Y = aMin if bMax > aMax { aMax = bMax } result.H = aMax - aMin return result } // Empty reports whether a rectangle has no area. // (https://wiki.libsdl.org/SDL_RectEmpty) func (a *FRect) Empty() bool { return a == nil || a.W <= 0 || a.H <= 0 } // Equals reports whether two rectangles are equal. // (https://wiki.libsdl.org/SDL_RectEquals) func (a *FRect) Equals(b *FRect) bool { if (a != nil) && (b != nil) && (a.X == b.X) && (a.Y == b.Y) && (a.W == b.W) && (a.H == b.H) { return true } return false } // EqualsEpsilon returns true if the two rectangles are equal, within some given epsilon. // (https://wiki.libsdl.org/SDL_FRectEqualsEpsilon) func (a *FRect) EqualsEpsilon(b *FRect, epsilon float32) bool { if (a != nil) && (b != nil) && (a == b || (float32(math.Abs(float64(a.X-b.X))) <= epsilon) && (float32(math.Abs(float64(a.Y-b.Y))) <= epsilon) && (float32(math.Abs(float64(a.W-b.W))) <= epsilon) && (float32(math.Abs(float64(a.H-b.H))) <= epsilon)) { return true } return false } // HasIntersection reports whether two rectangles intersect. // (https://wiki.libsdl.org/SDL_HasIntersection) func (a *FRect) HasIntersection(b *FRect) bool { if a == nil || b == nil { return false } // Special case for empty rects if a.Empty() || b.Empty() { return false } if a.X >= b.X+b.W || a.X+a.W <= b.X || a.Y >= b.Y+b.H || a.Y+a.H <= b.Y { return false } return true } // Intersect calculates the intersection of two rectangles. // (https://wiki.libsdl.org/SDL_IntersectRect) func (a *FRect) Intersect(b *FRect) (FRect, bool) { var result FRect if a == nil || b == nil { return result, false } // Special case for empty rects if a.Empty() || b.Empty() { result.W = 0 result.H = 0 return result, false } aMin := a.X aMax := aMin + a.W bMin := b.X bMax := bMin + b.W if bMin > aMin { aMin = bMin } result.X = aMin if bMax < aMax { aMax = bMax } result.W = aMax - aMin aMin = a.Y aMax = aMin + a.H bMin = b.Y bMax = bMin + b.H if bMin > aMin { aMin = bMin } result.Y = aMin if bMax < aMax { aMax = bMax } result.H = aMax - aMin return result, !result.Empty() } // Union calculates the union of two rectangles. // (https://wiki.libsdl.org/SDL_UnionRect) func (a *FRect) Union(b *FRect) FRect { var result FRect if a == nil || b == nil { return result } // Special case for empty rects if a.Empty() { return *b } else if b.Empty() { return *a } else if a.Empty() && b.Empty() { return result } aMin := a.X aMax := aMin + a.W bMin := b.X bMax := bMin + b.W if bMin < aMin { aMin = bMin } result.X = aMin if bMax > aMax { aMax = bMax } result.W = aMax - aMin aMin = a.Y aMax = aMin + a.H bMin = b.Y bMax = bMin + b.H if bMin < aMin { aMin = bMin } result.Y = aMin if bMax > aMax { aMax = bMax } result.H = aMax - aMin return result } // EnclosePoints calculates a minimal rectangle that encloses a set of points. // (https://wiki.libsdl.org/SDL_EnclosePoints) func EnclosePoints(points []Point, clip *Rect) (Rect, bool) { var result Rect if len(points) == 0 { return result, false } var minX, minY, maxX, maxY int32 if clip != nil { added := false clipMinX := clip.X clipMinY := clip.Y clipMaxX := clip.X + clip.W - 1 clipMaxY := clip.Y + clip.H - 1 // If the clip has no size, we're done if clip.Empty() { return result, false } for _, val := range points { // Check if the point is inside the clip rect if val.X < clipMinX || val.X > clipMaxX || val.Y < clipMinY || val.Y > clipMaxY { continue } if !added { // If it's the first point minX = val.X maxX = val.X minY = val.Y maxY = val.Y added = true } // Find mins and maxes if val.X < minX { minX = val.X } else if val.X > maxX { maxX = val.X } if val.Y < minY { minY = val.Y } else if val.Y > maxY { maxY = val.Y } } } else { for i, val := range points { if i == 0 { // Populate the first point minX = val.X maxX = val.X minY = val.Y maxY = val.Y continue } // Find mins and maxes if val.X < minX { minX = val.X } else if val.X > maxX { maxX = val.X } if val.Y < minY { minY = val.Y } else if val.Y > maxY { maxY = val.Y } } } result.X = minX result.Y = minY result.W = (maxX - minX) + 1 result.H = (maxY - minY) + 1 return result, true } // EncloseFPoints calculates a minimal rectangle that encloses a set of points with float precision. // (https://wiki.libsdl.org/SDL_EncloseFPoints) func EncloseFPoints(points []FPoint, clip *FRect) (result FRect, enclosed bool) { if len(points) == 0 { return result, false } var minX, minY, maxX, maxY float32 if clip != nil { added := false clipMinX := clip.X clipMinY := clip.Y clipMaxX := clip.X + clip.W - 1 clipMaxY := clip.Y + clip.H - 1 // If the clip has no size, we're done if clip.Empty() { return result, false } for _, val := range points { // Check if the point is inside the clip rect if val.X < clipMinX || val.X > clipMaxX || val.Y < clipMinY || val.Y > clipMaxY { continue } if !added { // If it's the first point minX = val.X maxX = val.X minY = val.Y maxY = val.Y added = true } // Find mins and maxes if val.X < minX { minX = val.X } else if val.X > maxX { maxX = val.X } if val.Y < minY { minY = val.Y } else if val.Y > maxY { maxY = val.Y } } } else { for i, val := range points { if i == 0 { // Populate the first point minX = val.X maxX = val.X minY = val.Y maxY = val.Y continue } // Find mins and maxes if val.X < minX { minX = val.X } else if val.X > maxX { maxX = val.X } if val.Y < minY { minY = val.Y } else if val.Y > maxY { maxY = val.Y } } } result.X = minX result.Y = minY result.W = (maxX - minX) + 1 result.H = (maxY - minY) + 1 return result, true } const ( codeBottom = 1 codeTop = 2 codeLeft = 4 codeRight = 8 ) func computeOutCode(rect *Rect, x, y int32) int { code := 0 if y < rect.Y { code |= codeTop } else if y >= rect.Y+rect.H { code |= codeBottom } if x < rect.X { code |= codeLeft } else if x >= rect.X+rect.W { code |= codeRight } return code } func computeFOutCode(rect *FRect, x, y float32) int { code := 0 if y < rect.Y { code |= codeTop } else if y >= rect.Y+rect.H { code |= codeBottom } if x < rect.X { code |= codeLeft } else if x >= rect.X+rect.W { code |= codeRight } return code } // IntersectLine calculates the intersection of a rectangle and a line segment. // (https://wiki.libsdl.org/SDL_IntersectRectAndLine) func (a *Rect) IntersectLine(X1, Y1, X2, Y2 *int32) bool { if a.Empty() { return false } x1 := *X1 y1 := *Y1 x2 := *X2 y2 := *Y2 rectX1 := a.X rectY1 := a.Y rectX2 := a.X + a.W - 1 rectY2 := a.Y + a.H - 1 // Check if the line is entirely inside the rect if x1 >= rectX1 && x1 <= rectX2 && x2 >= rectX1 && x2 <= rectX2 && y1 >= rectY1 && y1 <= rectY2 && y2 >= rectY1 && y2 <= rectY2 { return true } // Check if the line is entirely outside the rect if (x1 < rectX1 && x2 < rectX1) || (x1 > rectX2 && x2 > rectX2) || (y1 < rectY1 && y2 < rectY1) || (y1 > rectY2 && y2 > rectY2) { return false } // Check if the line is horizontal if y1 == y2 { if x1 < rectX1 { *X1 = rectX1 } else if x1 > rectX2 { *X1 = rectX2 } if x2 < rectX1 { *X2 = rectX1 } else if x2 > rectX2 { *X2 = rectX2 } return true } // Check if the line is vertical if x1 == x2 { if y1 < rectY1 { *Y1 = rectY1 } else if y1 > rectY2 { *Y1 = rectY2 } if y2 < rectY1 { *Y2 = rectY1 } else if y2 > rectY2 { *Y2 = rectY2 } return true } // Use Cohen-Sutherland algorithm when all shortcuts fail outCode1 := computeOutCode(a, x1, y1) outCode2 := computeOutCode(a, x2, y2) for outCode1 != 0 || outCode2 != 0 { if outCode1&outCode2 != 0 { return false } if outCode1 != 0 { var x, y int32 if outCode1&codeTop != 0 { y = rectY1 x = x1 + ((x2-x1)*(y-y1))/(y2-y1) } else if outCode1&codeBottom != 0 { y = rectY2 x = x1 + ((x2-x1)*(y-y1))/(y2-y1) } else if outCode1&codeLeft != 0 { x = rectX1 y = y1 + ((y2-y1)*(x-x1))/(x2-x1) } else if outCode1&codeRight != 0 { x = rectX2 y = y1 + ((y2-y1)*(x-x1))/(x2-x1) } x1 = x y1 = y outCode1 = computeOutCode(a, x, y) } else { var x, y int32 if outCode2&codeTop != 0 { y = rectY1 x = x1 + ((x2-x1)*(y-y1))/(y2-y1) } else if outCode2&codeBottom != 0 { y = rectY2 x = x1 + ((x2-x1)*(y-y1))/(y2-y1) } else if outCode2&codeLeft != 0 { x = rectX1 y = y1 + ((y2-y1)*(x-x1))/(x2-x1) } else if outCode2&codeRight != 0 { x = rectX2 y = y1 + ((y2-y1)*(x-x1))/(x2-x1) } x2 = x y2 = y outCode2 = computeOutCode(a, x, y) } } *X1 = x1 *Y1 = y1 *X2 = x2 *Y2 = y2 return true } // IntersectLine calculates the intersection of a rectangle and a line segment. // (https://wiki.libsdl.org/SDL_IntersectFRectAndLine) func (a *FRect) IntersectLine(X1, Y1, X2, Y2 *float32) bool { if a.Empty() { return false } x1 := *X1 y1 := *Y1 x2 := *X2 y2 := *Y2 rectX1 := a.X rectY1 := a.Y rectX2 := a.X + a.W - 1 rectY2 := a.Y + a.H - 1 // Check if the line is entirely inside the rect if x1 >= rectX1 && x1 <= rectX2 && x2 >= rectX1 && x2 <= rectX2 && y1 >= rectY1 && y1 <= rectY2 && y2 >= rectY1 && y2 <= rectY2 { return true } // Check if the line is entirely outside the rect if (x1 < rectX1 && x2 < rectX1) || (x1 > rectX2 && x2 > rectX2) || (y1 < rectY1 && y2 < rectY1) || (y1 > rectY2 && y2 > rectY2) { return false } // Check if the line is horizontal if y1 == y2 { if x1 < rectX1 { *X1 = rectX1 } else if x1 > rectX2 { *X1 = rectX2 } if x2 < rectX1 { *X2 = rectX1 } else if x2 > rectX2 { *X2 = rectX2 } return true } // Check if the line is vertical if x1 == x2 { if y1 < rectY1 { *Y1 = rectY1 } else if y1 > rectY2 { *Y1 = rectY2 } if y2 < rectY1 { *Y2 = rectY1 } else if y2 > rectY2 { *Y2 = rectY2 } return true } // Use Cohen-Sutherland algorithm when all shortcuts fail outCode1 := computeFOutCode(a, x1, y1) outCode2 := computeFOutCode(a, x2, y2) for outCode1 != 0 || outCode2 != 0 { if outCode1&outCode2 != 0 { return false } if outCode1 != 0 { var x, y float32 if outCode1&codeTop != 0 { y = rectY1 x = x1 + ((x2-x1)*(y-y1))/(y2-y1) } else if outCode1&codeBottom != 0 { y = rectY2 x = x1 + ((x2-x1)*(y-y1))/(y2-y1) } else if outCode1&codeLeft != 0 { x = rectX1 y = y1 + ((y2-y1)*(x-x1))/(x2-x1) } else if outCode1&codeRight != 0 { x = rectX2 y = y1 + ((y2-y1)*(x-x1))/(x2-x1) } x1 = x y1 = y outCode1 = computeFOutCode(a, x, y) } else { var x, y float32 if outCode2&codeTop != 0 { y = rectY1 x = x1 + ((x2-x1)*(y-y1))/(y2-y1) } else if outCode2&codeBottom != 0 { y = rectY2 x = x1 + ((x2-x1)*(y-y1))/(y2-y1) } else if outCode2&codeLeft != 0 { x = rectX1 y = y1 + ((y2-y1)*(x-x1))/(x2-x1) } else if outCode2&codeRight != 0 { x = rectX2 y = y1 + ((y2-y1)*(x-x1))/(x2-x1) } x2 = x y2 = y outCode2 = computeFOutCode(a, x, y) } } *X1 = x1 *Y1 = y1 *X2 = x2 *Y2 = y2 return true } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/render.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,1)) #if defined(WARN_OUTDATED) #pragma message("SDL_UpdateYUVTexture is not supported before SDL 2.0.1") #endif static inline int SDL_UpdateYUVTexture(SDL_Texture* texture, const SDL_Rect* rect, const Uint8* Yplane, int Ypitch, const Uint8* Uplane, int Upitch, const Uint8* Vplane, int Vpitch) { return -1; } #endif #if !(SDL_VERSION_ATLEAST(2,0,4)) #if defined(WARN_OUTDATED) #pragma message("SDL_RenderIsClipEnabled is not supported before SDL 2.0.4") #endif static inline SDL_bool SDLCALL SDL_RenderIsClipEnabled(SDL_Renderer * renderer) { return SDL_FALSE; } #endif #if !(SDL_VERSION_ATLEAST(2,0,5)) #if defined(WARN_OUTDATED) #pragma message("SDL_RenderSetIntegerScale is not supported before SDL 2.0.5") #endif static inline int SDL_RenderSetIntegerScale(SDL_Renderer* renderer, SDL_bool enable) { SDL_Unsupported(); return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_RenderGetIntegerScale is not supported before SDL 2.0.5") #endif static inline SDL_bool SDL_RenderGetIntegerScale(SDL_Renderer* renderer) { SDL_Unsupported(); return -1; } #endif #if !(SDL_VERSION_ATLEAST(2,0,8)) #if defined(WARN_OUTDATED) #pragma message("SDL_RenderGetMetalLayer is not supported before SDL 2.0.8") #endif static inline void * SDL_RenderGetMetalLayer(SDL_Renderer *renderer) { return NULL; } #if defined(WARN_OUTDATED) #pragma message("SDL_RenderGetMetalCommandEncoder is not supported before SDL 2.0.8") #endif static inline void * SDL_RenderGetMetalCommandEncoder(SDL_Renderer *renderer) { return NULL; } #endif #if !(SDL_VERSION_ATLEAST(2,0,10)) #if defined(WARN_OUTDATED) #pragma message("SDL_RenderDrawPointF is not supported before SDL 2.0.10") #endif static inline int SDL_RenderDrawPointF(SDL_Renderer * renderer, float x, float y) { return SDL_RenderDrawPoint(renderer, (int) x, (int) y); } #if defined(WARN_OUTDATED) #pragma message("SDL_RenderDrawPointsF is not supported before SDL 2.0.10") #endif static inline int SDL_RenderDrawPointsF(SDL_Renderer * renderer, const SDL_FPoint * points, int count) { return SDL_RenderDrawPoints(renderer, (const SDL_Point *) points, count); } #if defined(WARN_OUTDATED) #pragma message("SDL_RenderDrawLineF is not supported before SDL 2.0.10") #endif static inline int SDL_RenderDrawLineF(SDL_Renderer * renderer, float x1, float y1, float x2, float y2) { return SDL_RenderDrawLine(renderer, (int) x1, (int) y1, (int) x2, (int) y2); } #if defined(WARN_OUTDATED) #pragma message("SDL_RenderDrawLinesF is not supported before SDL 2.0.10") #endif static inline int SDL_RenderDrawLinesF(SDL_Renderer * renderer, const SDL_FPoint * points, int count) { return SDL_RenderDrawLines(renderer, (const SDL_Point *) points, count); } #if defined(WARN_OUTDATED) #pragma message("SDL_RenderDrawRectF is not supported before SDL 2.0.10") #endif static inline int SDL_RenderDrawRectF(SDL_Renderer * renderer, const SDL_FRect * rect) { return SDL_RenderDrawRect(renderer, (const SDL_Rect *) rect); } #if defined(WARN_OUTDATED) #pragma message("SDL_RenderDrawRectsF is not supported before SDL 2.0.10") #endif static inline int SDL_RenderDrawRectsF(SDL_Renderer * renderer, const SDL_FRect *rects, int count) { return SDL_RenderDrawRects(renderer, (const SDL_Rect *) rects, count); } #if defined(WARN_OUTDATED) #pragma message("SDL_RenderFillRectF is not supported before SDL 2.0.10") #endif static inline int SDL_RenderFillRectF(SDL_Renderer * renderer, const SDL_FRect * rect) { return SDL_RenderFillRect(renderer, (const SDL_Rect *) rect); } #if defined(WARN_OUTDATED) #pragma message("SDL_RenderFillRectsF is not supported before SDL 2.0.10") #endif static inline int SDL_RenderFillRectsF(SDL_Renderer * renderer, const SDL_FRect * rects, int count) { return SDL_RenderFillRects(renderer, (const SDL_Rect *) rects, count); } #if defined(WARN_OUTDATED) #pragma message("SDL_RenderCopyF is not supported before SDL 2.0.10") #endif static inline int SDL_RenderCopyF(SDL_Renderer * renderer, SDL_Texture * texture, const SDL_Rect * srcrect, const SDL_FRect * dstrect) { return SDL_RenderCopy(renderer, texture, srcrect, (const SDL_Rect *) dstrect); } #if defined(WARN_OUTDATED) #pragma message("SDL_RenderCopyExF is not supported before SDL 2.0.10") #endif static inline int SDL_RenderCopyExF(SDL_Renderer * renderer, SDL_Texture * texture, const SDL_Rect * srcrect, const SDL_FRect * dstrect, const double angle, const SDL_FPoint * center, const SDL_RendererFlip flip) { return SDL_RenderCopyEx(renderer, texture, srcrect, (const SDL_Rect *) dstrect, angle, (const SDL_Point *) center, flip); } #if defined(WARN_OUTDATED) #pragma message("SDL_RenderFlush is not supported before SDL 2.0.10") #endif static inline int SDL_RenderFlush(SDL_Renderer * renderer) { return 0; } #endif #if !(SDL_VERSION_ATLEAST(2,0,12)) typedef enum { SDL_ScaleModeNearest, SDL_ScaleModeLinear, SDL_ScaleModeBest } SDL_ScaleMode; #if defined(WARN_OUTDATED) #pragma message("SDL_SetTextureScaleMode is not supported before SDL 2.0.12") #pragma message("SDL_GetTextureScaleMode is not supported before SDL 2.0.12") #pragma message("SDL_LockTextureToSurface is not supported before SDL 2.0.12") #endif static int SDL_SetTextureScaleMode(SDL_Texture * texture, SDL_ScaleMode scaleMode) { return -1; } static int SDLCALL SDL_GetTextureScaleMode(SDL_Texture * texture, SDL_ScaleMode *scaleMode) { return -1; } static int SDL_LockTextureToSurface(SDL_Texture *texture, const SDL_Rect *rect, SDL_Surface **surface) { return -1; } #endif #if !(SDL_VERSION_ATLEAST(2,0,16)) #if defined(WARN_OUTDATED) #pragma message("SDL_UpdateNVTexture is not supported before SDL 2.0.16") #endif static int SDL_UpdateNVTexture(SDL_Texture * texture, const SDL_Rect * rect, const Uint8 *Yplane, int Ypitch, const Uint8 *UVplane, int UVpitch) { return -1; } #endif #if !(SDL_VERSION_ATLEAST(2,0,18)) #if defined(WARN_OUTDATED) #pragma message("SDL_RenderGeometry is not supported before SDL 2.0.18") #pragma message("SDL_RenderGeometryRaw is not supported before SDL 2.0.18") #pragma message("SDL_SetTextureUserData is not supported before SDL 2.0.18") #pragma message("SDL_GetTextureUserData is not supported before SDL 2.0.18") #pragma message("SDL_RenderWindowToLogical is not supported before SDL 2.0.18") #pragma message("SDL_RenderLogicalToWindow is not supported before SDL 2.0.18") #pragma message("SDL_RenderSetVSync is not supported before SDL 2.0.18") #endif // Vertex structure typedef struct SDL_Vertex { SDL_FPoint position; // Vertex position, in SDL_Renderer coordinates SDL_Color color; // Vertex color SDL_FPoint tex_coord; // Normalized texture coordinates, if needed } SDL_Vertex; static int SDL_RenderGeometry(SDL_Renderer *renderer, SDL_Texture *texture, const SDL_Vertex *vertices, int num_vertices, const int *indices, int num_indices) { return -1; } static int SDL_RenderGeometryRaw(SDL_Renderer *renderer, SDL_Texture *texture, const float *xy, int xy_stride, const SDL_Color *color, int color_stride, const float *uv, int uv_stride, int num_vertices, const void *indices, int num_indices, int size_indices) { return -1; } static int SDL_SetTextureUserData(SDL_Texture * texture, void *userdata) { return -1; } static void * SDLCALL SDL_GetTextureUserData(SDL_Texture * texture) { return NULL; } static void SDL_RenderWindowToLogical(SDL_Renderer * renderer, int windowX, int windowY, float *logicalX, float *logicalY) { } static void SDL_RenderLogicalToWindow(SDL_Renderer * renderer, float logicalX, float logicalY, int *windowX, int *windowY) { } static int SDL_RenderSetVSync(SDL_Renderer* renderer, int vsync) { return -1; } #endif #if SDL_COMPILEDVERSION == SDL_VERSIONNUM(2,0,18) static inline int RenderGeometryRaw(SDL_Renderer *renderer, SDL_Texture *texture, const float *xy, int xy_stride, const SDL_Color *color, int color_stride, const float *uv, int uv_stride, int num_vertices, const void *indices, int num_indices, int size_indices) { return SDL_RenderGeometryRaw(renderer, texture, xy, xy_stride, (int*) color, color_stride, uv, uv_stride, num_vertices, indices, num_indices, size_indices); } #else static inline int RenderGeometryRaw(SDL_Renderer *renderer, SDL_Texture *texture, const float *xy, int xy_stride, const SDL_Color *color, int color_stride, const float *uv, int uv_stride, int num_vertices, const void *indices, int num_indices, int size_indices) { return SDL_RenderGeometryRaw(renderer, texture, xy, xy_stride, color, color_stride, uv, uv_stride, num_vertices, indices, num_indices, size_indices); } #endif #if !(SDL_VERSION_ATLEAST(2,0,22)) #if defined(WARN_OUTDATED) #pragma message("SDL_RenderGetWindow is not supported before SDL 2.0.22") #endif static inline SDL_Window * SDLCALL SDL_RenderGetWindow(SDL_Renderer *renderer) { return NULL; } #endif // WORKAROUND: This prevents audio from seemingly going corrupt when drawing outside the screen bounding box? // It does that by allocating SDL_Rect in the C context instead of Go context. static inline int RenderCopy(SDL_Renderer *renderer, SDL_Texture *texture, SDL_Rect *src, int dst_x, int dst_y, int dst_w, int dst_h) { SDL_Rect dst = {dst_x, dst_y, dst_w, dst_h}; return SDL_RenderCopy(renderer, texture, src, &dst); } */ import "C" import ( "reflect" "unsafe" ) // An enumeration of flags used when creating a rendering context. // (https://wiki.libsdl.org/SDL_RendererFlags) const ( RENDERER_SOFTWARE = C.SDL_RENDERER_SOFTWARE // the renderer is a software fallback RENDERER_ACCELERATED = C.SDL_RENDERER_ACCELERATED // the renderer uses hardware acceleration RENDERER_PRESENTVSYNC = C.SDL_RENDERER_PRESENTVSYNC // present is synchronized with the refresh rate RENDERER_TARGETTEXTURE = C.SDL_RENDERER_TARGETTEXTURE // the renderer supports rendering to texture ) type ScaleMode C.SDL_ScaleMode // The scaling mode for a texture. const ( ScaleModeNearest ScaleMode = C.SDL_ScaleModeNearest // nearest pixel sampling ScaleModeLinear = C.SDL_ScaleModeLinear // linear filtering ScaleModeBest = C.SDL_ScaleModeBest // anisotropic filtering ) // An enumeration of texture access patterns.. // (https://wiki.libsdl.org/SDL_TextureAccess) const ( TEXTUREACCESS_STATIC = C.SDL_TEXTUREACCESS_STATIC // changes rarely, not lockable TEXTUREACCESS_STREAMING = C.SDL_TEXTUREACCESS_STREAMING // changes frequently, lockable TEXTUREACCESS_TARGET = C.SDL_TEXTUREACCESS_TARGET // can be used as a render target ) // An enumeration of the texture channel modulation used in Renderer.Copy(). // (https://wiki.libsdl.org/SDL_TextureModulate) const ( TEXTUREMODULATE_NONE = C.SDL_TEXTUREMODULATE_NONE // no modulation TEXTUREMODULATE_COLOR = C.SDL_TEXTUREMODULATE_COLOR // srcC = srcC * color TEXTUREMODULATE_ALPHA = C.SDL_TEXTUREMODULATE_ALPHA // srcA = srcA * alpha ) // An enumeration of flags that can be used in the flip parameter for Renderer.CopyEx(). // (https://wiki.libsdl.org/SDL_RendererFlip) const ( FLIP_NONE RendererFlip = C.SDL_FLIP_NONE // do not flip FLIP_HORIZONTAL = C.SDL_FLIP_HORIZONTAL // flip horizontally FLIP_VERTICAL = C.SDL_FLIP_VERTICAL // flip vertically ) // RendererInfo contains information on the capabilities of a render driver or the current render context. // (https://wiki.libsdl.org/SDL_RendererInfo) type RendererInfo struct { Name string // the name of the renderer RendererInfoData } type cRendererInfo struct { Name *C.char RendererInfoData } // RendererInfoData contains information on the capabilities of a render driver or the current render context. // (https://wiki.libsdl.org/SDL_RendererInfo) type RendererInfoData struct { Flags uint32 // a mask of supported renderer flags NumTextureFormats uint32 // the number of available texture formats TextureFormats [16]int32 // the available texture formats MaxTextureWidth int32 // the maximum texture width MaxTextureHeight int32 // the maximum texture height } func (info *RendererInfo) cptr() *C.SDL_RendererInfo { return (*C.SDL_RendererInfo)(unsafe.Pointer(info)) } func (info *cRendererInfo) cptr() *C.SDL_RendererInfo { return (*C.SDL_RendererInfo)(unsafe.Pointer(info)) } // RendererFlip is an enumeration of flags that can be used in the flip parameter for Renderer.CopyEx(). // (https://wiki.libsdl.org/SDL_RendererFlip) type RendererFlip uint32 type cRendererFlip C.SDL_RendererFlip // Vertex structure type Vertex struct { Position FPoint // Vertex position, in SDL_Renderer coordinates Color Color // Vertex color TexCoord FPoint // Normalized texture coordinates, if needed } func (flip RendererFlip) c() C.SDL_RendererFlip { return C.SDL_RendererFlip(flip) } // GetNumRenderDrivers returns the number of 2D rendering drivers available for the current display. // (https://wiki.libsdl.org/SDL_GetNumRenderDrivers) func GetNumRenderDrivers() (int, error) { i := int(C.SDL_GetNumRenderDrivers()) return i, errorFromInt(i) } // GetRenderDriverInfo returns information about a specific 2D rendering driver for the current display. // (https://wiki.libsdl.org/SDL_GetRenderDriverInfo) func GetRenderDriverInfo(index int, info *RendererInfo) (int, error) { var cinfo cRendererInfo ret := int(C.SDL_GetRenderDriverInfo(C.int(index), cinfo.cptr())) if ret < 0 { return ret, GetError() } info.RendererInfoData = cinfo.RendererInfoData // No need to free, it's done by DestroyRenderer info.Name = C.GoString(cinfo.Name) return ret, nil } // CreateWindowAndRenderer returns a new window and default renderer. // (https://wiki.libsdl.org/SDL_CreateWindowAndRenderer) func CreateWindowAndRenderer(w, h int32, flags uint32) (*Window, *Renderer, error) { var window *C.SDL_Window var renderer *C.SDL_Renderer ret := C.SDL_CreateWindowAndRenderer( C.int(w), C.int(h), C.Uint32(flags), &window, &renderer) if ret == -1 { return nil, nil, GetError() } return (*Window)(unsafe.Pointer(window)), (*Renderer)(unsafe.Pointer(renderer)), nil } // CreateRenderer returns a new 2D rendering context for a window. // (https://wiki.libsdl.org/SDL_CreateRenderer) func CreateRenderer(window *Window, index int, flags uint32) (*Renderer, error) { renderer := C.SDL_CreateRenderer(window.cptr(), C.int(index), C.Uint32(flags)) if renderer == nil { return nil, GetError() } return (*Renderer)(unsafe.Pointer(renderer)), nil } // CreateSoftwareRenderer returns a new 2D software rendering context for a surface. // (https://wiki.libsdl.org/SDL_CreateSoftwareRenderer) func CreateSoftwareRenderer(surface *Surface) (*Renderer, error) { renderer := C.SDL_CreateSoftwareRenderer(surface.cptr()) if renderer == nil { return nil, GetError() } return (*Renderer)(unsafe.Pointer(renderer)), nil } // GetRenderer returns the renderer associated with a window. // (https://wiki.libsdl.org/SDL_GetRenderer) func (window *Window) GetRenderer() (*Renderer, error) { renderer := C.SDL_GetRenderer(window.cptr()) if renderer == nil { return nil, GetError() } return (*Renderer)(unsafe.Pointer(renderer)), nil } // GetInfo returns information about a rendering context. // (https://wiki.libsdl.org/SDL_GetRendererInfo) func (renderer *Renderer) GetInfo() (RendererInfo, error) { var cinfo cRendererInfo var info RendererInfo ret := int(C.SDL_GetRendererInfo(renderer.cptr(), cinfo.cptr())) if ret < 0 { return info, GetError() } info.RendererInfoData = cinfo.RendererInfoData // No need to free, it's done by DestroyRenderer info.Name = C.GoString(cinfo.Name) return info, nil } // GetOutputSize returns the output size in pixels of a rendering context. // (https://wiki.libsdl.org/SDL_GetRendererOutputSize) func (renderer *Renderer) GetOutputSize() (w, h int32, err error) { ret := C.SDL_GetRendererOutputSize( renderer.cptr(), (*C.int)(unsafe.Pointer(&w)), (*C.int)(unsafe.Pointer(&h))) err = errorFromInt(int(ret)) return } // CreateTexture returns a new texture for a rendering context. // (https://wiki.libsdl.org/SDL_CreateTexture) func (renderer *Renderer) CreateTexture(format uint32, access int, w, h int32) (*Texture, error) { texture := C.SDL_CreateTexture( renderer.cptr(), C.Uint32(format), C.int(access), C.int(w), C.int(h)) if texture == nil { return nil, GetError() } return (*Texture)(unsafe.Pointer(texture)), nil } // CreateTextureFromSurface returns a new texture from an existing surface. // (https://wiki.libsdl.org/SDL_CreateTextureFromSurface) func (renderer *Renderer) CreateTextureFromSurface(surface *Surface) (*Texture, error) { texture := C.SDL_CreateTextureFromSurface(renderer.cptr(), surface.cptr()) if texture == nil { return nil, GetError() } return (*Texture)(unsafe.Pointer(texture)), nil } // Query returns the attributes of a texture. // (https://wiki.libsdl.org/SDL_QueryTexture) func (texture *Texture) Query() (format uint32, access int, width int32, height int32, err error) { var _format C.Uint32 var _access C.int var _width C.int var _height C.int ret := int(C.SDL_QueryTexture(texture.cptr(), &_format, &_access, &_width, &_height)) format = uint32(_format) access = int(_access) width = int32(_width) height = int32(_height) err = errorFromInt(ret) return } // SetColorMod sets an additional color value multiplied into render copy operations. // (https://wiki.libsdl.org/SDL_SetTextureColorMod) func (texture *Texture) SetColorMod(r uint8, g uint8, b uint8) error { return errorFromInt(int( C.SDL_SetTextureColorMod( texture.cptr(), C.Uint8(r), C.Uint8(g), C.Uint8(b)))) } // SetAlphaMod sets an additional alpha value multiplied into render copy operations. // (https://wiki.libsdl.org/SDL_SetTextureAlphaMod) func (texture *Texture) SetAlphaMod(alpha uint8) error { return errorFromInt(int( C.SDL_SetTextureAlphaMod(texture.cptr(), C.Uint8(alpha)))) } // GetAlphaMod returns the additional alpha value multiplied into render copy operations. // (https://wiki.libsdl.org/SDL_GetTextureAlphaMod) func (texture *Texture) GetAlphaMod() (alpha uint8, err error) { ret := C.SDL_GetTextureAlphaMod(texture.cptr(), (*C.Uint8)(unsafe.Pointer(&alpha))) return alpha, errorFromInt(int(ret)) } // SetBlendMode sets the blend mode for a texture, used by Renderer.Copy(). // (https://wiki.libsdl.org/SDL_SetTextureBlendMode) func (texture *Texture) SetBlendMode(bm BlendMode) error { return errorFromInt(int( C.SDL_SetTextureBlendMode(texture.cptr(), bm.c()))) } // GetBlendMode returns the blend mode used for texture copy operations. // (https://wiki.libsdl.org/SDL_GetTextureBlendMode) func (texture *Texture) GetBlendMode() (bm BlendMode, err error) { ret := C.SDL_GetTextureBlendMode(texture.cptr(), bm.cptr()) return bm, errorFromInt(int(ret)) } // Update updates the given texture rectangle with new pixel data. // (https://wiki.libsdl.org/SDL_UpdateTexture) func (texture *Texture) Update(rect *Rect, pixels unsafe.Pointer, pitch int) error { if pixels == nil { return nil } return errorFromInt(int( C.SDL_UpdateTexture( texture.cptr(), rect.cptr(), pixels, C.int(pitch)))) } // UpdateRGBA updates the given texture rectangle with new uint32 pixel data. // (https://wiki.libsdl.org/SDL_UpdateTexture) func (texture *Texture) UpdateRGBA(rect *Rect, pixels []uint32, pitch int) error { if pixels == nil { return nil } return errorFromInt(int( C.SDL_UpdateTexture( texture.cptr(), rect.cptr(), unsafe.Pointer(&pixels[0]), C.int(4*pitch)))) // 4 bytes in one uint32 } // UpdateYUV updates a rectangle within a planar YV12 or IYUV texture with new pixel data. // (https://wiki.libsdl.org/SDL_UpdateYUVTexture) func (texture *Texture) UpdateYUV(rect *Rect, yPlane []byte, yPitch int, uPlane []byte, uPitch int, vPlane []byte, vPitch int) error { var yPlanePtr, uPlanePtr, vPlanePtr *byte if yPlane != nil { yPlanePtr = &yPlane[0] } if uPlane != nil { uPlanePtr = &uPlane[0] } if vPlane != nil { vPlanePtr = &vPlane[0] } return errorFromInt(int( C.SDL_UpdateYUVTexture( texture.cptr(), rect.cptr(), (*C.Uint8)(unsafe.Pointer(yPlanePtr)), C.int(yPitch), (*C.Uint8)(unsafe.Pointer(uPlanePtr)), C.int(uPitch), (*C.Uint8)(unsafe.Pointer(vPlanePtr)), C.int(vPitch)))) } // Lock locks a portion of the texture for write-only pixel access. // (https://wiki.libsdl.org/SDL_LockTexture) func (texture *Texture) Lock(rect *Rect) ([]byte, int, error) { var _pitch C.int var _pixels unsafe.Pointer var b []byte var length int ret := C.SDL_LockTexture(texture.cptr(), rect.cptr(), &_pixels, &_pitch) if ret < 0 { return b, int(_pitch), GetError() } _, _, w, h, err := texture.Query() if err != nil { return b, int(_pitch), GetError() } pitch := int32(_pitch) if rect != nil { bytesPerPixel := pitch / w length = int(bytesPerPixel * (w*rect.H - rect.X - (w - rect.X - rect.W))) } else { length = int(pitch * h) } sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b)) sliceHeader.Cap = int(length) sliceHeader.Len = int(length) sliceHeader.Data = uintptr(_pixels) return b, int(pitch), nil } // Unlock unlocks a texture, uploading the changes to video memory, if needed. // (https://wiki.libsdl.org/SDL_UnlockTexture) func (texture *Texture) Unlock() { C.SDL_UnlockTexture(texture.cptr()) } // RenderTargetSupported reports whether a window supports the use of render targets. // (https://wiki.libsdl.org/SDL_RenderTargetSupported) func (renderer *Renderer) RenderTargetSupported() bool { return C.SDL_RenderTargetSupported(renderer.cptr()) != 0 } // SetRenderTarget sets a texture as the current rendering target. // (https://wiki.libsdl.org/SDL_SetRenderTarget) func (renderer *Renderer) SetRenderTarget(texture *Texture) error { return errorFromInt(int( C.SDL_SetRenderTarget(renderer.cptr(), texture.cptr()))) } // GetRenderTarget returns the current render target. // (https://wiki.libsdl.org/SDL_GetRenderTarget) func (renderer *Renderer) GetRenderTarget() *Texture { return (*Texture)(unsafe.Pointer(C.SDL_GetRenderTarget(renderer.cptr()))) } // SetLogicalSize sets a device independent resolution for rendering. // (https://wiki.libsdl.org/SDL_RenderSetLogicalSize) func (renderer *Renderer) SetLogicalSize(w, h int32) error { return errorFromInt(int( C.SDL_RenderSetLogicalSize(renderer.cptr(), C.int(w), C.int(h)))) } // GetLogicalSize returns device independent resolution for rendering. // (https://wiki.libsdl.org/SDL_RenderGetLogicalSize) func (renderer *Renderer) GetLogicalSize() (w, h int32) { C.SDL_RenderGetLogicalSize( renderer.cptr(), (*C.int)(unsafe.Pointer(&w)), (*C.int)(unsafe.Pointer(&h))) return } // SetViewport sets the drawing area for rendering on the current target. // (https://wiki.libsdl.org/SDL_RenderSetViewport) func (renderer *Renderer) SetViewport(rect *Rect) error { return errorFromInt(int( C.SDL_RenderSetViewport(renderer.cptr(), rect.cptr()))) } // GetViewport returns the drawing area for the current target. // (https://wiki.libsdl.org/SDL_RenderGetViewport) func (renderer *Renderer) GetViewport() (rect Rect) { C.SDL_RenderGetViewport(renderer.cptr(), rect.cptr()) return } // IsClipEnabled returns whether clipping is enabled on the given renderer. // (https://wiki.libsdl.org/SDL_RenderIsClipEnabled) func (renderer *Renderer) IsClipEnabled() bool { return C.SDL_RenderIsClipEnabled(renderer.cptr()) == C.SDL_TRUE } // SetClipRect sets the clip rectangle for rendering on the specified target. // (https://wiki.libsdl.org/SDL_RenderSetClipRect) func (renderer *Renderer) SetClipRect(rect *Rect) error { return errorFromInt(int( C.SDL_RenderSetClipRect(renderer.cptr(), rect.cptr()))) } // GetClipRect returns the clip rectangle for the current target. // (https://wiki.libsdl.org/SDL_RenderGetClipRect) func (renderer *Renderer) GetClipRect() (rect Rect) { C.SDL_RenderGetClipRect(renderer.cptr(), rect.cptr()) return } // SetScale sets the drawing scale for rendering on the current target. // (https://wiki.libsdl.org/SDL_RenderSetScale) func (renderer *Renderer) SetScale(scaleX, scaleY float32) error { return errorFromInt(int( C.SDL_RenderSetScale( renderer.cptr(), C.float(scaleX), C.float(scaleY)))) } // GetScale returns the drawing scale for the current target. // (https://wiki.libsdl.org/SDL_RenderGetScale) func (renderer *Renderer) GetScale() (scaleX, scaleY float32) { C.SDL_RenderGetScale( renderer.cptr(), (*C.float)(unsafe.Pointer(&scaleX)), (*C.float)(unsafe.Pointer(&scaleY))) return } // SetIntegerScale sets whether to force integer scales for // resolution-independent rendering. // // This function restricts the logical viewport to integer values - that is, // when a resolution is between two multiples of a logical size, the viewport // size is rounded down to the lower multiple. // // (https://wiki.libsdl.org/SDL_RenderSetIntegerScale) func (renderer *Renderer) SetIntegerScale(v bool) error { var cv C.SDL_bool = C.SDL_FALSE if v { cv = C.SDL_TRUE } return errorFromInt(int(C.SDL_RenderSetIntegerScale(renderer.cptr(), cv))) } // GetIntegerScale reports whether integer scales are forced for // resolution-independent rendering. // // (https://wiki.libsdl.org/SDL_RenderGetIntegerScale) func (renderer *Renderer) GetIntegerScale() (bool, error) { ClearError() if C.SDL_RenderGetIntegerScale(renderer.cptr()) == C.SDL_TRUE { return true, nil } return false, GetError() } // SetDrawColor sets the color used for drawing operations (Rect, Line and Clear). // (https://wiki.libsdl.org/SDL_SetRenderDrawColor) func (renderer *Renderer) SetDrawColor(r, g, b, a uint8) error { return errorFromInt(int( C.SDL_SetRenderDrawColor( renderer.cptr(), C.Uint8(r), C.Uint8(g), C.Uint8(b), C.Uint8(a)))) } // SetDrawColorArray is a custom variant of SetDrawColor. func (renderer *Renderer) SetDrawColorArray(bs ...uint8) error { _bs := []C.Uint8{0, 0, 0, 255} for i := 0; i < len(_bs) && i < len(bs); i++ { _bs[i] = C.Uint8(bs[i]) } return errorFromInt(int( C.SDL_SetRenderDrawColor( renderer.cptr(), _bs[0], _bs[1], _bs[2], _bs[3]))) } // GetDrawColor returns the color used for drawing operations (Rect, Line and Clear). // (https://wiki.libsdl.org/SDL_GetRenderDrawColor) func (renderer *Renderer) GetDrawColor() (r, g, b, a uint8, err error) { ret := C.SDL_GetRenderDrawColor( renderer.cptr(), (*C.Uint8)(unsafe.Pointer(&r)), (*C.Uint8)(unsafe.Pointer(&g)), (*C.Uint8)(unsafe.Pointer(&b)), (*C.Uint8)(unsafe.Pointer(&a))) return r, g, b, a, errorFromInt(int(ret)) } // SetDrawBlendMode sets the blend mode used for drawing operations (Fill and Line). // (https://wiki.libsdl.org/SDL_SetRenderDrawBlendMode) func (renderer *Renderer) SetDrawBlendMode(bm BlendMode) error { return errorFromInt(int( C.SDL_SetRenderDrawBlendMode(renderer.cptr(), bm.c()))) } // GetDrawBlendMode returns the blend mode used for drawing operations. // (https://wiki.libsdl.org/SDL_GetRenderDrawBlendMode) func (renderer *Renderer) GetDrawBlendMode(bm *BlendMode) error { return errorFromInt(int( C.SDL_GetRenderDrawBlendMode(renderer.cptr(), bm.cptr()))) } // Clear clears the current rendering target with the drawing color. // (https://wiki.libsdl.org/SDL_RenderClear) func (renderer *Renderer) Clear() error { return errorFromInt(int( C.SDL_RenderClear(renderer.cptr()))) } // DrawPoint draws a point on the current rendering target. // (https://wiki.libsdl.org/SDL_RenderDrawPoint) func (renderer *Renderer) DrawPoint(x, y int32) error { return errorFromInt(int( C.SDL_RenderDrawPoint(renderer.cptr(), C.int(x), C.int(y)))) } // DrawPoints draws multiple points on the current rendering target. // (https://wiki.libsdl.org/SDL_RenderDrawPoints) func (renderer *Renderer) DrawPoints(points []Point) error { return errorFromInt(int( C.SDL_RenderDrawPoints( renderer.cptr(), points[0].cptr(), C.int(len(points))))) } // DrawLine draws a line on the current rendering target. // (https://wiki.libsdl.org/SDL_RenderDrawLine) func (renderer *Renderer) DrawLine(x1, y1, x2, y2 int32) error { return errorFromInt(int( C.SDL_RenderDrawLine( renderer.cptr(), C.int(x1), C.int(y1), C.int(x2), C.int(y2)))) } // DrawLines draws a series of connected lines on the current rendering target. // (https://wiki.libsdl.org/SDL_RenderDrawLines) func (renderer *Renderer) DrawLines(points []Point) error { return errorFromInt(int( C.SDL_RenderDrawLines( renderer.cptr(), points[0].cptr(), C.int(len(points))))) } // DrawRect draws a rectangle on the current rendering target. // (https://wiki.libsdl.org/SDL_RenderDrawRect) func (renderer *Renderer) DrawRect(rect *Rect) error { return errorFromInt(int( C.SDL_RenderDrawRect(renderer.cptr(), rect.cptr()))) } // DrawRects draws some number of rectangles on the current rendering target. // (https://wiki.libsdl.org/SDL_RenderDrawRects) func (renderer *Renderer) DrawRects(rects []Rect) error { return errorFromInt(int( C.SDL_RenderDrawRects( renderer.cptr(), rects[0].cptr(), C.int(len(rects))))) } // FillRect fills a rectangle on the current rendering target with the drawing color. // (https://wiki.libsdl.org/SDL_RenderFillRect) func (renderer *Renderer) FillRect(rect *Rect) error { return errorFromInt(int( C.SDL_RenderFillRect(renderer.cptr(), rect.cptr()))) } // FillRects fills some number of rectangles on the current rendering target with the drawing color. // (https://wiki.libsdl.org/SDL_RenderFillRects) func (renderer *Renderer) FillRects(rects []Rect) error { return errorFromInt(int( C.SDL_RenderFillRects( renderer.cptr(), rects[0].cptr(), C.int(len(rects))))) } // Copy copies a portion of the texture to the current rendering target. // (https://wiki.libsdl.org/SDL_RenderCopy) func (renderer *Renderer) Copy(texture *Texture, src, dst *Rect) error { if dst == nil { return errorFromInt(int( C.SDL_RenderCopy( renderer.cptr(), texture.cptr(), src.cptr(), dst.cptr()))) } return errorFromInt(int( C.RenderCopy( renderer.cptr(), texture.cptr(), src.cptr(), C.int(dst.X), C.int(dst.Y), C.int(dst.W), C.int(dst.H)))) } // CopyEx copies a portion of the texture to the current rendering target, optionally rotating it by angle around the given center and also flipping it top-bottom and/or left-right. // (https://wiki.libsdl.org/SDL_RenderCopyEx) func (renderer *Renderer) CopyEx(texture *Texture, src, dst *Rect, angle float64, center *Point, flip RendererFlip) error { return errorFromInt(int( C.SDL_RenderCopyEx( renderer.cptr(), texture.cptr(), src.cptr(), dst.cptr(), C.double(angle), center.cptr(), flip.c()))) } // DrawPointF draws a point on the current rendering target. // TODO: (https://wiki.libsdl.org/SDL_RenderDrawPointF) func (renderer *Renderer) DrawPointF(x, y float32) error { return errorFromInt(int( C.SDL_RenderDrawPointF(renderer.cptr(), C.float(x), C.float(y)))) } // DrawPointsF draws multiple points on the current rendering target. // TODO: (https://wiki.libsdl.org/SDL_RenderDrawPointsF) func (renderer *Renderer) DrawPointsF(points []FPoint) error { return errorFromInt(int( C.SDL_RenderDrawPointsF( renderer.cptr(), points[0].cptr(), C.int(len(points))))) } // DrawLineF draws a line on the current rendering target. // TODO: (https://wiki.libsdl.org/SDL_RenderDrawLineF) func (renderer *Renderer) DrawLineF(x1, y1, x2, y2 float32) error { return errorFromInt(int( C.SDL_RenderDrawLineF( renderer.cptr(), C.float(x1), C.float(y1), C.float(x2), C.float(y2)))) } // DrawLinesF draws a series of connected lines on the current rendering target. // TODO: (https://wiki.libsdl.org/SDL_RenderDrawLinesF) func (renderer *Renderer) DrawLinesF(points []FPoint) error { return errorFromInt(int( C.SDL_RenderDrawLinesF( renderer.cptr(), points[0].cptr(), C.int(len(points))))) } // DrawRectF draws a rectangle on the current rendering target. // TODO: (https://wiki.libsdl.org/SDL_RenderDrawRectF) func (renderer *Renderer) DrawRectF(rect *FRect) error { return errorFromInt(int( C.SDL_RenderDrawRectF(renderer.cptr(), rect.cptr()))) } // DrawRectsF draws some number of rectangles on the current rendering target. // TODO: (https://wiki.libsdl.org/SDL_RenderDrawRectsF) func (renderer *Renderer) DrawRectsF(rects []FRect) error { return errorFromInt(int( C.SDL_RenderDrawRectsF( renderer.cptr(), rects[0].cptr(), C.int(len(rects))))) } // FillRectF fills a rectangle on the current rendering target with the drawing color. // TODO: (https://wiki.libsdl.org/SDL_RenderFillRectF) func (renderer *Renderer) FillRectF(rect *FRect) error { return errorFromInt(int( C.SDL_RenderFillRectF(renderer.cptr(), rect.cptr()))) } // FillRectsF fills some number of rectangles on the current rendering target with the drawing color. // TODO: (https://wiki.libsdl.org/SDL_RenderFillRectsF) func (renderer *Renderer) FillRectsF(rects []FRect) error { return errorFromInt(int( C.SDL_RenderFillRectsF( renderer.cptr(), rects[0].cptr(), C.int(len(rects))))) } // CopyF copies a portion of the texture to the current rendering target. // TODO: (https://wiki.libsdl.org/SDL_RenderCopyF) func (renderer *Renderer) CopyF(texture *Texture, src *Rect, dst *FRect) error { return errorFromInt(int( C.SDL_RenderCopyF( renderer.cptr(), texture.cptr(), src.cptr(), dst.cptr()))) } // CopyExF copies a portion of the texture to the current rendering target, optionally rotating it by angle around the given center and also flipping it top-bottom and/or left-right. // TODO: (https://wiki.libsdl.org/SDL_RenderCopyExF) func (renderer *Renderer) CopyExF(texture *Texture, src *Rect, dst *FRect, angle float64, center *FPoint, flip RendererFlip) error { return errorFromInt(int( C.SDL_RenderCopyExF( renderer.cptr(), texture.cptr(), src.cptr(), dst.cptr(), C.double(angle), center.cptr(), flip.c()))) } // ReadPixels reads pixels from the current rendering target. // (https://wiki.libsdl.org/SDL_RenderReadPixels) func (renderer *Renderer) ReadPixels(rect *Rect, format uint32, pixels unsafe.Pointer, pitch int) error { return errorFromInt(int( C.SDL_RenderReadPixels( renderer.cptr(), rect.cptr(), C.Uint32(format), pixels, C.int(pitch)))) } // Present updates the screen with any rendering performed since the previous call. // (https://wiki.libsdl.org/SDL_RenderPresent) func (renderer *Renderer) Present() { C.SDL_RenderPresent(renderer.cptr()) } // Destroy destroys the specified texture. // (https://wiki.libsdl.org/SDL_DestroyTexture) func (texture *Texture) Destroy() error { lastErr := GetError() ClearError() C.SDL_DestroyTexture(texture.cptr()) err := GetError() if err != nil { return err } SetError(lastErr) return nil } // Destroy destroys the rendering context for a window and free associated textures. // (https://wiki.libsdl.org/SDL_DestroyRenderer) func (renderer *Renderer) Destroy() error { lastErr := GetError() ClearError() C.SDL_DestroyRenderer(renderer.cptr()) err := GetError() if err != nil { return err } SetError(lastErr) return nil } // Flush forces the rendering context to flush any pending commands to the underlying rendering API. // TODO: (https://wiki.libsdl.org/SDL_RenderFlush) func (renderer *Renderer) Flush() error { return errorFromInt(int(C.SDL_RenderFlush(renderer.cptr()))) } // GLBind binds an OpenGL/ES/ES2 texture to the current context for use with OpenGL instructions when rendering OpenGL primitives directly. // (https://wiki.libsdl.org/SDL_GL_BindTexture) func (texture *Texture) GLBind(texw, texh *float32) error { return errorFromInt(int( C.SDL_GL_BindTexture( texture.cptr(), (*C.float)(unsafe.Pointer(texw)), (*C.float)(unsafe.Pointer(texh))))) } // GLUnbind unbinds an OpenGL/ES/ES2 texture from the current context. // (https://wiki.libsdl.org/SDL_GL_UnbindTexture) func (texture *Texture) GLUnbind() error { return errorFromInt(int( C.SDL_GL_UnbindTexture(texture.cptr()))) } // GetMetalLayer gets the CAMetalLayer associated with the given Metal renderer // (https://wiki.libsdl.org/SDL_RenderGetMetalLayer) func (renderer *Renderer) GetMetalLayer() (layer unsafe.Pointer, err error) { layer = C.SDL_RenderGetMetalLayer(renderer.cptr()) if layer == nil { err = GetError() } return } // GetMetalCommandEncoder gets the Metal command encoder for the current frame // (https://wiki.libsdl.org/SDL_RenderGetMetalCommandEncoder) func (renderer *Renderer) GetMetalCommandEncoder() (encoder unsafe.Pointer, err error) { encoder = C.SDL_RenderGetMetalCommandEncoder(renderer.cptr()) if encoder == nil { err = GetError() } return } // UpdateNV updates a rectangle within a planar NV12 or NV21 texture with new pixels. // (https://wiki.libsdl.org/SDL_UpdateNVTexture) func (texture *Texture) UpdateNV(rect *Rect, yPlane []byte, yPitch int, uvPlane []byte, uvPitch int) error { var yPlanePtr, uvPlanePtr *byte if yPlane != nil { yPlanePtr = &yPlane[0] } if uvPlane != nil { uvPlanePtr = &uvPlane[0] } return errorFromInt(int( C.SDL_UpdateNVTexture( texture.cptr(), rect.cptr(), (*C.Uint8)(unsafe.Pointer(yPlanePtr)), C.int(yPitch), (*C.Uint8)(unsafe.Pointer(uvPlanePtr)), C.int(uvPitch)))) } // RenderGeometry renders a list of triangles, optionally using a texture and // indices into the vertex array Color and alpha modulation is done per vertex // (SDL_SetTextureColorMod and SDL_SetTextureAlphaMod are ignored). // (https://wiki.libsdl.org/SDL_RenderGeometry) func (renderer *Renderer) RenderGeometry(texture *Texture, vertices []Vertex, indices []int32) (err error) { _texture := texture.cptr() _vertices := (*C.SDL_Vertex)(unsafe.Pointer(&vertices[0])) _num_vertices := C.int(len(vertices)) var _indices *C.int _num_indices := C.int(0) if indices != nil { _indices = (*C.int)(unsafe.Pointer(&indices[0])) _num_indices = C.int(len(indices)) } err = errorFromInt(int(C.SDL_RenderGeometry(renderer.cptr(), _texture, _vertices, _num_vertices, _indices, _num_indices))) return } // RenderGeomtryRaw renders a list of triangles, optionally using a texture and // indices into the vertex arrays Color and alpha modulation is done per vertex // (SDL_SetTextureColorMod and SDL_SetTextureAlphaMod are ignored). // (https://wiki.libsdl.org/SDL_RenderGeometryRaw) func (renderer *Renderer) RenderGeometryRaw(texture *Texture, xy *float32, xy_stride int, color *Color, color_stride int, uv *float32, uv_stride int, num_vertices int, indices unsafe.Pointer, num_indices int, size_indices int) (err error) { _texture := texture.cptr() _xy := (*C.float)(xy) _xy_stride := C.int(xy_stride) _color := (*C.SDL_Color)(unsafe.Pointer(color)) _color_stride := C.int(color_stride) _uv := (*C.float)(uv) _uv_stride := C.int(uv_stride) _num_vertices := C.int(num_vertices) _num_indices := C.int(num_indices) _size_indices := C.int(size_indices) _indices := indices err = errorFromInt(int(C.RenderGeometryRaw(renderer.cptr(), _texture, _xy, _xy_stride, _color, _color_stride, _uv, _uv_stride, _num_vertices, _indices, _num_indices, _size_indices))) return } // SetTextureUserData associates a user-specified pointer with a texture. // (https://wiki.libsdl.org/SDL_SetTextureUserData) func (texture *Texture) SetTextureUserData(userdata unsafe.Pointer) (err error) { err = errorFromInt(int(C.SDL_SetTextureUserData(texture.cptr(), userdata))) return } // GetTextureUserData gets the user-specified pointer associated with a texture. // (https://wiki.libsdl.org/SDL_GetTextureUserData) func (texture *Texture) GetTextureUserData() (userdata unsafe.Pointer) { userdata = C.SDL_GetTextureUserData(texture.cptr()) return } // RenderWindowToLogical gets logical coordinates of point in renderer when given real coordinates of // point in window. // // Logical coordinates will differ from real coordinates when render is scaled // and logical renderer size set // // (https://wiki.libsdl.org/SDL_RenderWindowToLogical) func (renderer *Renderer) RenderWindowToLogical(windowX, windowY int) (logicalX, logicalY float32) { _windowX := C.int(windowX) _windowY := C.int(windowY) _logicalX := C.float(0) _logicalY := C.float(0) C.SDL_RenderWindowToLogical(renderer.cptr(), _windowX, _windowY, &_logicalX, &_logicalY) logicalX = float32(_logicalX) logicalY = float32(_logicalY) return } // RenderLogicalToWindow gets real coordinates of point in window when given logical coordinates of point in renderer. // Logical coordinates will differ from real coordinates when render is scaled and logical renderer size set. // (https://wiki.libsdl.org/SDL_RenderLogicalToWindow) func (renderer *Renderer) RenderLogicalToWindow(logicalX, logicalY float32) (windowX, windowY int) { _logicalX := C.float(logicalX) _logicalY := C.float(logicalY) _windowX := C.int(0) _windowY := C.int(0) C.SDL_RenderLogicalToWindow(renderer.cptr(), _logicalX, _logicalY, &_windowX, &_windowY) windowX = int(_windowX) windowY = int(_windowY) return } // RenderSetVSync toggles VSync of the given renderer. // (https://wiki.libsdl.org/SDL_RenderSetVSync) func (renderer *Renderer) RenderSetVSync(vsync bool) (err error) { _vsync := C.int(Btoi(vsync)) err = errorFromInt(int(C.SDL_RenderSetVSync(renderer.cptr(), _vsync))) return } // GetWindow gets the window associated with a renderer. // (https://wiki.libsdl.org/SDL_RenderGetWindow) func (renderer *Renderer) GetWindow() (window *Window, err error) { window = (*Window)(unsafe.Pointer(C.SDL_RenderGetWindow(renderer.cptr()))) return } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/rwops.go ================================================ package sdl /* #include "sdl_wrapper.h" static Sint64 RWsize(SDL_RWops *ctx) { return ctx->size(ctx); } static Sint64 RWseek(SDL_RWops *ctx, Sint64 offset, int whence) { return ctx->seek(ctx, offset, whence); } static size_t RWread(SDL_RWops *ctx, void *ptr, size_t size, size_t maxnum) { return ctx->read(ctx, ptr, size, maxnum); } static size_t RWwrite(SDL_RWops *ctx, void *ptr, size_t size, size_t num) { return ctx->write(ctx, ptr, size, num); } static int RWclose(SDL_RWops *ctx) { return ctx->close(ctx); } #if !(SDL_VERSION_ATLEAST(2,0,6)) #if defined(WARN_OUTDATED) #pragma message("SDL_LoadFile_RW is not supported before SDL 2.0.6") #endif static void * SDL_LoadFile_RW(SDL_RWops * src, size_t *datasize, int freesrc) { return 0; } #endif */ import "C" import ( "reflect" "unsafe" ) // RWops types const ( RWOPS_UNKNOWN = 0 // unknown stream type RWOPS_WINFILE = 1 // win32 file RWOPS_STDFILE = 2 // stdio file RWOPS_JNIFILE = 3 // android asset RWOPS_MEMORY = 4 // memory stream RWOPS_MEMORY_RO = 5 // read-only memory stream ) // RWops seek from const ( RW_SEEK_SET = C.RW_SEEK_SET // seek from the beginning of data RW_SEEK_CUR = C.RW_SEEK_CUR // seek relative to current read point RW_SEEK_END = C.RW_SEEK_END // seek relative to the end of data ) // RWops provides an abstract interface to stream I/O. Applications can generally ignore the specifics of this structure's internals and treat them as opaque pointers. The details are important to lower-level code that might need to implement one of these, however. // (https://wiki.libsdl.org/SDL_RWops) type RWops C.SDL_RWops func (rwops *RWops) cptr() *C.SDL_RWops { return (*C.SDL_RWops)(rwops) } // RWFromFile creates a new RWops structure for reading from and/or writing to a named file. // (https://wiki.libsdl.org/SDL_RWFromFile) func RWFromFile(file, mode string) *RWops { _file := C.CString(file) _mode := C.CString(mode) defer C.free(unsafe.Pointer(_file)) defer C.free(unsafe.Pointer(_mode)) return (*RWops)(unsafe.Pointer(C.SDL_RWFromFile(_file, _mode))) } // RWFromMem prepares a read-write memory buffer for use with RWops. // (https://wiki.libsdl.org/SDL_RWFromMem) func RWFromMem(mem []byte) (*RWops, error) { if mem == nil { return nil, ErrInvalidParameters } header := (*reflect.SliceHeader)(unsafe.Pointer(&mem)) _mem := unsafe.Pointer(header.Data) rwops := (*RWops)(unsafe.Pointer(C.SDL_RWFromMem(_mem, C.int(len(mem))))) if rwops == nil { return nil, GetError() } return rwops, nil } // AllocRW allocates an empty, unpopulated RWops structure. // (https://wiki.libsdl.org/SDL_AllocRW) func AllocRW() *RWops { return (*RWops)(unsafe.Pointer(C.SDL_AllocRW())) } // Free frees the RWops structure allocated by AllocRW(). // (https://wiki.libsdl.org/SDL_FreeRW) func (rwops *RWops) Free() error { if rwops == nil { return ErrInvalidParameters } C.SDL_FreeRW(rwops.cptr()) return nil } // Size returns the size of the data stream in the RWops. // (https://wiki.libsdl.org/SDL_RWsize) func (rwops *RWops) Size() (int64, error) { n := int64(C.RWsize(rwops.cptr())) if n < 0 { return n, GetError() } return n, nil } // Seek seeks within the RWops data stream. // (https://wiki.libsdl.org/SDL_RWseek) func (rwops *RWops) Seek(offset int64, whence int) (int64, error) { if rwops == nil { return -1, ErrInvalidParameters } ret := int64(C.RWseek(rwops.cptr(), C.Sint64(offset), C.int(whence))) if ret < 0 { return ret, GetError() } return ret, nil } // Read reads from a data source. // (https://wiki.libsdl.org/SDL_RWread) func (rwops *RWops) Read(buf []byte) (n int, err error) { return rwops.Read2(buf, 1, uint(len(buf))) } // Read2 reads from a data source (native). // (https://wiki.libsdl.org/SDL_RWread) func (rwops *RWops) Read2(buf []byte, size, maxnum uint) (n int, err error) { if rwops == nil || buf == nil { return 0, ErrInvalidParameters } header := (*reflect.SliceHeader)(unsafe.Pointer(&buf)) _data := unsafe.Pointer(header.Data) n = int(C.RWread(rwops.cptr(), _data, C.size_t(size), C.size_t(maxnum))) if n == 0 { err = GetError() } return } // Tell returns the current read/write offset in the RWops data stream. // (https://wiki.libsdl.org/SDL_RWtell) func (rwops *RWops) Tell() (int64, error) { if rwops == nil { return 0, ErrInvalidParameters } ret := int64(C.RWseek(rwops.cptr(), 0, C.int(RW_SEEK_CUR))) if ret < 0 { return ret, GetError() } return ret, nil } // Write writes to the RWops data stream. // (https://wiki.libsdl.org/SDL_RWwrite) func (rwops *RWops) Write(buf []byte) (n int, err error) { return rwops.Write2(buf, 1, uint(len(buf))) } // Write2 writes to the RWops data stream (native). // (https://wiki.libsdl.org/SDL_RWwrite) func (rwops *RWops) Write2(buf []byte, size, num uint) (n int, err error) { if rwops == nil || buf == nil { return 0, ErrInvalidParameters } header := (*reflect.SliceHeader)(unsafe.Pointer(&buf)) _data := unsafe.Pointer(header.Data) n = int(C.RWwrite(rwops.cptr(), _data, C.size_t(size), C.size_t(num))) if n < int(num) { err = GetError() } return } // Close closes and frees the allocated RWops structure. // (https://wiki.libsdl.org/SDL_RWclose) func (rwops *RWops) Close() error { if rwops != nil && C.RWclose(rwops.cptr()) != 0 { return GetError() } return nil } // ReadU8 reads a byte from the RWops. // (https://wiki.libsdl.org/SDL_ReadU8) func (rwops *RWops) ReadU8() uint8 { if rwops == nil { return 0 } return uint8(C.SDL_ReadU8(rwops.cptr())) } // ReadLE16 reads 16 bits of little-endian data from the RWops and returns in native format. // (https://wiki.libsdl.org/SDL_ReadLE16) func (rwops *RWops) ReadLE16() uint16 { if rwops == nil { return 0 } return uint16(C.SDL_ReadLE16(rwops.cptr())) } // ReadBE16 read 16 bits of big-endian data from the RWops and returns in native format. // (https://wiki.libsdl.org/SDL_ReadBE16) func (rwops *RWops) ReadBE16() uint16 { if rwops == nil { return 0 } return uint16(C.SDL_ReadBE16(rwops.cptr())) } // ReadLE32 reads 32 bits of little-endian data from the RWops and returns in native format. // (https://wiki.libsdl.org/SDL_ReadLE32) func (rwops *RWops) ReadLE32() uint32 { if rwops == nil { return 0 } return uint32(C.SDL_ReadLE32(rwops.cptr())) } // ReadBE32 reads 32 bits of big-endian data from the RWops and returns in native format. // (https://wiki.libsdl.org/SDL_ReadBE32) func (rwops *RWops) ReadBE32() uint32 { if rwops == nil { return 0 } return uint32(C.SDL_ReadBE32(rwops.cptr())) } // ReadLE64 reads 64 bits of little-endian data from the RWops and returns in native format. // (https://wiki.libsdl.org/SDL_ReadLE64) func (rwops *RWops) ReadLE64() uint64 { if rwops == nil { return 0 } return uint64(C.SDL_ReadLE64(rwops.cptr())) } // ReadBE64 reads 64 bits of big-endian data from the RWops and returns in native format. // (https://wiki.libsdl.org/SDL_ReadBE64) func (rwops *RWops) ReadBE64() uint64 { if rwops == nil { return 0 } return uint64(C.SDL_ReadBE64(rwops.cptr())) } // LoadFile_RW loads all the data from an SDL data stream. // (https://wiki.libsdl.org/SDL_LoadFile_RW) func (src *RWops) LoadFileRW(freesrc bool) (data []byte, size int) { var _size C.size_t var _freesrc C.int = 0 if freesrc { _freesrc = 1 } _data := C.SDL_LoadFile_RW(src.cptr(), &_size, _freesrc) sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&data)) sliceHeader.Cap = int(_size) sliceHeader.Len = int(_size) sliceHeader.Data = uintptr(_data) size = int(_size) return } // LoadFile loads an entire file // (https://wiki.libsdl.org/SDL_LoadFile) func LoadFile(file string) (data []byte, size int) { return RWFromFile(file, "rb").LoadFileRW(true) } // WriteU8 writes a byte to the RWops. // (https://wiki.libsdl.org/SDL_WriteU8) func (rwops *RWops) WriteU8(value uint8) uint { if rwops == nil { return 0 } return uint(C.SDL_WriteU8(rwops.cptr(), C.Uint8(value))) } // WriteLE16 writes 16 bits in native format to the RWops as little-endian data. // (https://wiki.libsdl.org/SDL_WriteLE16) func (rwops *RWops) WriteLE16(value uint16) uint { if rwops == nil { return 0 } return uint(C.SDL_WriteLE16(rwops.cptr(), C.Uint16(value))) } // WriteBE16 writes 16 bits in native format to the RWops as big-endian data. // (https://wiki.libsdl.org/SDL_WriteBE16) func (rwops *RWops) WriteBE16(value uint16) uint { if rwops == nil { return 0 } return uint(C.SDL_WriteBE16(rwops.cptr(), C.Uint16(value))) } // WriteLE32 writes 32 bits in native format to the RWops as little-endian data. // (https://wiki.libsdl.org/SDL_WriteLE32) func (rwops *RWops) WriteLE32(value uint32) uint { if rwops == nil { return 0 } return uint(C.SDL_WriteLE32(rwops.cptr(), C.Uint32(value))) } // WriteBE32 writes 32 bits in native format to the RWops as big-endian data. // (https://wiki.libsdl.org/SDL_WriteBE32) func (rwops *RWops) WriteBE32(value uint32) uint { if rwops == nil { return 0 } return uint(C.SDL_WriteBE32(rwops.cptr(), C.Uint32(value))) } // WriteLE64 writes 64 bits in native format to the RWops as little-endian data. // (https://wiki.libsdl.org/SDL_WriteLE64) func (rwops *RWops) WriteLE64(value uint64) uint { if rwops == nil { return 0 } return uint(C.SDL_WriteLE64(rwops.cptr(), C.Uint64(value))) } // WriteBE64 writes 64 bits in native format to the RWops as big-endian data. // (https://wiki.libsdl.org/SDL_WriteBE64) func (rwops *RWops) WriteBE64(value uint64) uint { if rwops == nil { return 0 } return uint(C.SDL_WriteBE64(rwops.cptr(), C.Uint64(value))) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/scancode.go ================================================ package sdl // #include "sdl_wrapper.h" import "C" // The SDL keyboard scancode representation. // (https://wiki.libsdl.org/SDL_Scancode) // (https://wiki.libsdl.org/SDLScancodeLookup) const ( SCANCODE_UNKNOWN = 0 // "" (no name, empty string) SCANCODE_A = C.SDL_SCANCODE_A // "A" SCANCODE_B = C.SDL_SCANCODE_B // "B" SCANCODE_C = C.SDL_SCANCODE_C // "C" SCANCODE_D = C.SDL_SCANCODE_D // "D" SCANCODE_E = C.SDL_SCANCODE_E // "E" SCANCODE_F = C.SDL_SCANCODE_F // "F" SCANCODE_G = C.SDL_SCANCODE_G // "G" SCANCODE_H = C.SDL_SCANCODE_H // "H" SCANCODE_I = C.SDL_SCANCODE_I // "I" SCANCODE_J = C.SDL_SCANCODE_J // "J" SCANCODE_K = C.SDL_SCANCODE_K // "K" SCANCODE_L = C.SDL_SCANCODE_L // "L" SCANCODE_M = C.SDL_SCANCODE_M // "M" SCANCODE_N = C.SDL_SCANCODE_N // "N" SCANCODE_O = C.SDL_SCANCODE_O // "O" SCANCODE_P = C.SDL_SCANCODE_P // "P" SCANCODE_Q = C.SDL_SCANCODE_Q // "Q" SCANCODE_R = C.SDL_SCANCODE_R // "R" SCANCODE_S = C.SDL_SCANCODE_S // "S" SCANCODE_T = C.SDL_SCANCODE_T // "T" SCANCODE_U = C.SDL_SCANCODE_U // "U" SCANCODE_V = C.SDL_SCANCODE_V // "V" SCANCODE_W = C.SDL_SCANCODE_W // "W" SCANCODE_X = C.SDL_SCANCODE_X // "X" SCANCODE_Y = C.SDL_SCANCODE_Y // "Y" SCANCODE_Z = C.SDL_SCANCODE_Z // "Z" SCANCODE_1 = C.SDL_SCANCODE_1 // "1" SCANCODE_2 = C.SDL_SCANCODE_2 // "2" SCANCODE_3 = C.SDL_SCANCODE_3 // "3" SCANCODE_4 = C.SDL_SCANCODE_4 // "4" SCANCODE_5 = C.SDL_SCANCODE_5 // "5" SCANCODE_6 = C.SDL_SCANCODE_6 // "6" SCANCODE_7 = C.SDL_SCANCODE_7 // "7" SCANCODE_8 = C.SDL_SCANCODE_8 // "8" SCANCODE_9 = C.SDL_SCANCODE_9 // "9" SCANCODE_0 = C.SDL_SCANCODE_0 // "0" SCANCODE_RETURN = C.SDL_SCANCODE_RETURN // "Return" SCANCODE_ESCAPE = C.SDL_SCANCODE_ESCAPE // "Escape" (the Esc key) SCANCODE_BACKSPACE = C.SDL_SCANCODE_BACKSPACE // "Backspace" SCANCODE_TAB = C.SDL_SCANCODE_TAB // "Tab" (the Tab key) SCANCODE_SPACE = C.SDL_SCANCODE_SPACE // "Space" (the Space Bar key(s)) SCANCODE_MINUS = C.SDL_SCANCODE_MINUS // "-" SCANCODE_EQUALS = C.SDL_SCANCODE_EQUALS // "=" SCANCODE_LEFTBRACKET = C.SDL_SCANCODE_LEFTBRACKET // "[" SCANCODE_RIGHTBRACKET = C.SDL_SCANCODE_RIGHTBRACKET // "]" SCANCODE_BACKSLASH = C.SDL_SCANCODE_BACKSLASH // "\" SCANCODE_NONUSHASH = C.SDL_SCANCODE_NONUSHASH // "#" (ISO USB keyboards actually use this code instead of 49 for the same key, but all OSes I've seen treat the two codes identically. So, as an implementor, unless your keyboard generates both of those codes and your OS treats them differently, you should generate SDL_SCANCODE_BACKSLASH instead of this code. As a user, you should not rely on this code because SDL will never generate it with most (all?) keyboards.) SCANCODE_SEMICOLON = C.SDL_SCANCODE_SEMICOLON // ";" SCANCODE_APOSTROPHE = C.SDL_SCANCODE_APOSTROPHE // "'" SCANCODE_GRAVE = C.SDL_SCANCODE_GRAVE // "`" SCANCODE_COMMA = C.SDL_SCANCODE_COMMA // "," SCANCODE_PERIOD = C.SDL_SCANCODE_PERIOD // "." SCANCODE_SLASH = C.SDL_SCANCODE_SLASH // "/" SCANCODE_CAPSLOCK = C.SDL_SCANCODE_CAPSLOCK // "CapsLock" SCANCODE_F1 = C.SDL_SCANCODE_F1 // "F1" SCANCODE_F2 = C.SDL_SCANCODE_F2 // "F2" SCANCODE_F3 = C.SDL_SCANCODE_F3 // "F3" SCANCODE_F4 = C.SDL_SCANCODE_F4 // "F4" SCANCODE_F5 = C.SDL_SCANCODE_F5 // "F5" SCANCODE_F6 = C.SDL_SCANCODE_F6 // "F6" SCANCODE_F7 = C.SDL_SCANCODE_F7 // "F7" SCANCODE_F8 = C.SDL_SCANCODE_F8 // "F8" SCANCODE_F9 = C.SDL_SCANCODE_F9 // "F9" SCANCODE_F10 = C.SDL_SCANCODE_F10 // "F10" SCANCODE_F11 = C.SDL_SCANCODE_F11 // "F11" SCANCODE_F12 = C.SDL_SCANCODE_F12 // "F12" SCANCODE_PRINTSCREEN = C.SDL_SCANCODE_PRINTSCREEN // "PrintScreen" SCANCODE_SCROLLLOCK = C.SDL_SCANCODE_SCROLLLOCK // "ScrollLock" SCANCODE_PAUSE = C.SDL_SCANCODE_PAUSE // "Pause" (the Pause / Break key) SCANCODE_INSERT = C.SDL_SCANCODE_INSERT // "Insert" (insert on PC, help on some Mac keyboards (but does send code 73, not 117)) SCANCODE_HOME = C.SDL_SCANCODE_HOME // "Home" SCANCODE_PAGEUP = C.SDL_SCANCODE_PAGEUP // "PageUp" SCANCODE_DELETE = C.SDL_SCANCODE_DELETE // "Delete" SCANCODE_END = C.SDL_SCANCODE_END // "End" SCANCODE_PAGEDOWN = C.SDL_SCANCODE_PAGEDOWN // "PageDown" SCANCODE_RIGHT = C.SDL_SCANCODE_RIGHT // "Right" (the Right arrow key (navigation keypad)) SCANCODE_LEFT = C.SDL_SCANCODE_LEFT // "Left" (the Left arrow key (navigation keypad)) SCANCODE_DOWN = C.SDL_SCANCODE_DOWN // "Down" (the Down arrow key (navigation keypad)) SCANCODE_UP = C.SDL_SCANCODE_UP // "Up" (the Up arrow key (navigation keypad)) SCANCODE_NUMLOCKCLEAR = C.SDL_SCANCODE_NUMLOCKCLEAR // "Numlock" (the Num Lock key (PC) / the Clear key (Mac)) SCANCODE_KP_DIVIDE = C.SDL_SCANCODE_KP_DIVIDE // "Keypad /" (the / key (numeric keypad)) SCANCODE_KP_MULTIPLY = C.SDL_SCANCODE_KP_MULTIPLY // "Keypad *" (the * key (numeric keypad)) SCANCODE_KP_MINUS = C.SDL_SCANCODE_KP_MINUS // "Keypad -" (the - key (numeric keypad)) SCANCODE_KP_PLUS = C.SDL_SCANCODE_KP_PLUS // "Keypad +" (the + key (numeric keypad)) SCANCODE_KP_ENTER = C.SDL_SCANCODE_KP_ENTER // "Keypad Enter" (the Enter key (numeric keypad)) SCANCODE_KP_1 = C.SDL_SCANCODE_KP_1 // "Keypad 1" (the 1 key (numeric keypad)) SCANCODE_KP_2 = C.SDL_SCANCODE_KP_2 // "Keypad 2" (the 2 key (numeric keypad)) SCANCODE_KP_3 = C.SDL_SCANCODE_KP_3 // "Keypad 3" (the 3 key (numeric keypad)) SCANCODE_KP_4 = C.SDL_SCANCODE_KP_4 // "Keypad 4" (the 4 key (numeric keypad)) SCANCODE_KP_5 = C.SDL_SCANCODE_KP_5 // "Keypad 5" (the 5 key (numeric keypad)) SCANCODE_KP_6 = C.SDL_SCANCODE_KP_6 // "Keypad 6" (the 6 key (numeric keypad)) SCANCODE_KP_7 = C.SDL_SCANCODE_KP_7 // "Keypad 7" (the 7 key (numeric keypad)) SCANCODE_KP_8 = C.SDL_SCANCODE_KP_8 // "Keypad 8" (the 8 key (numeric keypad)) SCANCODE_KP_9 = C.SDL_SCANCODE_KP_9 // "Keypad 9" (the 9 key (numeric keypad)) SCANCODE_KP_0 = C.SDL_SCANCODE_KP_0 // "Keypad 0" (the 0 key (numeric keypad)) SCANCODE_KP_PERIOD = C.SDL_SCANCODE_KP_PERIOD // "Keypad ." (the . key (numeric keypad)) SCANCODE_NONUSBACKSLASH = C.SDL_SCANCODE_NONUSBACKSLASH // "" (no name, empty string; This is the additional key that ISO keyboards have over ANSI ones, located between left shift and Y. Produces GRAVE ACCENT and TILDE in a US or UK Mac layout, REVERSE SOLIDUS (backslash) and VERTICAL LINE in a US or UK Windows layout, and LESS-THAN SIGN and GREATER-THAN SIGN in a Swiss German, German, or French layout.) SCANCODE_APPLICATION = C.SDL_SCANCODE_APPLICATION // "Application" (the Application / Compose / Context Menu (Windows) key) SCANCODE_POWER = C.SDL_SCANCODE_POWER // "Power" (The USB document says this is a status flag, not a physical key - but some Mac keyboards do have a power key.) SCANCODE_KP_EQUALS = C.SDL_SCANCODE_KP_EQUALS // "Keypad =" (the = key (numeric keypad)) SCANCODE_F13 = C.SDL_SCANCODE_F13 // "F13" SCANCODE_F14 = C.SDL_SCANCODE_F14 // "F14" SCANCODE_F15 = C.SDL_SCANCODE_F15 // "F15" SCANCODE_F16 = C.SDL_SCANCODE_F16 // "F16" SCANCODE_F17 = C.SDL_SCANCODE_F17 // "F17" SCANCODE_F18 = C.SDL_SCANCODE_F18 // "F18" SCANCODE_F19 = C.SDL_SCANCODE_F19 // "F19" SCANCODE_F20 = C.SDL_SCANCODE_F20 // "F20" SCANCODE_F21 = C.SDL_SCANCODE_F21 // "F21" SCANCODE_F22 = C.SDL_SCANCODE_F22 // "F22" SCANCODE_F23 = C.SDL_SCANCODE_F23 // "F23" SCANCODE_F24 = C.SDL_SCANCODE_F24 // "F24" SCANCODE_EXECUTE = C.SDL_SCANCODE_EXECUTE // "Execute" SCANCODE_HELP = C.SDL_SCANCODE_HELP // "Help" SCANCODE_MENU = C.SDL_SCANCODE_MENU // "Menu" SCANCODE_SELECT = C.SDL_SCANCODE_SELECT // "Select" SCANCODE_STOP = C.SDL_SCANCODE_STOP // "Stop" SCANCODE_AGAIN = C.SDL_SCANCODE_AGAIN // "Again" (the Again key (Redo)) SCANCODE_UNDO = C.SDL_SCANCODE_UNDO // "Undo" SCANCODE_CUT = C.SDL_SCANCODE_CUT // "Cut" SCANCODE_COPY = C.SDL_SCANCODE_COPY // "Copy" SCANCODE_PASTE = C.SDL_SCANCODE_PASTE // "Paste" SCANCODE_FIND = C.SDL_SCANCODE_FIND // "Find" SCANCODE_MUTE = C.SDL_SCANCODE_MUTE // "Mute" SCANCODE_VOLUMEUP = C.SDL_SCANCODE_VOLUMEUP // "VolumeUp" SCANCODE_VOLUMEDOWN = C.SDL_SCANCODE_VOLUMEDOWN // "VolumeDown" SCANCODE_KP_COMMA = C.SDL_SCANCODE_KP_COMMA // "Keypad ," (the Comma key (numeric keypad)) SCANCODE_KP_EQUALSAS400 = C.SDL_SCANCODE_KP_EQUALSAS400 // "Keypad = (AS400)" (the Equals AS400 key (numeric keypad)) SCANCODE_INTERNATIONAL1 = C.SDL_SCANCODE_INTERNATIONAL1 // "" (no name, empty string; used on Asian keyboards, see footnotes in USB doc) SCANCODE_INTERNATIONAL2 = C.SDL_SCANCODE_INTERNATIONAL2 // "" (no name, empty string) SCANCODE_INTERNATIONAL3 = C.SDL_SCANCODE_INTERNATIONAL3 // "" (no name, empty string; Yen) SCANCODE_INTERNATIONAL4 = C.SDL_SCANCODE_INTERNATIONAL4 // "" (no name, empty string) SCANCODE_INTERNATIONAL5 = C.SDL_SCANCODE_INTERNATIONAL5 // "" (no name, empty string) SCANCODE_INTERNATIONAL6 = C.SDL_SCANCODE_INTERNATIONAL6 // "" (no name, empty string) SCANCODE_INTERNATIONAL7 = C.SDL_SCANCODE_INTERNATIONAL7 // "" (no name, empty string) SCANCODE_INTERNATIONAL8 = C.SDL_SCANCODE_INTERNATIONAL8 // "" (no name, empty string) SCANCODE_INTERNATIONAL9 = C.SDL_SCANCODE_INTERNATIONAL9 // "" (no name, empty string) SCANCODE_LANG1 = C.SDL_SCANCODE_LANG1 // "" (no name, empty string; Hangul/English toggle) SCANCODE_LANG2 = C.SDL_SCANCODE_LANG2 // "" (no name, empty string; Hanja conversion) SCANCODE_LANG3 = C.SDL_SCANCODE_LANG3 // "" (no name, empty string; Katakana) SCANCODE_LANG4 = C.SDL_SCANCODE_LANG4 // "" (no name, empty string; Hiragana) SCANCODE_LANG5 = C.SDL_SCANCODE_LANG5 // "" (no name, empty string; Zenkaku/Hankaku) SCANCODE_LANG6 = C.SDL_SCANCODE_LANG6 // "" (no name, empty string; reserved) SCANCODE_LANG7 = C.SDL_SCANCODE_LANG7 // "" (no name, empty string; reserved) SCANCODE_LANG8 = C.SDL_SCANCODE_LANG8 // "" (no name, empty string; reserved) SCANCODE_LANG9 = C.SDL_SCANCODE_LANG9 // "" (no name, empty string; reserved) SCANCODE_ALTERASE = C.SDL_SCANCODE_ALTERASE // "AltErase" (Erase-Eaze) SCANCODE_SYSREQ = C.SDL_SCANCODE_SYSREQ // "SysReq" (the SysReq key) SCANCODE_CANCEL = C.SDL_SCANCODE_CANCEL // "Cancel" SCANCODE_CLEAR = C.SDL_SCANCODE_CLEAR // "Clear" SCANCODE_PRIOR = C.SDL_SCANCODE_PRIOR // "Prior" SCANCODE_RETURN2 = C.SDL_SCANCODE_RETURN2 // "Return" SCANCODE_SEPARATOR = C.SDL_SCANCODE_SEPARATOR // "Separator" SCANCODE_OUT = C.SDL_SCANCODE_OUT // "Out" SCANCODE_OPER = C.SDL_SCANCODE_OPER // "Oper" SCANCODE_CLEARAGAIN = C.SDL_SCANCODE_CLEARAGAIN // "Clear / Again" SCANCODE_CRSEL = C.SDL_SCANCODE_CRSEL // "CrSel" SCANCODE_EXSEL = C.SDL_SCANCODE_EXSEL // "ExSel" SCANCODE_KP_00 = C.SDL_SCANCODE_KP_00 // "Keypad 00" (the 00 key (numeric keypad)) SCANCODE_KP_000 = C.SDL_SCANCODE_KP_000 // "Keypad 000" (the 000 key (numeric keypad)) SCANCODE_THOUSANDSSEPARATOR = C.SDL_SCANCODE_THOUSANDSSEPARATOR // "ThousandsSeparator" (the Thousands Separator key) SCANCODE_DECIMALSEPARATOR = C.SDL_SCANCODE_DECIMALSEPARATOR // "DecimalSeparator" (the Decimal Separator key) SCANCODE_CURRENCYUNIT = C.SDL_SCANCODE_CURRENCYUNIT // "CurrencyUnit" (the Currency Unit key) SCANCODE_CURRENCYSUBUNIT = C.SDL_SCANCODE_CURRENCYSUBUNIT // "CurrencySubUnit" (the Currency Subunit key) SCANCODE_KP_LEFTPAREN = C.SDL_SCANCODE_KP_LEFTPAREN // "Keypad (" (the Left Parenthesis key (numeric keypad)) SCANCODE_KP_RIGHTPAREN = C.SDL_SCANCODE_KP_RIGHTPAREN // "Keypad )" (the Right Parenthesis key (numeric keypad)) SCANCODE_KP_LEFTBRACE = C.SDL_SCANCODE_KP_LEFTBRACE // "Keypad {" (the Left Brace key (numeric keypad)) SCANCODE_KP_RIGHTBRACE = C.SDL_SCANCODE_KP_RIGHTBRACE // "Keypad }" (the Right Brace key (numeric keypad)) SCANCODE_KP_TAB = C.SDL_SCANCODE_KP_TAB // "Keypad Tab" (the Tab key (numeric keypad)) SCANCODE_KP_BACKSPACE = C.SDL_SCANCODE_KP_BACKSPACE // "Keypad Backspace" (the Backspace key (numeric keypad)) SCANCODE_KP_A = C.SDL_SCANCODE_KP_A // "Keypad A" (the A key (numeric keypad)) SCANCODE_KP_B = C.SDL_SCANCODE_KP_B // "Keypad B" (the B key (numeric keypad)) SCANCODE_KP_C = C.SDL_SCANCODE_KP_C // "Keypad C" (the C key (numeric keypad)) SCANCODE_KP_D = C.SDL_SCANCODE_KP_D // "Keypad D" (the D key (numeric keypad)) SCANCODE_KP_E = C.SDL_SCANCODE_KP_E // "Keypad E" (the E key (numeric keypad)) SCANCODE_KP_F = C.SDL_SCANCODE_KP_F // "Keypad F" (the F key (numeric keypad)) SCANCODE_KP_XOR = C.SDL_SCANCODE_KP_XOR // "Keypad XOR" (the XOR key (numeric keypad)) SCANCODE_KP_POWER = C.SDL_SCANCODE_KP_POWER // "Keypad ^" (the Power key (numeric keypad)) SCANCODE_KP_PERCENT = C.SDL_SCANCODE_KP_PERCENT // "Keypad %" (the Percent key (numeric keypad)) SCANCODE_KP_LESS = C.SDL_SCANCODE_KP_LESS // "Keypad <" (the Less key (numeric keypad)) SCANCODE_KP_GREATER = C.SDL_SCANCODE_KP_GREATER // "Keypad >" (the Greater key (numeric keypad)) SCANCODE_KP_AMPERSAND = C.SDL_SCANCODE_KP_AMPERSAND // "Keypad &" (the & key (numeric keypad)) SCANCODE_KP_DBLAMPERSAND = C.SDL_SCANCODE_KP_DBLAMPERSAND // "Keypad &&" (the && key (numeric keypad)) SCANCODE_KP_VERTICALBAR = C.SDL_SCANCODE_KP_VERTICALBAR // "Keypad |" (the | key (numeric keypad)) SCANCODE_KP_DBLVERTICALBAR = C.SDL_SCANCODE_KP_DBLVERTICALBAR // "Keypad ||" (the || key (numeric keypad)) SCANCODE_KP_COLON = C.SDL_SCANCODE_KP_COLON // "Keypad :" (the : key (numeric keypad)) SCANCODE_KP_HASH = C.SDL_SCANCODE_KP_HASH // "Keypad #" (the # key (numeric keypad)) SCANCODE_KP_SPACE = C.SDL_SCANCODE_KP_SPACE // "Keypad Space" (the Space key (numeric keypad)) SCANCODE_KP_AT = C.SDL_SCANCODE_KP_AT // "Keypad @" (the @ key (numeric keypad)) SCANCODE_KP_EXCLAM = C.SDL_SCANCODE_KP_EXCLAM // "Keypad !" (the ! key (numeric keypad)) SCANCODE_KP_MEMSTORE = C.SDL_SCANCODE_KP_MEMSTORE // "Keypad MemStore" (the Mem Store key (numeric keypad)) SCANCODE_KP_MEMRECALL = C.SDL_SCANCODE_KP_MEMRECALL // "Keypad MemRecall" (the Mem Recall key (numeric keypad)) SCANCODE_KP_MEMCLEAR = C.SDL_SCANCODE_KP_MEMCLEAR // "Keypad MemClear" (the Mem Clear key (numeric keypad)) SCANCODE_KP_MEMADD = C.SDL_SCANCODE_KP_MEMADD // "Keypad MemAdd" (the Mem Add key (numeric keypad)) SCANCODE_KP_MEMSUBTRACT = C.SDL_SCANCODE_KP_MEMSUBTRACT // "Keypad MemSubtract" (the Mem Subtract key (numeric keypad)) SCANCODE_KP_MEMMULTIPLY = C.SDL_SCANCODE_KP_MEMMULTIPLY // "Keypad MemMultiply" (the Mem Multiply key (numeric keypad)) SCANCODE_KP_MEMDIVIDE = C.SDL_SCANCODE_KP_MEMDIVIDE // "Keypad MemDivide" (the Mem Divide key (numeric keypad)) SCANCODE_KP_PLUSMINUS = C.SDL_SCANCODE_KP_PLUSMINUS // "Keypad +/-" (the +/- key (numeric keypad)) SCANCODE_KP_CLEAR = C.SDL_SCANCODE_KP_CLEAR // "Keypad Clear" (the Clear key (numeric keypad)) SCANCODE_KP_CLEARENTRY = C.SDL_SCANCODE_KP_CLEARENTRY // "Keypad ClearEntry" (the Clear Entry key (numeric keypad)) SCANCODE_KP_BINARY = C.SDL_SCANCODE_KP_BINARY // "Keypad Binary" (the Binary key (numeric keypad)) SCANCODE_KP_OCTAL = C.SDL_SCANCODE_KP_OCTAL // "Keypad Octal" (the Octal key (numeric keypad)) SCANCODE_KP_DECIMAL = C.SDL_SCANCODE_KP_DECIMAL // "Keypad Decimal" (the Decimal key (numeric keypad)) SCANCODE_KP_HEXADECIMAL = C.SDL_SCANCODE_KP_HEXADECIMAL // "Keypad Hexadecimal" (the Hexadecimal key (numeric keypad)) SCANCODE_LCTRL = C.SDL_SCANCODE_LCTRL // "Left Ctrl" SCANCODE_LSHIFT = C.SDL_SCANCODE_LSHIFT // "Left Shift" SCANCODE_LALT = C.SDL_SCANCODE_LALT // "Left Alt" (alt, option) SCANCODE_LGUI = C.SDL_SCANCODE_LGUI // "Left GUI" (windows, command (apple), meta) SCANCODE_RCTRL = C.SDL_SCANCODE_RCTRL // "Right Ctrl" SCANCODE_RSHIFT = C.SDL_SCANCODE_RSHIFT // "Right Shift" SCANCODE_RALT = C.SDL_SCANCODE_RALT // "Right Alt" (alt gr, option) SCANCODE_RGUI = C.SDL_SCANCODE_RGUI // "Right GUI" (windows, command (apple), meta) SCANCODE_MODE = C.SDL_SCANCODE_MODE // "ModeSwitch" (I'm not sure if this is really not covered by any of the above, but since there's a special KMOD_MODE for it I'm adding it here) SCANCODE_AUDIONEXT = C.SDL_SCANCODE_AUDIONEXT // "AudioNext" (the Next Track media key) SCANCODE_AUDIOPREV = C.SDL_SCANCODE_AUDIOPREV // "AudioPrev" (the Previous Track media key) SCANCODE_AUDIOSTOP = C.SDL_SCANCODE_AUDIOSTOP // "AudioStop" (the Stop media key) SCANCODE_AUDIOPLAY = C.SDL_SCANCODE_AUDIOPLAY // "AudioPlay" (the Play media key) SCANCODE_AUDIOMUTE = C.SDL_SCANCODE_AUDIOMUTE // "AudioMute" (the Mute volume key) SCANCODE_MEDIASELECT = C.SDL_SCANCODE_MEDIASELECT // "MediaSelect" (the Media Select key) SCANCODE_WWW = C.SDL_SCANCODE_WWW // "WWW" (the WWW/World Wide Web key) SCANCODE_MAIL = C.SDL_SCANCODE_MAIL // "Mail" (the Mail/eMail key) SCANCODE_CALCULATOR = C.SDL_SCANCODE_CALCULATOR // "Calculator" (the Calculator key) SCANCODE_COMPUTER = C.SDL_SCANCODE_COMPUTER // "Computer" (the My Computer key) SCANCODE_AC_SEARCH = C.SDL_SCANCODE_AC_SEARCH // "AC Search" (the Search key (application control keypad)) SCANCODE_AC_HOME = C.SDL_SCANCODE_AC_HOME // "AC Home" (the Home key (application control keypad)) SCANCODE_AC_BACK = C.SDL_SCANCODE_AC_BACK // "AC Back" (the Back key (application control keypad)) SCANCODE_AC_FORWARD = C.SDL_SCANCODE_AC_FORWARD // "AC Forward" (the Forward key (application control keypad)) SCANCODE_AC_STOP = C.SDL_SCANCODE_AC_STOP // "AC Stop" (the Stop key (application control keypad)) SCANCODE_AC_REFRESH = C.SDL_SCANCODE_AC_REFRESH // "AC Refresh" (the Refresh key (application control keypad)) SCANCODE_AC_BOOKMARKS = C.SDL_SCANCODE_AC_BOOKMARKS // "AC Bookmarks" (the Bookmarks key (application control keypad)) SCANCODE_BRIGHTNESSDOWN = C.SDL_SCANCODE_BRIGHTNESSDOWN // "BrightnessDown" (the Brightness Down key) SCANCODE_BRIGHTNESSUP = C.SDL_SCANCODE_BRIGHTNESSUP // "BrightnessUp" (the Brightness Up key) SCANCODE_DISPLAYSWITCH = C.SDL_SCANCODE_DISPLAYSWITCH // "DisplaySwitch" (display mirroring/dual display switch, video mode switch) SCANCODE_KBDILLUMTOGGLE = C.SDL_SCANCODE_KBDILLUMTOGGLE // "KBDIllumToggle" (the Keyboard Illumination Toggle key) SCANCODE_KBDILLUMDOWN = C.SDL_SCANCODE_KBDILLUMDOWN // "KBDIllumDown" (the Keyboard Illumination Down key) SCANCODE_KBDILLUMUP = C.SDL_SCANCODE_KBDILLUMUP // "KBDIllumUp" (the Keyboard Illumination Up key) SCANCODE_EJECT = C.SDL_SCANCODE_EJECT // "Eject" (the Eject key) SCANCODE_SLEEP = C.SDL_SCANCODE_SLEEP // "Sleep" (the Sleep key) SCANCODE_APP1 = C.SDL_SCANCODE_APP1 SCANCODE_APP2 = C.SDL_SCANCODE_APP2 NUM_SCANCODES = C.SDL_NUM_SCANCODES ) // Scancode is an SDL keyboard scancode representation. // (https://wiki.libsdl.org/SDL_Scancode) type Scancode uint32 func (code Scancode) c() C.SDL_Scancode { return C.SDL_Scancode(code) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/sdl.go ================================================ // Package sdl 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. SDL2 is a cross-platform development library designed to provide low level access to audio, keyboard, mouse, joystick, and graphics hardware via OpenGL and Direct3D. package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,9)) #if defined(WARN_OUTDATED) #pragma message("SDL_INIT_SENSOR is not supported before SDL 2.0.9") #endif #define SDL_INIT_SENSOR (0x00008000u) #endif */ import "C" import ( "runtime" ) // These are the flags which may be passed to SDL_Init(). // (https://wiki.libsdl.org/SDL_Init) const ( INIT_TIMER = C.SDL_INIT_TIMER // timer subsystem INIT_AUDIO = C.SDL_INIT_AUDIO // audio subsystem INIT_VIDEO = C.SDL_INIT_VIDEO // video subsystem; automatically initializes the events subsystem INIT_JOYSTICK = C.SDL_INIT_JOYSTICK // joystick subsystem; automatically initializes the events subsystem INIT_HAPTIC = C.SDL_INIT_HAPTIC // haptic (force feedback) subsystem INIT_GAMECONTROLLER = C.SDL_INIT_GAMECONTROLLER // controller subsystem; automatically initializes the joystick subsystem INIT_EVENTS = C.SDL_INIT_EVENTS // events subsystem INIT_NOPARACHUTE = C.SDL_INIT_NOPARACHUTE // compatibility; this flag is ignored INIT_SENSOR = C.SDL_INIT_SENSOR // sensor subsystem INIT_EVERYTHING = C.SDL_INIT_EVERYTHING // all of the above subsystems ) const ( RELEASED = 0 PRESSED = 1 ) // Calls a function in the main thread. It is only properly initialized inside // sdl.Main(..). As a default, it panics. It is used by sdl.Do(..) below. var callInMain = func(f func()) { panic("sdl.Main(main func()) must be called before sdl.Do(f func())") } func init() { // Make sure the main goroutine is bound to the main thread. runtime.LockOSThread() } // Main entry point. Run this function at the beginning of main(), and pass your // own main body to it as a function. E.g.: // // func main() { // sdl.Main(func() { // // Your code here.... // // [....] // // // Calls to SDL can be made by any goroutine, but always guarded by sdl.Do() // sdl.Do(func() { // sdl.Init(0) // }) // }) // } // // Avoid calling functions like os.Exit(..) within your passed-in function since // they don't respect deferred calls. Instead, do this: // // func main() { // var exitcode int // sdl.Main(func() { // exitcode = run()) // assuming run has signature func() int // }) // os.Exit(exitcode) // } func Main(main func()) { // Queue of functions that are thread-sensitive callQueue := make(chan func()) // Properly initialize callInMain for use by sdl.Do(..) callInMain = func(f func()) { done := make(chan bool, 1) callQueue <- func() { f() done <- true } <-done } go func() { main() // fmt.Println("END") // to check if os.Exit(..) is called by main() above close(callQueue) }() for f := range callQueue { f() } } // Do the specified function in the main thread. // For this function to work, you must have correctly used sdl.Main(..) in your // main() function. Calling this function before/without sdl.Main(..) will cause // a panic. func Do(f func()) { callInMain(f) } // Init initialize the SDL library. This must be called before using most other SDL functions. // (https://wiki.libsdl.org/SDL_Init) func Init(flags uint32) error { if C.SDL_Init(C.Uint32(flags)) != 0 { return GetError() } return nil } // Quit cleans up all initialized subsystems. You should call it upon all exit conditions. // (https://wiki.libsdl.org/SDL_Quit) func Quit() { C.SDL_Quit() eventFilterCache = nil for k := range eventWatches { delete(eventWatches, k) } } // InitSubSystem initializes specific SDL subsystems. // (https://wiki.libsdl.org/SDL_InitSubSystem) func InitSubSystem(flags uint32) error { if C.SDL_InitSubSystem(C.Uint32(flags)) != 0 { return GetError() } return nil } // QuitSubSystem shuts down specific SDL subsystems. // (https://wiki.libsdl.org/SDL_QuitSubSystem) func QuitSubSystem(flags uint32) { C.SDL_QuitSubSystem(C.Uint32(flags)) } // WasInit returns a mask of the specified subsystems which have previously been initialized. // (https://wiki.libsdl.org/SDL_WasInit) func WasInit(flags uint32) uint32 { return uint32(C.SDL_WasInit(C.Uint32(flags))) } // GetPlatform returns the name of the platform. // (https://wiki.libsdl.org/SDL_GetPlatform) func GetPlatform() string { return string(C.GoString(C.SDL_GetPlatform())) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/sdl_cgo.go ================================================ // +build !static package sdl //#cgo windows LDFLAGS: -lSDL2 //#cgo linux freebsd darwin openbsd pkg-config: sdl2 import "C" ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/sdl_cgo_static.go ================================================ // +build static package sdl //#cgo CFLAGS: -I${SRCDIR}/../_libs/include -I${SRCDIR}/../_libs/include/SDL2 //#cgo LDFLAGS: -L${SRCDIR}/../_libs //#cgo linux,386 LDFLAGS: -lSDL2_linux_386 -lm -ldl -lasound -lm -ldl -lpthread -lX11 -lXext -lXcursor -lXinerama -lXi -lXrandr -lXss -lXxf86vm -lpthread -lrt //#cgo linux,amd64 LDFLAGS: -lSDL2_linux_amd64 -lm -ldl -lasound -lm -ldl -lpthread -lX11 -lXext -lXcursor -lXinerama -lXi -lXrandr -lXss -lXxf86vm -lpthread -lrt //#cgo windows,386 LDFLAGS: -lSDL2_windows_386 -lSDL2main_windows_386 -lm -ldinput8 -ldxguid -ldxerr8 -luser32 -lgdi32 -lwinmm -limm32 -lole32 -loleaut32 -lshell32 -lsetupapi -lversion -luuid -static-libgcc //#cgo windows,amd64 LDFLAGS: -lSDL2_windows_amd64 -lSDL2main_windows_amd64 -lm -ldinput8 -ldxguid -ldxerr8 -luser32 -lgdi32 -lwinmm -limm32 -lole32 -loleaut32 -lshell32 -lversion -luuid -lsetupapi -static-libgcc //#cgo darwin,amd64 LDFLAGS: -lSDL2_darwin_amd64 -lm -liconv -Wl,-framework,OpenGL -Wl,-framework,CoreAudio -Wl,-framework,AudioToolbox -Wl,-framework,ForceFeedback -lobjc -Wl,-framework,CoreVideo -Wl,-framework,Cocoa -Wl,-framework,Carbon -Wl,-framework,IOKit -Wl,-framework,Metal //#cgo darwin,arm64 LDFLAGS: -lSDL2_darwin_arm64 -lm -liconv -Wl,-framework,OpenGL -Wl,-framework,CoreAudio -Wl,-framework,AudioToolbox -Wl,-framework,ForceFeedback -lobjc -Wl,-framework,CoreVideo -Wl,-framework,Cocoa -Wl,-framework,Carbon -Wl,-framework,IOKit -Wl,-framework,Metal //#cgo android,arm LDFLAGS: -lSDL2_android_arm -lm -ldl -llog -landroid -lGLESv2 -lGLESv1_CM //#cgo linux,arm,!android LDFLAGS: -L/opt/vc/lib -L/opt/vc/lib64 -lSDL2_linux_arm -lm -ldl -liconv -lbcm_host -lvcos -lvchiq_arm -pthread import "C" import ( _ "github.com/veandco/go-sdl2/_libs" _ "github.com/veandco/go-sdl2/_libs" ) ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/sdl_wrapper.h ================================================ #if defined(_WIN32) #include #include #else #include #endif #if !defined(SDL_2_0_10) #define SDL_2_0_10 #if !(SDL_VERSION_ATLEAST(2,0,10)) #if defined(WARN_OUTDATED) #pragma message("SDL_FPoint is not supported before SDL 2.0.10") #endif typedef struct SDL_FPoint { float x; float y; } SDL_FPoint; #if defined(WARN_OUTDATED) #pragma message("SDL_FRect is not supported before SDL 2.0.10") #endif typedef struct SDL_FRect { float x; float y; float w; float h; } SDL_FRect; #endif #endif ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/sensor.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,9)) typedef struct _SDL_Sensor SDL_Sensor; typedef Sint32 SDL_SensorID; typedef enum { SDL_SENSOR_INVALID = -1, SDL_SENSOR_UNKNOWN, SDL_SENSOR_ACCEL, SDL_SENSOR_GYRO } SDL_SensorType; #if defined(WARN_OUTDATED) #pragma message("SDL_NumSensors is not supported before SDL 2.0.9") #endif static inline int SDL_NumSensors() { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_SensorGetDeviceName is not supported before SDL 2.0.9") #endif static const char * SDL_SensorGetDeviceName(int device_index) { return NULL; } #if defined(WARN_OUTDATED) #pragma message("SDL_SensorGetDeviceType is not supported before SDL 2.0.9") #endif static SDL_SensorType SDL_SensorGetDeviceType(int device_index) { return SDL_SENSOR_INVALID; } #if defined(WARN_OUTDATED) #pragma message("SDL_SensorGetDeviceNonPortableType is not supported before SDL 2.0.9") #endif static int SDL_SensorGetDeviceNonPortableType(int device_index) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_SensorGetDeviceInstanceID is not supported before SDL 2.0.9") #endif static SDL_SensorID SDL_SensorGetDeviceInstanceID(int device_index) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_SensorOpen is not supported before SDL 2.0.9") #endif static SDL_Sensor * SDL_SensorOpen(int device_index) { return NULL; } #if defined(WARN_OUTDATED) #pragma message("SDL_SensorFromInstanceID is not supported before SDL 2.0.9") #endif static SDL_Sensor * SDL_SensorFromInstanceID(SDL_SensorID instance_id) { return NULL; } #if defined(WARN_OUTDATED) #pragma message("SDL_SensorGetName is not supported before SDL 2.0.9") #endif static const char * SDL_SensorGetName(SDL_Sensor *sensor) { return NULL; } #if defined(WARN_OUTDATED) #pragma message("SDL_SensorGetType is not supported before SDL 2.0.9") #endif static SDL_SensorType SDL_SensorGetType(SDL_Sensor *sensor) { return SDL_SENSOR_INVALID; } #if defined(WARN_OUTDATED) #pragma message("SDL_SensorGetNonPortableType is not supported before SDL 2.0.9") #endif static int SDL_SensorGetNonPortableType(SDL_Sensor *sensor) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_SensorGetInstanceID is not supported before SDL 2.0.9") #endif static SDL_SensorID SDL_SensorGetInstanceID(SDL_Sensor *sensor) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_SensorGetData is not supported before SDL 2.0.9") #endif static int SDL_SensorGetData(SDL_Sensor *sensor, float *data, int num_values) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_SensorClose is not supported before SDL 2.0.9") #endif static void SDL_SensorClose(SDL_Sensor *sensor) { } #if defined(WARN_OUTDATED) #pragma message("SDL_SensorUpdate is not supported before SDL 2.0.9") #endif static void SDL_SensorUpdate() { } #endif */ import "C" import "unsafe" const ( STANDARD_GRAVITY = 9.80665 ) // The different sensors defined by SDL // // Additional sensors may be available, using platform dependent semantics. // // Here are the additional Android sensors: // https://developer.android.com/reference/android/hardware/SensorEvent.html#values const ( SENSOR_INVALID SensorType = C.SDL_SENSOR_INVALID // Returned for an invalid sensor SENSOR_UNKNOWN SensorType = C.SDL_SENSOR_UNKNOWN // Unknown sensor type SENSOR_ACCEL SensorType = C.SDL_SENSOR_ACCEL // Accelerometer SENSOR_GYRO SensorType = C.SDL_SENSOR_GYRO // Gyroscope ) type Sensor C.SDL_Sensor type SensorID int32 type SensorType int // NumSensors counts the number of sensors attached to the system right now // (https://wiki.libsdl.org/SDL_NumSensors) func NumSensors() int { return int(C.SDL_NumSensors()) } // SensorGetDeviceName gets the implementation dependent name of a sensor. // // This can be called before any sensors are opened. // // Returns the sensor name, or empty string if deviceIndex is out of range. // (https://wiki.libsdl.org/SDL_SensorGetDeviceName) func SensorGetDeviceName(deviceIndex int) (name string) { name = C.GoString(C.SDL_SensorGetDeviceName(C.int(deviceIndex))) return } // SensorGetDeviceType gets the type of a sensor. // // This can be called before any sensors are opened. // // Returns the sensor type, or SDL_SENSOR_INVALID if deviceIndex is out of range. // (https://wiki.libsdl.org/SDL_SensorGetDeviceType) func SensorGetDeviceType(deviceIndex int) (typ SensorType) { typ = SensorType(C.SDL_SensorGetDeviceType(C.int(deviceIndex))) return } // SensorGetDeviceNonPortableType gets the platform dependent type of a sensor. // // This can be called before any sensors are opened. // // Returns the sensor platform dependent type, or -1 if deviceIndex is out of range. // (https://wiki.libsdl.org/SDL_SensorGetDeviceNonPortableType) func SensorGetDeviceNonPortableType(deviceIndex int) (typ int) { typ = int(C.SDL_SensorGetDeviceNonPortableType(C.int(deviceIndex))) return } // SensorGetDeviceInstanceID gets the instance ID of a sensor. // // This can be called before any sensors are opened. // // Returns the sensor instance ID, or -1 if deviceIndex is out of range. // (https://wiki.libsdl.org/SDL_SensorGetDeviceInstanceID) func SensorGetDeviceInstanceID(deviceIndex int) (id SensorID) { id = SensorID(C.SDL_SensorGetDeviceInstanceID(C.int(deviceIndex))) return } // SensorOpen opens a sensor for use. // // The index passed as an argument refers to the N'th sensor on the system. // // Returns a sensor identifier, or nil if an error occurred. // (https://wiki.libsdl.org/SDL_SensorOpen) func SensorOpen(deviceIndex int) (sensor *Sensor) { sensor = (*Sensor)(unsafe.Pointer(C.SDL_SensorOpen(C.int(deviceIndex)))) return } // SensorFromInstanceID returns the Sensor associated with an instance id. // (https://wiki.libsdl.org/SDL_SensorFromInstanceID) func SensorFromInstanceID(id SensorID) (sensor *Sensor) { sensor = (*Sensor)(unsafe.Pointer(C.SDL_SensorFromInstanceID(C.SDL_SensorID(id)))) return } // GetName gets the implementation dependent name of a sensor. // // Returns the sensor name, or empty string if the sensor is nil. // (https://wiki.libsdl.org/SDL_SensorGetName) func (sensor *Sensor) GetName() (name string) { name = C.GoString(C.SDL_SensorGetName((*C.SDL_Sensor)(sensor))) return } // GetType gets the type of a sensor. // // This can be called before any sensors are opened. // // Returns the sensor type, or SENSOR_INVALID if the sensor is nil. // (https://wiki.libsdl.org/SDL_SensorGetType) func (sensor *Sensor) GetType() (typ SensorType) { typ = SensorType(C.SDL_SensorGetType((*C.SDL_Sensor)(sensor))) return } // GetNonPortableType gets the platform dependent type of a sensor. // // This can be called before any sensors are opened. // // Returns the sensor platform dependent type, or -1 if the sensor is nil. // (https://wiki.libsdl.org/SDL_SensorGetNonPortableType) func (sensor *Sensor) GetNonPortableType() (typ int) { typ = int(C.SDL_SensorGetNonPortableType((*C.SDL_Sensor)(sensor))) return } // GetInstanceID gets the instance ID of a sensor. // // This can be called before any sensors are opened. // // Returns the sensor instance ID, or -1 if the sensor is nil. // (https://wiki.libsdl.org/SDL_SensorGetInstanceID) func (sensor *Sensor) GetInstanceID() (id SensorID) { id = SensorID(C.SDL_SensorGetInstanceID((*C.SDL_Sensor)(sensor))) return } // GetData gets the current state of an opened sensor. // // The number of values and interpretation of the data is sensor dependent. // (https://wiki.libsdl.org/SDL_SensorGetData) func (sensor *Sensor) GetData(data []float32) (err error) { if data == nil { return nil } _data := (*C.float)(unsafe.Pointer(&data[0])) _numValues := C.int(len(data)) err = errorFromInt(int(C.SDL_SensorGetData((*C.SDL_Sensor)(sensor), _data, _numValues))) return } // Close closes a sensor previously opened with SensorOpen() // (https://wiki.libsdl.org/SDL_SensorClose) func (sensor *Sensor) Close() { C.SDL_SensorClose((*C.SDL_Sensor)(sensor)) } // SensorUpdate updates the current state of the open sensors. // // This is called automatically by the event loop if sensor events are enabled. // // This needs to be called from the thread that initialized the sensor subsystem. // (https://wiki.libsdl.org/SDL_SensorUpdate) func SensorUpdate() { C.SDL_SensorUpdate() } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/shape.go ================================================ package sdl /* #include "sdl_wrapper.h" // until SDL 2.0.6 SDL_shape.h was not included in SDL.h #if !(SDL_VERSION_ATLEAST(2,0,6)) #if defined(_WIN32) #include #else #include #endif #endif */ import "C" import "unsafe" const ( NONSHAPEABLE_WINDOW = C.SDL_NONSHAPEABLE_WINDOW INVALID_SHAPE_ARGUMENT = C.SDL_INVALID_SHAPE_ARGUMENT WINDOW_LACKS_SHAPE = C.SDL_WINDOW_LACKS_SHAPE ) type WindowShapeModeKind C.WindowShapeMode const ( ShapeModeDefaultKind WindowShapeModeKind = C.ShapeModeDefault // the default mode, a binarized alpha cutoff of 1 ShapeModeBinarizeAlphaKind WindowShapeModeKind = C.ShapeModeBinarizeAlpha // a binarized alpha cutoff with a given integer value ShapeModeReverseBinarizeAlphaKind WindowShapeModeKind = C.ShapeModeReverseBinarizeAlpha // a binarized alpha cutoff with a given integer value, but with the opposite comparison ShapeModeColorKeyKind WindowShapeModeKind = C.ShapeModeColorKey // a color key is applied ) func SHAPEMODEALPHA(mode WindowShapeModeKind) bool { return (mode == ShapeModeDefaultKind || mode == ShapeModeBinarizeAlphaKind || mode == ShapeModeReverseBinarizeAlphaKind) } // A union containing parameters for shaped windows // uint8 or Color type cWindowShapeParams C.SDL_WindowShapeParams type cWindowShapeMode struct { mode WindowShapeModeKind parameters cWindowShapeParams } type WindowShapeMode interface { Mode() WindowShapeModeKind cWSM() cWindowShapeMode } type ShapeModeDefault struct{} func (smd ShapeModeDefault) Mode() WindowShapeModeKind { return ShapeModeDefaultKind } func (smd ShapeModeDefault) cWSM() cWindowShapeMode { return cWindowShapeMode{ mode: ShapeModeDefaultKind, parameters: [4]uint8{1, 0, 0, 0}, } } type ShapeModeBinarizeAlpha struct { Cutoff uint8 } func (smba ShapeModeBinarizeAlpha) Mode() WindowShapeModeKind { return ShapeModeBinarizeAlphaKind } func (smba ShapeModeBinarizeAlpha) cWSM() cWindowShapeMode { return cWindowShapeMode{ mode: ShapeModeBinarizeAlphaKind, parameters: [4]uint8{smba.Cutoff, 0, 0, 0}, } } type ShapeModeReverseBinarizeAlpha struct { Cutoff uint8 } func (smba ShapeModeReverseBinarizeAlpha) Mode() WindowShapeModeKind { return ShapeModeReverseBinarizeAlphaKind } func (smba ShapeModeReverseBinarizeAlpha) cWSM() cWindowShapeMode { return cWindowShapeMode{ mode: ShapeModeReverseBinarizeAlphaKind, parameters: [4]uint8{smba.Cutoff, 0, 0, 0}, } } type ShapeModeColorKey struct { Color Color } func (smck ShapeModeColorKey) Mode() WindowShapeModeKind { return ShapeModeColorKeyKind } func (smck ShapeModeColorKey) cWSM() cWindowShapeMode { return cWindowShapeMode{ mode: ShapeModeReverseBinarizeAlphaKind, parameters: [4]uint8{smck.Color.R, smck.Color.G, smck.Color.B, smck.Color.A}, } } func (cwsm cWindowShapeMode) goWSM() WindowShapeMode { switch cwsm.mode { case ShapeModeDefaultKind: return ShapeModeDefault{} case ShapeModeBinarizeAlphaKind: return ShapeModeBinarizeAlpha{ Cutoff: ([4]uint8)(cwsm.parameters)[0], } case ShapeModeReverseBinarizeAlphaKind: return ShapeModeReverseBinarizeAlpha{ Cutoff: ([4]uint8)(cwsm.parameters)[0], } case ShapeModeColorKeyKind: return ShapeModeColorKey{ Color: Color{ R: ([4]uint8)(cwsm.parameters)[0], G: ([4]uint8)(cwsm.parameters)[1], B: ([4]uint8)(cwsm.parameters)[2], A: ([4]uint8)(cwsm.parameters)[3], }, } default: panic("Unknown WindowShapeModeKind") } } func (wsm *cWindowShapeMode) cptr() *C.SDL_WindowShapeMode { return (*C.SDL_WindowShapeMode)(unsafe.Pointer(wsm)) } // CreateShapedWindow creates a window that can be shaped with the specified position, dimensions, and flags // (https://wiki.libsdl.org/SDL_CreateShapedWindow) func CreateShapedWindow(title string, x, y, w, h uint32, flags uint32) (*Window, error) { var _window = C.SDL_CreateShapedWindow(C.CString(title), C.uint(x), C.uint(y), C.uint(w), C.uint(h), C.Uint32(flags)) if _window == nil { return nil, GetError() } return (*Window)(unsafe.Pointer(_window)), nil } // IsShapedWindow returns whether the given window is a shaped window. // (https://wiki.libsdl.org/SDL_IsShapedWindow) func (window *Window) IsShaped() bool { return (C.SDL_IsShapedWindow(window.cptr()) & 1) == 1 } // SetShape sets the shape and parameters of a shaped window // (https://wiki.libsdl.org/SDL_SetWindowShape) func (window *Window) SetShape(shape *Surface, shape_mode WindowShapeMode) int32 { if shape_mode == nil { panic("shape_mode can not be nil") } var _cWSM cWindowShapeMode = shape_mode.cWSM() return (int32)(C.SDL_SetWindowShape(window.cptr(), shape.cptr(), _cWSM.cptr())) } // GetShapeMode gets the shape parameters of a shaped window // (https://wiki.libsdl.org/SDL_GetShapedWindowMode) func (window *Window) GetShapeMode() (WindowShapeMode, int32) { var _cWSM cWindowShapeMode var _resInt32 = (int32)(C.SDL_GetShapedWindowMode(window.cptr(), _cWSM.cptr())) if _resInt32 != 0 { return nil, _resInt32 } return _cWSM.goWSM(), _resInt32 } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/surface.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,9)) #if defined(WARN_OUTDATED) #pragma message("SDL_HasColorKey is not supported before SDL 2.0.9") #endif static SDL_bool SDL_HasColorKey(SDL_Surface * surface) { return SDL_FALSE; } #endif #if !(SDL_VERSION_ATLEAST(2,0,8)) typedef enum { SDL_YUV_CONVERSION_JPEG, SDL_YUV_CONVERSION_BT601, SDL_YUV_CONVERSION_BT709, SDL_YUV_CONVERSION_AUTOMATIC } SDL_YUV_CONVERSION_MODE; #if defined(WARN_OUTDATED) #pragma message("SDL_SetYUVConversionMode is not supported before SDL 2.0.8") #endif void SDL_SetYUVConversionMode(SDL_YUV_CONVERSION_MODE mode) { } #if defined(WARN_OUTDATED) #pragma message("SDL_GetYUVConversionMode is not supported before SDL 2.0.8") #endif SDL_YUV_CONVERSION_MODE SDL_GetYUVConversionMode(void) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_GetYUVConversionModeForResolution is not supported before SDL 2.0.8") #endif SDL_YUV_CONVERSION_MODE SDL_GetYUVConversionModeForResolution(int width, int height) { return -1; } #endif #if !(SDL_VERSION_ATLEAST(2,0,6)) #if defined(WARN_OUTDATED) #pragma message("SDL_DuplicateSurface is not supported before SDL 2.0.6") #endif static inline SDL_Surface* SDL_DuplicateSurface(SDL_Surface *surface) { return NULL; } #endif #if !(SDL_VERSION_ATLEAST(2,0,5)) #if defined(WARN_OUTDATED) #pragma message("SDL_CreateRGBSurfaceWithFormat is not supported before SDL 2.0.5") #endif static inline SDL_Surface* SDL_CreateRGBSurfaceWithFormat(Uint32 flags, int width, int height, int depth, Uint32 format) { return NULL; } #if defined(WARN_OUTDATED) #pragma message("SDL_CreateRGBSurfaceWithFormatFrom is not supported before SDL 2.0.5") #endif static inline SDL_Surface* SDL_CreateRGBSurfaceWithFormatFrom(void* pixels, int width, int height, int depth, int pitch, Uint32 format) { return NULL; } #endif #if !(SDL_VERSION_ATLEAST(2,0,16)) #if defined(WARN_OUTDATED) #pragma message("SDL_SoftStretchLinear is not supported before SDL 2.0.16") #endif static int SDL_SoftStretchLinear(SDL_Surface * src, const SDL_Rect * srcrect, SDL_Surface * dst, const SDL_Rect * dstrect) { return -1; } #endif #if !(SDL_VERSION_ATLEAST(2,0,18)) #if defined(WARN_OUTDATED) #pragma message("SDL_PremultiplyAlpha is not supported before SDL 2.0.18") #endif static int SDL_PremultiplyAlpha(int width, int height, Uint32 src_format, const void * src, int src_pitch, Uint32 dst_format, void * dst, int dst_pitch) { return -1; } #endif */ import "C" import ( "image" "image/color" "reflect" "unsafe" ) // Surface flags (internal use) const ( SWSURFACE = C.SDL_SWSURFACE // just here for compatibility PREALLOC = C.SDL_PREALLOC // surface uses preallocated memory RLEACCEL = C.SDL_RLEACCEL // surface is RLE encoded DONTFREE = C.SDL_DONTFREE // surface is referenced internally ) type YUV_CONVERSION_MODE C.SDL_YUV_CONVERSION_MODE // YUV Conversion Modes const ( YUV_CONVERSION_JPEG YUV_CONVERSION_MODE = C.SDL_YUV_CONVERSION_JPEG // Full range JPEG YUV_CONVERSION_BT601 = C.SDL_YUV_CONVERSION_BT601 // BT.601 (the default) YUV_CONVERSION_BT709 = C.SDL_YUV_CONVERSION_BT709 // BT.709 YUV_CONVERSION_AUTOMATIC = C.SDL_YUV_CONVERSION_AUTOMATIC // BT.601 for SD content, BT.709 for HD content ) // Surface contains a collection of pixels used in software blitting. // (https://wiki.libsdl.org/SDL_Surface) type Surface struct { flags uint32 // (internal use) Format *PixelFormat // the format of the pixels stored in the surface (read-only) (https://wiki.libsdl.org/SDL_PixelFormat) W int32 // the width in pixels (read-only) H int32 // the height in pixels (read-only) Pitch int32 // the length of a row of pixels in bytes (read-only) pixels unsafe.Pointer // the pointer to the actual pixel data; use Pixels() for access UserData unsafe.Pointer // an arbitrary pointer you can set locked int32 // used for surfaces that require locking (internal use) lockData unsafe.Pointer // used for surfaces that require locking (internal use) ClipRect Rect // a Rect structure used to clip blits to the surface which can be set by SetClipRect() (read-only) _ unsafe.Pointer // map; info for fast blit mapping to other surfaces (internal use) RefCount int32 // reference count that can be incremented by the application } type cSurface C.SDL_Surface func (surface *Surface) cptr() *C.SDL_Surface { return (*C.SDL_Surface)(unsafe.Pointer(surface)) } // MustLock reports whether the surface must be locked for access. // (https://wiki.libsdl.org/SDL_MUSTLOCK) func (surface *Surface) MustLock() bool { return (surface.flags & RLEACCEL) != 0 } // CreateRGBSurface allocates a new RGB surface. // (https://wiki.libsdl.org/SDL_CreateRGBSurface) func CreateRGBSurface(flags uint32, width, height, depth int32, Rmask, Gmask, Bmask, Amask uint32) (*Surface, error) { surface := (*Surface)(unsafe.Pointer(C.SDL_CreateRGBSurface( C.Uint32(flags), C.int(width), C.int(height), C.int(depth), C.Uint32(Rmask), C.Uint32(Gmask), C.Uint32(Bmask), C.Uint32(Amask)))) if surface == nil { return nil, GetError() } return surface, nil } // CreateRGBSurfaceFrom allocate a new RGB surface with existing pixel data. // (https://wiki.libsdl.org/SDL_CreateRGBSurfaceFrom) func CreateRGBSurfaceFrom(pixels unsafe.Pointer, width, height int32, depth, pitch int, Rmask, Gmask, Bmask, Amask uint32) (*Surface, error) { surface := (*Surface)(unsafe.Pointer(C.SDL_CreateRGBSurfaceFrom( pixels, C.int(width), C.int(height), C.int(depth), C.int(pitch), C.Uint32(Rmask), C.Uint32(Gmask), C.Uint32(Bmask), C.Uint32(Amask)))) if surface == nil { return nil, GetError() } return surface, nil } // CreateRGBSurfaceWithFormat allocates an RGB surface. // (https://wiki.libsdl.org/SDL_CreateRGBSurfaceWithFormat) func CreateRGBSurfaceWithFormat(flags uint32, width, height, depth int32, format uint32) (*Surface, error) { surface := (*Surface)(unsafe.Pointer(C.SDL_CreateRGBSurfaceWithFormat( C.Uint32(flags), C.int(width), C.int(height), C.int(depth), C.Uint32(format)))) if surface == nil { return nil, GetError() } return surface, nil } // CreateRGBSurfaceWithFormatFrom allocates an RGB surface from provided pixel data. // (https://wiki.libsdl.org/SDL_CreateRGBSurfaceWithFormatFrom) func CreateRGBSurfaceWithFormatFrom(pixels unsafe.Pointer, width, height, depth, pitch int32, format uint32) (*Surface, error) { surface := (*Surface)(unsafe.Pointer(C.SDL_CreateRGBSurfaceWithFormatFrom( pixels, C.int(width), C.int(height), C.int(depth), C.int(pitch), C.Uint32(format)))) if surface == nil { return nil, GetError() } return surface, nil } // SetYUVConversionMode sets the YUV conversion mode // TODO: (https://wiki.libsdl.org/SDL_SetYUVConversionMode) func SetYUVConversionMode(mode YUV_CONVERSION_MODE) { _mode := C.SDL_YUV_CONVERSION_MODE(mode) C.SDL_SetYUVConversionMode(_mode) } // GetYUVConversionMode gets the YUV conversion mode // TODO: (https://wiki.libsdl.org/SDL_GetYUVConversionMode) func GetYUVConversionMode() YUV_CONVERSION_MODE { return YUV_CONVERSION_MODE(C.SDL_GetYUVConversionMode()) } // GetYUVConversionModeForResolution gets the YUV conversion mode // TODO: (https://wiki.libsdl.org/SDL_GetYUVConversionModeForResolution) func GetYUVConversionModeForResolution(width, height int) YUV_CONVERSION_MODE { _width := C.int(width) _height := C.int(height) return YUV_CONVERSION_MODE(C.SDL_GetYUVConversionModeForResolution(_width, _height)) } // Free frees the RGB surface. // (https://wiki.libsdl.org/SDL_FreeSurface) func (surface *Surface) Free() { C.SDL_FreeSurface(surface.cptr()) } // SetPalette sets the palette used by the surface. // (https://wiki.libsdl.org/SDL_SetSurfacePalette) func (surface *Surface) SetPalette(palette *Palette) error { if C.SDL_SetSurfacePalette(surface.cptr(), palette.cptr()) != 0 { return GetError() } return nil } // Lock sets up the surface for directly accessing the pixels. // (https://wiki.libsdl.org/SDL_LockSurface) func (surface *Surface) Lock() error { if C.SDL_LockSurface(surface.cptr()) != 0 { return GetError() } return nil } // Unlock releases the surface after directly accessing the pixels. // (https://wiki.libsdl.org/SDL_UnlockSurface) func (surface *Surface) Unlock() { C.SDL_UnlockSurface(surface.cptr()) } // LoadBMPRW loads a BMP image from a seekable SDL data stream (memory or file). // (https://wiki.libsdl.org/SDL_LoadBMP_RW) func LoadBMPRW(src *RWops, freeSrc bool) (*Surface, error) { surface := (*Surface)(unsafe.Pointer(C.SDL_LoadBMP_RW(src.cptr(), C.int(Btoi(freeSrc))))) if surface == nil { return nil, GetError() } return surface, nil } // LoadBMP loads a surface from a BMP file. // (https://wiki.libsdl.org/SDL_LoadBMP) func LoadBMP(file string) (*Surface, error) { return LoadBMPRW(RWFromFile(file, "rb"), true) } // SaveBMPRW save the surface to a seekable SDL data stream (memory or file) in BMP format. // (https://wiki.libsdl.org/SDL_SaveBMP_RW) func (surface *Surface) SaveBMPRW(dst *RWops, freeDst bool) error { if C.SDL_SaveBMP_RW(surface.cptr(), dst.cptr(), C.int(Btoi(freeDst))) != 0 { return GetError() } return nil } // SaveBMP saves the surface to a BMP file. // (https://wiki.libsdl.org/SDL_SaveBMP) func (surface *Surface) SaveBMP(file string) error { return surface.SaveBMPRW(RWFromFile(file, "wb"), true) } // SetRLE sets the RLE acceleration hint for the surface. // (https://wiki.libsdl.org/SDL_SetSurfaceRLE) func (surface *Surface) SetRLE(flag bool) error { if C.SDL_SetSurfaceRLE(surface.cptr(), C.int(Btoi(flag))) != 0 { return GetError() } return nil } // SetColorKey sets the color key (transparent pixel) in the surface. // (https://wiki.libsdl.org/SDL_SetColorKey) func (surface *Surface) SetColorKey(flag bool, key uint32) error { if C.SDL_SetColorKey(surface.cptr(), C.int(Btoi(flag)), C.Uint32(key)) != 0 { return GetError() } return nil } // HasColorKey returns the color key (transparent pixel) for the surface. // TODO: (https://wiki.libsdl.org/SDL_HasColorKey) func (surface *Surface) HasColorKey() bool { return C.SDL_HasColorKey(surface.cptr()) == C.SDL_TRUE } // GetColorKey returns the color key (transparent pixel) for the surface. // (https://wiki.libsdl.org/SDL_GetColorKey) func (surface *Surface) GetColorKey() (key uint32, err error) { _key := (*C.Uint32)(unsafe.Pointer(&key)) if C.SDL_GetColorKey(surface.cptr(), _key) != 0 { return key, GetError() } return key, nil } // SetColorMod sets an additional color value multiplied into blit operations. // (https://wiki.libsdl.org/SDL_SetSurfaceColorMod) func (surface *Surface) SetColorMod(r, g, b uint8) error { if C.SDL_SetSurfaceColorMod(surface.cptr(), C.Uint8(r), C.Uint8(g), C.Uint8(b)) != 0 { return GetError() } return nil } // GetColorMod returns the additional color value multiplied into blit operations. // (https://wiki.libsdl.org/SDL_GetSurfaceColorMod) func (surface *Surface) GetColorMod() (r, g, b uint8, err error) { _r := (*C.Uint8)(unsafe.Pointer(&r)) _g := (*C.Uint8)(unsafe.Pointer(&g)) _b := (*C.Uint8)(unsafe.Pointer(&b)) if C.SDL_GetSurfaceColorMod(surface.cptr(), _r, _g, _b) != 0 { return r, g, b, GetError() } return r, g, b, nil } // SetAlphaMod sets an additional alpha value used in blit operations. // (https://wiki.libsdl.org/SDL_SetSurfaceAlphaMod) func (surface *Surface) SetAlphaMod(alpha uint8) error { if C.SDL_SetSurfaceAlphaMod(surface.cptr(), C.Uint8(alpha)) != 0 { return GetError() } return nil } // GetAlphaMod returns the additional alpha value used in blit operations. // (https://wiki.libsdl.org/SDL_GetSurfaceAlphaMod) func (surface *Surface) GetAlphaMod() (alpha uint8, err error) { _alpha := (*C.Uint8)(unsafe.Pointer(&alpha)) if C.SDL_GetSurfaceAlphaMod(surface.cptr(), _alpha) != 0 { return alpha, GetError() } return alpha, nil } // SetBlendMode sets the blend mode used for blit operations. // (https://wiki.libsdl.org/SDL_SetSurfaceBlendMode) func (surface *Surface) SetBlendMode(bm BlendMode) error { if C.SDL_SetSurfaceBlendMode(surface.cptr(), bm.c()) != 0 { return GetError() } return nil } // GetBlendMode returns the blend mode used for blit operations. // (https://wiki.libsdl.org/SDL_GetSurfaceBlendMode) func (surface *Surface) GetBlendMode() (bm BlendMode, err error) { if C.SDL_GetSurfaceBlendMode(surface.cptr(), bm.cptr()) != 0 { return bm, GetError() } return bm, nil } // SetClipRect sets the clipping rectangle for the surface // (https://wiki.libsdl.org/SDL_SetClipRect) func (surface *Surface) SetClipRect(rect *Rect) bool { return C.SDL_SetClipRect(surface.cptr(), rect.cptr()) > 0 } // GetClipRect returns the clipping rectangle for a surface. // (https://wiki.libsdl.org/SDL_GetClipRect) func (surface *Surface) GetClipRect(rect *Rect) { C.SDL_GetClipRect(surface.cptr(), rect.cptr()) } // Convert copies the existing surface into a new one that is optimized for blitting to a surface of a specified pixel format. // (https://wiki.libsdl.org/SDL_ConvertSurface) func (surface *Surface) Convert(fmt *PixelFormat, flags uint32) (*Surface, error) { _surface := (*Surface)(unsafe.Pointer(C.SDL_ConvertSurface(surface.cptr(), fmt.cptr(), C.Uint32(flags)))) if _surface == nil { return nil, GetError() } return _surface, nil } // ConvertFormat copies the existing surface to a new surface of the specified format. // (https://wiki.libsdl.org/SDL_ConvertSurfaceFormat) func (surface *Surface) ConvertFormat(pixelFormat uint32, flags uint32) (*Surface, error) { _surface := (*Surface)(unsafe.Pointer(C.SDL_ConvertSurfaceFormat(surface.cptr(), C.Uint32(pixelFormat), C.Uint32(flags)))) if _surface == nil { return nil, GetError() } return _surface, nil } // ConvertPixels copies a block of pixels of one format to another format. // (https://wiki.libsdl.org/SDL_ConvertPixels) func ConvertPixels(width, height int32, srcFormat uint32, src unsafe.Pointer, srcPitch int, dstFormat uint32, dst unsafe.Pointer, dstPitch int) error { if C.SDL_ConvertPixels(C.int(width), C.int(height), C.Uint32(srcFormat), src, C.int(srcPitch), C.Uint32(dstFormat), dst, C.int(dstPitch)) != 0 { return GetError() } return nil } // FillRect performs a fast fill of a rectangle with a specific color. // (https://wiki.libsdl.org/SDL_FillRect) func (surface *Surface) FillRect(rect *Rect, color uint32) error { if C.SDL_FillRect(surface.cptr(), rect.cptr(), C.Uint32(color)) != 0 { return GetError() } return nil } // FillRects performs a fast fill of a set of rectangles with a specific color. // (https://wiki.libsdl.org/SDL_FillRects) func (surface *Surface) FillRects(rects []Rect, color uint32) error { if C.SDL_FillRects(surface.cptr(), rects[0].cptr(), C.int(len(rects)), C.Uint32(color)) != 0 { return GetError() } return nil } // Blit performs a fast surface copy to a destination surface. // (https://wiki.libsdl.org/SDL_BlitSurface) func (surface *Surface) Blit(srcRect *Rect, dst *Surface, dstRect *Rect) error { if C.SDL_BlitSurface(surface.cptr(), srcRect.cptr(), dst.cptr(), dstRect.cptr()) != 0 { return GetError() } return nil } // BlitScaled performs a scaled surface copy to a destination surface. // (https://wiki.libsdl.org/SDL_BlitScaled) func (surface *Surface) BlitScaled(srcRect *Rect, dst *Surface, dstRect *Rect) error { if C.SDL_BlitScaled(surface.cptr(), srcRect.cptr(), dst.cptr(), dstRect.cptr()) != 0 { return GetError() } return nil } // UpperBlit has been replaced by Blit(). // (https://wiki.libsdl.org/SDL_UpperBlit) func (surface *Surface) UpperBlit(srcRect *Rect, dst *Surface, dstRect *Rect) error { if C.SDL_UpperBlit(surface.cptr(), srcRect.cptr(), dst.cptr(), dstRect.cptr()) != 0 { return GetError() } return nil } // LowerBlit performs low-level surface blitting only. // (https://wiki.libsdl.org/SDL_LowerBlit) func (surface *Surface) LowerBlit(srcRect *Rect, dst *Surface, dstRect *Rect) error { if C.SDL_LowerBlit(surface.cptr(), srcRect.cptr(), dst.cptr(), dstRect.cptr()) != 0 { return GetError() } return nil } // SoftStretch has been replaced by BlitScaled(). // (https://wiki.libsdl.org/SDL_SoftStretch) func (surface *Surface) SoftStretch(srcRect *Rect, dst *Surface, dstRect *Rect) error { if C.SDL_SoftStretch(surface.cptr(), srcRect.cptr(), dst.cptr(), dstRect.cptr()) != 0 { return GetError() } return nil } // UpperBlitScaled has been replaced by BlitScaled(). // (https://wiki.libsdl.org/SDL_UpperBlitScaled) func (surface *Surface) UpperBlitScaled(srcRect *Rect, dst *Surface, dstRect *Rect) error { if C.SDL_UpperBlitScaled(surface.cptr(), srcRect.cptr(), dst.cptr(), dstRect.cptr()) != 0 { return GetError() } return nil } // LowerBlitScaled performs low-level surface scaled blitting only. // (https://wiki.libsdl.org/SDL_LowerBlitScaled) func (surface *Surface) LowerBlitScaled(srcRect *Rect, dst *Surface, dstRect *Rect) error { if C.SDL_LowerBlitScaled(surface.cptr(), srcRect.cptr(), dst.cptr(), dstRect.cptr()) != 0 { return GetError() } return nil } // PixelNum returns the number of pixels stored in the surface. func (surface *Surface) PixelNum() int { return int(surface.W * surface.H) } // BytesPerPixel return the number of significant bits in a pixel values of the surface. func (surface *Surface) BytesPerPixel() int { return int(surface.Format.BytesPerPixel) } // Pixels returns the actual pixel data of the surface. func (surface *Surface) Pixels() []byte { var b []byte length := int(surface.H) * int(surface.Pitch) sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b)) sliceHeader.Cap = int(length) sliceHeader.Len = int(length) sliceHeader.Data = uintptr(surface.pixels) return b } // Data returns the pointer to the actual pixel data of the surface. func (surface *Surface) Data() unsafe.Pointer { return surface.pixels } // Duplicate creates a new surface identical to the existing surface func (surface *Surface) Duplicate() (newSurface *Surface, err error) { _newSurface := C.SDL_DuplicateSurface(surface.cptr()) if _newSurface == nil { err = GetError() return } newSurface = (*Surface)(unsafe.Pointer(_newSurface)) return } // ColorModel returns the color model used by this Surface. func (surface *Surface) ColorModel() color.Model { switch surface.Format.Format { case PIXELFORMAT_ARGB8888, PIXELFORMAT_ABGR8888: return color.RGBAModel case PIXELFORMAT_RGB888: return color.RGBAModel case PIXELFORMAT_RGB444: return RGB444Model case PIXELFORMAT_RGB332: return RGB332Model case PIXELFORMAT_RGB555: return RGB555Model case PIXELFORMAT_RGB565: return RGB565Model case PIXELFORMAT_BGR555: return BGR555Model case PIXELFORMAT_BGR565: return BGR565Model case PIXELFORMAT_ARGB4444: return ARGB4444Model case PIXELFORMAT_ABGR4444: return ABGR4444Model case PIXELFORMAT_RGBA4444: return RGBA4444Model case PIXELFORMAT_BGRA4444: return BGRA4444Model case PIXELFORMAT_ARGB1555: return ARGB1555Model case PIXELFORMAT_RGBA5551: return RGBA5551Model case PIXELFORMAT_ABGR1555: return ABGR1555Model case PIXELFORMAT_BGRA5551: return BGRA5551Model case PIXELFORMAT_RGBA8888: return RGBA8888Model case PIXELFORMAT_BGRA8888: return BGRA8888Model default: panic("Not implemented yet") } } // Bounds return the bounds of this surface. Currently, it always starts at // (0,0), but this is not guaranteed in the future so don't rely on it. func (surface *Surface) Bounds() image.Rectangle { return image.Rect(0, 0, int(surface.W), int(surface.H)) } // At returns the pixel color at (x, y) func (surface *Surface) At(x, y int) color.Color { pix := surface.Pixels() i := int32(y)*surface.Pitch + int32(x)*int32(surface.Format.BytesPerPixel) r, g, b, a := GetRGBA(*((*uint32)(unsafe.Pointer(&pix[i]))), surface.Format) return color.NRGBA{R: r, G: g, B: b, A: a} } // Set the color of the pixel at (x, y) using this surface's color format to // convert c to the appropriate byte sequence. This method is required for the // draw.Image interface. The surface may require locking before calling Set. func (surface *Surface) Set(x, y int, c color.Color) { // All sdl2 colors are a subset of NRGBA so it is safe precision-wise to // convert to NRGBA and use the color components from there. nrgbaColor := color.NRGBAModel.Convert(c).(color.NRGBA) colR, colG, colB, colA := nrgbaColor.R, nrgbaColor.G, nrgbaColor.B, nrgbaColor.A pix := surface.Pixels() i := int32(y)*surface.Pitch + int32(x)*int32(surface.Format.BytesPerPixel) switch surface.Format.Format { case PIXELFORMAT_ARGB8888: pix[i+3] = colA pix[i+2] = colR pix[i+1] = colG pix[i+0] = colB case PIXELFORMAT_ABGR8888: pix[i+3] = colA pix[i+2] = colB pix[i+1] = colG pix[i+0] = colR case PIXELFORMAT_RGB24, PIXELFORMAT_RGB888: pix[i+2] = colR pix[i+1] = colG pix[i+0] = colB case PIXELFORMAT_BGR24, PIXELFORMAT_BGR888: pix[i+2] = colB pix[i+1] = colG pix[i+0] = colR case PIXELFORMAT_RGB444: buf := (*uint32)(unsafe.Pointer(&pix[i])) r := uint32(colR) >> 4 & 0x0F g := uint32(colG) >> 4 & 0x0F b := uint32(colB) >> 4 & 0x0F *buf = r<<8 | g<<4 | b case PIXELFORMAT_RGB332: buf := (*uint32)(unsafe.Pointer(&pix[i])) r := uint32(colR) >> 5 & 0x0F g := uint32(colG) >> 5 & 0x0F b := uint32(colB) >> 6 & 0x0F *buf = r<<5 | g<<2 | b case PIXELFORMAT_RGB565: buf := (*uint32)(unsafe.Pointer(&pix[i])) r := uint32(colR) >> 3 & 0xFF g := uint32(colG) >> 2 & 0xFF b := uint32(colB) >> 3 & 0xFF *buf = r<<11 | g<<5 | b case PIXELFORMAT_RGB555: buf := (*uint32)(unsafe.Pointer(&pix[i])) r := uint32(colR) >> 3 & 0xFF g := uint32(colG) >> 3 & 0xFF b := uint32(colB) >> 3 & 0xFF *buf = r<<10 | g<<5 | b case PIXELFORMAT_BGR565: buf := (*uint32)(unsafe.Pointer(&pix[i])) r := uint32(colR) >> 3 & 0xFF g := uint32(colG) >> 2 & 0xFF b := uint32(colB) >> 3 & 0xFF *buf = b<<11 | g<<5 | r case PIXELFORMAT_BGR555: buf := (*uint32)(unsafe.Pointer(&pix[i])) r := uint32(colR) >> 3 & 0xFF g := uint32(colG) >> 3 & 0xFF b := uint32(colB) >> 3 & 0xFF *buf = b<<10 | g<<5 | r case PIXELFORMAT_ARGB4444: buf := (*uint32)(unsafe.Pointer(&pix[i])) a := uint32(colA) >> 4 & 0x0F r := uint32(colR) >> 4 & 0x0F g := uint32(colG) >> 4 & 0x0F b := uint32(colB) >> 4 & 0x0F *buf = a<<12 | r<<8 | g<<4 | b case PIXELFORMAT_ABGR4444: buf := (*uint32)(unsafe.Pointer(&pix[i])) a := uint32(colA) >> 4 & 0x0F r := uint32(colR) >> 4 & 0x0F g := uint32(colG) >> 4 & 0x0F b := uint32(colB) >> 4 & 0x0F *buf = a<<12 | b<<8 | g<<4 | r case PIXELFORMAT_RGBA4444: buf := (*uint32)(unsafe.Pointer(&pix[i])) r := uint32(colR) >> 4 & 0x0F g := uint32(colG) >> 4 & 0x0F b := uint32(colB) >> 4 & 0x0F a := uint32(colA) >> 4 & 0x0F *buf = r<<12 | g<<8 | b<<4 | a case PIXELFORMAT_BGRA4444: buf := (*uint32)(unsafe.Pointer(&pix[i])) r := uint32(colR) >> 4 & 0x0F g := uint32(colG) >> 4 & 0x0F b := uint32(colB) >> 4 & 0x0F a := uint32(colA) >> 4 & 0x0F *buf = b<<12 | g<<8 | r<<4 | a case PIXELFORMAT_ARGB1555: buf := (*uint32)(unsafe.Pointer(&pix[i])) r := uint32(colR) >> 3 & 0xFF g := uint32(colG) >> 3 & 0xFF b := uint32(colB) >> 3 & 0xFF a := uint32(0) if colA > 0 { a = 1 } *buf = a<<15 | r<<10 | g<<5 | b case PIXELFORMAT_RGBA5551: buf := (*uint32)(unsafe.Pointer(&pix[i])) r := uint32(colR) >> 3 & 0xFF g := uint32(colG) >> 3 & 0xFF b := uint32(colB) >> 3 & 0xFF a := uint32(0) if colA > 0 { a = 1 } *buf = r<<11 | g<<6 | b<<1 | a case PIXELFORMAT_ABGR1555: buf := (*uint32)(unsafe.Pointer(&pix[i])) r := uint32(colR) >> 3 & 0xFF g := uint32(colG) >> 3 & 0xFF b := uint32(colB) >> 3 & 0xFF a := uint32(0) if colA > 0 { a = 1 } *buf = a<<15 | b<<10 | g<<5 | r case PIXELFORMAT_BGRA5551: buf := (*uint32)(unsafe.Pointer(&pix[i])) r := uint32(colR) >> 3 & 0xFF g := uint32(colG) >> 3 & 0xFF b := uint32(colB) >> 3 & 0xFF a := uint32(0) if colA > 0 { a = 1 } *buf = b<<11 | g<<6 | r<<1 | a case PIXELFORMAT_RGBA8888: pix[i+3] = colR pix[i+2] = colG pix[i+1] = colB pix[i+0] = colA case PIXELFORMAT_BGRA8888: pix[i+3] = colB pix[i+2] = colG pix[i+1] = colR pix[i+0] = colA default: panic("Unknown pixel format!") } } // SoftStretchLinear performs bilinear scaling between two surfaces of the same format, 32BPP. // (https://wiki.libsdl.org/SDL_SoftStretchLinear) func (surface *Surface) SoftStretchLinear(srcRect *Rect, dst *Surface, dstRect *Rect) (err error) { return errorFromInt(int(C.SDL_SoftStretchLinear(surface.cptr(), srcRect.cptr(), dst.cptr(), dstRect.cptr()))) } // PremultiplyAlpha premultiplies the alpha on a block of pixels. // // This is safe to use with src == dst, but not for other overlapping areas. // // This function is currently only implemented for SDL_PIXELFORMAT_ARGB8888. // // (https://wiki.libsdl.org/SDL_PremultiplyAlpha) func PremultiplyAlpha(width, height int, srcFormat uint32, src []byte, srcPitch int, dstFormat uint32, dst []byte, dstPitch int) (err error) { _width := C.int(width) _height := C.int(height) _srcFormat := C.Uint32(srcFormat) _src := unsafe.Pointer(&src[0]) _srcPitch := C.int(srcPitch) _dstFormat := C.Uint32(dstFormat) _dst := unsafe.Pointer(&dst[0]) _dstPitch := C.int(dstPitch) err = errorFromInt(int(C.SDL_PremultiplyAlpha(_width, _height, _srcFormat, _src, _srcPitch, _dstFormat, _dst, _dstPitch))) return } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/sysrender.go ================================================ package sdl // #include "sdl_wrapper.h" import "C" import "unsafe" // Texture contains an efficient, driver-specific representation of pixel data. // (https://wiki.libsdl.org/SDL_Texture) type Texture C.SDL_Texture // Renderer contains a rendering state. // (https://wiki.libsdl.org/SDL_Renderer) type Renderer C.SDL_Renderer func (t *Texture) cptr() *C.SDL_Texture { return (*C.SDL_Texture)(unsafe.Pointer(t)) } func (r *Renderer) cptr() *C.SDL_Renderer { return (*C.SDL_Renderer)(unsafe.Pointer(r)) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/system.c ================================================ #include "_cgo_export.h" #include "system.h" #if defined(_WIN32) void SetWindowsMessageHook() { SDL_SetWindowsMessageHook((SDL_WindowsMessageHook) goWindowsMessageHook, NULL); } #endif ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/system.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,9)) #if defined(WARN_OUTDATED) #pragma message("SDL_IsTablet is not supported before SDL 2.0.9") #endif static inline SDL_bool SDL_IsTablet() { return SDL_FALSE; } #endif */ import "C" // IsTablet returns true if the current device is a tablet // TODO: (https://wiki.libsdl.org/SDL_IsTablet) func IsTablet() bool { return C.SDL_IsTablet() == C.SDL_TRUE } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/system.h ================================================ #ifndef _GO_SDL_SYSTEM_H #define _GO_SDL_SYSTEM_H #if defined(_WIN32) extern void SetWindowsMessageHook(); #endif #endif ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/system_android.go ================================================ // +build go1.4 package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,8)) #if defined(WARN_OUTDATED) #pragma message("SDL_IsAndroidTV is not supported before SDL 2.0.8") #endif static int SDL_IsAndroidTV(void) { return -1; } #endif #if !(SDL_VERSION_ATLEAST(2,0,16)) #if defined(WARN_OUTDATED) #pragma message("SDL_AndroidShowToast is not supported before SDL 2.0.16") #endif static int SDL_AndroidShowToast(const char* message, int duration, int gravity, int xoffset, int yoffset) { return -1; } #endif */ import "C" import "unsafe" // External storage states. See the official Android developer guide for more information. // (http://developer.android.com/guide/topics/data/data-storage.html) const ( ANDROID_EXTERNAL_STORAGE_READ = C.SDL_ANDROID_EXTERNAL_STORAGE_READ ANDROID_EXTERNAL_STORAGE_WRITE = C.SDL_ANDROID_EXTERNAL_STORAGE_WRITE ) // AndroidGetInternalStoragePath returns the path used for internal storage for this application. // (https://wiki.libsdl.org/SDL_AndroidGetInternalStoragePath) func AndroidGetInternalStoragePath() string { return C.GoString(C.SDL_AndroidGetInternalStoragePath()) } // AndroidGetExternalStoragePath returns the path used for external storage for this application. // (https://wiki.libsdl.org/SDL_AndroidGetExternalStoragePath) func AndroidGetExternalStoragePath() string { return C.GoString(C.SDL_AndroidGetExternalStoragePath()) } // AndroidGetExternalStorageState returns the current state of external storage. // (https://wiki.libsdl.org/SDL_AndroidGetExternalStorageState) func AndroidGetExternalStorageState() int { return int(C.SDL_AndroidGetExternalStorageState()) } // AndroidGetJNIEnv returns the Java native interface object (JNIEnv) of the current thread on Android builds. // (https://wiki.libsdl.org/SDL_AndroidGetJNIEnv) func AndroidGetJNIEnv() unsafe.Pointer { return unsafe.Pointer(C.SDL_AndroidGetJNIEnv()) } // AndroidGetActivity returns the Java instance of the activity class in an Android application. // (https://wiki.libsdl.org/SDL_AndroidGetActivity) func AndroidGetActivity() unsafe.Pointer { return unsafe.Pointer(C.SDL_AndroidGetActivity()) } // IsAndroidTV returns true if the application is running on Android TV // (https://wiki.libsdl.org/SDL_IsAndroidTV) func IsAndroidTV() bool { return C.SDL_IsAndroidTV() >= 0 } // AndroidShowToast shows an Android toast notification. // (https://wiki.libsdl.org/SDL_AndroidShowToast) func AndroidShowToast(message string, duration, gravity, xoffset, yoffset int) (err error) { _message := C.CString(message) defer C.free(unsafe.Pointer(_message)) return errorFromInt(int(C.SDL_AndroidShowToast(_message, C.int(duration), C.int(gravity), C.int(xoffset), C.int(yoffset)))) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/system_linux.go ================================================ // +build !android package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,9)) #if defined(WARN_OUTDATED) #pragma message("SDL_LinuxSetThreadPriority is not supported before SDL 2.0.9") #endif static int SDL_LinuxSetThreadPriority(Sint64 threadID, int priority) { return -1; } #endif #if !(SDL_VERSION_ATLEAST(2,0,18)) #if defined(WARN_OUTDATED) #pragma message("SDL_LinuxSetThreadPriorityAndPolicy is not supported before SDL 2.0.18") #endif static int SDL_LinuxSetThreadPriorityAndPolicy(Sint64 threadID, int sdlPriority, int schedPolicy) { return -1; } #endif */ import "C" // LinuxSetThreadPriority sets the UNIX nice value for a thread. // // This uses setpriority() if possible, and RealtimeKit if available. // // (https://wiki.libsdl.org/SDL_LinuxSetThreadPriority) func LinuxSetThreadPriority(threadID int64, priority int) (err error) { _threadID := C.Sint64(threadID) _priority := C.int(priority) return errorFromInt(int(C.SDL_LinuxSetThreadPriority(_threadID, _priority))) } // LinuxSetThreadPriority sets the priority (not nice level) and scheduling policy for a thread. // // This uses setpriority() if possible, and RealtimeKit if available. // // (https://wiki.libsdl.org/SDL_LinuxSetThreadPriorityAndPolicy) func LinuxSetThreadPriorityAndPolicy(threadID int64, sdlPriority, schedPolicy int) (err error) { _threadID := C.Sint64(threadID) _sdlPriority := C.int(sdlPriority) _schedPolicy := C.int(schedPolicy) return errorFromInt(int(C.SDL_LinuxSetThreadPriorityAndPolicy(_threadID, _sdlPriority, _schedPolicy))) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/system_windows.go ================================================ package sdl /* #include "sdl_wrapper.h" #include "system.h" #if !(SDL_VERSION_ATLEAST(2,0,16)) #if defined(WARN_OUTDATED) #pragma message("SDL_RenderGetD3D11Device is not supported before SDL 2.0.16") #endif typedef struct ID3D11Device ID3D11Device; static ID3D11Device* SDL_RenderGetD3D11Device(SDL_Renderer * renderer) { return NULL; } #endif */ import "C" import ( "unsafe" ) type WindowsMessageHook func(userdata interface{}, hWnd unsafe.Pointer, message uint32, wParam uint64, lParam int64) var windowsMessageHook WindowsMessageHook type ID3D11Device C.ID3D11Device; // SetWindowsMessageHook sets a callback for every Windows message, run before TranslateMessage(). // (https://wiki.libsdl.org/SDL_SetWindowsMessageHook) func SetWindowsMessageHook(callback WindowsMessageHook, userdata interface{}) { windowsMessageHook = callback C.SetWindowsMessageHook() } //export goWindowsMessageHook func goWindowsMessageHook(userdata interface{}, hWnd unsafe.Pointer, message uint32, wParam uint64, lParam int64) { if windowsMessageHook == nil { return } windowsMessageHook(userdata, hWnd, message, wParam, lParam) } // SDL_RenderGetD3D11Device gets the D3D11 device associated with a renderer. // (https://wiki.libsdl.org/SDL_RenderGetD3D11Device) func (renderer *Renderer) GetD3D11Device() (device *ID3D11Device, err error) { device = (*ID3D11Device)(C.SDL_RenderGetD3D11Device(renderer.cptr())) if device == nil { err = GetError() } return } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/syswm.go ================================================ package sdl /* #include "sdl_wrapper.h" #if defined(__WIN32) #include #else #include #endif #if !(SDL_VERSION_ATLEAST(2,0,2)) #define SDL_SYSWM_WAYLAND SDL_SYSWM_UNKNOWN #define SDL_SYSWM_MIR SDL_SYSWM_UNKNOWN #endif #if !(SDL_VERSION_ATLEAST(2,0,3)) #if defined(WARN_OUTDATED) #pragma message("SDL_SYSWM_WINRT is not supported before SDL 2.0.3") #endif #define SDL_SYSWM_WINRT (0) #endif #if !(SDL_VERSION_ATLEAST(2,0,4)) #if defined(WARN_OUTDATED) #pragma message("SDL_SYSWM_ANDROID is not supported before SDL 2.0.4") #endif #define SDL_SYSWM_ANDROID (0) #endif #if !(SDL_VERSION_ATLEAST(2,0,5)) #if defined(WARN_OUTDATED) #pragma message("SDL_SYSWM_VIVANTE is not supported before SDL 2.0.5") #endif #define SDL_SYSWM_VIVANTE (0) #endif */ import "C" import "unsafe" // Various supported windowing subsystems. const ( SYSWM_UNKNOWN = C.SDL_SYSWM_UNKNOWN SYSWM_WINDOWS = C.SDL_SYSWM_WINDOWS // Microsoft Windows SYSWM_X11 = C.SDL_SYSWM_X11 // X Window System SYSWM_DIRECTFB = C.SDL_SYSWM_DIRECTFB // DirectFB SYSWM_COCOA = C.SDL_SYSWM_COCOA // Apple Mac OS X SYSWM_UIKIT = C.SDL_SYSWM_UIKIT // Apple iOS SYSWM_WAYLAND = C.SDL_SYSWM_WAYLAND // Wayland (>= SDL 2.0.2) SYSWM_MIR = C.SDL_SYSWM_MIR // Mir (>= SDL 2.0.2) SYSWM_WINRT = C.SDL_SYSWM_WINRT // WinRT (>= SDL 2.0.3) SYSWM_ANDROID = C.SDL_SYSWM_ANDROID // Android (>= SDL 2.0.4) SYSWM_VIVANTE = C.SDL_SYSWM_VIVANTE // Vivante (>= SDL 2.0.5) ) // SysWMInfo contains system-dependent information about a window. // (https://wiki.libsdl.org/SDL_SysWMinfo) type SysWMInfo struct { Version Version // a Version structure that contains the current SDL version Subsystem uint32 // the windowing system type dummy [24]byte // unused (to help compilers when no specific system is available) } // WindowsInfo contains Microsoft Windows window information. type WindowsInfo struct { Window unsafe.Pointer // the window handle DeviceContext unsafe.Pointer // the device context handle Instance unsafe.Pointer // the instance handle } // X11Info contains X Window System window information. type X11Info struct { Display unsafe.Pointer // the X11 display Window uint // the X11 window } // DFBInfo contains DirectFB window information. type DFBInfo struct { Dfb unsafe.Pointer // the DirectFB main interface Window unsafe.Pointer // the DirectFB window handle Surface unsafe.Pointer // the DirectFB client surface } // CocoaInfo contains Apple Mac OS X window information. type CocoaInfo struct { Window unsafe.Pointer // the Cocoa window } // UIKitInfo contains Apple iOS window information. type UIKitInfo struct { Window unsafe.Pointer // the UIKit window } // SysWMmsg contains system-dependent window manager messages. // (https://wiki.libsdl.org/SDL_SysWMmsg) type SysWMmsg struct { Version Version // a Version structure that contains the current SDL version Subsystem uint32 // the windowing system type data [24]byte // internal data } func (info *SysWMInfo) cptr() *C.SDL_SysWMinfo { return (*C.SDL_SysWMinfo)(unsafe.Pointer(info)) } // GetWMInfo returns driver specific information about a window. // (https://wiki.libsdl.org/SDL_GetWindowWMInfo) func (window *Window) GetWMInfo() (*SysWMInfo, error) { var info SysWMInfo VERSION(&info.Version) if C.SDL_GetWindowWMInfo(window.cptr(), info.cptr()) == 0 { return nil, GetError() } return &info, nil } // GetWindowsInfo returns Microsoft Windows window information. func (info *SysWMInfo) GetWindowsInfo() *WindowsInfo { return (*WindowsInfo)(unsafe.Pointer(&info.dummy[0])) } // GetX11Info returns X Window System window information. func (info *SysWMInfo) GetX11Info() *X11Info { return (*X11Info)(unsafe.Pointer(&info.dummy[0])) } // GetDFBInfo returns DirectFB window information. func (info *SysWMInfo) GetDFBInfo() *DFBInfo { return (*DFBInfo)(unsafe.Pointer(&info.dummy[0])) } // GetCocoaInfo returns Apple Mac OS X window information. func (info *SysWMInfo) GetCocoaInfo() *CocoaInfo { return (*CocoaInfo)(unsafe.Pointer(&info.dummy[0])) } // GetUIKitInfo returns Apple iOS window information. func (info *SysWMInfo) GetUIKitInfo() *UIKitInfo { return (*UIKitInfo)(unsafe.Pointer(&info.dummy[0])) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/syswm_cocoa.go ================================================ // +build cocoa OR darwin package sdl import "C" import "unsafe" // CocoaMsg contains Apple Mac OS X window information. type CocoaMsg struct { dummy C.int } // Cocoa() returns Apple Mac OS X message. func (msg *SysWMmsg) Cocoa() *CocoaMsg { return (*CocoaMsg)(unsafe.Pointer(&msg.data[0])) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/syswm_dfb.go ================================================ // +build dfb package sdl import "C" import "unsafe" // DFBMsg contains DirectFB window information. type DFBMsg struct { Event C.DFBEvent } // DFB() returns DirectFB message. func (msg *SysWMmsg) DFB() *DFBMsg { return (*DFBMsg)(unsafe.Pointer(&msg.data[0])) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/syswm_uikit.go ================================================ // +build uikit package sdl import "C" import "unsafe" // UIKitMsg contains Apple iOS window information. type UIKitMsg struct { dummy C.int } // UIKit() returns Apple iOS message. func (msg *SysWMmsg) UIKit() *UIKitMsg { return (*UIKitMsg)(unsafe.Pointer(&msg.data[0])) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/syswm_vivante.go ================================================ // +build vivante package sdl import "C" import "unsafe" // VivanteKitMsg contains Vivante window information. type VivanteKitMsg struct { dummy C.int } // Vivante() returns Vivante message. func (msg *SysWMmsg) Vivante() *VivanteMsg { return (*VivanteMsg)(unsafe.Pointer(&msg.data[0])) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/syswm_windows.go ================================================ // +build windows package sdl /* #include */ import "C" import "unsafe" // WindowsMsg contains Microsoft Windows window information. type WindowsMsg struct { Hwnd C.HWND Msg C.UINT WParam C.WPARAM LParam C.LPARAM } // Windows() returns Microsoft Windows message. func (msg *SysWMmsg) Windows() *WindowsMsg { return (*WindowsMsg)(unsafe.Pointer(&msg.data[0])) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/syswm_x11.go ================================================ // +build x11 package sdl /* #include */ import "C" import "unsafe" // X11Msg contains X Window System window information. type X11Msg struct { Event C.XEvent } // X11() returns X Window System message. func (msg *SysWMmsg) X11() *X11Msg { return (*X11Msg)(unsafe.Pointer(&msg.data[0])) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/thread.go ================================================ package sdl // #include "sdl_wrapper.h" import "C" // CurrentThreadID gets the thread identifier for the current thread. // (https://wiki.libsdl.org/SDL_ThreadID) func CurrentThreadID() uint { return uint(C.SDL_ThreadID()) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/timer.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,18)) #if defined(WARN_OUTDATED) #pragma message("SDL_GetTicks64 is not supported before SDL 2.0.18") #endif static inline Uint64 SDLCALL SDL_GetTicks64(void) { return 0; } #endif */ import "C" // GetTicks returns the number of milliseconds since the SDL library initialization. // // Deprecated: This function is not recommended as of SDL 2.0.18; use GetTicks64() // instead, where the value doesn't wrap every ~49 days. There are places in // SDL where we provide a 32-bit timestamp that can not change without // breaking binary compatibility, though, so this function isn't officially // deprecated. // // (https://wiki.libsdl.org/SDL_GetTicks) func GetTicks() uint32 { return uint32(C.SDL_GetTicks()) } // GetTicks64 returns the number of milliseconds since the SDL library initialization. // (https://wiki.libsdl.org/SDL_GetTicks64) func GetTicks64() uint64 { return uint64(C.SDL_GetTicks64()) } // GetPerformanceCounter returns the current value of the high resolution counter. // (https://wiki.libsdl.org/SDL_GetPerformanceCounter) func GetPerformanceCounter() uint64 { return uint64(C.SDL_GetPerformanceCounter()) } // GetPerformanceFrequency returns the count per second of the high resolution counter. // (https://wiki.libsdl.org/SDL_GetPerformanceFrequency) func GetPerformanceFrequency() uint64 { return uint64(C.SDL_GetPerformanceFrequency()) } // Delay waits a specified number of milliseconds before returning. // (https://wiki.libsdl.org/SDL_Delay) func Delay(ms uint32) { C.SDL_Delay(C.Uint32(ms)) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/touch.go ================================================ package sdl /* #include "sdl_wrapper.h" #if !(SDL_VERSION_ATLEAST(2,0,10)) typedef enum { SDL_TOUCH_DEVICE_INVALID = -1, SDL_TOUCH_DEVICE_DIRECT, // touch screen with window-relative coordinates SDL_TOUCH_DEVICE_INDIRECT_ABSOLUTE, // trackpad with absolute device coordinates SDL_TOUCH_DEVICE_INDIRECT_RELATIVE // trackpad with screen cursor-relative coordinates } SDL_TouchDeviceType; #if defined(WARN_OUTDATED) #pragma message("SDL_GetTouchDeviceType is not supported before SDL 2.0.10") #endif static inline SDL_TouchDeviceType SDL_GetTouchDeviceType(SDL_TouchID touchID) { return SDL_TOUCH_DEVICE_INVALID; } #endif */ import "C" import "unsafe" // TOUCH_MOUSEID is the device ID for mouse events simulated with touch input const TOUCH_MOUSEID = C.SDL_TOUCH_MOUSEID // TouchID is the ID of a touch device. type TouchID C.SDL_TouchID // FingerID is a finger id. type FingerID C.SDL_FingerID // TouchDeviceType is a touch device type. type TouchDeviceType C.SDL_TouchDeviceType const ( TOUCH_DEVICE_INVALID TouchDeviceType = C.SDL_TOUCH_DEVICE_INVALID TOUCH_DEVICE_DIRECT = C.SDL_TOUCH_DEVICE_DIRECT // touch screen with window-relative coordinates TOUCH_DEVICE_INDIRECT_ABSOLUTE = C.SDL_TOUCH_DEVICE_INDIRECT_ABSOLUTE // trackpad with absolute device coordinates TOUCH_DEVICE_INDIRECT_RELATIVE = C.SDL_TOUCH_DEVICE_INDIRECT_RELATIVE // trackpad with screen cursor-relative coordinates ) // Finger contains touch information. type Finger struct { ID FingerID // the finger id X float32 // the x-axis location of the touch event, normalized (0...1) Y float32 // the y-axis location of the touch event, normalized (0...1) Pressure float32 // the quantity of pressure applied, normalized (0...1) } func (t TouchID) c() C.SDL_TouchID { return C.SDL_TouchID(t) } // GetNumTouchDevices returns the number of registered touch devices. // (https://wiki.libsdl.org/SDL_GetNumTouchDevices) func GetNumTouchDevices() int { return int(C.SDL_GetNumTouchDevices()) } // GetTouchDevice returns the touch ID with the given index. // (https://wiki.libsdl.org/SDL_GetTouchDevice) func GetTouchDevice(index int) TouchID { return TouchID(C.SDL_GetTouchDevice(C.int(index))) } // GetTouchDeviceType returns the type of the given touch device. // TODO: (https://wiki.libsdl.org/SDL_GetTouchDeviceType) func GetTouchDeviceType(id TouchID) TouchDeviceType { return TouchDeviceType(C.SDL_GetTouchDeviceType(C.SDL_TouchID(id))) } // GetNumTouchFingers returns the number of active fingers for a given touch device. // (https://wiki.libsdl.org/SDL_GetNumTouchFingers) func GetNumTouchFingers(t TouchID) int { return int(C.SDL_GetNumTouchFingers(t.c())) } // GetTouchFinger returns the finger object for specified touch device ID and finger index. // (https://wiki.libsdl.org/SDL_GetTouchFinger) func GetTouchFinger(t TouchID, index int) *Finger { return (*Finger)(unsafe.Pointer(C.SDL_GetTouchFinger(t.c(), C.int(index)))) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/version.go ================================================ package sdl /* #include "sdl_wrapper.h" #if SDL_VERSION_ATLEAST(2,0,16) static inline int GetRevisionNumber(void) { return 0; } #else static inline int GetRevisionNumber(void) { return SDL_GetRevisionNumber(); } #endif */ import "C" import "unsafe" // The version of SDL in use. const ( MAJOR_VERSION = C.SDL_MAJOR_VERSION // major version MINOR_VERSION = C.SDL_MINOR_VERSION // minor version PATCHLEVEL = C.SDL_PATCHLEVEL // update version (patchlevel) ) // Version contains information about the version of SDL in use. // (https://wiki.libsdl.org/SDL_version) type Version struct { Major uint8 // major version Minor uint8 // minor version Patch uint8 // update version (patchlevel) } type cVersion C.SDL_version func (v *Version) cptr() *C.SDL_version { return (*C.SDL_version)(unsafe.Pointer(v)) } // VERSION fills the selected struct with the version of SDL in use. // (https://wiki.libsdl.org/SDL_VERSION) func VERSION(v *Version) { v.Major = MAJOR_VERSION v.Minor = MINOR_VERSION v.Patch = PATCHLEVEL } // VERSIONNUM converts separate version components into a single numeric value. // (https://wiki.libsdl.org/SDL_VERSIONNUM) func VERSIONNUM(x, y, z int) int { return (x*1000 + y*100 + z) } // COMPILEDVERSION returns the SDL version number that you compiled against. // (https://wiki.libsdl.org/SDL_COMPILEDVERSION) func COMPILEDVERSION() int { return VERSIONNUM(MAJOR_VERSION, MINOR_VERSION, PATCHLEVEL) } // VERSION_ATLEAST reports whether the SDL version compiled against is at least as new as the specified version. // (https://wiki.libsdl.org/SDL_VERSION_ATLEAST) func VERSION_ATLEAST(x, y, z int) bool { return COMPILEDVERSION() >= VERSIONNUM(x, y, z) } // GetVersion returns the version of SDL that is linked against your program. // (https://wiki.libsdl.org/SDL_GetVersion) func GetVersion(v *Version) { C.SDL_GetVersion(v.cptr()) } // GetRevision returns the code revision of SDL that is linked against your program. // (https://wiki.libsdl.org/SDL_GetRevision) func GetRevision() string { return (string)(C.GoString(C.SDL_GetRevision())) } // Deprecated: GetRevisionNumber is deprecated in SDL2 2.0.16 and will return 0. Users should use GetRevision instead. func GetRevisionNumber() int { return (int)(C.GetRevisionNumber()) } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/video.go ================================================ package sdl /* #include "sdl_wrapper.h" static inline Sint32 ShowMessageBox(SDL_MessageBoxData data) { Sint32 buttonid; SDL_ShowMessageBox(&data, &buttonid); return buttonid; } #if !(SDL_VERSION_ATLEAST(2,0,1)) static void SDL_GL_GetDrawableSize(SDL_Window *window, int *w, int *h) { *w = 0; *h = 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_WINDOW_ALLOW_HIGHDPI is not supported before SDL 2.0.1") #endif #define SDL_WINDOW_ALLOW_HIGHDPI (0) #if defined(WARN_OUTDATED) #pragma message("SDL_GL_FRAMEBUFFER_SRGB_CAPABLE is not supported before SDL 2.0.1") #endif #define SDL_GL_FRAMEBUFFER_SRGB_CAPABLE (0) #endif #if !(SDL_VERSION_ATLEAST(2,0,4)) #if defined(WARN_OUTDATED) #pragma message("SDL_WINDOW_MOUSE_CAPTURE is not supported before SDL 2.0.4") #endif #define SDL_WINDOW_MOUSE_CAPTURE (0) #if defined(WARN_OUTDATED) #pragma message("SDL_GL_CONTEXT_RELEASE_BEHAVIOR is not supported before SDL 2.0.4") #endif #define SDL_GL_CONTEXT_RELEASE_BEHAVIOR (0) #if defined(WARN_OUTDATED) #pragma message("SDL_GetDisplayDPI is not supported before SDL 2.0.4") #endif static int SDL_GetDisplayDPI(int displayIndex, float* ddpi, float* hdpi, float* vdpi) { return -1; } #endif #if !(SDL_VERSION_ATLEAST(2,0,5)) #if defined(WARN_OUTDATED) #pragma message("SDL_SetWindowResizable is not supported before SDL 2.0.5") #endif static void SDL_SetWindowResizable(SDL_Window *window, SDL_bool resizable) { } #if defined(WARN_OUTDATED) #pragma message("SDL_SetWindowOpacity is not supported before SDL 2.0.5") #endif static int SDL_SetWindowOpacity(SDL_Window *window, float opacity) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_GetWindowOpacity is not supported before SDL 2.0.5") #endif static int SDL_GetWindowOpacity(SDL_Window *window, float *opacity) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_GetDisplayUsableBounds is not supported before SDL 2.0.5") #endif static int SDL_GetDisplayUsableBounds(int displayIndex, SDL_Rect* rect) { return -1; } #if defined(WARN_OUTDATED) #pragma message("SDL_WINDOW_ALWAYS_ON_TOP is not supported before SDL 2.0.5") #endif #define SDL_WINDOW_ALWAYS_ON_TOP (0) #if defined(WARN_OUTDATED) #pragma message("SDL_WINDOW_SKIP_TASKBAR is not supported before SDL 2.0.5") #endif #define SDL_WINDOW_SKIP_TASKBAR (0) #if defined(WARN_OUTDATED) #pragma message("SDL_WINDOW_UTILITY is not supported before SDL 2.0.5") #endif #define SDL_WINDOW_UTILITY (0) #if defined(WARN_OUTDATED) #pragma message("SDL_WINDOW_TOOLTIP is not supported before SDL 2.0.5") #endif #define SDL_WINDOW_TOOLTIP (0) #if defined(WARN_OUTDATED) #pragma message("SDL_WINDOW_POPUP_MENU is not supported before SDL 2.0.5") #endif #define SDL_WINDOW_POPUP_MENU (0) #if defined(WARN_OUTDATED) #pragma message("SDL_WINDOWEVENT_TAKE_FOCUS is not supported before SDL 2.0.5") #endif #define SDL_WINDOWEVENT_TAKE_FOCUS (0) #if defined(WARN_OUTDATED) #pragma message("SDL_WINDOWEVENT_HIT_TEST is not supported before SDL 2.0.5") #endif #define SDL_WINDOWEVENT_HIT_TEST (0) #endif #if !(SDL_VERSION_ATLEAST(2,0,6)) #if defined(WARN_OUTDATED) #pragma message("SDL_WINDOW_VULKAN is not supported before SDL 2.0.6") #endif #define SDL_WINDOW_VULKAN (0) #if defined(WARN_OUTDATED) #pragma message("SDL_GL_CONTEXT_RESET_NOTIFICATION is not supported before SDL 2.0.6") #endif #define SDL_GL_CONTEXT_RESET_NOTIFICATION (0) #if defined(WARN_OUTDATED) #pragma message("SDL_GL_CONTEXT_NO_ERROR is not supported before SDL 2.0.6") #endif #define SDL_GL_CONTEXT_NO_ERROR (0) #endif #if !(SDL_VERSION_ATLEAST(2,0,16)) #if defined(WARN_OUTDATED) #pragma message("SDL_FlashWindow is not supported before SDL 2.0.16") #pragma message("SDL_SetWindowAlwaysOnTop is not supported before SDL 2.0.16") #pragma message("SDL_SetWindowKeyboardGrab is not supported before SDL 2.0.16") #endif typedef enum { SDL_FLASH_CANCEL, // Cancel any window flash state SDL_FLASH_BRIEFLY, // Flash the window briefly to get attention SDL_FLASH_UNTIL_FOCUSED, // Flash the window until it gets focus } SDL_FlashOperation; static int SDL_FlashWindow(SDL_Window * window, SDL_FlashOperation operation) { return -1; } static void SDL_SetWindowAlwaysOnTop(SDL_Window * window, SDL_bool on_top) { return; } static void SDL_SetWindowKeyboardGrab(SDL_Window * window, SDL_bool grabbed) { return; } #endif #if !(SDL_VERSION_ATLEAST(2,0,18)) #if defined(WARN_OUTDATED) #pragma message("SDL_GetWindowICCProfile is not supported before SDL 2.0.18") #pragma message("SDL_SetWindowMouseRect is not supported before SDL 2.0.18") #pragma message("SDL_GetWindowMouseRect is not supported before SDL 2.0.18") #endif #define SDL_WINDOWEVENT_ICCPROF_CHANGED (17) // The ICC profile of the window's display has changed. #define SDL_WINDOWEVENT_DISPLAY_CHANGED (18) // Window has been moved to display data1. static void* SDLCALL SDL_GetWindowICCProfile(SDL_Window * window, size_t* size) { return NULL; } static int SDL_SetWindowMouseRect(SDL_Window * window, const SDL_Rect * rect) { return -1; } static const SDL_Rect * SDLCALL SDL_GetWindowMouseRect(SDL_Window * window) { return NULL; } #endif */ import "C" import "unsafe" // An enumeration of window states. // (https://wiki.libsdl.org/SDL_WindowFlags) const ( WINDOW_FULLSCREEN = C.SDL_WINDOW_FULLSCREEN // fullscreen window WINDOW_OPENGL = C.SDL_WINDOW_OPENGL // window usable with OpenGL context WINDOW_SHOWN = C.SDL_WINDOW_SHOWN // window is visible WINDOW_HIDDEN = C.SDL_WINDOW_HIDDEN // window is not visible WINDOW_BORDERLESS = C.SDL_WINDOW_BORDERLESS // no window decoration WINDOW_RESIZABLE = C.SDL_WINDOW_RESIZABLE // window can be resized WINDOW_MINIMIZED = C.SDL_WINDOW_MINIMIZED // window is minimized WINDOW_MAXIMIZED = C.SDL_WINDOW_MAXIMIZED // window is maximized WINDOW_INPUT_GRABBED = C.SDL_WINDOW_INPUT_GRABBED // window has grabbed input focus WINDOW_INPUT_FOCUS = C.SDL_WINDOW_INPUT_FOCUS // window has input focus WINDOW_MOUSE_FOCUS = C.SDL_WINDOW_MOUSE_FOCUS // window has mouse focus WINDOW_FULLSCREEN_DESKTOP = C.SDL_WINDOW_FULLSCREEN_DESKTOP // fullscreen window at the current desktop resolution WINDOW_FOREIGN = C.SDL_WINDOW_FOREIGN // window not created by SDL WINDOW_ALLOW_HIGHDPI = C.SDL_WINDOW_ALLOW_HIGHDPI // window should be created in high-DPI mode if supported (>= SDL 2.0.1) WINDOW_MOUSE_CAPTURE = C.SDL_WINDOW_MOUSE_CAPTURE // window has mouse captured (unrelated to INPUT_GRABBED, >= SDL 2.0.4) WINDOW_ALWAYS_ON_TOP = C.SDL_WINDOW_ALWAYS_ON_TOP // window should always be above others (X11 only, >= SDL 2.0.5) WINDOW_SKIP_TASKBAR = C.SDL_WINDOW_SKIP_TASKBAR // window should not be added to the taskbar (X11 only, >= SDL 2.0.5) WINDOW_UTILITY = C.SDL_WINDOW_UTILITY // window should be treated as a utility window (X11 only, >= SDL 2.0.5) WINDOW_TOOLTIP = C.SDL_WINDOW_TOOLTIP // window should be treated as a tooltip (X11 only, >= SDL 2.0.5) WINDOW_POPUP_MENU = C.SDL_WINDOW_POPUP_MENU // window should be treated as a popup menu (X11 only, >= SDL 2.0.5) WINDOW_VULKAN = C.SDL_WINDOW_VULKAN // window usable for Vulkan surface (>= SDL 2.0.6) ) // An enumeration of window events. // (https://wiki.libsdl.org/SDL_WindowEventID) const ( WINDOWEVENT_NONE = C.SDL_WINDOWEVENT_NONE // (never used) WINDOWEVENT_SHOWN = C.SDL_WINDOWEVENT_SHOWN // window has been shown WINDOWEVENT_HIDDEN = C.SDL_WINDOWEVENT_HIDDEN // window has been hidden WINDOWEVENT_EXPOSED = C.SDL_WINDOWEVENT_EXPOSED // window has been exposed and should be redrawn WINDOWEVENT_MOVED = C.SDL_WINDOWEVENT_MOVED // window has been moved to data1, data2 WINDOWEVENT_RESIZED = C.SDL_WINDOWEVENT_RESIZED // window has been resized to data1xdata2; this event is always preceded by WINDOWEVENT_SIZE_CHANGED WINDOWEVENT_SIZE_CHANGED = C.SDL_WINDOWEVENT_SIZE_CHANGED // window size has changed, either as a result of an API call or through the system or user changing the window size; this event is followed by WINDOWEVENT_RESIZED if the size was changed by an external event, i.e. the user or the window manager WINDOWEVENT_MINIMIZED = C.SDL_WINDOWEVENT_MINIMIZED // window has been minimized WINDOWEVENT_MAXIMIZED = C.SDL_WINDOWEVENT_MAXIMIZED // window has been maximized WINDOWEVENT_RESTORED = C.SDL_WINDOWEVENT_RESTORED // window has been restored to normal size and position WINDOWEVENT_ENTER = C.SDL_WINDOWEVENT_ENTER // window has gained mouse focus WINDOWEVENT_LEAVE = C.SDL_WINDOWEVENT_LEAVE // window has lost mouse focus WINDOWEVENT_FOCUS_GAINED = C.SDL_WINDOWEVENT_FOCUS_GAINED // window has gained keyboard focus WINDOWEVENT_FOCUS_LOST = C.SDL_WINDOWEVENT_FOCUS_LOST // window has lost keyboard focus WINDOWEVENT_CLOSE = C.SDL_WINDOWEVENT_CLOSE // the window manager requests that the window be closed WINDOWEVENT_TAKE_FOCUS = C.SDL_WINDOWEVENT_TAKE_FOCUS // window is being offered a focus (should SDL_SetWindowInputFocus() on itself or a subwindow, or ignore) (>= SDL 2.0.5) WINDOWEVENT_HIT_TEST = C.SDL_WINDOWEVENT_HIT_TEST // window had a hit test that wasn't SDL_HITTEST_NORMAL (>= SDL 2.0.5) WINDOWEVENT_ICCPROF_CHANGED = C.SDL_WINDOWEVENT_ICCPROF_CHANGED // the ICC profile of the window's display has changed WINDOWEVENT_DISPLAY_CHANGED = C.SDL_WINDOWEVENT_DISPLAY_CHANGED // window has been moved to display data1 ) // Window position flags. // (https://wiki.libsdl.org/SDL_CreateWindow) const ( WINDOWPOS_UNDEFINED_MASK = C.SDL_WINDOWPOS_UNDEFINED_MASK // used to indicate that you don't care what the window position is WINDOWPOS_UNDEFINED = C.SDL_WINDOWPOS_UNDEFINED // used to indicate that you don't care what the window position is WINDOWPOS_CENTERED_MASK = C.SDL_WINDOWPOS_CENTERED_MASK // used to indicate that the window position should be centered WINDOWPOS_CENTERED = C.SDL_WINDOWPOS_CENTERED // used to indicate that the window position should be centered ) // An enumeration of message box flags (e.g. if supported message box will display warning icon). // (https://wiki.libsdl.org/SDL_MessageBoxFlags) const ( MESSAGEBOX_ERROR = C.SDL_MESSAGEBOX_ERROR // error dialog MESSAGEBOX_WARNING = C.SDL_MESSAGEBOX_WARNING // warning dialog MESSAGEBOX_INFORMATION = C.SDL_MESSAGEBOX_INFORMATION // informational dialog ) // Flags for MessageBoxButtonData. const ( MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT = C.SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT // marks the default button when return is hit MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT = C.SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT // marks the default button when escape is hit ) // OpenGL configuration attributes. // (https://wiki.libsdl.org/SDL_GL_SetAttribute) const ( GL_RED_SIZE = C.SDL_GL_RED_SIZE // the minimum number of bits for the red channel of the color buffer; defaults to 3 GL_GREEN_SIZE = C.SDL_GL_GREEN_SIZE // the minimum number of bits for the green channel of the color buffer; defaults to 3 GL_BLUE_SIZE = C.SDL_GL_BLUE_SIZE // the minimum number of bits for the blue channel of the color buffer; defaults to 2 GL_ALPHA_SIZE = C.SDL_GL_ALPHA_SIZE // the minimum number of bits for the alpha channel of the color buffer; defaults to 0 GL_BUFFER_SIZE = C.SDL_GL_BUFFER_SIZE // the minimum number of bits for frame buffer size; defaults to 0 GL_DOUBLEBUFFER = C.SDL_GL_DOUBLEBUFFER // whether the output is single or double buffered; defaults to double buffering on GL_DEPTH_SIZE = C.SDL_GL_DEPTH_SIZE // the minimum number of bits in the depth buffer; defaults to 16 GL_STENCIL_SIZE = C.SDL_GL_STENCIL_SIZE // the minimum number of bits in the stencil buffer; defaults to 0 GL_ACCUM_RED_SIZE = C.SDL_GL_ACCUM_RED_SIZE // the minimum number of bits for the red channel of the accumulation buffer; defaults to 0 GL_ACCUM_GREEN_SIZE = C.SDL_GL_ACCUM_GREEN_SIZE // the minimum number of bits for the green channel of the accumulation buffer; defaults to 0 GL_ACCUM_BLUE_SIZE = C.SDL_GL_ACCUM_BLUE_SIZE // the minimum number of bits for the blue channel of the accumulation buffer; defaults to 0 GL_ACCUM_ALPHA_SIZE = C.SDL_GL_ALPHA_SIZE // the minimum number of bits for the alpha channel of the accumulation buffer; defaults to 0 GL_STEREO = C.SDL_GL_STEREO // whether the output is stereo 3D; defaults to off GL_MULTISAMPLEBUFFERS = C.SDL_GL_MULTISAMPLEBUFFERS // the number of buffers used for multisample anti-aliasing; defaults to 0; see Remarks for details GL_MULTISAMPLESAMPLES = C.SDL_GL_MULTISAMPLESAMPLES // the number of samples used around the current pixel used for multisample anti-aliasing; defaults to 0; see Remarks for details GL_ACCELERATED_VISUAL = C.SDL_GL_ACCELERATED_VISUAL // set to 1 to require hardware acceleration, set to 0 to force software rendering; defaults to allow either GL_RETAINED_BACKING = C.SDL_GL_RETAINED_BACKING // not used (deprecated) GL_CONTEXT_MAJOR_VERSION = C.SDL_GL_CONTEXT_MAJOR_VERSION // OpenGL context major version GL_CONTEXT_MINOR_VERSION = C.SDL_GL_CONTEXT_MINOR_VERSION // OpenGL context minor version GL_CONTEXT_EGL = C.SDL_GL_CONTEXT_EGL // not used (deprecated) GL_CONTEXT_FLAGS = C.SDL_GL_CONTEXT_FLAGS // some combination of 0 or more of elements of the GLcontextFlag enumeration; defaults to 0 (https://wiki.libsdl.org/SDL_GLcontextFlag) GL_CONTEXT_PROFILE_MASK = C.SDL_GL_CONTEXT_PROFILE_MASK // type of GL context (Core, Compatibility, ES); default value depends on platform (https://wiki.libsdl.org/SDL_GLprofile) GL_SHARE_WITH_CURRENT_CONTEXT = C.SDL_GL_SHARE_WITH_CURRENT_CONTEXT // OpenGL context sharing; defaults to 0 GL_FRAMEBUFFER_SRGB_CAPABLE = C.SDL_GL_FRAMEBUFFER_SRGB_CAPABLE // requests sRGB capable visual; defaults to 0 (>= SDL 2.0.1) GL_CONTEXT_RELEASE_BEHAVIOR = C.SDL_GL_CONTEXT_RELEASE_BEHAVIOR // sets context the release behavior; defaults to 1 (>= SDL 2.0.4) GL_CONTEXT_RESET_NOTIFICATION = C.SDL_GL_CONTEXT_RESET_NOTIFICATION // (>= SDL 2.0.6) GL_CONTEXT_NO_ERROR = C.SDL_GL_CONTEXT_NO_ERROR // (>= SDL 2.0.6) ) // An enumeration of OpenGL profiles. // (https://wiki.libsdl.org/SDL_GLprofile) const ( GL_CONTEXT_PROFILE_CORE = C.SDL_GL_CONTEXT_PROFILE_CORE // OpenGL core profile - deprecated functions are disabled GL_CONTEXT_PROFILE_COMPATIBILITY = C.SDL_GL_CONTEXT_PROFILE_COMPATIBILITY // OpenGL compatibility profile - deprecated functions are allowed GL_CONTEXT_PROFILE_ES = C.SDL_GL_CONTEXT_PROFILE_ES // OpenGL ES profile - only a subset of the base OpenGL functionality is available ) // An enumeration of OpenGL context configuration flags. // (https://wiki.libsdl.org/SDL_GLcontextFlag) const ( GL_CONTEXT_DEBUG_FLAG = C.SDL_GL_CONTEXT_DEBUG_FLAG // intended to put the GL into a "debug" mode which might offer better developer insights, possibly at a loss of performance GL_CONTEXT_FORWARD_COMPATIBLE_FLAG = C.SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG // intended to put the GL into a "forward compatible" mode, which means that no deprecated functionality will be supported, possibly at a gain in performance, and only applies to GL 3.0 and later contexts GL_CONTEXT_ROBUST_ACCESS_FLAG = C.SDL_GL_CONTEXT_ROBUST_ACCESS_FLAG // intended to require a GL context that supports the GL_ARB_robustness extension--a mode that offers a few APIs that are safer than the usual defaults (think snprintf() vs sprintf()) GL_CONTEXT_RESET_ISOLATION_FLAG = C.SDL_GL_CONTEXT_RESET_ISOLATION_FLAG // intended to require the GL to make promises about what to do in the face of driver or hardware failure ) // // Window flash operation // const ( FLASH_CANCEL FlashOperation = C.SDL_FLASH_CANCEL // Cancel any window flash state FLASH_BRIEFLY = C.SDL_FLASH_BRIEFLY // Flash the window briefly to get attention FLASH_UNTIL_FOCUSED = C.SDL_FLASH_UNTIL_FOCUSED // Flash the window until it gets focus ) type FlashOperation C.SDL_FlashOperation // DisplayMode contains the description of a display mode. // (https://wiki.libsdl.org/SDL_DisplayMode) type DisplayMode struct { Format uint32 // one of the PixelFormatEnum values (https://wiki.libsdl.org/SDL_PixelFormatEnum) W int32 // width, in screen coordinates H int32 // height, in screen coordinates RefreshRate int32 // refresh rate (in Hz), or 0 for unspecified DriverData unsafe.Pointer // driver-specific data, initialize to 0 } type cDisplayMode C.SDL_DisplayMode // Window is a type used to identify a window. type Window C.SDL_Window // GLContext is an opaque handle to an OpenGL context. type GLContext C.SDL_GLContext // GLattr is an OpenGL configuration attribute. //(https://wiki.libsdl.org/SDL_GLattr) type GLattr C.SDL_GLattr // MessageBoxColor contains RGB value used in an MessageBoxColorScheme. // (https://wiki.libsdl.org/SDL_MessageBoxColor) type MessageBoxColor struct { R uint8 // the red component in the range 0-255 G uint8 // the green component in the range 0-255 B uint8 // the blue component in the range 0-255 } type cMessageBoxColor C.SDL_MessageBoxColor // MessageBoxColorScheme contains a set of colors to use for message box dialogs. // (https://wiki.libsdl.org/SDL_MessageBoxColorScheme) type MessageBoxColorScheme struct { Colors [5]MessageBoxColor // background, text, button border, button background, button selected } type cMessageBoxColorScheme C.SDL_MessageBoxColorScheme // MessageBoxButtonData contains individual button data for a message box. // (https://wiki.libsdl.org/SDL_MessageBoxButtonData) type MessageBoxButtonData struct { Flags uint32 // MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT, MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT ButtonID int32 // user defined button id (value returned via ShowMessageBox()) Text string // the UTF-8 button text } // MessageBoxData contains title, text, window and other data for a message box. // (https://wiki.libsdl.org/SDL_MessageBoxData) type MessageBoxData struct { Flags uint32 // MESSAGEBOX_ERROR, MESSAGEBOX_WARNING, MESSAGEBOX_INFORMATION Window *Window // parent window or nil Title string Message string Buttons []MessageBoxButtonData ColorScheme *MessageBoxColorScheme // nil to use system settings } func (window *Window) cptr() *C.SDL_Window { return (*C.SDL_Window)(unsafe.Pointer(window)) } func (dm *DisplayMode) cptr() *C.SDL_DisplayMode { return (*C.SDL_DisplayMode)(unsafe.Pointer(dm)) } func (mc *MessageBoxColor) cptr() *C.SDL_MessageBoxColor { return (*C.SDL_MessageBoxColor)(unsafe.Pointer(mc)) } func (mcs *MessageBoxColorScheme) cptr() *C.SDL_MessageBoxColorScheme { return (*C.SDL_MessageBoxColorScheme)(unsafe.Pointer(mcs)) } func (mbd *MessageBoxButtonData) cptr() *C.SDL_MessageBoxButtonData { return (*C.SDL_MessageBoxButtonData)(unsafe.Pointer(mbd)) } func (md *MessageBoxData) cptr() *C.SDL_MessageBoxData { return (*C.SDL_MessageBoxData)(unsafe.Pointer(md)) } func (attr GLattr) c() C.SDL_GLattr { return C.SDL_GLattr(attr) } // GetDisplayName returns the name of a display in UTF-8 encoding. // (https://wiki.libsdl.org/SDL_GetDisplayName) func GetDisplayName(displayIndex int) (string, error) { name := C.SDL_GetDisplayName(C.int(displayIndex)) if name == nil { return "", GetError() } return C.GoString(name), nil } // GetNumVideoDisplays returns the number of available video displays. // (https://wiki.libsdl.org/SDL_GetNumVideoDisplays) func GetNumVideoDisplays() (int, error) { n := int(C.SDL_GetNumVideoDisplays()) return n, errorFromInt(n) } // GetNumVideoDrivers returns the number of video drivers compiled into SDL. // (https://wiki.libsdl.org/SDL_GetNumVideoDrivers) func GetNumVideoDrivers() (int, error) { n := int(C.SDL_GetNumVideoDrivers()) return n, errorFromInt(n) } // GetVideoDriver returns the name of a built in video driver. // (https://wiki.libsdl.org/SDL_GetVideoDriver) func GetVideoDriver(index int) string { return string(C.GoString(C.SDL_GetVideoDriver(C.int(index)))) } // VideoInit initializes the video subsystem, optionally specifying a video driver. // (https://wiki.libsdl.org/SDL_VideoInit) func VideoInit(driverName string) error { return errorFromInt(int( C.SDL_VideoInit(C.CString(driverName)))) } // VideoQuit shuts down the video subsystem, if initialized with VideoInit(). // (https://wiki.libsdl.org/SDL_VideoQuit) func VideoQuit() { C.SDL_VideoQuit() } // GetCurrentVideoDriver returns the name of the currently initialized video driver. // (https://wiki.libsdl.org/SDL_GetCurrentVideoDriver) func GetCurrentVideoDriver() (string, error) { name := C.SDL_GetCurrentVideoDriver() if name == nil { return "", GetError() } return C.GoString(name), nil } // GetNumDisplayModes returns the number of available display modes. // (https://wiki.libsdl.org/SDL_GetNumDisplayModes) func GetNumDisplayModes(displayIndex int) (int, error) { n := int(C.SDL_GetNumDisplayModes(C.int(displayIndex))) return n, errorFromInt(n) } // GetDisplayBounds returns the desktop area represented by a display, with the primary display located at 0,0. // (https://wiki.libsdl.org/SDL_GetDisplayBounds) func GetDisplayBounds(displayIndex int) (rect Rect, err error) { err = errorFromInt(int( C.SDL_GetDisplayBounds(C.int(displayIndex), (&rect).cptr()))) return } // GetDisplayUsableBounds returns the usable desktop area represented by a display, with the primary display located at 0,0. // (https://wiki.libsdl.org/SDL_GetDisplayUsableBounds) func GetDisplayUsableBounds(displayIndex int) (rect Rect, err error) { err = errorFromInt(int( C.SDL_GetDisplayUsableBounds(C.int(displayIndex), rect.cptr()))) return } // GetDisplayMode returns information about a specific display mode. // (https://wiki.libsdl.org/SDL_GetDisplayMode) func GetDisplayMode(displayIndex int, modeIndex int) (mode DisplayMode, err error) { err = errorFromInt(int( C.SDL_GetDisplayMode(C.int(displayIndex), C.int(modeIndex), (&mode).cptr()))) return } // GetDesktopDisplayMode returns information about the desktop display mode. // (https://wiki.libsdl.org/SDL_GetDesktopDisplayMode) func GetDesktopDisplayMode(displayIndex int) (mode DisplayMode, err error) { err = errorFromInt(int( C.SDL_GetDesktopDisplayMode(C.int(displayIndex), (&mode).cptr()))) return } // GetCurrentDisplayMode returns information about the current display mode. // (https://wiki.libsdl.org/SDL_GetCurrentDisplayMode) func GetCurrentDisplayMode(displayIndex int) (mode DisplayMode, err error) { err = errorFromInt(int( C.SDL_GetCurrentDisplayMode(C.int(displayIndex), (&mode).cptr()))) return } // GetClosestDisplayMode returns the closest match to the requested display mode. // (https://wiki.libsdl.org/SDL_GetClosestDisplayMode) func GetClosestDisplayMode(displayIndex int, mode *DisplayMode, closest *DisplayMode) (*DisplayMode, error) { m := (*DisplayMode)(unsafe.Pointer((C.SDL_GetClosestDisplayMode(C.int(displayIndex), mode.cptr(), closest.cptr())))) if m == nil { return nil, GetError() } return m, nil } // GetDisplayDPI returns the dots/pixels-per-inch for a display. // (https://wiki.libsdl.org/SDL_GetDisplayDPI) func GetDisplayDPI(displayIndex int) (ddpi, hdpi, vdpi float32, err error) { err = errorFromInt(int( C.SDL_GetDisplayDPI(C.int(displayIndex), (*C.float)(unsafe.Pointer(&ddpi)), (*C.float)(unsafe.Pointer(&hdpi)), (*C.float)(unsafe.Pointer(&vdpi))))) return } // GetDisplayIndex returns the index of the display associated with the window. // (https://wiki.libsdl.org/SDL_GetWindowDisplayIndex) func (window *Window) GetDisplayIndex() (int, error) { i := int(C.SDL_GetWindowDisplayIndex(window.cptr())) return i, errorFromInt(i) } // SetDisplayMode sets the display mode to use when the window is visible at fullscreen. // (https://wiki.libsdl.org/SDL_SetWindowDisplayMode) func (window *Window) SetDisplayMode(mode *DisplayMode) error { return errorFromInt(int( C.SDL_SetWindowDisplayMode(window.cptr(), mode.cptr()))) } // GetDisplayMode fills in information about the display mode to use when the window is visible at fullscreen. // (https://wiki.libsdl.org/SDL_GetWindowDisplayMode) func (window *Window) GetDisplayMode() (mode DisplayMode, err error) { err = errorFromInt(int( C.SDL_GetWindowDisplayMode(window.cptr(), (&mode).cptr()))) return } // GetPixelFormat returns the pixel format associated with the window. // (https://wiki.libsdl.org/SDL_GetWindowPixelFormat) func (window *Window) GetPixelFormat() (uint32, error) { f := (uint32)(C.SDL_GetWindowPixelFormat(window.cptr())) if f == PIXELFORMAT_UNKNOWN { return f, GetError() } return f, nil } // CreateWindow creates a window with the specified position, dimensions, and flags. // (https://wiki.libsdl.org/SDL_CreateWindow) func CreateWindow(title string, x, y, w, h int32, flags uint32) (*Window, error) { var _window = C.SDL_CreateWindow(C.CString(title), C.int(x), C.int(y), C.int(w), C.int(h), C.Uint32(flags)) if _window == nil { return nil, GetError() } return (*Window)(unsafe.Pointer(_window)), nil } // CreateWindowFrom creates an SDL window from an existing native window. // (https://wiki.libsdl.org/SDL_CreateWindowFrom) func CreateWindowFrom(data unsafe.Pointer) (*Window, error) { _window := C.SDL_CreateWindowFrom(data) if _window == nil { return nil, GetError() } return (*Window)(unsafe.Pointer(_window)), nil } // Destroy destroys the window. // (https://wiki.libsdl.org/SDL_DestroyWindow) func (window *Window) Destroy() error { lastErr := GetError() ClearError() C.SDL_DestroyWindow(window.cptr()) err := GetError() if err != nil { return err } SetError(lastErr) return nil } // GetID returns the numeric ID of the window, for logging purposes. // (https://wiki.libsdl.org/SDL_GetWindowID) func (window *Window) GetID() (uint32, error) { id := uint32(C.SDL_GetWindowID(window.cptr())) if id == 0 { return 0, GetError() } return id, nil } // GetWindowFromID returns a window from a stored ID. // (https://wiki.libsdl.org/SDL_GetWindowFromID) func GetWindowFromID(id uint32) (*Window, error) { _window := C.SDL_GetWindowFromID(C.Uint32(id)) if _window == nil { return nil, GetError() } return (*Window)(unsafe.Pointer((_window))), nil } // GetFlags returns the window flags. // (https://wiki.libsdl.org/SDL_GetWindowFlags) func (window *Window) GetFlags() uint32 { return (uint32)(C.SDL_GetWindowFlags(window.cptr())) } // SetTitle sets the title of the window. // (https://wiki.libsdl.org/SDL_SetWindowTitle) func (window *Window) SetTitle(title string) { C.SDL_SetWindowTitle(window.cptr(), C.CString(title)) } // GetTitle returns the title of the window. // (https://wiki.libsdl.org/SDL_GetWindowTitle) func (window *Window) GetTitle() string { return C.GoString(C.SDL_GetWindowTitle(window.cptr())) } // SetIcon sets the icon for the window. // (https://wiki.libsdl.org/SDL_SetWindowIcon) func (window *Window) SetIcon(icon *Surface) { C.SDL_SetWindowIcon(window.cptr(), icon.cptr()) } // SetData associates an arbitrary named pointer with the window. // (https://wiki.libsdl.org/SDL_SetWindowData) func (window *Window) SetData(name string, userdata unsafe.Pointer) unsafe.Pointer { return unsafe.Pointer(C.SDL_SetWindowData(window.cptr(), C.CString(name), userdata)) } // GetData returns the data pointer associated with the window. // (https://wiki.libsdl.org/SDL_GetWindowData) func (window *Window) GetData(name string) unsafe.Pointer { return unsafe.Pointer(C.SDL_GetWindowData(window.cptr(), C.CString(name))) } // SetPosition sets the position of the window. // (https://wiki.libsdl.org/SDL_SetWindowPosition) func (window *Window) SetPosition(x, y int32) { C.SDL_SetWindowPosition(window.cptr(), C.int(x), C.int(y)) } // GetPosition returns the position of the window. // (https://wiki.libsdl.org/SDL_GetWindowPosition) func (window *Window) GetPosition() (x, y int32) { var _x, _y C.int C.SDL_GetWindowPosition(window.cptr(), &_x, &_y) return int32(_x), int32(_y) } // SetResizable sets the user-resizable state of the window. // (https://wiki.libsdl.org/SDL_SetWindowResizable) func (window *Window) SetResizable(resizable bool) { C.SDL_SetWindowResizable(window.cptr(), C.SDL_bool(Btoi(resizable))) } // SetSize sets the size of the window's client area. // (https://wiki.libsdl.org/SDL_SetWindowSize) func (window *Window) SetSize(w, h int32) { C.SDL_SetWindowSize(window.cptr(), C.int(w), C.int(h)) } // GetSize returns the size of the window's client area. // (https://wiki.libsdl.org/SDL_GetWindowSize) func (window *Window) GetSize() (w, h int32) { var _w, _h C.int C.SDL_GetWindowSize(window.cptr(), &_w, &_h) return int32(_w), int32(_h) } // SetMinimumSize sets the minimum size of the window's client area. // (https://wiki.libsdl.org/SDL_SetWindowMinimumSize) func (window *Window) SetMinimumSize(minW, minH int32) { C.SDL_SetWindowMinimumSize(window.cptr(), C.int(minW), C.int(minH)) } // GetMinimumSize returns the minimum size of the window's client area. // (https://wiki.libsdl.org/SDL_GetWindowMinimumSize) func (window *Window) GetMinimumSize() (w, h int32) { var _w, _h C.int C.SDL_GetWindowMinimumSize(window.cptr(), &_w, &_h) return int32(_w), int32(_h) } // SetMaximumSize sets the maximum size of the window's client area. // (https://wiki.libsdl.org/SDL_SetWindowMaximumSize) func (window *Window) SetMaximumSize(maxW, maxH int32) { C.SDL_SetWindowMaximumSize(window.cptr(), C.int(maxW), C.int(maxH)) } // GetMaximumSize returns the maximum size of the window's client area. // (https://wiki.libsdl.org/SDL_GetWindowMaximumSize) func (window *Window) GetMaximumSize() (w, h int32) { var _w, _h C.int C.SDL_GetWindowMaximumSize(window.cptr(), &_w, &_h) return int32(_w), int32(_h) } // SetBordered sets the border state of the window. // (https://wiki.libsdl.org/SDL_SetWindowBordered) func (window *Window) SetBordered(bordered bool) { C.SDL_SetWindowBordered(window.cptr(), C.SDL_bool(Btoi(bordered))) } // Show shows the window. // (https://wiki.libsdl.org/SDL_ShowWindow) func (window *Window) Show() { C.SDL_ShowWindow(window.cptr()) } // Hide hides the window. // (https://wiki.libsdl.org/SDL_HideWindow) func (window *Window) Hide() { C.SDL_HideWindow(window.cptr()) } // Raise raises the window above other windows and set the input focus. // (https://wiki.libsdl.org/SDL_RaiseWindow) func (window *Window) Raise() { C.SDL_RaiseWindow(window.cptr()) } // Maximize makes the window as large as possible. // (https://wiki.libsdl.org/SDL_MaximizeWindow) func (window *Window) Maximize() { C.SDL_MaximizeWindow(window.cptr()) } // Minimize minimizes the window to an iconic representation. // (https://wiki.libsdl.org/SDL_MinimizeWindow) func (window *Window) Minimize() { C.SDL_MinimizeWindow(window.cptr()) } // Restore restores the size and position of a minimized or maximized window. // (https://wiki.libsdl.org/SDL_RestoreWindow) func (window *Window) Restore() { C.SDL_RestoreWindow(window.cptr()) } // SetFullscreen sets the window's fullscreen state. // (https://wiki.libsdl.org/SDL_SetWindowFullscreen) func (window *Window) SetFullscreen(flags uint32) error { return errorFromInt(int( C.SDL_SetWindowFullscreen(window.cptr(), C.Uint32(flags)))) } // GetSurface returns the SDL surface associated with the window. // (https://wiki.libsdl.org/SDL_GetWindowSurface) func (window *Window) GetSurface() (*Surface, error) { surface := (*Surface)(unsafe.Pointer(C.SDL_GetWindowSurface(window.cptr()))) if surface == nil { return nil, GetError() } return surface, nil } // UpdateSurface copies the window surface to the screen. // (https://wiki.libsdl.org/SDL_UpdateWindowSurface) func (window *Window) UpdateSurface() error { return errorFromInt(int( C.SDL_UpdateWindowSurface(window.cptr()))) } // UpdateSurfaceRects copies areas of the window surface to the screen. // (https://wiki.libsdl.org/SDL_UpdateWindowSurfaceRects) func (window *Window) UpdateSurfaceRects(rects []Rect) error { return errorFromInt(int( C.SDL_UpdateWindowSurfaceRects(window.cptr(), rects[0].cptr(), C.int(len(rects))))) } // SetGrab sets the window's input grab mode. // (https://wiki.libsdl.org/SDL_SetWindowGrab) func (window *Window) SetGrab(grabbed bool) { C.SDL_SetWindowGrab(window.cptr(), C.SDL_bool((Btoi(grabbed)))) } // GetGrab returns the window's input grab mode. // (https://wiki.libsdl.org/SDL_GetWindowGrab) func (window *Window) GetGrab() bool { return C.SDL_GetWindowGrab(window.cptr()) != 0 } // SetBrightness sets the brightness (gamma multiplier) for the display that owns the given window. // (https://wiki.libsdl.org/SDL_SetWindowBrightness) func (window *Window) SetBrightness(brightness float32) error { return errorFromInt(int( C.SDL_SetWindowBrightness(window.cptr(), C.float(brightness)))) } // GetBrightness returns the brightness (gamma multiplier) for the display that owns the given window. // (https://wiki.libsdl.org/SDL_GetWindowBrightness) func (window *Window) GetBrightness() float32 { return float32(C.SDL_GetWindowBrightness(window.cptr())) } // SetGammaRamp sets the gamma ramp for the display that owns the given window. // (https://wiki.libsdl.org/SDL_SetWindowGammaRamp) func (window *Window) SetGammaRamp(red, green, blue *[256]uint16) error { return errorFromInt(int( C.SDL_SetWindowGammaRamp( window.cptr(), (*C.Uint16)(unsafe.Pointer(red)), (*C.Uint16)(unsafe.Pointer(green)), (*C.Uint16)(unsafe.Pointer(blue))))) } // GetGammaRamp returns the gamma ramp for the display that owns a given window. // (https://wiki.libsdl.org/SDL_GetWindowGammaRamp) func (window *Window) GetGammaRamp() (red, green, blue *[256]uint16, err error) { code := int(C.SDL_GetWindowGammaRamp( window.cptr(), (*C.Uint16)(unsafe.Pointer(red)), (*C.Uint16)(unsafe.Pointer(green)), (*C.Uint16)(unsafe.Pointer(blue)))) return red, green, blue, errorFromInt(code) } // SetWindowOpacity sets the opacity of the window. // (https://wiki.libsdl.org/SDL_SetWindowOpacity) func (window *Window) SetWindowOpacity(opacity float32) error { return errorFromInt(int( C.SDL_SetWindowOpacity(window.cptr(), C.float(opacity)))) } // GetWindowOpacity returns the opacity of the window. // (https://wiki.libsdl.org/SDL_GetWindowOpacity) func (window *Window) GetWindowOpacity() (opacity float32, err error) { return opacity, errorFromInt(int( C.SDL_GetWindowOpacity(window.cptr(), (*C.float)(unsafe.Pointer(&opacity))))) } // ShowSimpleMessageBox displays a simple modal message box. // (https://wiki.libsdl.org/SDL_ShowSimpleMessageBox) func ShowSimpleMessageBox(flags uint32, title, message string, window *Window) error { _title := C.CString(title) defer C.free(unsafe.Pointer(_title)) _message := C.CString(message) defer C.free(unsafe.Pointer(_message)) return errorFromInt(int( C.SDL_ShowSimpleMessageBox(C.Uint32(flags), _title, _message, window.cptr()))) } // ShowMessageBox creates a modal message box. // (https://wiki.libsdl.org/SDL_ShowMessageBox) func ShowMessageBox(data *MessageBoxData) (buttonid int32, err error) { _title := C.CString(data.Title) defer C.free(unsafe.Pointer(_title)) _message := C.CString(data.Message) defer C.free(unsafe.Pointer(_message)) var cbuttons []C.SDL_MessageBoxButtonData var cbtntexts []*C.char defer func(texts []*C.char) { for _, t := range texts { C.free(unsafe.Pointer(t)) } }(cbtntexts) for _, btn := range data.Buttons { ctext := C.CString(btn.Text) cbtn := C.SDL_MessageBoxButtonData{ flags: C.Uint32(btn.Flags), buttonid: C.int(btn.ButtonID), text: ctext, } cbuttons = append(cbuttons, cbtn) cbtntexts = append(cbtntexts, ctext) } var buttonPtr *C.SDL_MessageBoxButtonData if len(cbuttons) > 0 { buttonPtr = &cbuttons[0] } cdata := C.SDL_MessageBoxData{ flags: C.Uint32(data.Flags), window: data.Window.cptr(), title: _title, message: _message, numbuttons: C.int(len(data.Buttons)), buttons: buttonPtr, colorScheme: data.ColorScheme.cptr(), } buttonid = int32(C.ShowMessageBox(cdata)) return buttonid, errorFromInt(int(buttonid)) } // IsScreenSaverEnabled reports whether the screensaver is currently enabled. // (https://wiki.libsdl.org/SDL_IsScreenSaverEnabled) func IsScreenSaverEnabled() bool { return C.SDL_IsScreenSaverEnabled() != 0 } // EnableScreenSaver allows the screen to be blanked by a screen saver. // (https://wiki.libsdl.org/SDL_EnableScreenSaver) func EnableScreenSaver() { C.SDL_EnableScreenSaver() } // DisableScreenSaver prevents the screen from being blanked by a screen saver. // (https://wiki.libsdl.org/SDL_DisableScreenSaver) func DisableScreenSaver() { C.SDL_DisableScreenSaver() } // GLLoadLibrary dynamically loads an OpenGL library. // (https://wiki.libsdl.org/SDL_GL_LoadLibrary) func GLLoadLibrary(path string) error { return errorFromInt(int( C.SDL_GL_LoadLibrary(C.CString(path)))) } // GLGetProcAddress returns an OpenGL function by name. // (https://wiki.libsdl.org/SDL_GL_GetProcAddress) func GLGetProcAddress(proc string) unsafe.Pointer { return unsafe.Pointer(C.SDL_GL_GetProcAddress(C.CString(proc))) } // GLUnloadLibrary unloads the OpenGL library previously loaded by GLLoadLibrary(). // (https://wiki.libsdl.org/SDL_GL_UnloadLibrary) func GLUnloadLibrary() { C.SDL_GL_UnloadLibrary() } // GLExtensionSupported reports whether an OpenGL extension is supported for the current context. // (https://wiki.libsdl.org/SDL_GL_ExtensionSupported) func GLExtensionSupported(extension string) bool { return C.SDL_GL_ExtensionSupported(C.CString(extension)) != 0 } // GLSetAttribute sets an OpenGL window attribute before window creation. // (https://wiki.libsdl.org/SDL_GL_SetAttribute) func GLSetAttribute(attr GLattr, value int) error { return errorFromInt(int( C.SDL_GL_SetAttribute(attr.c(), C.int(value)))) } // GLGetAttribute returns the actual value for an attribute from the current context. // (https://wiki.libsdl.org/SDL_GL_GetAttribute) func GLGetAttribute(attr GLattr) (int, error) { var _value C.int if C.SDL_GL_GetAttribute(attr.c(), &_value) != 0 { return int(_value), GetError() } return int(_value), nil } // GLCreateContext creates an OpenGL context for use with an OpenGL window, and make it current. // (https://wiki.libsdl.org/SDL_GL_CreateContext) func (window *Window) GLCreateContext() (GLContext, error) { c := GLContext(C.SDL_GL_CreateContext(window.cptr())) if c == nil { return nil, GetError() } return c, nil } // GLMakeCurrent sets up an OpenGL context for rendering into an OpenGL window. // (https://wiki.libsdl.org/SDL_GL_MakeCurrent) func (window *Window) GLMakeCurrent(glcontext GLContext) error { return errorFromInt(int( C.SDL_GL_MakeCurrent(window.cptr(), C.SDL_GLContext(glcontext)))) } // GLSetSwapInterval sets the swap interval for the current OpenGL context. // (https://wiki.libsdl.org/SDL_GL_SetSwapInterval) func GLSetSwapInterval(interval int) error { return errorFromInt(int( C.SDL_GL_SetSwapInterval(C.int(interval)))) } // GLGetSwapInterval returns the swap interval for the current OpenGL context. // (https://wiki.libsdl.org/SDL_GL_GetSwapInterval) func GLGetSwapInterval() (int, error) { i := int(C.SDL_GL_GetSwapInterval()) // -1 means adaptive vsync, not an error // 0 means vsync off // 1 means vsync on if i == -1 || i == 0 || i == 1 { return i, nil } // any other value should be an error return i, errorFromInt(i) } // GLGetDrawableSize returns the size of a window's underlying drawable in pixels (for use with glViewport). // (https://wiki.libsdl.org/SDL_GL_GetDrawableSize) func (window *Window) GLGetDrawableSize() (w, h int32) { var _w, _h C.int C.SDL_GL_GetDrawableSize(window.cptr(), &_w, &_h) return int32(_w), int32(_h) } // GLSwap updates a window with OpenGL rendering. // (https://wiki.libsdl.org/SDL_GL_SwapWindow) func (window *Window) GLSwap() { C.SDL_GL_SwapWindow(window.cptr()) } // GLDeleteContext deletes an OpenGL context. // (https://wiki.libsdl.org/SDL_GL_DeleteContext) func GLDeleteContext(context GLContext) { C.SDL_GL_DeleteContext(C.SDL_GLContext(context)) } // Flash requests the window to demand attention from the user. // (https://wiki.libsdl.org/SDL_FlashWindow) func (window *Window) Flash(operation FlashOperation) (err error) { return errorFromInt(int(C.SDL_FlashWindow(window.cptr(), C.SDL_FlashOperation(operation)))) } // SetAlwaysOnTop sets the window to always be above the others. // (https://wiki.libsdl.org/SDL_SetWindowAlwaysOnTop) func (window *Window) SetAlwaysOnTop(onTop bool) { C.SDL_SetWindowAlwaysOnTop(window.cptr(), C.SDL_bool(Btoi(onTop))) } // SetKeyboardGrab sets a window's keyboard grab mode. // (https://wiki.libsdl.org/SDL_GetWindowKeyboardGrab) func (window *Window) SetKeyboardGrab(grabbed bool) { C.SDL_SetWindowKeyboardGrab(window.cptr(), C.SDL_bool(Btoi(grabbed))) } // GetICCProfile gets the raw ICC profile data for the screen the window is currently on. // // Data returned should be freed with SDL_free. // // (https://wiki.libsdl.org/SDL_GetWindowICCProfile) func (window *Window) GetICCProfile() (iccProfile unsafe.Pointer, size uintptr, err error) { _size := (*C.size_t)(unsafe.Pointer(&size)) iccProfile = C.SDL_GetWindowICCProfile(window.cptr(), _size) if iccProfile == nil { err = GetError() } return } // SetMouseRect confines the cursor to the specified area of a window. // // Note that this does NOT grab the cursor, it only defines the area a cursor // is restricted to when the window has mouse focus. // // (https://wiki.libsdl.org/SDL_SetWindowMouseRect) func (window *Window) SetMouseRect(rect Rect) (err error) { _rect := (*C.SDL_Rect)(unsafe.Pointer(&rect)) err = errorFromInt(int(C.SDL_SetWindowMouseRect(window.cptr(), _rect))) return } // GetMouseRect gets the mouse confinement rectangle of a window. // (https://wiki.libsdl.org/SDL_GetWindowMouseRect) func (window *Window) GetMouseRect() (rect Rect) { _rect := C.SDL_GetWindowMouseRect(window.cptr()) rect = *((*Rect)(unsafe.Pointer(_rect))) return } ================================================ FILE: go/vendor/github.com/veandco/go-sdl2/sdl/vulkan.go ================================================ package sdl /* #include "sdl_wrapper.h" #if (SDL_VERSION_ATLEAST(2,0,6)) #if defined(_WIN32) #include #else #include #endif #else //!SDL_VERSION_ATLEAST(2,0,6) #define VK_DEFINE_HANDLE(object) typedef struct object##_T* object; #if defined(__LP64__) || defined(_WIN64) || defined(__x86_64__) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__) #define VK_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef struct object##_T *object; #else #define VK_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef uint64_t object; #endif VK_DEFINE_HANDLE(VkInstance) VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkSurfaceKHR) typedef VkInstance SDL_vulkanInstance; typedef VkSurfaceKHR SDL_vulkanSurface; #if defined(WARN_OUTDATED) #pragma message("SDL_Vulkan_LoadLibrary is not supported before SDL 2.0.6") #endif static int SDL_Vulkan_LoadLibrary(const char *path) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_Vulkan_GetVkGetInstanceProcAddr is not supported before SDL 2.0.6") #endif static void* SDL_Vulkan_GetVkGetInstanceProcAddr(void) { return NULL; } #if defined(WARN_OUTDATED) #pragma message("SDL_Vulkan_UnloadLibrary is not supported before SDL 2.0.6") #endif static void SDL_Vulkan_UnloadLibrary(void) {} #if defined(WARN_OUTDATED) #pragma message("SDL_Vulkan_GetInstanceExtensions is not supported before SDL 2.0.6") #endif static int SDL_Vulkan_GetInstanceExtensions(SDL_Window *window, unsigned int *pCount, const char **pNames) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_Vulkan_CreateSurface is not supported before SDL 2.0.6") #endif static int SDL_Vulkan_CreateSurface(SDL_Window *window, VkInstance instance, VkSurfaceKHR *surface) { return 0; } #if defined(WARN_OUTDATED) #pragma message("SDL_Vulkan_GetDrawableSize is not supported before SDL 2.0.6") #endif static void SDL_Vulkan_GetDrawableSize(SDL_Window *window, int *w, int *h) { *w = 0; *h = 0; } #endif */ import "C" import ( "errors" "reflect" "unsafe" ) // VulkanLoadLibrary dynamically loads a Vulkan loader library. // (https://wiki.libsdl.org/SDL_Vulkan_LoadLibrary) func VulkanLoadLibrary(path string) error { var ret C.int if path == "" { ret = C.SDL_Vulkan_LoadLibrary(nil) } else { cpath := C.CString(path) defer C.free(unsafe.Pointer(cpath)) ret = C.SDL_Vulkan_LoadLibrary(cpath) } if int(ret) == -1 { return GetError() } return nil } // VulkanGetVkGetInstanceProcAddr gets the address of the vkGetInstanceProcAddr function. // (https://wiki.libsdl.org/SDL_Vulkan_GetVkInstanceProcAddr) func VulkanGetVkGetInstanceProcAddr() unsafe.Pointer { return C.SDL_Vulkan_GetVkGetInstanceProcAddr() } // VulkanUnloadLibrary unloads the Vulkan loader library previously loaded by VulkanLoadLibrary(). // (https://wiki.libsdl.org/SDL_Vulkan_UnloadLibrary) func VulkanUnloadLibrary() { C.SDL_Vulkan_UnloadLibrary() } // VulkanGetInstanceExtensions gets the names of the Vulkan instance extensions needed to create a surface with VulkanCreateSurface(). // (https://wiki.libsdl.org/SDL_Vulkan_GetInstanceExtensions) func (window *Window) VulkanGetInstanceExtensions() []string { var count C.uint C.SDL_Vulkan_GetInstanceExtensions(window.cptr(), &count, nil) if count == 0 { return nil } strptrs := make([]*C.char, uint(count)) C.SDL_Vulkan_GetInstanceExtensions(window.cptr(), &count, &strptrs[0]) extensions := make([]string, uint(count)) for i := range strptrs { extensions[i] = C.GoString(strptrs[i]) } return extensions } // VulkanCreateSurface creates a Vulkan rendering surface for a window. // (https://wiki.libsdl.org/SDL_Vulkan_CreateSurface) func (window *Window) VulkanCreateSurface(instance interface{}) (surface unsafe.Pointer, err error) { if instance == nil { return nil, errors.New("vulkan: instance is nil") } val := reflect.ValueOf(instance) if val.Kind() != reflect.Ptr { return nil, errors.New("vulkan: instance is not a VkInstance (expected kind Ptr, got " + val.Kind().String() + ")") } var vulkanSurface C.VkSurfaceKHR if C.SDL_Vulkan_CreateSurface(window.cptr(), (C.VkInstance)(unsafe.Pointer(val.Pointer())), (*C.VkSurfaceKHR)(unsafe.Pointer(&vulkanSurface))) == C.SDL_FALSE { return nil, GetError() } return unsafe.Pointer(&vulkanSurface), nil } // VulkanGetDrawableSize gets the size of a window's underlying drawable in pixels (for use with setting viewport, scissor & etc). // (https://wiki.libsdl.org/SDL_Vulkan_GetDrawableSize) func (window *Window) VulkanGetDrawableSize() (w, h int32) { var _w, _h C.int C.SDL_Vulkan_GetDrawableSize(window.cptr(), &_w, &_h) return int32(_w), int32(_h) } ================================================ FILE: go/vendor/modules.txt ================================================ # github.com/veandco/go-sdl2 v0.4.36 ## explicit; go 1.15 github.com/veandco/go-sdl2/_libs github.com/veandco/go-sdl2/img github.com/veandco/go-sdl2/sdl ================================================ FILE: haskell/.gitignore ================================================ .stack-work/ *~ ================================================ FILE: haskell/Makefile ================================================ .PHONY: all msg clean fullclean main all: msg main msg: @echo '--- Haskell ---' main: src/Lib.hs app/Main.hs stack build run: msg time stack run clean: stack clean fullclean: clean ================================================ FILE: haskell/README.md ================================================ ## SDL2 example for Haskell Requires `stack` and `SDL2`. ### Building stack setup stack build ### Running stack exec grumpycat-exe Or simply stack run ### Source code The source code is in `src/Lib.hs` (library) and `app/Main.hs` (executable). The main package configuration file is `package.yaml`. The `.cabal` file is generated by Stack. ================================================ FILE: haskell/Setup.hs ================================================ import Distribution.Simple main = defaultMain ================================================ FILE: haskell/app/Main.hs ================================================ {-# LANGUAGE OverloadedStrings #-} module Main where import Lib import Foreign.C.Types import SDL.Vect import qualified SDL import System.FilePath import System.Directory (getCurrentDirectory) screenWidth, screenHeight :: CInt (screenWidth, screenHeight) = (620, 387) main :: IO () main = do SDL.initializeAll win <- SDL.createWindow "Hello World!" SDL.defaultWindow { SDL.windowInitialSize = V2 screenWidth screenHeight } ren <- SDL.createRenderer win (-1) SDL.defaultRenderer -- Load the image from ../img/grumpy-cat.bmp currentDirectory <- getCurrentDirectory let imageFileName = currentDirectory ".." "img" "grumpy-cat.bmp" putStrLn ("Loading " ++ imageFileName) bmp <- SDL.loadBMP imageFileName -- Create a texture from the surface tex <- SDL.createTextureFromSurface ren bmp -- Render the image in a loop for 2 seconds (20 * 100ms) mainLoop ren tex 20 SDL.destroyWindow win ================================================ FILE: haskell/grumpycat.cabal ================================================ cabal-version: 1.12 -- This file has been generated from package.yaml by hpack version 0.35.0. -- -- see: https://github.com/sol/hpack name: grumpycat version: 0.1.0.0 description: Please see the README on GitHub at homepage: https://github.com/githubuser/grumpycat#readme bug-reports: https://github.com/githubuser/grumpycat/issues author: Author name here maintainer: example@example.com copyright: 2022 Author name here license: BSD3 build-type: Simple extra-source-files: README.md source-repository head type: git location: https://github.com/githubuser/grumpycat library exposed-modules: Lib other-modules: Paths_grumpycat hs-source-dirs: src build-depends: base >=4.7 && <5 , directory , filepath , sdl2 default-language: Haskell2010 executable grumpycat-exe main-is: Main.hs other-modules: Paths_grumpycat hs-source-dirs: app ghc-options: -threaded -rtsopts -with-rtsopts=-N build-depends: base >=4.7 && <5 , directory , filepath , grumpycat , sdl2 default-language: Haskell2010 test-suite grumpycat-test type: exitcode-stdio-1.0 main-is: Spec.hs other-modules: Paths_grumpycat hs-source-dirs: test ghc-options: -threaded -rtsopts -with-rtsopts=-N build-depends: base >=4.7 && <5 , directory , filepath , grumpycat , sdl2 default-language: Haskell2010 ================================================ FILE: haskell/package.yaml ================================================ name: grumpycat version: 0.1.0.0 github: "githubuser/grumpycat" license: BSD3 author: "Author name here" maintainer: "example@example.com" copyright: "2022 Author name here" extra-source-files: - README.md # Metadata used when publishing your package # synopsis: Short description of your package # category: Web # To avoid duplicated efforts in documentation and dealing with the # complications of embedding Haddock markup inside cabal files, it is # common to point users to the README.md file. description: Please see the README on GitHub at dependencies: - base >= 4.7 && < 5 - sdl2 - filepath - directory library: source-dirs: src executables: grumpycat-exe: main: Main.hs source-dirs: app ghc-options: - -threaded - -rtsopts - -with-rtsopts=-N dependencies: - grumpycat tests: grumpycat-test: main: Spec.hs source-dirs: test ghc-options: - -threaded - -rtsopts - -with-rtsopts=-N dependencies: - grumpycat ================================================ FILE: haskell/src/Lib.hs ================================================ {-# LANGUAGE OverloadedStrings #-} module Lib ( mainLoop ) where import SDL mainLoop :: Renderer -> Texture -> Int -> IO () mainLoop ren tex 0 = return () mainLoop ren tex n = do -- Present the texture and wait 100 ms SDL.clear ren SDL.copy ren tex Nothing Nothing SDL.present ren SDL.delay 100 -- Call mainLoop recursively until n is 0 mainLoop ren tex (n - 1) ================================================ FILE: haskell/stack.yaml ================================================ # This file was automatically generated by 'stack init' # # Some commonly used options have been documented as comments in this file. # For advanced use and comprehensive documentation of the format, please see: # https://docs.haskellstack.org/en/stable/yaml_configuration/ # Resolver to choose a 'specific' stackage snapshot or a compiler version. # A snapshot resolver dictates the compiler version and the set of packages # to be used for project dependencies. For example: # # resolver: lts-3.5 # resolver: nightly-2015-09-21 # resolver: ghc-7.10.2 # # The location of a snapshot can be provided as a file or url. Stack assumes # a snapshot provided as a file might change, whereas a url resource does not. # # resolver: ./custom-snapshot.yaml # resolver: https://example.com/snapshots/2018-01-01.yaml resolver: url: https://raw.githubusercontent.com/commercialhaskell/stackage-snapshots/master/lts/19/5.yaml # User packages to be built. # Various formats can be used as shown in the example below. # # packages: # - some-directory # - https://example.com/foo/bar/baz-0.0.2.tar.gz # subdirs: # - auto-update # - wai packages: - . # Dependency packages to be pulled from upstream that are not in the resolver. # These entries can reference officially published versions as well as # forks / in-progress versions pinned to a git hash. For example: # # extra-deps: # - acme-missiles-0.3 # - git: https://github.com/commercialhaskell/stack.git # commit: e7b331f14bcffb8367cd58fbfc8b40ec7642100a # # extra-deps: [] # Override default flag values for local packages and extra-deps # flags: {} # Extra package databases containing global packages # extra-package-dbs: [] # Control whether we use the GHC we find on the path # system-ghc: true # # Require a specific version of stack, using version ranges # require-stack-version: -any # Default # require-stack-version: ">=2.7" # # Override the architecture used by stack, especially useful on Windows # arch: i386 # arch: x86_64 # # Extra directories used by stack for building # extra-include-dirs: [/path/to/dir] # extra-lib-dirs: [/path/to/dir] # # Allow a newer minor version of GHC than the snapshot specifies # compiler-check: newer-minor ================================================ FILE: haskell/test/Spec.hs ================================================ main :: IO () main = putStrLn "Test suite not yet implemented" ================================================ FILE: include/sdl2.h ================================================ #pragma once #include #include namespace sdl2 { // Very useful function from Eric Scott Barr: // https://eb2.co/blog/2014/04/c-plus-plus-14-and-sdl2-managing-resources/ template auto make_resource(Creator c, Destructor d, Arguments&&... args) { auto r = c(std::forward(args)...); return std::unique_ptr, decltype(d)>(r, d); } // The "internal type" of the SDL System using SDL_System = int; // SDL_CreateSDL initiates the use of SDL. // The given flags are passed to SDL_Init. // The returned value contains the exit code. inline SDL_System* SDL_CreateSDL(Uint32 flags) { auto init_status = new SDL_System; *init_status = SDL_Init(flags); return init_status; } // SDL_DestroySDL ends the use of SDL inline void SDL_DestroySDL(SDL_System* init_status) { delete init_status; // Delete the int that contains the return value from SDL_Init SDL_Quit(); } using sdlsystem_ptr_t = std::unique_ptr; using window_ptr_t = std::unique_ptr; using renderer_ptr_t = std::unique_ptr; using surf_ptr_t = std::unique_ptr; using texture_ptr_t = std::unique_ptr; // Initialize SDL (the returned int* contains the return value from SDL_Init) inline sdlsystem_ptr_t make_sdlsystem(Uint32 flags) { return make_resource(SDL_CreateSDL, SDL_DestroySDL, flags); } // Create a window (that contains both a SDL_Window and the destructor for SDL_Windows) inline window_ptr_t make_window(const char* title, int x, int y, int w, int h, Uint32 flags) { return make_resource(SDL_CreateWindow, SDL_DestroyWindow, title, x, y, w, h, flags); } // Create a renderer given a window, containing both the renderer and the destructor inline renderer_ptr_t make_renderer(SDL_Window* win, int x, Uint32 flags) { return make_resource(SDL_CreateRenderer, SDL_DestroyRenderer, win, x, flags); } // Create a surface from a bmp file, containing both the surface and the destructor inline surf_ptr_t make_bmp(SDL_RWops* sdlfile) { // May throw an exception if sdlfile is nullptr return make_resource(SDL_LoadBMP_RW, SDL_FreeSurface, sdlfile, 1); } // Create a texture from a renderer and a surface inline texture_ptr_t make_texture(SDL_Renderer* ren, SDL_Surface* surf) { return make_resource(SDL_CreateTextureFromSurface, SDL_DestroyTexture, ren, surf); } } // namespace sdl2 ================================================ FILE: java22/Main.java ================================================ import static java.lang.foreign.ValueLayout.*; import java.lang.foreign.*; import java.lang.invoke.MethodHandle; import java.nio.charset.StandardCharsets; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; public class Main { private static final Linker linker = Linker.nativeLinker(); private static SymbolLookup lib; // Constants from SDL private static final int SDL_INIT_VIDEO = 0x00000020; private static final int SDL_WINDOWPOS_UNDEFINED = 0x1FFF0000; private static final int SDL_WINDOW_SHOWN = 0x00000004; private static final int SDL_RENDERER_ACCELERATED = 0x00000002; private static final int SDL_RENDERER_PRESENTVSYNC = 0x00000004; private static final int SDL_QUIT = 0x100; private static final int SDL_KEYDOWN = 0x300; private static final int SDLK_ESCAPE = 0x1B; public static void main(String[] args) { try { runSDL(); } catch (Throwable e) { e.printStackTrace(); } } private static void runSDL() throws Throwable { String libPath = System.getProperty("sdl2.library.path"); if (libPath == null || libPath.isEmpty()) { throw new IllegalArgumentException("Library path not specified. Use -Dsdl2.library.path="); } try (Arena arena = Arena.ofConfined()) { lib = SymbolLookup.libraryLookup(libPath, arena); MethodHandle SDL_Init = loadFunction("SDL_Init", FunctionDescriptor.of(JAVA_INT, JAVA_INT)); MethodHandle SDL_Quit = loadFunction("SDL_Quit", FunctionDescriptor.ofVoid()); MethodHandle SDL_CreateWindow = loadFunction("SDL_CreateWindow", FunctionDescriptor.of(ADDRESS, ADDRESS, JAVA_INT, JAVA_INT, JAVA_INT, JAVA_INT, JAVA_INT)); MethodHandle SDL_CreateRenderer = loadFunction("SDL_CreateRenderer", FunctionDescriptor.of(ADDRESS, ADDRESS, JAVA_INT, JAVA_INT)); MethodHandle SDL_CreateTextureFromSurface = loadFunction("SDL_CreateTextureFromSurface", FunctionDescriptor.of(ADDRESS, ADDRESS, ADDRESS)); MethodHandle SDL_DestroyRenderer = loadFunction("SDL_DestroyRenderer", FunctionDescriptor.ofVoid(ADDRESS)); MethodHandle SDL_DestroyWindow = loadFunction("SDL_DestroyWindow", FunctionDescriptor.ofVoid(ADDRESS)); MethodHandle SDL_FreeSurface = loadFunction("SDL_FreeSurface", FunctionDescriptor.ofVoid(ADDRESS)); MethodHandle SDL_DestroyTexture = loadFunction("SDL_DestroyTexture", FunctionDescriptor.ofVoid(ADDRESS)); MethodHandle SDL_RenderClear = loadFunction("SDL_RenderClear", FunctionDescriptor.of(JAVA_INT, ADDRESS)); MethodHandle SDL_RenderCopy = loadFunction("SDL_RenderCopy", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, ADDRESS)); MethodHandle SDL_RenderPresent = loadFunction("SDL_RenderPresent", FunctionDescriptor.ofVoid(ADDRESS)); MethodHandle SDL_LoadBMP_RW = loadFunction("SDL_LoadBMP_RW", FunctionDescriptor.of(ADDRESS, ADDRESS, JAVA_INT)); MethodHandle SDL_RWFromFile = loadFunction("SDL_RWFromFile", FunctionDescriptor.of(ADDRESS, ADDRESS, ADDRESS)); MethodHandle SDL_GetError = loadFunction("SDL_GetError", FunctionDescriptor.of(ADDRESS)); MethodHandle SDL_PollEvent = loadFunction("SDL_PollEvent", FunctionDescriptor.of(JAVA_INT, ADDRESS)); MethodHandle SDL_Delay = loadFunction("SDL_Delay", FunctionDescriptor.ofVoid(JAVA_INT)); if (SDL_Init == null || SDL_Quit == null || SDL_CreateWindow == null || SDL_CreateRenderer == null || SDL_CreateTextureFromSurface == null || SDL_DestroyRenderer == null || SDL_DestroyWindow == null || SDL_FreeSurface == null || SDL_DestroyTexture == null || SDL_RenderClear == null || SDL_RenderCopy == null || SDL_RenderPresent == null || SDL_LoadBMP_RW == null || SDL_RWFromFile == null || SDL_GetError == null || SDL_PollEvent == null || SDL_Delay == null) { System.err.println("Failed to load one or more SDL functions"); return; } int result = (int) SDL_Init.invoke(SDL_INIT_VIDEO); if (result != 0) { System.err.println("SDL_Init failed with error code: " + result); return; } MemorySegment title = allocateString(arena, "Hello, World!"); MemorySegment window = (MemorySegment) SDL_CreateWindow.invoke(title, 100, 100, 620, 387, SDL_WINDOW_SHOWN); if (window.address() == 0) { System.err.println("SDL_CreateWindow failed: " + getError(SDL_GetError)); SDL_Quit.invoke(); return; } MemorySegment renderer = (MemorySegment) SDL_CreateRenderer.invoke(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (renderer.address() == 0) { System.err.println("SDL_CreateRenderer failed: " + getError(SDL_GetError)); SDL_DestroyWindow.invoke(window); SDL_Quit.invoke(); return; } MemorySegment filename = allocateString(arena, "../img/grumpy-cat.bmp"); MemorySegment rwop = (MemorySegment) SDL_RWFromFile.invoke(filename, allocateString(arena, "rb")); if (rwop.address() == 0) { System.err.println("SDL_RWFromFile failed: " + getError(SDL_GetError)); SDL_DestroyRenderer.invoke(renderer); SDL_DestroyWindow.invoke(window); SDL_Quit.invoke(); return; } MemorySegment bmp = (MemorySegment) SDL_LoadBMP_RW.invoke(rwop, 1); if (bmp.address() == 0) { System.err.println("SDL_LoadBMP_RW failed: " + getError(SDL_GetError)); SDL_DestroyRenderer.invoke(renderer); SDL_DestroyWindow.invoke(window); SDL_Quit.invoke(); return; } MemorySegment texture = (MemorySegment) SDL_CreateTextureFromSurface.invoke(renderer, bmp); SDL_FreeSurface.invoke(bmp); if (texture.address() == 0) { System.err.println("SDL_CreateTextureFromSurface failed: " + getError(SDL_GetError)); SDL_DestroyRenderer.invoke(renderer); SDL_DestroyWindow.invoke(window); SDL_Quit.invoke(); return; } AtomicBoolean quit = new AtomicBoolean(false); long startTime = System.currentTimeMillis(); MemorySegment event = arena.allocate(56); // Size of SDL_Event structure while (!quit.get()) { while ((int) SDL_PollEvent.invoke(event) != 0) { int type = event.get(JAVA_INT, 0); switch (type) { case SDL_QUIT: quit.set(true); break; case SDL_KEYDOWN: int key = event.get(JAVA_INT, 4); if (key == SDLK_ESCAPE) { quit.set(true); } } } long elapsedTime = System.currentTimeMillis() - startTime; if (elapsedTime > 2000) { break; } SDL_RenderClear.invoke(renderer); SDL_RenderCopy.invoke(renderer, texture, MemorySegment.NULL, MemorySegment.NULL); SDL_RenderPresent.invoke(renderer); SDL_Delay.invoke(100); } SDL_DestroyTexture.invoke(texture); SDL_DestroyRenderer.invoke(renderer); SDL_DestroyWindow.invoke(window); SDL_Quit.invoke(); } } private static String getError(MethodHandle SDL_GetError) { try { MemorySegment errorSegment = (MemorySegment) SDL_GetError.invoke(); return segmentToString(errorSegment); } catch (Throwable e) { return "Unknown error"; } } private static String segmentToString(MemorySegment segment) { int length = 0; while (segment.get(ValueLayout.JAVA_BYTE, length) != 0) { length++; } byte[] bytes = new byte[length]; for (int i = 0; i < length; i++) { bytes[i] = segment.get(ValueLayout.JAVA_BYTE, i); } return new String(bytes, StandardCharsets.UTF_8); } private static MemorySegment allocateString(Arena arena, String str) { byte[] bytes = str.getBytes(StandardCharsets.UTF_8); MemorySegment segment = arena.allocate(bytes.length + 1); // +1 for null terminator segment.asByteBuffer().put(bytes).put((byte) 0); return segment; } private static MethodHandle loadFunction(String name, FunctionDescriptor descriptor) { Optional address = lib.find(name); if (address.isPresent()) { return linker.downcallHandle(address.get(), descriptor); } else { System.err.println("Failed to load function: " + name); return null; } } } ================================================ FILE: java22/Makefile ================================================ .PHONY: all clean build run # Java setup JAVA_HOME ?= $(shell if [ -x /usr/libexec/java_home ]; then /usr/libexec/java_home -v 22; elif [ -d /opt/homebrew/Cellar/openjdk/22.0.1 ]; then echo /opt/homebrew/Cellar/openjdk/22.0.1; else echo /usr/lib/jvm/java-22-openjdk; fi) JAVA=$(JAVA_HOME)/bin/java JAVAC=$(JAVA_HOME)/bin/javac JAR=$(JAVA_HOME)/bin/jar # Get Java version information once JAVA_VERSION_INFO=$(shell $(JAVA) -version 2>&1 | awk -F '"' '/version/ {split($$2,v,"."); print v[1]}') JAVA_VERSION=$(JAVA_VERSION_INFO) # Check if Java version is sufficient ifeq ($(shell expr $(JAVA_VERSION) \>= 22 2>/dev/null), 1) JAVA_VERSION_CHECK=found else JAVA_VERSION_CHECK=not found endif ifeq ($(JAVA_VERSION_CHECK), not found) $(error JAVA_HOME needs to point to Java 22 or later) endif # Java options - conditional on Java version ifeq ($(JAVA_VERSION), 22) JAVA_OPTS=--enable-preview --enable-native-access=ALL-UNNAMED JAVAC_OPTS=--enable-preview --source 22 else JAVA_OPTS=--enable-native-access=ALL-UNNAMED JAVAC_OPTS=--source $(JAVA_VERSION) endif # Project setup TARGET_JAR=main.jar JAVA_FILES=Main.java MAIN_CLASS=Main PACKAGE_NAME=main BUILD_DIR=build # Detect OS and set library path ifeq ($(shell uname), Darwin) SDL2_LIB_PATH=$(shell if [ -f /opt/homebrew/lib/libSDL2.dylib ]; then echo /opt/homebrew/lib/libSDL2.dylib; elif [ -f /usr/local/lib/libSDL2.dylib ]; then echo /usr/local/lib/libSDL2.dylib; else echo notfound; fi) else ifeq ($(shell uname), Linux) SDL2_LIB_PATH=$(shell pkg-config --variable=libdir sdl2 2>/dev/null)/libSDL2.so ifeq ($(wildcard $(SDL2_LIB_PATH)),) SDL2_LIB_PATH=$(shell if [ -f /usr/lib/libSDL2.so ]; then echo /usr/lib/libSDL2.so; elif [ -f /usr/lib64/libSDL2.so ]; then echo /usr/lib64/libSDL2.so; else echo notfound; fi) endif else ifeq ($(shell uname), FreeBSD) SDL2_LIB_PATH=/usr/local/lib/libSDL2.so else ifeq ($(OS), Windows_NT) SDL2_LIB_PATH=SDL2.dll else $(error Unsupported OS) endif # Check if SDL2 library exists ifeq ($(SDL2_LIB_PATH), notfound) $(error SDL2 library not found. Please install SDL2 using your system's package manager) endif all: build build: $(TARGET_JAR) $(TARGET_JAR): $(JAVA_FILES) @mkdir -p "$(BUILD_DIR)/META-INF" @$(JAVAC) $(JAVAC_OPTS) -d "$(BUILD_DIR)" $(JAVA_FILES) @echo "Main-Class: $(MAIN_CLASS)" > "$(BUILD_DIR)/META-INF/MANIFEST.MF" @$(JAR) cmf "$(BUILD_DIR)/META-INF/MANIFEST.MF" $(TARGET_JAR) -C "$(BUILD_DIR)" . @rm -rf "$(BUILD_DIR)" run: @$(JAVA) $(JAVA_OPTS) -Dsdl2.library.path=$(SDL2_LIB_PATH) -jar $(TARGET_JAR) script_with_jar.sh: $(TARGET_JAR) @echo '#!/bin/bash' > $@ @echo 'me=`realpath $$0`' >> $@ @echo 'exec $(JAVA) $(JAVA_OPTS) -Dsdl2.library.path=$(SDL2_LIB_PATH) -jar $$me "$$@"' >> $@ @cat $(TARGET_JAR) >> $@ @chmod +x $@ clean: @rm -f $(TARGET_JAR) script_with_jar.sh ================================================ FILE: java22/README.md ================================================ # Java * Requires Java 22 or later. Tested with OpenJDK 22. * Requires `make` and `SDL2`. * Builds and runs on Arch Linux. * ❗ Builds and crashes on macOS❗ * Other platforms are a work in progress. ## Build and run make make run ### SDL2 `SDL2.dll` is included (zlib license). It can also be downloaded from here: https://www.libsdl.org/download-2.0.php This text came together with the `SDL2.dll` binary: ``` The Simple DirectMedia Layer (SDL for short) is a cross-platform library designed to make it easy to write multi-media software, such as games and emulators. The Simple DirectMedia Layer library source code is available from: https://www.libsdl.org/ This library is distributed under the terms of the zlib license: http://www.zlib.net/zlib_license.html ``` ================================================ FILE: kotlin/.gitignore ================================================ build/ ================================================ FILE: kotlin/Main.kt ================================================ import kotlin.OptIn import kotlinx.cinterop.* import sdl2.* @OptIn(ExperimentalForeignApi::class) fun main() { if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { println("SDL_Init failed: ${SDL_GetError()?.toKString()}") return } val window = SDL_CreateWindow( "Hello World!", // Match the window title with the C program 100, 100, 620, 387, SDL_WINDOW_SHOWN ) if (window == null) { println("SDL_CreateWindow failed: ${SDL_GetError()?.toKString()}") SDL_Quit() return } val renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED or SDL_RENDERER_PRESENTVSYNC) if (renderer == null) { println("SDL_CreateRenderer failed: ${SDL_GetError()?.toKString()}") SDL_DestroyWindow(window) SDL_Quit() return } val imageFilename = "../img/grumpy-cat.bmp" val rwop = SDL_RWFromFile(imageFilename, "rb") if (rwop == null) { println("SDL_RWFromFile failed: ${SDL_GetError()?.toKString()}") SDL_DestroyRenderer(renderer) SDL_DestroyWindow(window) SDL_Quit() return } val bmp = SDL_LoadBMP_RW(rwop, 1) if (bmp == null) { println("SDL_LoadBMP_RW failed: ${SDL_GetError()?.toKString()}") SDL_DestroyRenderer(renderer) SDL_DestroyWindow(window) SDL_Quit() return } val tex = SDL_CreateTextureFromSurface(renderer, bmp) if (tex == null) { println("SDL_CreateTextureFromSurface failed: ${SDL_GetError()?.toKString()}") SDL_FreeSurface(bmp) SDL_DestroyRenderer(renderer) SDL_DestroyWindow(window) SDL_Quit() return } SDL_FreeSurface(bmp) repeat(20) { SDL_RenderClear(renderer) SDL_RenderCopy(renderer, tex, null, null) SDL_RenderPresent(renderer) SDL_Delay(100u) } SDL_DestroyTexture(tex) SDL_DestroyRenderer(renderer) SDL_DestroyWindow(window) SDL_Quit() } ================================================ FILE: kotlin/Makefile ================================================ all: build/main.kexe build/sdl2.klib: sdl2.def mkdir -p build cinterop \ -compiler-options -I/usr/local/include/SDL2 \ -def sdl2.def \ -o build/sdl2 build/main.kexe: build/sdl2.klib Main.kt kotlinc-native \ -l build/sdl2.klib \ -linker-options /opt/homebrew/lib/libSDL2.dylib \ -o build/main \ Main.kt run: build/main.kexe build/main.kexe clean: @-rm -rfv build sdl2-build ================================================ FILE: kotlin/README.md ================================================ This is an early version of an example for Kotlin Native + SDL2. It is currently only tested on macOS Sonoma with XCode installed, and with Kotlin Native installed through Homebrew. Currently, the program compiles and runs, but no window appears here (!). Pull requests are welcome! ================================================ FILE: kotlin/sdl2.def ================================================ headers = SDL.h stdlib.h time.h entryPoint = SDL_main headerFilter = SDL* stdlib.h time.h compilerOpts = -D_POSIX_SOURCE compilerOpts.osx = -I/opt/homebrew/include/SDL2 -I/usr/local/include/SDL2 compilerOpts.linux = -I/usr/include/SDL2 -D_REENTRANT linkerOpts = linkerOpts.osx = -L/opt/homebrew/lib -L/usr/local/lib -lSDL2 linkerOpts.linux = -I/usr/lib -lSDL2 ================================================ FILE: lisp/Makefile ================================================ .PHONY: all clean fullclean msg2 run PACKAGE_NAME := sdl2-examples MAIN_FUNCTION := renderer-test all: msg main quicklisp.lisp: @curl -Os "https://beta.quicklisp.org/$@" quicklisp/setup.lisp: quicklisp.lisp @sbcl \ --non-interactive \ --noprint \ --no-sysinit \ --no-userinit \ --load $< \ --eval "(quicklisp-quickstart:install :path \"quicklisp\")" msg: @echo '--- Common Lisp ---' main: quicklisp/setup.lisp main.lisp @echo -n '[main] Compiling...' @sbcl \ --non-interactive \ --noprint \ --no-sysinit \ --no-userinit \ --load quicklisp/setup.lisp \ --eval "(ql:quickload 'sdl2)" \ --eval "(ql:quickload 'cl-opengl)" \ --load main.lisp \ --eval "(sb-ext:save-lisp-and-die \"$@\" :executable t :toplevel '${PACKAGE_NAME}:${MAIN_FUNCTION})" @echo 'ok' small: quicklisp/setup.lisp main.lisp @echo -n '[main] Compiling, with compression enabled...' @sbcl \ --non-interactive \ --noprint \ --no-sysinit \ --no-userinit \ --load quicklisp/setup.lisp \ --eval "(ql:quickload 'sdl2)" \ --eval "(ql:quickload 'cl-opengl)" \ --load main.lisp \ --eval "(sb-ext:save-lisp-and-die \"$@\" :executable t :compression 9 :toplevel '${PACKAGE_NAME}:${MAIN_FUNCTION})" @echo 'ok' run: msg quicklisp/setup.lisp main.lisp @time sbcl \ --non-interactive \ --noprint \ --no-sysinit \ --no-userinit \ --load quicklisp/setup.lisp \ --eval "(ql:quickload 'sdl2)" \ --eval "(ql:quickload 'cl-opengl)" \ --load main.lisp \ --eval "(${PACKAGE_NAME}:${MAIN_FUNCTION})" clean: @-rm -f main small *.fas *.o fullclean: clean @-rm -fr quicklisp quicklisp.lisp ================================================ FILE: lisp/README.md ================================================ # Common Lisp This example uses SDL2 and QuickLisp, and is based on examples from [cl-sdl2](https://github.com/lispgames/cl-sdl2). The main function and package name are defined at the top of the `Makefile`. Tested on Arch Linux (works) and macOS (didn't work). * [Additional examples for Common Lisp](https://github.com/lispgames/cl-sdl2/tree/master/examples) ================================================ FILE: lisp/main.lisp ================================================ (in-package :sdl2-examples) (require :sdl2) (defun renderer-test () "Display an image of a grumpy cat" (sdl2:with-init (:everything) (sdl2:with-window (win :title "Hello World!" :x 100 :y 100 :w 620 :h 387 :flags '(:shown)) (sdl2:with-renderer (ren win :flags '(:accelerated :presentvsync)) (let* ( (bmp (sdl2:load-bmp "../img/grumpy-cat.bmp")) (tex (sdl2:create-texture-from-surface ren bmp))) (loop repeat 20 do (sdl2:render-clear ren) (sdl2:render-copy ren tex) (sdl2:render-present ren) (sdl2:delay 100))))))) ================================================ FILE: lua/Makefile ================================================ .PHONY: all msg clean fullclean LUA_VERSION ?= 5.3 all: msg @# Nothing to build @true msg: @echo '--- Lua ---' run: msg main.lua time lua$(LUA_VERSION) main.lua clean: @# Nothing to clean @true fullclean: clean ================================================ FILE: lua/README.md ================================================ Instructions ------------ # Installation of SDL2 for Lua ### With luarocks `sudo luarocks install lua-sdl2` ### For Arch Linux `pacman -S lua-sdl2` # Running If `lua main.lua` does not work, try using a specific Lua version that may have the SDL2 bindings available on your system, like `lua5.3 main.lua`. ================================================ FILE: lua/main.lua ================================================ local SDL = require "SDL" local image = require "SDL.image" local ret, err = SDL.init { SDL.flags.Video } if not ret then error(err) end local win, err = SDL.createWindow { title = "Hello World!", width = 620, height = 387, flags = SDL.window.Shown } if not win then error(err) end local rdr, err = SDL.createRenderer(win, -1, SDL.rendererFlags.Accelerated + SDL.rendererFlags.PresentVSYNC) if not rdr then error(err) end local img, ret = SDL.loadBMP("../img/grumpy-cat.bmp") if not img then error(err) end tex = rdr:createTextureFromSurface(img) for i = 1, 20 do rdr:clear() rdr:copy(tex) rdr:present() SDL.delay(100) end ================================================ FILE: mruby/Makefile ================================================ .PHONY: all msg clean fullclean all: msg @# Nothing to build @true msg: @echo '--- Ruby ---' run: msg main.rb time mruby main.rb clean: @# Nothing to clean @true fullclean: clean ================================================ FILE: mruby/README.md ================================================ # Ruby This example uses MRuby. * Install the SDL2 libraries and include files. * Install [MRuby](https://github.com/mruby/mruby) and [mruby-sdl2](https://github.com/crimsonwoods/mruby-sdl2). The installation of `mruby-sdl2` may be tricky, and may involve recompiling mruby and also adding this line to `build_config.rb`: conf.gem :github => 'crimsonwoods/mruby-sdl2', :branch => 'master' Consult the [mruby-sdl2 project](https://github.com/crimsonwoods/mruby-sdl2) for more information. * Run the SDL2 sample with `mruby main.rb`. ================================================ FILE: mruby/main.rb ================================================ SDL2::init X = SDL2::Video::Window::SDL_WINDOWPOS_UNDEFINED Y = SDL2::Video::Window::SDL_WINDOWPOS_UNDEFINED W = 620 H = 387 FLAGS = SDL2::Video::Window::SDL_WINDOW_SHOWN # Note that error checking is built in for many of the functions below. begin begin win = SDL2::Video::Window.new "Hello World!", X, Y, W, H, FLAGS ren = SDL2::Video::Renderer.new(win) bmp = SDL2::Video::Surface::load_bmp("../img/grumpy-cat.bmp") tex = SDL2::Video::Texture.new(ren, bmp) bmp.free for i in 0..20 # Show the image ren.clear ren.copy(tex) ren.present # Wait 100 ms SDL2::delay(100) end # Clean up tex.destroy ren.destroy win.destroy ensure SDL2::Video::quit end ensure SDL2::quit end ================================================ FILE: nim/Makefile ================================================ .PHONY: all clean fullclean msg sdl2 all: msg main msg: @echo '--- Nim ---' sdl2: @-if [ ! -n "$$(find ~/.nimble/pkgs -maxdepth 1 -type d -name "sdl2-*" | head -1)" ]; then nimble install -y sdl2; fi main: sdl2 main.nim nim -d:release c main.nim run: msg main time ./main clean: rm -rf main nimcache fullclean: clean rm -rf sdl2 ================================================ FILE: nim/README.md ================================================ # SDL2 example for Nim Requirements: * Nim * Nimble (the Nim package manager) On some platforms, `nimble install sdl2` might be required before building with `nim c main.nim`. ================================================ FILE: nim/main.nim ================================================ import sdl2 var win: WindowPtr ren: RendererPtr bmp: SurfacePtr tex: TexturePtr discard init(INIT_EVERYTHING) win = createWindow("Hello World!", 100, 100, 620, 387, SDL_WINDOW_SHOWN) if win == nil: echo("createWindow Error: ", getError()) quit(1) ren = createRenderer(win, -1, Renderer_Accelerated or Renderer_PresentVsync) if ren == nil: echo("createRenderer Error: ", getError()) quit(1) bmp = loadBMP("../img/grumpy-cat.bmp") if bmp == nil: echo("loadBMP Error: ", getError()) quit(1) tex = createTextureFromSurface(ren, bmp) if tex == nil: echo("createTextureFromSurface Error: ", getError()) quit(1) freeSurface(bmp) for i in countup(1, 20): ren.clear copy(ren, tex, nil, nil) ren.present delay(100) destroy tex destroy ren destroy win sdl2.quit() ================================================ FILE: objc-cmake/CMakeLists.txt ================================================ cmake_minimum_required(VERSION 3.26) project(main) # Enable Objective-C support enable_language(OBJC) aux_source_directory(. SRC_LIST) add_executable(${PROJECT_NAME} ${SRC_LIST}) target_include_directories(${PROJECT_NAME} PRIVATE ../include) # Remove C++23 and add Objective-C specific flags target_compile_options(${PROJECT_NAME} PRIVATE -fobjc-arc # Enable ARC (Automatic Reference Counting) ) target_compile_definitions(${PROJECT_NAME} PRIVATE IMGDIR="../img/") # Add Foundation framework (required for Objective-C) find_library(FOUNDATION_LIBRARY Foundation) target_link_libraries(${PROJECT_NAME} PRIVATE ${FOUNDATION_LIBRARY}) # For macOS M2 systems with SDL2 installed via Homebrew list(APPEND CMAKE_MODULE_PATH "/usr/local/lib/cmake/SDL2" "/opt/homebrew/lib/cmake/SDL2") list(APPEND CMAKE_PREFIX_PATH "/usr/local" "/opt/homebrew") find_package(SDL2 QUIET) if (SDL2_FOUND) message("Using SDL2 from find_package") target_include_directories(${PROJECT_NAME} PRIVATE ${SDL2_INCLUDE_DIRS}) target_link_libraries(${PROJECT_NAME} PRIVATE ${SDL2_LIBRARIES}) else() # Fall back on pkg-config include(FindPkgConfig) pkg_search_module(SDL2 REQUIRED sdl2) message("Using SDL2 from pkg-config") target_include_directories(${PROJECT_NAME} PRIVATE ${SDL2_INCLUDE_DIRS}) target_link_libraries(${PROJECT_NAME} PRIVATE ${SDL2_LIBRARIES}) endif() ================================================ FILE: objc-cmake/README.md ================================================ SDL2, Objective-C and CMake =========================== Requirements ------------ * CMake * Compiler that supports Objective-C (like `clang`) * SDL2 One way of building with Objective-C, SDL2 and CMake ---------------------------------------------------- cmake -S . -B build -DCMAKE_BUILD_TYPE=Release make -C build Running ------- build/main Cleaning up the binary file and build directory ----------------------------------------------- rm -rf build/ ================================================ FILE: objc-cmake/main.m ================================================ #import #import @interface SDLWrapper : NSObject + (SDL_Window*)createWindowWithTitle:(const char*)title x:(int)x y:(int)y width:(int)width height:(int)height flags:(Uint32)flags; + (SDL_Renderer*)createRendererForWindow:(SDL_Window*)window driver:(int)driver flags:(Uint32)flags; + (SDL_Texture*)createTextureFromBMP:(const char*)filename renderer:(SDL_Renderer*)renderer; + (void)runEventLoopWithRenderer:(SDL_Renderer*)renderer texture:(SDL_Texture*)texture; @end @implementation SDLWrapper + (SDL_Window*)createWindowWithTitle:(const char*)title x:(int)x y:(int)y width:(int)width height:(int)height flags:(Uint32)flags { return SDL_CreateWindow(title, x, y, width, height, flags); } + (SDL_Renderer*)createRendererForWindow:(SDL_Window*)window driver:(int)driver flags:(Uint32)flags { return SDL_CreateRenderer(window, driver, flags); } + (SDL_Texture*)createTextureFromBMP:(const char*)filename renderer:(SDL_Renderer*)renderer { SDL_Surface* surface = SDL_LoadBMP(filename); if (!surface) { NSLog(@"SDL_LoadBMP Error: %s", SDL_GetError()); return NULL; } SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface); SDL_FreeSurface(surface); if (!texture) { NSLog(@"SDL_CreateTextureFromSurface Error: %s", SDL_GetError()); return NULL; } return texture; } + (void)runEventLoopWithRenderer:(SDL_Renderer*)renderer texture:(SDL_Texture*)texture { SDL_Event event; BOOL quit = NO; Uint32 startTime = SDL_GetTicks(); while (!quit) { while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: quit = YES; break; case SDL_KEYDOWN: if (event.key.keysym.sym == SDLK_ESCAPE) { quit = YES; } break; } } Uint32 elapsedTime = SDL_GetTicks() - startTime; if (elapsedTime > 2000) { break; } SDL_RenderClear(renderer); SDL_RenderCopy(renderer, texture, NULL, NULL); SDL_RenderPresent(renderer); SDL_Delay(100); } } @end int main(int argc, char* argv[]) { @autoreleasepool { if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { NSLog(@"SDL_Init Error: %s", SDL_GetError()); return EXIT_FAILURE; } SDL_Window* window = [SDLWrapper createWindowWithTitle:"Hello World!" x:-1 y:-1 width:620 height:387 flags:SDL_WINDOW_SHOWN]; if (!window) { NSLog(@"SDL_CreateWindow Error: %s", SDL_GetError()); SDL_Quit(); return EXIT_FAILURE; } SDL_Renderer* renderer = [SDLWrapper createRendererForWindow:window driver:-1 flags:SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC]; if (!renderer) { NSLog(@"SDL_CreateRenderer Error: %s", SDL_GetError()); SDL_DestroyWindow(window); SDL_Quit(); return EXIT_FAILURE; } SDL_Texture* texture = [SDLWrapper createTextureFromBMP:"../img/grumpy-cat.bmp" renderer:renderer]; if (!texture) { SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return EXIT_FAILURE; } [SDLWrapper runEventLoopWithRenderer:renderer texture:texture]; SDL_DestroyTexture(texture); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return EXIT_SUCCESS; } } ================================================ FILE: objectpascal/Makefile ================================================ .PHONY: all msg sdl2 clean fullclean all: msg main msg: @echo '--- FPC ---' main: sdl2 SDL2/SDL2.o main.pas @echo -n '[main] Compiling...' @fpc -FuSDL2 main.pas @echo 'ok' sdl2: checkout.sh @echo -n '[SDL2 for FPC] Checking out...' @./checkout.sh > /dev/null @echo 'ok' SDL2/SDL2.o: SDL2/SDL2.pas @fpc $< SDL2/SDL2_image.o: SDL2/SDL2_image.pas @fpc $< SDL2/SDL2_mixer.o: SDL2/SDL2_mixer.pas @fpc $< SDL2/SDL2_net.o: SDL2/SDL2_net.pas @fpc $< SDL2/SDL2_ttf.o: SDL2/SDL2_ttf.pas @fpc $< run: msg main time ./main clean: rm -f *.o main link.res SDL2/*.o SDL2/*.ppu fullclean: clean rm -rf SDL2 ================================================ FILE: objectpascal/README.md ================================================ Requirements ------------ * git * fpc * sdl2 ================================================ FILE: objectpascal/checkout.sh ================================================ #!/bin/bash [[ -d SDL2 ]] || git clone -q https://git@github.com/de-signer/sdl2-fpc SDL2 [[ -d SDL2/SDL2 ]] && (mv SDL2/SDL2 temp; rm -rf SDL2; mv temp SDL2; chmod -x SDL2/*) true ================================================ FILE: objectpascal/main.pas ================================================ program sdltest; uses SDL2; var win : PSDL_Window; ren : PSDL_Renderer; bmp : PSDL_Surface; tex : PSDL_Texture; i : Integer; begin if SDL_Init(SDL_INIT_EVERYTHING) <> 0 then begin WriteLn('SDL_Init Error: ', SDL_GetError()); Halt(1); end; win := SDL_CreateWindow('Hello World!', 100, 100, 620, 387, SDL_WINDOW_SHOWN); if win = nil then begin WriteLn('SDL_CreateWindow Error: ', SDL_GetError()); Halt(1); end; ren := SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED or SDL_RENDERER_PRESENTVSYNC); if ren = nil then begin WriteLn('SDL_CreateRenderer Error: ', SDL_GetError()); Halt(1); end; bmp := SDL_LoadBMP('../img/grumpy-cat.bmp'); if bmp = nil then begin WriteLn('SDL_LoadBMP Error: ', SDL_GetError()); Halt(1); end; tex := SDL_CreateTextureFromSurface(ren, bmp); SDL_FreeSurface(bmp); if tex = nil then begin WriteLn('SDL_CreateTextureFromSurface Error: ', SDL_GetError()); Halt(1); end; for i := 0 to 20 do begin SDL_RenderClear(ren); SDL_RenderCopy(ren, tex, nil, nil); SDL_RenderPresent(ren); SDL_Delay(100); end; SDL_DestroyTexture(tex); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); end. ================================================ FILE: ocaml/Makefile ================================================ .PHONY: all msg run clean fullclean all: msg main msg: @echo --- OCaml --- main: main.ml @echo -n '[main] Compiling...' ocamlfind ocamlopt -package tsdl -linkpkg -thread -o $@ $< @echo 'ok' run: msg main time ./main clean: rm -f main *.o *.cmx fullclean: clean rm -f *.cmi ================================================ FILE: ocaml/README.md ================================================ Requirements ------------ Install tsdl and tsdl-image with opam: opam install tsdl Now everything is ready to build and run. ================================================ FILE: ocaml/main.ml ================================================ open Tsdl let run () = let (let*) = Result.bind in let* _ = Sdl.init Sdl.Init.everything in let* w = Sdl.create_window "Hello World!" ~x:Sdl.Window.pos_centered ~y:Sdl.Window.pos_centered ~w:620 ~h:387 Sdl.Window.shown in let* r = Sdl.create_renderer w ~index:(-1) ~flags:Sdl.Renderer.software in let* bmp = Sdl.load_bmp "../img/grumpy-cat.bmp" in let* txt = Sdl.create_texture_from_surface r bmp in Sdl.free_surface bmp; for i = 0 to 20 do ignore @@ Sdl.render_clear r; ignore @@ Sdl.render_copy r txt; Sdl.render_present r; Sdl.delay (Int32.of_int 100); done; Sdl.destroy_texture txt; Sdl.destroy_renderer r; Sdl.destroy_window w; Sdl.quit (); Ok () let () = match run () with | Ok _ -> exit 0 | Error (`Msg e) -> Sdl.log "Error: %s" e; exit 1 ================================================ FILE: odin/Makefile ================================================ .PHONY: all msg clean fullclean all: msg main msg: @echo '--- Odin ---' main: main.odin odin build main.odin -file -out:main run: msg main time ./main odinrun: main.odin odin run main.odin -file clean: rm -f main fullclean: clean ================================================ FILE: odin/README.md ================================================ Requirements ------------ * git * odin * sdl2 ================================================ FILE: odin/main.odin ================================================ package main import "core:log" import "vendor:sdl2" main :: proc() { // Initialize if err := sdl2.Init(sdl2.INIT_EVERYTHING); err < 0 { log.fatal("Init Error:", sdl2.GetError()) } // Make sure to quit when the function returns defer sdl2.Quit() // Create the window win := sdl2.CreateWindow("Hello World!", 100, 100, 620, 387, sdl2.WINDOW_SHOWN) defer sdl2.DestroyWindow(win) // Create a renderer ren := sdl2.CreateRenderer(win, -1, sdl2.RENDERER_ACCELERATED|sdl2.RENDERER_PRESENTVSYNC) defer sdl2.DestroyRenderer(ren) // Load the image bmp := sdl2.LoadBMP("../img/grumpy-cat.bmp") // Use the image as a texture tex := sdl2.CreateTextureFromSurface(ren,bmp) defer sdl2.DestroyTexture(tex) // No need for the image data after the texture has been created sdl2.FreeSurface(bmp) for i := 0; i < 20; i += 1 { // Clear the renderer and display the image/texture sdl2.RenderClear(ren) sdl2.RenderCopy(ren, tex, nil, nil) sdl2.RenderPresent(ren) // Wait 100 ms sdl2.Delay(100) } } ================================================ FILE: python/Makefile ================================================ .PHONY: all msg clean fullclean all: msg @# Nothing to build @true msg: @echo '--- Python ---' run: msg main.py time python main.py clean: @# Nothing to clean @true fullclean: clean ================================================ FILE: python/README.md ================================================ # Python * First install SDL2. * Then install PySDL2 (the package may be named `python-pysdl2`). * Alternatively, install PySDL2 with `easy_install`. More information about getting started with PySDL2: http://pysdl2.readthedocs.org/en/latest/ ================================================ FILE: python/main.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- from sdl2 import * # There are more pythonic ways of doing this, by using the sdl2.ext module. def main(): SDL_Init(SDL_INIT_VIDEO) win = SDL_CreateWindow(b"Hello World!", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 620, 387, SDL_WINDOW_SHOWN) ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC) bmp = SDL_LoadBMP(b"../img/grumpy-cat.bmp") tex = SDL_CreateTextureFromSurface(ren, bmp) SDL_FreeSurface(bmp) for i in range(20): SDL_RenderClear(ren) SDL_RenderCopy(ren, tex, None, None) SDL_RenderPresent(ren) SDL_Delay(100) SDL_DestroyTexture(tex) SDL_DestroyRenderer(ren) SDL_DestroyWindow(win) SDL_Quit() if __name__ == "__main__": main() ================================================ FILE: ring/Makefile ================================================ .PHONY: all msg clean fullclean all: msg msg: @echo '--- Ring ---' run: msg main.ring time ring main.ring clean: @# Nothing to clean @true fullclean: clean ================================================ FILE: ring/README.md ================================================ Requirements ------------ * git * ring * sdl2 ================================================ FILE: ring/main.ring ================================================ Load "libsdl.ring" if SDL_Init(SDL_INIT_EVERYTHING) < 0 see "Init Error:" + SDL_GetError() exit(-1) end // Create the window win = SDL_CreateWindow("Hello World!", 100, 100, 620, 387, SDL_WINDOW_SHOWN) // Create a renderer ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC) // Load the image bmp = SDL_LoadBMP("../img/grumpy-cat.bmp") // Use the image as a texture tex = SDL_CreateTextureFromSurface(ren,bmp) // No need for the image data after the texture has been created SDL_FreeSurface(bmp) for i = 0 to 20 // Clear the renderer and display the image/texture SDL_RenderClear(ren) SDL_RenderCopy(ren, tex, NULL, NULL) SDL_RenderPresent(ren) // Wait 100 ms SDL_Delay(100) next SDL_DestroyTexture(tex) SDL_DestroyRenderer(ren) SDL_DestroyWindow(win) SDL_Quit() ================================================ FILE: run.sh ================================================ #!/bin/sh make run make fullclean ================================================ FILE: rust/.gitignore ================================================ target *.lock ================================================ FILE: rust/Cargo.toml ================================================ [package] name = "hello_sdl2" version = "1.1.0" authors = ["jdeseno", "Alexander F. Rødseth "] [dependencies] sdl2 = "0.34.3" [[bin]] name = "rust" path = "src/main.rs" ================================================ FILE: rust/Makefile ================================================ .PHONY: all msg clean fullclean all: msg main msg: @echo '--- Rust ---' main: cargo build --release run: msg main time ./target/release/rust clean: cargo clean fullclean: clean rm -f Cargo.lock ================================================ FILE: rust/README.md ================================================ Requires `rustc`, `cargo`, and `git`. Use `cargo run` to build and run the example. ================================================ FILE: rust/src/main.rs ================================================ extern crate sdl2; use sdl2::surface::Surface; use std::path::Path; fn main() { let ctx = sdl2::init().unwrap(); let video_subsystem = ctx.video().unwrap(); let mut timer = ctx.timer().unwrap(); // Create a new OpenGL window let window = match video_subsystem .window("Hello World!", 620, 387) .position_centered() .opengl() .build() { Ok(window) => window, Err(err) => panic!("failed to create window: {}", err), }; // Load the image as a surface let surface = match Surface::load_bmp(&Path::new("../img/grumpy-cat.bmp")) { Ok(surface) => surface, Err(err) => panic!("failed to load surface: {}", err), }; // Get the window surface, and prepare to handle events let event_pump = ctx.event_pump().unwrap(); let mut window_surf = window.surface(&event_pump).unwrap(); // Blit the image to the window surface surface.blit(None, &mut window_surf, None).unwrap(); for _ in 0..20 { // Display the contents of the window surface on the screen if let Err(err) = window_surf.update_window() { panic!("failed to update window surface: {}", err); } // Wait 100ms timer.delay(100); } } ================================================ FILE: scala/Main.scala ================================================ /* * An SDL2 example in Scala Native * * Inspired by a Scala Native program by @densh: https://gist.github.com/densh/1885e8b03127fd52ff659505d8b3b76b */ import scalanative.unsafe._ import scala.scalanative.unsigned._ import SDL._ import SDLNonExternal._ @extern @link("SDL2") object SDL { // --- Types used by the external SDL2 functions --- type Window = CStruct0 type Renderer = CStruct0 type Surface = CStruct0 type Texture = CStruct0 type SDL_RWops = CStruct0 type Rect = CStruct4[CInt, CInt, CInt, CInt] // -- External functions that are provided by the SDL2 library --- def SDL_Init(flags: CUnsignedInt): CInt = extern def SDL_CreateWindow( title: CString, x: CUnsignedInt, y: CUnsignedInt, w: Int, h: Int, flags: CUnsignedInt ): Ptr[Window] = extern def SDL_CreateRenderer( win: Ptr[Window], index: CInt, flags: CUnsignedInt ): Ptr[Renderer] = extern def SDL_CreateTextureFromSurface( ren: Ptr[Renderer], surf: Ptr[Surface] ): Ptr[Texture] = extern def SDL_DestroyRenderer(ren: Ptr[Renderer]): Unit = extern def SDL_DestroyWindow(ren: Ptr[Window]): Unit = extern def SDL_FreeSurface(ren: Ptr[Surface]): Unit = extern def SDL_DestroyTexture(tex: Ptr[Texture]): Unit = extern def SDL_RenderClear(ren: Ptr[Renderer]): Unit = extern def SDL_RenderCopy( ren: Ptr[Renderer], tex: Ptr[Texture], src: Ptr[Rect], dst: Ptr[Rect] ): CInt = extern def SDL_RenderPresent(ren: Ptr[Renderer]): Unit = extern def SDL_LoadBMP_RW(src: Ptr[SDL_RWops], freesrc: CInt): Ptr[Surface] = extern def SDL_RWFromFile(filename: CString, permissions: CString): Ptr[SDL_RWops] = extern def SDL_Quit(): Unit = extern def SDL_GetError(): CString = extern def SDL_Delay(ms: CUnsignedInt): Unit = extern } object SDLNonExternal { // --- SDL2 constants found in the SDL2 headers --- // From SDL.h final val SDL_INIT_VIDEO = 0x00000020.toUInt // From SDL_video.h final val SDL_WINDOWPOS_UNDEFINED = 0x1FFF0000.toUInt final val SDL_WINDOW_SHOWN = 0x00000004.toUInt // From SDL_render.h final val SDL_RENDERER_ACCELERATED: UInt = 0x00000002.toUInt final val SDL_RENDERER_PRESENTVSYNC: UInt = 0x00000004.toUInt // printErr is a helper function that prints a topic for the error, // and the error message from SDL_GetError() to stderr. def printErr(topic: String): Unit = { Console.err.println(s"$topic Error: ${fromCString(SDL.SDL_GetError())}") } } class HelloSDL { val title = c"Hello, World!" val width = 620 val height = 387 val imageFilename = c"../img/grumpy-cat.bmp" var win: Ptr[Window] = _ var ren: Ptr[Renderer] = _ var rwop: Ptr[SDL_RWops] = _ var bmp: Ptr[Surface] = _ var tex: Ptr[Texture] = _ def init(): Boolean = { if (SDL_Init(SDL_INIT_VIDEO.toUInt) != 0) { printErr("SDL_Init") return false } win = SDL_CreateWindow( title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_SHOWN ) if (win == null) { printErr("SDL_CreateWindow") return false } ren = SDL_CreateRenderer( win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC ) if (ren == null) { printErr("SDL_CreateRenderer") SDL_DestroyWindow(win) return false } rwop = SDL_RWFromFile(imageFilename, c"rb") if (rwop == null) { printErr("SDL_RWFromFile") SDL_DestroyRenderer(ren) SDL_DestroyWindow(win) return false } bmp = SDL_LoadBMP_RW(rwop, 1) // this also frees rwop if (bmp == null) { printErr("SDL_LoadBMP_RW") SDL_DestroyRenderer(ren) SDL_DestroyWindow(win) return false } tex = SDL_CreateTextureFromSurface(ren, bmp) if (tex == null) { printErr("SDL_CreateTextureFromSurface") SDL_FreeSurface(bmp) SDL_DestroyRenderer(ren) SDL_DestroyWindow(win) return false } SDL_FreeSurface(bmp) true } def loop(): Unit = { // Repeat 20 times (1 to 20).foreach { _ => SDL_RenderClear(ren) SDL_RenderCopy(ren, tex, null, null) SDL_RenderPresent(ren) SDL_Delay(100.toUInt) } } def destroy(): Unit = { SDL_DestroyTexture(tex) SDL_DestroyRenderer(ren) SDL_DestroyWindow(win) } def quit(): Unit = { SDL_Quit() } def run(): Unit = { if (init()) { loop() destroy() } quit() } } object Main extends App { new HelloSDL().run() } ================================================ FILE: scala/Makefile ================================================ .PHONY: all msg clean fullclean run all: msg main msg: @echo '--- Scala Native ---' main: Main.scala build.sbt project/plugins.sbt sbt nativeLink @mv -f ./target/scala-*/scalanative-out ./main run: msg main @#time sbt run time ./main clean: @#sbt clean @-rm -f main fullclean: clean @-rm -f project/build.properties @-rm -rf target project/{project,target} ================================================ FILE: scala/README.md ================================================ # Scala Build and run with: sbt run Depends on sbt, scala native, java and SDL2. When upgrading the scala stdlib version and the scala native version, view the changelog for the latest version here: https://scala-native.org/en/stable/ Then, in the table of `Scala binary version` and `Scala release`, use the ones at the bottom row to update `build.sbt` and `project/plugins.sbt`. Then see if it builds by running `sbt run`. ================================================ FILE: scala/build.sbt ================================================ scalaVersion := "3.3.0" enablePlugins(ScalaNativePlugin) // needed to be able to set the build options below import scala.scalanative.build._ // compilation options, with available options shown in the comments nativeConfig ~= { c => c.withLTO(LTO.none) // none | full | thin .withMode(Mode.releaseFast) // debug | releaseFast | releaseSize | releaseFull .withGC(GC.immix) // none | boehm | immix | commix .withBuildTarget(BuildTarget.application) // application | libraryDynamic | libraryStatic } // nativeLinkingOptions += "-static" ================================================ FILE: scala/project/plugins.sbt ================================================ addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.4.14") ================================================ FILE: v/Makefile ================================================ .PHONY: all msg clean fullclean all: msg main msg: @echo '--- V ---' main: main.v v -o main main.v run: msg main time ./main vrun: main.v v run main.v clean: rm -f main fullclean: clean ================================================ FILE: v/README.md ================================================ Install v then: * ´v install sdl´ Run with `v run .` ================================================ FILE: v/main.v ================================================ module main import sdl fn main() { if sdl.init(sdl.init_everything) != 0 { error_msg := unsafe { cstring_to_vstring(sdl.get_error()) } panic('sdl.init error:\n$error_msg') } window := sdl.create_window(c'Hello World!', 100, 100, 620, 387, u32(sdl.WindowFlags.shown)) if window == sdl.null { error_msg := unsafe { cstring_to_vstring(sdl.get_error()) } panic('sdl.create_window error:\n$error_msg') } renderer := sdl.create_renderer(window, -1, u32(sdl.RendererFlags.accelerated) | u32(sdl.RendererFlags.presentvsync)) if renderer == sdl.null { sdl.destroy_window(window) sdl.quit() error_msg := unsafe { cstring_to_vstring(sdl.get_error()) } panic('sdl.create_renderer error:\n$error_msg') } bmp := sdl.load_bmp(c'../img/grumpy-cat.bmp') if bmp == sdl.null { error_msg := unsafe { cstring_to_vstring(sdl.get_error()) } panic('sdl.load_bmp error:\n$error_msg') } texture := sdl.create_texture_from_surface(renderer, bmp) if texture == sdl.null { sdl.free_surface(bmp) sdl.destroy_renderer(renderer) sdl.destroy_window(window) sdl.quit() error_msg := unsafe { cstring_to_vstring(sdl.get_error()) } panic('sdl.create_texture_from_surface error:\n$error_msg') } sdl.free_surface(bmp) for i := 0; i < 20; i++ { sdl.render_clear(renderer) sdl.render_copy(renderer, texture, sdl.null, sdl.null) sdl.render_present(renderer) sdl.delay(100) } sdl.destroy_texture(texture) sdl.destroy_renderer(renderer) sdl.destroy_window(window) sdl.quit() } ================================================ FILE: zig/Makefile ================================================ .PHONY: all msg clean fullclean all: msg main msg: @echo '--- Zig ---' main: main.zig zig build-exe -lc -lSDL2 -OReleaseFast --name $@ $< small: main.zig zig build-exe -lc -lSDL2 -OReleaseSmall --strip --name $@ $< -sstrip "$@" debug: main.zig zig build-exe -lc -lSDL2 --name $@ $< main.s: main.zig @# This only works after clearing the cache! @-rm -rf zig-cache zig build-exe -lc -lSDL2 -OReleaseFast -femit-asm $< asm: main.s run: msg main time ./main clean: rm -f main small *.o *.s fullclean: clean rm -rf zig-cache ================================================ FILE: zig/README.md ================================================ # Zig SDL2 example Tested with these versions of Zig on Arch Linux: * 0.7.1 * 0.8.0 * 0.9.1 ================================================ FILE: zig/build.zig ================================================ const Builder = @import("std").build.Builder; pub fn build(b: *Builder) void { // Standard target options allows the person running `zig build` to choose // what target to build for. Here we do not override the defaults, which // means any target is allowed, and the default is native. Other options // for restricting supported target set are available. const target = b.standardTargetOptions(.{}); // Standard release options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. const mode = b.standardReleaseOptions(); const exe = b.addExecutable("zig", "main.zig"); exe.setTarget(target); exe.setBuildMode(mode); exe.install(); exe.linkSystemLibrary("sdl2"); const run_cmd = exe.run(); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); } ================================================ FILE: zig/main.zig ================================================ const sdl2 = @cImport(@cInclude("SDL2/SDL.h")); const print = @import("std").debug.print; pub fn main() !u8 { // Initialize SDL2 if (sdl2.SDL_Init(sdl2.SDL_INIT_EVERYTHING) != 0) { print("SDL_Init Error: {s}\n", .{sdl2.SDL_GetError()}); return 1; } defer sdl2.SDL_Quit(); // Create a SDL_Window const win: ?*sdl2.SDL_Window = sdl2.SDL_CreateWindow("Hello World!", 100, 100, 620, 387, sdl2.SDL_WINDOW_SHOWN); if (win == null) { print("SDL_CreateWindow Error: {s}\n", .{sdl2.SDL_GetError()}); return 1; } defer sdl2.SDL_DestroyWindow(win); // Create a SDL_Renderer const ren: ?*sdl2.SDL_Renderer = sdl2.SDL_CreateRenderer(win, -1, sdl2.SDL_RENDERER_ACCELERATED | sdl2.SDL_RENDERER_PRESENTVSYNC); if (ren == null) { print("SDL_CreateRenderer Error: {s}\n", .{sdl2.SDL_GetError()}); return 1; } defer sdl2.SDL_DestroyRenderer(ren); // Load the image as an SDL_Surface const bmp: ?*sdl2.SDL_Surface = sdl2.SDL_LoadBMP("../img/grumpy-cat.bmp"); if (bmp == null) { print("SDL_LoadBMP Error: {s}\n", .{sdl2.SDL_GetError()}); return 1; } defer sdl2.SDL_FreeSurface(bmp); // Create a SDL_Texture from the SDL_Surface const tex: ?*sdl2.SDL_Texture = sdl2.SDL_CreateTextureFromSurface(ren, bmp); if (tex == null) { print("SDL_CreateTextureFromSurface Error: {s}\n", .{sdl2.SDL_GetError()}); return 1; } defer sdl2.SDL_DestroyTexture(tex); // Render the SDL_Texture to the SDL_Window, repeatedly var i: usize = 0; while (i < 20) : (i += 1) { _ = sdl2.SDL_RenderClear(ren); _ = sdl2.SDL_RenderCopy(ren, tex, null, null); sdl2.SDL_RenderPresent(ren); sdl2.SDL_Delay(100); } return 0; }