- Notifications
You must be signed in to change notification settings - Fork468
Rust-SDL2/rust-sdl2
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Bindings for SDL2 in Rust
Rust-SDL2 is a library for talking to the new SDL2.0 libraries from Rust.Low-level C components are wrapped in Rust code to make them more idiomatic andabstract away inappropriate manual memory management.
Rust-SDL2 uses the MIT license, but SDL2 itself is under the zlib license.
gfx
to link against SDL2_gfx and have access to gfx featuresimage
to link against SDL2_image and have access to image reading and writing featuresmixer
to link against SDL2_mixer and have access to sound mixing featuresttf
to link against SDL2_ttf and have access to various font featuresraw-window-handle
to enable the crateraw-window-handle
, which is useful to interop with various other backends.unsafe-textures
to not have a lifetime inTexture
structs. Texture are only freed when the program exits, or can be done manually throughunsafe
.use-bindgen
to customize bindings instead of using pre-generatedsdl_bindings
which were created from a Linux environment. It generates your own custom SDL2 bindings, tailored to your distro. Useful for specific window-related scenarios.use-vcpkg
to pull SDL2 from vcpkg instead of looking in your system.use-pkgconfig
use pkg-config to detect where your library is located on your system. Mostly useful on unix systems for static linking.static-link
to link to SDL2 statically instead of dynamically.use_mac_framework
to use SDL2 from a Framework, on macOS onlyuse_ios_framework
to use SDL2 from a Framework, on iOS onlybundled
, which pulls the SDL repository and compiles it from source. More information below.
We currently target the latest stable release of Rust.
SDL2 >= 2.0.26 is recommended to use these bindings; below 2.0.26, you may experience link-time errors as some functions are used here but are not defined in SDL2. If you experience this issue because you are on a LTS machine (for instance, Ubuntu), we definitely recommend you to use the feature "bundled" which will compile the lastest stable version of SDL2 for your project.
Since 0.31, this crate supports a feature named "bundled" which compiles SDL2 from source and links it automatically. While this should work for any architecture, youwill need a C compiler (likegcc
,clang
, or MS's own compiler) to use this feature properly.
By default, macOS and Linux only load libraries from system directories like/usr/lib
. If you wish to distribute the newly built libSDL2.so/libSDL2.dylib alongside your executable, you will need to add rpath to your executable. Add the following lines tobuild.rs
script:
#[cfg(target_os="macos")]println!("cargo:rustc-link-arg=-Wl,-rpath,@loader_path");#[cfg(target_os="linux")]println!("cargo:rustc-link-arg=-Wl,-rpath,$ORIGIN");
This ONLY works with SDL2, NOT SDL2_image, SDL2_mixer, SDL2_ttf, SDL2_gfx
Install these through your favourite package management tool, or viahttp://www.libsdl.org/
Ubuntu example:
sudo apt-get install libsdl2-dev
Fedora example:
sudo dnf install SDL2-devel
Arch example:
(Arch doesn't have separate regular and development packages, everything goes together.)
sudo pacman -S sdl2
You might also need a C compiler (gcc
).
You can choose to link SDL2 statically instead of dynamically with thestatic-link
feature.On Linux, you will need to additionally do one of the following:
- use the
bundled
feature - use the feature
use-pkgconfig
so that rustc knows where to look for your SDL2 libraries and its dependencies for static linking. This is required because there is no built-in way to find the resources needed to link statically SDL2 from your system - install development libraries withvcpkg. Instructions to generate a static binary on Linux and other operating systems using vcpkg arehere
On macOS, it's a good idea to install these viahomebrew.
brew install sdl2
In recent versions of Homebrew, the installed libraries are usually linked into$(brew --prefix)/lib
.If you are running an older version, the symlink for SDL might reside in/usr/local/lib
.
To make linking libraries installed by Homebrew easier, do the following for your respective shell.
Add this line to your~/.zshenv
or~/.bash_profile
depending on whether you use ZSH or Bash.
export LIBRARY_PATH="$LIBRARY_PATH:$(brew --prefix)/lib"
You can also get sdl2 viamacports
.
sudo port install libsdl2
Then add the following to your~/.bash_profile
if not already present.
export LIBRARY_PATH="$LIBRARY_PATH:/opt/local/lib/"
If you're having issues with either Homebrew or MacPorts,see here.
You can download and install the SDL2 Mac OS X framework from:https://www.libsdl.org/download-2.0.php
To make thesdl2
crate link with the SDL2 framework, you will need to enabletheuse_mac_framework
feature. To build and test thesdl2
crate with thisfeature, use:
cargo test --features use_mac_framework
To depend on thesdl2
crate with this feature enabled, put the following inyour project'sCargo.toml
file:
[dependencies.sdl2]features = ["use_mac_framework"]version = ...# Whichever version you are using
Alternatively, you can re-export the feature in your package by putting thefollowing in yourCargo.toml
file:
[features]default = []use_sdl2_mac_framework = ["sdl2/use_mac_framework"]
Similarly for iOS you can follow the same process using theuse_ios_framework
feature. Howeverofficial builds of the iOS framework are not available so you must compile your own SDL2.framework.
Using the iOS framework also requires adding the 'Frameworks' directory to your rpath so that thedynamic linker can find SDL2.framework inside your app bundle. This is done by adding this to yourbuild.rs
:
#[cfg(target_os="ios")]println!("cargo:rustc-link-arg=-Wl,-rpath,@loader_path/Frameworks");
Instructions to generate a static binary on macOS and other operating systems usingvcpkg arehere.
Download MSVC development libraries fromhttp://www.libsdl.org/ (SDL2-devel-2.0.x-VC.zip).
Unpack SDL2-devel-2.0.x-VC.zip to a folder of your choosing (You can delete it afterwards).
Copy all lib files from
SDL2-devel-2.0.x-VC\SDL2-2.0.x\lib\x64\
to (for Rust 1.6 and above)
C:\Program Files\Rust\lib\rustlib\x86_64-pc-windows-msvc\lib
or to (for Rust versions 1.5 and below)
C:\Program Files\Rust\bin\rustlib\x86_64-pc-windows-msvc\lib
or to your library folder of choice, and ensure you have a system environment variable of
LIB = C:\your\rust\library\folder
For Rustup users, this folder will be in
C:\Users\{Your Username}\.rustup\toolchains\{current toolchain}\lib\rustlib\{current toolchain}\lib
Where current toolchain is likelystable-x86_64-pc-windows-msvc
.
Copy
SDL2.lib
andSDL2.dll
fromSDL2-devel-2.0.x-VC\SDL2-2.0.x\lib\x64\
into your cargo project, right next to your Cargo.toml.
When you're shipping your game make sure to copy
SDL2.dll
to the same directory that your compiled exe is in, otherwise the game won't launch.
The MSVC development libraries provided byhttp://libsdl.org/ don't include a static library. This means that if you want to use thestatic-link
feature with the windows-msvc toolchain, you have to do one of
- build an SDL2 static library yourself and copy it to your toolchain's
lib
directory; or - also enable the
bundled
feature, which will build a static library for you; or - use a static SDL2 library from vcpkg as described below.
Download mingw development libraries fromhttp://www.libsdl.org/ (SDL2-devel-2.0.x-mingw.tar.gz).
Unpack to a folder of your choosing (You can delete it afterwards).
Copy all lib files from
SDL2-devel-2.0.x-mingw\SDL2-2.0.x\x86_64-w64-mingw32\lib
to (for Rust 1.6 and above)
C:\Program Files\Rust\lib\rustlib\x86_64-pc-windows-gnu\lib
or to (for Rust versions 1.5 and below)
C:\Program Files\Rust\bin\rustlib\x86_64-pc-windows-gnu\lib
or to your library folder of choice, and ensure you have a system environment variable of
LIBRARY_PATH = C:\your\rust\library\folder
For Rustup users, this folder will be in
C:\Users\{Your Username}\.rustup\toolchains\{current toolchain}\lib\rustlib\{current toolchain}\lib
Where current toolchain is likelystable-x86_64-pc-windows-gnu
.
Copy SDL2.dll from
SDL2-devel-2.0.x-mingw\SDL2-2.0.x\x86_64-w64-mingw32\bin
into your cargo project, right next to your Cargo.toml.
When you're shipping your game make sure to copy SDL2.dll to the same directory that your compiled exe is in, otherwise the game won't launch.
If you want to use thestatic-link
feature with the windows-gnu toolchain, then you will also need the following libraries:
libimm32.alibversion.alibdinput8.alibdxguid.a
These files are not currently included with the windows-gnu toolchain, but can be downloadedhere. For the x86_64 toolchain, you want thex86_64-win32-seh
package, and for i686 you want thei686-win32-dwarf
one.
You will find the aforementioned libraries undermingw64/x86_64-w64-mingw32/lib/
(for x86_64) ormingw32/i686-w64-mingw32/lib/
(for i686). Copy them to your toolchain'slib
directory (the same one you copied the SDL .a files to).
- Download mingw and msvc development libraries fromhttp://www.libsdl.org/ (SDL2-devel-2.0.x-mingw.tar.gz & SDL2-devel-2.0.x-VC.zip).
- Unpack to folders of your choosing (You can delete it afterwards).
- Create the following folder structure in the same folder as your Cargo.toml:
gnu-mingw\dll\32gnu-mingw\dll\64gnu-mingw\lib\32gnu-mingw\lib\64msvc\dll\32msvc\dll\64msvc\lib\32msvc\lib\64
- Copy the lib and dll files from the source archive to the directories we created in step 3 like so:
SDL2-devel-2.0.x-mingw.tar.gz\SDL2-2.0.x\i686-w64-mingw32\bin -> gnu-mingw\dll\32SDL2-devel-2.0.x-mingw.tar.gz\SDL2-2.0.x\x86_64-w64-mingw32\bin -> gnu-mingw\dll\64SDL2-devel-2.0.x-mingw.tar.gz\SDL2-2.0.x\i686-w64-mingw32\lib -> gnu-mingw\lib\32SDL2-devel-2.0.x-mingw.tar.gz\SDL2-2.0.x\x86_64-w64-mingw32\lib -> gnu-mingw\lib\64SDL2-devel-2.0.8-VC.zip\SDL2-2.0.x\lib\x86\*.dll -> msvc\dll\32SDL2-devel-2.0.8-VC.zip\SDL2-2.0.x\lib\x64\*.dll -> msvc\dll\64SDL2-devel-2.0.8-VC.zip\SDL2-2.0.x\lib\x86\*.lib -> msvc\lib\32SDL2-devel-2.0.8-VC.zip\SDL2-2.0.x\lib\x64\*.lib -> msvc\lib\64
- Create a build script, if you don't already have one put this in your Cargo.toml under
[package]
:
build = "build.rs"
- Create a file in the same directory as Cargo.toml called build.rs (if you didn't already have a build script) and paste this into it:
use std::env;use std::path::PathBuf;fnmain(){let target = env::var("TARGET").unwrap();if target.contains("pc-windows"){let manifest_dir =PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());letmut lib_dir = manifest_dir.clone();letmut dll_dir = manifest_dir.clone();if target.contains("msvc"){ lib_dir.push("msvc"); dll_dir.push("msvc");}else{ lib_dir.push("gnu-mingw"); dll_dir.push("gnu-mingw");} lib_dir.push("lib"); dll_dir.push("dll");if target.contains("x86_64"){ lib_dir.push("64"); dll_dir.push("64");}else{ lib_dir.push("32"); dll_dir.push("32");}println!("cargo:rustc-link-search=all={}", lib_dir.display());for entryin std::fs::read_dir(dll_dir).expect("Can't read DLL dir"){let entry_path = entry.expect("Invalid fs entry").path();let file_name_result = entry_path.file_name();letmut new_file_path = manifest_dir.clone();ifletSome(file_name) = file_name_result{let file_name = file_name.to_str().unwrap();if file_name.ends_with(".dll"){ new_file_path.push(file_name); std::fs::copy(&entry_path, new_file_path.as_path()).expect("Can't copy from DLL dir");}}}}}
- On build the build script will copy the needed DLLs into the same directory as your Cargo.toml, you probably don't want to commit these to any Git repositories though so add the following line to your .gitignore file
/*.dll
- When you're publish your game make sure to copy the corresponding SDL2.dll to the same directory that your compiled exe is in, otherwise the game won't launch.
And now your project should build and run on any Windows computer!
- InstallMS build tools andvcpkg
- Install the needed SDL2 libs:
vcpkg.exe install sdl2-ttf:x64-windows sdl2:x64-windows
- Open a x64 native tools prompt (x64 Native Tools Command Prompt for VS 2019)
- set env vars:
SET PATH=%PATH%;C:\Users\my_user\dev\vcpkg\installed\x64-windows\binSET INCLUDE=%INCLUDE%;C:\Users\my_user\dev\vcpkg\installed\x64-windows\includeSET LIB=%LIB%;C:\Users\my_user\dev\vcpkg\installed\x64-windows\lib
cargo build
Another method of getting the development libraries is withvcpkg. To set up a project to build a static binary on Windows (MSVC), Linux or macOS that is buildable like this:
cargo install cargo-vcpkgcargo vcpkg buildcargo build
add the following yourCargo.toml
:
[dependencies.sdl2]version ="0.37"default-features =falsefeatures = ["ttf","image","gfx","mixer","static-link","use-vcpkg"][package.metadata.vcpkg]dependencies = ["sdl2","sdl2-image[libjpeg-turbo,tiff,libwebp]","sdl2-ttf","sdl2-gfx","sdl2-mixer"]git ="https://github.com/microsoft/vcpkg"rev ="2024.05.24"# release 2024.05.24 # to check for a new one, check https://github.com/microsoft/vcpkg/releases[package.metadata.vcpkg.target]x86_64-pc-windows-msvc = {triplet ="x64-windows-static-md" }
More information on thecargo vcpkg
tool ishere.
If you're usingcargo to manage your project, you candownload through Crates.io:
[dependencies]sdl2 ="0.37"
Alternatively, pull it from GitHub to obtain the latest version from master
[dependencies.sdl2]git ="https://github.com/rust-sdl2/rust-sdl2"
Otherwise, clone this repo and runcargo
cargo build
You can enable features such as ttf, image, gfx and mixer byadding this instead:
[dependencies.sdl2]version ="0.37"default-features =falsefeatures = ["ttf","image","gfx","mixer"]
Those features need their respective libraries, whichcan be found at these locations : (the install processis the same as SDL2)
As of now, sdl2_net is meaningless compared to what other cratessuch asserde
andbincode
can offer.We highly recommend using those to develop anything UDP or TCPrelated (along with futures or TCP/UDP from the standard library).
If you still want an implementation of sdl2_net, you can try toadd it in this repo as a feature via a Pull Request. A somewhatoutdated version of this binding can be foundhere
We have several simple example projects included:
cargo run --example demo
You can see the full list in theexamples/
folder. Some examples require some features, you can enable them like so:
cargo run --example gfx-demo --features "gfx"
Replace "gfx" by the feature(s) needed for the example you want.
In thesdl2::render
module,Texture
has by default lifetimes to prevent it from out-living its parentTextureCreator
.These lifetimes are sometimes too hard to deal with in Rust, and so you have the option to enable theunsafe_textures
feature.
This removes the lifetimes on theTexture
s, at the cost of optional manual memory management. If you want to manually destroytheTexture
s you use, you can call thedestroy
method of yourTexture
s, but beware thatit should not be called if none ofthe parents (Canvas
orTextureCreator
) are alive. If you do not call this method, the memory will simply be freed whenthe lastCanvas
or the lastTextureCreator
will be freed.
There is no online documentation for this feature, however you can build it yourself in your project by enabling the feature in yourCargo.toml, runningcargo doc
and accessingtarget/doc/sdl2/index.html
via a browser.
The sdl2-sys that was generated for this crate is very generic and can be used on a lot of platforms with very few limitations. However,you may sometimes face trouble when using platform-specific features of SDL2, for instance the WindowManager category.
The feature "use-bindgen" allows you to avoid this limitation by generating the proper bindings depending on your target. It will takethe headers based on whatpkg-config
outputs (if you enabled the feature "use-pkg-config") and generate bindings based on them.If you don't have pkg-config or disabled the feature, it will try to get the headers inSDL-2.0.8/include
of this crate instead.
If somehow you have your own headers that you want to use (use a beta version, an older version, ...),you can set the environment variable "SDL2_INCLUDE_PATH" and those headers will be used by bindgen instead.
If you are creating a*-sys
crate for a library which requires SDL2, you can usesdl2-sys
to provide both the compiled libraryand the headers for SDL2.
Follow the following process to get the header directory. In theCargo.toml
for your crate, addsdl2-sys
as a dependency (not a build-dependency).Cargo will then provide your build script with an environment variableDEP_SDL2_INCLUDE
which is populated with the include directory for SDL2.If there is more than one directory, they are combined with:
as a separator. Pass these directories to whatever is building your C/C++.
Once everything is linked together, there will be a single copy of SDL2 (the one provided bysdl2-sys
) for all C, C++, and Rust code.
For more discussion see the correspondingissue
There are two ways to use OpenGL:
- As a backend for sdl2::render, where everything is done for you by sdl2. It is the default for linux devices.
- Manually, using only sdl2 as a "shell" for your window (akin to
glutin
andwinit
crates), and still use sdl2's joystick, events, audio, text input, ect capabilities.
If you want to use OpenGL, you also need thegl-rs package. If you're usingcargo, just add these lines to your Cargo.toml:
[dependencies.gl]git ="https://github.com/bjz/gl-rs"
You have two options to use OpenGL with sdl2:
- Use OpenGL with Canvas and use sdl2::render
- Use OpenGL directly on the Window "shell" and use manual OpenGL calls to render something
First, find the OpenGL driver from SDL:
fnfind_sdl_gl_driver() ->Option<u32>{for(index, item)in sdl2::render::drivers().enumerate(){if item.name =="opengl"{returnSome(indexasu32);}}None}fnmain(){let sdl_context = sdl2::init().unwrap();let video_subsystem = sdl_context.video().unwrap();let window = video_subsystem.window("Window",800,600).opengl()// this line DOES NOT enable opengl, but allows you to create/get an OpenGL context from your window..build().unwrap();let canvas = window.into_canvas().index(find_sdl_gl_driver().unwrap()).build().unwrap();// ...}
If you don't plan to use OpenGL calls via thegl-rs crate, you can stop here. SDL2 will automatically use the OpenGL backend
If you plan to have your own calls intertwined with the sdl2 calls, you need to use the context of your canvas first:
// initializationgl::load_with(|name| video_subsystem.gl_get_proc_address(name)as*const_);// sdl::render creates a context for you, if you use a Canvas you need to use it.canvas.window().gl_set_context_to_current();// ... in the main loop ...unsafe{ gl::ClearColor(0.6,0.0,0.8,1.0); gl::Clear(gl::COLOR_BUFFER_BIT);}canvas.present();
Be wary though, sdl2 has its own internal state which you should avoid messing with.Avoid using manual OpenGL in the middle of SDL2 calls, or make sure to restore the previous state.
externcrate sdl2;externcrate gl;use sdl2::event::Event;use sdl2::keyboard::Keycode;use sdl2::video::GLProfile;fnmain(){let sdl_context = sdl2::init().unwrap();let video_subsystem = sdl_context.video().unwrap();let gl_attr = video_subsystem.gl_attr(); gl_attr.set_context_profile(GLProfile::Core); gl_attr.set_context_version(3,3);let window = video_subsystem.window("Window",800,600).opengl().build().unwrap();// Unlike the other example above, nobody created a context for your window, so you need to create one.let ctx = window.gl_create_context().unwrap(); gl::load_with(|name| video_subsystem.gl_get_proc_address(name)as*const_);debug_assert_eq!(gl_attr.context_profile(),GLProfile::Core);debug_assert_eq!(gl_attr.context_version(),(3,3));letmut event_pump = sdl_context.event_pump().unwrap();'running:loop{unsafe{ gl::ClearColor(0.6,0.0,0.8,1.0); gl::Clear(gl::COLOR_BUFFER_BIT);} window.gl_swap_window();for eventin event_pump.poll_iter(){match event{Event::Quit{..} |Event::KeyDown{keycode:Some(Keycode::Escape), ..} =>{break'running}, _ =>{}}}::std::thread::sleep(::std::time::Duration::new(0,1_000_000_000u32 /60));}}
As mentionned above, this method is useful when you don't care about sdl2's render capabilities, but you do care aboutits audio, controller and other neat features that sdl2 has.
You don't have to worry about messing with the state intertwined with sdl2 or a version you don't like: SDL2 will nevercall any OpenGL function outside therender
module.
To use Vulkan, you need a Vulkan library for Rust. This example uses theVulkano library. Other libraries may use different datatypes for raw Vulkan object handles. The procedure to interface SDL2's Vulkan functions with thesewill be different for each one.
First, make sure you enable theraw-window-handle
feature.
externcrate sdl2;externcrate vulkano;use sdl2::event::Event;use sdl2::keyboard::Keycode;use vulkano::instance::{Instance,InstanceCreateInfo,InstanceExtensions};use vulkano::swapchain::Surface;use vulkano::VulkanLibrary;fnmain(){let sdl_context = sdl2::init().unwrap();let video_subsystem = sdl_context.video().unwrap();let window = video_subsystem.window("Window Title - My Vulkano-SDL2 application",1024,768).vulkan().build().unwrap();let instance_extensions =InstanceExtensions::from_iter(window.vulkan_instance_extensions().unwrap());let instance =Instance::new(VulkanLibrary::new().unwrap(),InstanceCreateInfo{enabled_extensions: instance_extensions, ..Default::default()},).unwrap();// SAFETY: Be sure not to drop the `window` before the `Surface` or vulkan `Swapchain`!// (SIGSEGV otherwise)let surface =unsafe{Surface::from_window_ref(instance.clone(),&window)};letmut event_pump = sdl_context.event_pump().unwrap();'running:loop{for eventin event_pump.poll_iter(){match event{Event::Quit{ ..} |Event::KeyDown{keycode:Some(Keycode::Escape), ..} =>{break'running;} _ =>{}}}::std::thread::sleep(::std::time::Duration::new(0,1_000_000_000u32 /60));}}
raw-window-handle
can be enabled using the feature name:
[dependencies.sdl2]version ="0.37"features = ["raw-window-handle"]
An example working withwgpu
is also available:
cargo run --example raw-window-handle-with-wgpu --features raw-window-handle
On macOS theRawWindowHandle.ns_view
field is returned null. Libraries consuming theRawWindowHandle
(such aswgpu
) should determine a sane default forns_view
. If they do not, please file an issue with the associatedproject.
On some platforms, including Android, SDL2 tries to create the OpenGL context by itself even without creatinga renderer. This can manifest in errors likeVK_ERROR_NATIVE_WINDOW_IN_USE_KHR
when initializing Vulkan or GLES.Add the following code before creating a window to fix the errors:
sdl2::hint::set("SDL_VIDEO_EXTERNAL_CONTEXT","1")
Rust, and Rust-SDL2, are both still heavily in development, and you may runinto teething issues when using this. Before panicking, check that you're usingthe latest version of both Rust and Cargo, check that you've updated Rust-SDL2to the latest version, and runcargo clean
. If that fails, please let us knowon the issue tracker.
Any Pull Request is welcome, however small your contribution may be ! There are, however, conditions to contribute:
- New features must be properly documented, be it via examples or inline documentation (via
cargo doc
). Documentation must be for the end user as well as your next fellow contributor. - Breaking changes must have a proper argumentation with it. While the pre-1.0 state of this crate allows us to be somewhat unstable,useless breaking changes will be denied.
- Minor changes, breaking changes and new features added via Pull Request must be added in thechangelog file. It is nowmandatory to log your changes in the changelog. A short description with a link to your commit/pull request within GitHub is fine. Internal, documentation or meta-changes (travis build change, README instructions updates, ...) don't have to be added in the changelog.