{"id":13439511,"url":"https://github.com/Rust-SDL2/rust-sdl2","last_synced_at":"2025-03-20T08:31:26.716Z","repository":{"id":10110815,"uuid":"12176600","full_name":"Rust-SDL2/rust-sdl2","owner":"Rust-SDL2","description":"SDL2 bindings for Rust","archived":false,"fork":false,"pushed_at":"2024-08-05T02:54:22.000Z","size":8811,"stargazers_count":2690,"open_issues_count":249,"forks_count":466,"subscribers_count":46,"default_branch":"master","last_synced_at":"2024-08-11T17:08:14.570Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Rust-SDL2.png","metadata":{"files":{"readme":"README.md","changelog":"changelog.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2013-08-17T09:27:54.000Z","updated_at":"2024-08-11T17:08:19.568Z","dependencies_parsed_at":"2023-01-13T15:45:01.210Z","dependency_job_id":"4aef0c79-df57-4c9d-8883-3c850c7b5552","html_url":"https://github.com/Rust-SDL2/rust-sdl2","commit_stats":{"total_commits":1912,"total_committers":324,"mean_commits":5.901234567901234,"dds":0.8776150627615062,"last_synced_commit":"27cd1fd67c811e06b9d997a77bb6089a1b65070d"},"previous_names":["angrylawyer/rust-sdl2"],"tags_count":9,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Rust-SDL2%2Frust-sdl2","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Rust-SDL2%2Frust-sdl2/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Rust-SDL2%2Frust-sdl2/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Rust-SDL2%2Frust-sdl2/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Rust-SDL2","download_url":"https://codeload.github.com/Rust-SDL2/rust-sdl2/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":221739727,"owners_count":16872778,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T03:01:14.527Z","updated_at":"2025-03-20T08:31:26.709Z","avatar_url":"https://github.com/Rust-SDL2.png","language":"Rust","readme":"# Rust-SDL2 [![Build Status][workflows-ci-img]][workflows-ci] [![crates.io badge][crates-io-badge]][crates-io-url]\n\nBindings for SDL2 in Rust\n\n### [Changelog for 0.37.0](changelog.md#v0370)\n\n# Overview\n\nRust-SDL2 is a library for talking to the new SDL2.0 libraries from Rust.\nLow-level C components are wrapped in Rust code to make them more idiomatic and\nabstract away inappropriate manual memory management.\n\nRust-SDL2 uses the MIT license, but SDL2 itself is under the zlib license.\n\n## Available rust features \n\n* `gfx` to link against SDL2\\_gfx and have access to gfx features\n* `image` to link against SDL2\\_image and have access to image reading and writing features\n* `mixer` to link against SDL2\\_mixer and have access to sound mixing features\n* `ttf` to link against SDL2\\_ttf and have access to various font features\n* `raw-window-handle` to enable the crate `raw-window-handle`, which is useful to interop with various other backends.\n* `unsafe-textures` to not have a lifetime in `Texture` structs. Texture are only freed when the program exits, or can be done manually through `unsafe`.\n* `use-bindgen` to customize bindings instead of using pre-generated `sdl_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.\n* `use-vcpkg` to pull SDL2 from vcpkg instead of looking in your system.\n* `use-pkgconfig` use pkg-config to detect where your library is located on your system. Mostly useful on unix systems for static linking.\n* `static-link` to link to SDL2 statically instead of dynamically.\n* `use_mac_framework` to use SDL2 from a Framework, on macOS only\n* `use_ios_framework` to use SDL2 from a Framework, on iOS only\n* `bundled`, which pulls the SDL repository and compiles it from source. More information below.\n\n# Documentation\n\n[Read the documentation here](https://docs.rs/sdl2/).\n\n# Requirements\n\n## Rust\n\nWe currently target the latest stable release of Rust.\n\n## *SDL2.0 development libraries*\n\nSDL2 \u003e= 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.\n\n### \"Bundled\" Feature\n\nSince 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, you **will** need a C compiler (like `gcc`, `clang`, or MS's own compiler) to use this feature properly.\n\nBy 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 to `build.rs` script:\n\n```rust\n#[cfg(target_os=\"macos\")]\nprintln!(\"cargo:rustc-link-arg=-Wl,-rpath,@loader_path\");\n\n#[cfg(target_os=\"linux\")]\nprintln!(\"cargo:rustc-link-arg=-Wl,-rpath,$ORIGIN\");\n```\n\n**This ONLY works with SDL2, NOT SDL2_image, SDL2_mixer, SDL2_ttf, SDL2_gfx**\n\n### Linux\nInstall these through your favourite package management tool, or via\nhttp://www.libsdl.org/\n\nUbuntu example:\n\u003e sudo apt-get install libsdl2-dev\n\nFedora example:\n\u003e sudo dnf install SDL2-devel\n\nArch example:  \n(Arch doesn't have separate regular and development packages, everything goes together.)  \n\u003e sudo pacman -S sdl2\n\nYou might also need a C compiler (`gcc`).\n\n#### Static linking in Linux\n\nYou can choose to link SDL2 statically instead of dynamically with the `static-link` feature.\nOn Linux, you will need to additionally do one of the following:\n* use the `bundled` feature\n* 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\n* install development libraries with [vcpkg][vcpkg]. Instructions to generate a static binary on Linux and other operating systems using vcpkg are [here][cargo-vcpkg-usage]\n\n### macOS\n#### Homebrew\nOn macOS, it's a good idea to install these via\n[homebrew][homebrew].\n\n```\nbrew install sdl2\n```\n\nIn recent versions of Homebrew, the installed libraries are usually linked into `$(brew --prefix)/lib`.\nIf you are running an older version, the symlink for SDL might reside in `/usr/local/lib`.\n\nTo make linking libraries installed by Homebrew easier, do the following for your respective shell.\n\nAdd this line to your `~/.zshenv` or `~/.bash_profile` depending on whether you use ZSH or Bash.\n```\nexport LIBRARY_PATH=\"$LIBRARY_PATH:$(brew --prefix)/lib\"\n```\n#### MacPorts\nYou can also get sdl2 via `macports`.\n\n```\nsudo port install libsdl2\n```\n\nThen add the following to your `~/.bash_profile` if not already present.\n```\nexport LIBRARY_PATH=\"$LIBRARY_PATH:/opt/local/lib/\"\n```\n\nIf you're having issues with either Homebrew or MacPorts, [see here][pdev-issue].\n\n#### If you are using the SDL2 framework\n\nYou can download and install the SDL2 Mac OS X framework from:\nhttps://www.libsdl.org/download-2.0.php\n\nTo make the `sdl2` crate link with the SDL2 framework, you will need to enable\nthe `use_mac_framework` feature.  To build and test the `sdl2` crate with this\nfeature, use:\n\n\u003e cargo test --features use\\_mac\\_framework\n\nTo depend on the `sdl2` crate with this feature enabled, put the following in\nyour project's `Cargo.toml` file:\n\n```toml\n[dependencies.sdl2]\nfeatures = [\"use_mac_framework\"]\nversion = ...  # Whichever version you are using\n```\n\nAlternatively, you can re-export the feature in your package by putting the\nfollowing in your `Cargo.toml` file:\n\n```toml\n[features]\ndefault = []\nuse_sdl2_mac_framework = [\"sdl2/use_mac_framework\"]\n```\n\nSimilarly for iOS you can follow the same process using the `use_ios_framework` feature. However\nofficial builds of the iOS framework are not available so you must compile your own SDL2.framework.\n\nUsing the iOS framework also requires adding the 'Frameworks' directory to your rpath so that the\ndynamic linker can find SDL2.framework inside your app bundle. This is done by adding this to your\n`build.rs`:\n\n```rust\n#[cfg(target_os=\"ios\")]\nprintln!(\"cargo:rustc-link-arg=-Wl,-rpath,@loader_path/Frameworks\");\n```\n\n#### Static linking on macOS using vcpkg\n\nInstructions to generate a static binary on macOS and other operating systems using [vcpkg][vcpkg] are [here][cargo-vcpkg-usage].\n\n### Windows (MSVC)\n\n1. Download MSVC development libraries from http://www.libsdl.org/ (SDL2-devel-2.0.x-VC.zip).\n2. Unpack SDL2-devel-2.0.x-VC.zip to a folder of your choosing (You can delete it afterwards).\n3. Copy all lib files from\n    \u003e SDL2-devel-2.0.x-VC\\SDL2-2.0.x\\lib\\x64\\\n\n    to (for Rust 1.6 and above)\n    \u003e C:\\Program Files\\Rust\\\\**lib**\\rustlib\\x86_64-pc-windows-msvc\\lib\n\n    or to (for Rust versions 1.5 and below)\n    \u003e C:\\Program Files\\Rust\\\\**bin**\\rustlib\\x86_64-pc-windows-msvc\\lib\n\n    or to your library folder of choice, and ensure you have a system environment variable of\n    \u003e LIB = C:\\your\\rust\\library\\folder\n\n    For Rustup users, this folder will be in\n    \u003e C:\\Users\\\\{Your Username}\\\\.rustup\\toolchains\\\\{current toolchain}\\lib\\rustlib\\\\{current toolchain}\\lib\n\n  Where current toolchain is likely `stable-x86_64-pc-windows-msvc`.\n\n4. Copy `SDL2.lib` and `SDL2.dll` from\n    \u003e SDL2-devel-2.0.x-VC\\SDL2-2.0.x\\lib\\x64\\\n\n    into your cargo project, right next to your Cargo.toml.\n\n5. 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.\n\n#### Static linking with MSVC\n\nThe MSVC development libraries provided by http://libsdl.org/ don't include a static library. This means that if you want to use the `static-link` feature with the windows-msvc toolchain, you have to do one of\n\n- build an SDL2 static library yourself and copy it to your toolchain's `lib` directory; or\n- also enable the `bundled` feature, which will build a static library for you; or\n- use a static SDL2 library from vcpkg as described below.\n\n### Windows (MinGW)\n\n1. Download mingw development libraries from\nhttp://www.libsdl.org/ (SDL2-devel-2.0.x-mingw.tar.gz).\n2. Unpack to a folder of your choosing (You can delete it afterwards).\n3. Copy all lib files from\n    \u003e SDL2-devel-2.0.x-mingw\\SDL2-2.0.x\\x86_64-w64-mingw32\\lib\n\n    to (for Rust 1.6 and above)\n    \u003e C:\\Program Files\\Rust\\\\**lib**\\rustlib\\x86_64-pc-windows-gnu\\lib\n\n    or to (for Rust versions 1.5 and below)\n    \u003e C:\\Program Files\\Rust\\\\**bin**\\rustlib\\x86_64-pc-windows-gnu\\lib\n\n    or to your library folder of choice, and ensure you have a system environment variable of\n    \u003e LIBRARY_PATH = C:\\your\\rust\\library\\folder\n\n    For Rustup users, this folder will be in\n    \u003e C:\\Users\\\\{Your Username}\\\\.rustup\\toolchains\\\\{current toolchain}\\lib\\rustlib\\\\{current toolchain}\\lib\n\n  Where current toolchain is likely `stable-x86_64-pc-windows-gnu`.\n\n4. Copy SDL2.dll from\n    \u003e SDL2-devel-2.0.x-mingw\\SDL2-2.0.x\\x86_64-w64-mingw32\\bin\n\n    into your cargo project, right next to your Cargo.toml.\n\n5. 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.\n\n#### Static linking with MinGW\n\nIf you want to use the `static-link` feature with the windows-gnu toolchain, then you will also need the following libraries:\n\n    libimm32.a\n    libversion.a\n    libdinput8.a\n    libdxguid.a\n\nThese files are not currently included with the windows-gnu toolchain, but can be downloaded [here](https://sourceforge.net/projects/mingw-w64/files/). For the x86_64 toolchain, you want the `x86_64-win32-seh` package, and for i686 you want the `i686-win32-dwarf` one.\n\nYou will find the aforementioned libraries under `mingw64/x86_64-w64-mingw32/lib/` (for x86_64) or `mingw32/i686-w64-mingw32/lib/` (for i686). Copy them to your toolchain's `lib` directory (the same one you copied the SDL .a files to).\n\n### Windows with build script\n\n1. Download mingw and msvc development libraries from\nhttp://www.libsdl.org/ (SDL2-devel-2.0.x-mingw.tar.gz \u0026 SDL2-devel-2.0.x-VC.zip).\n2. Unpack to folders of your choosing (You can delete it afterwards).\n3. Create the following folder structure in the same folder as your Cargo.toml:\n\n```\ngnu-mingw\\dll\\32\ngnu-mingw\\dll\\64\ngnu-mingw\\lib\\32\ngnu-mingw\\lib\\64\nmsvc\\dll\\32\nmsvc\\dll\\64\nmsvc\\lib\\32\nmsvc\\lib\\64\n```\n\n4. Copy the lib and dll files from the source archive to the directories we created in step 3 like so:\n```\nSDL2-devel-2.0.x-mingw.tar.gz\\SDL2-2.0.x\\i686-w64-mingw32\\bin \t\t-\u003e \tgnu-mingw\\dll\\32\nSDL2-devel-2.0.x-mingw.tar.gz\\SDL2-2.0.x\\x86_64-w64-mingw32\\bin \t-\u003e \tgnu-mingw\\dll\\64\nSDL2-devel-2.0.x-mingw.tar.gz\\SDL2-2.0.x\\i686-w64-mingw32\\lib \t\t-\u003e \tgnu-mingw\\lib\\32\nSDL2-devel-2.0.x-mingw.tar.gz\\SDL2-2.0.x\\x86_64-w64-mingw32\\lib \t-\u003e \tgnu-mingw\\lib\\64\nSDL2-devel-2.0.8-VC.zip\\SDL2-2.0.x\\lib\\x86\\*.dll\t \t\t-\u003e \tmsvc\\dll\\32\nSDL2-devel-2.0.8-VC.zip\\SDL2-2.0.x\\lib\\x64\\*.dll \t\t\t-\u003e \tmsvc\\dll\\64\nSDL2-devel-2.0.8-VC.zip\\SDL2-2.0.x\\lib\\x86\\*.lib\t \t\t-\u003e \tmsvc\\lib\\32\nSDL2-devel-2.0.8-VC.zip\\SDL2-2.0.x\\lib\\x64\\*.lib\t \t\t-\u003e \tmsvc\\lib\\64\n```\n\n5. Create a build script, if you don't already have one put this in your Cargo.toml under `[package]`:\n\u003e build = \"build.rs\"\n\n6. 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:\n\n```Rust\nuse std::env;\nuse std::path::PathBuf;\n\nfn main() {\n    let target = env::var(\"TARGET\").unwrap();\n    if target.contains(\"pc-windows\") {\n        let manifest_dir = PathBuf::from(env::var(\"CARGO_MANIFEST_DIR\").unwrap());\n        let mut lib_dir = manifest_dir.clone();\n        let mut dll_dir = manifest_dir.clone();\n        if target.contains(\"msvc\") {\n            lib_dir.push(\"msvc\");\n            dll_dir.push(\"msvc\");\n        }\n        else {\n            lib_dir.push(\"gnu-mingw\");\n            dll_dir.push(\"gnu-mingw\");\n        }\n        lib_dir.push(\"lib\");\n        dll_dir.push(\"dll\");\n        if target.contains(\"x86_64\") {\n            lib_dir.push(\"64\");\n            dll_dir.push(\"64\");\n        }\n        else {\n            lib_dir.push(\"32\");\n            dll_dir.push(\"32\");\n        }\n        println!(\"cargo:rustc-link-search=all={}\", lib_dir.display());\n        for entry in std::fs::read_dir(dll_dir).expect(\"Can't read DLL dir\")  {\n            let entry_path = entry.expect(\"Invalid fs entry\").path();\n            let file_name_result = entry_path.file_name();\n            let mut new_file_path = manifest_dir.clone();\n            if let Some(file_name) = file_name_result {\n                let file_name = file_name.to_str().unwrap();\n                if file_name.ends_with(\".dll\") {\n                    new_file_path.push(file_name);\n                    std::fs::copy(\u0026entry_path, new_file_path.as_path()).expect(\"Can't copy from DLL dir\");\n                }\n            }\n        }\n    }\n}\n```\n\n7. 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\n\n`/*.dll`\n\n8. 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.\n\nAnd now your project should build and run on any Windows computer!\n\n\n### Windows (MSVC with vcpkg)\n1. Install [MS build tools](https://visualstudio.microsoft.com/downloads/) and [vcpkg][vcpkg]\n2. Install the needed SDL2 libs: `vcpkg.exe install sdl2-ttf:x64-windows sdl2:x64-windows`\n3. Open a x64 native tools prompt (x64 Native Tools Command Prompt for VS 2019)\n4. set env vars:\n```\nSET PATH=%PATH%;C:\\Users\\my_user\\dev\\vcpkg\\installed\\x64-windows\\bin\nSET INCLUDE=%INCLUDE%;C:\\Users\\my_user\\dev\\vcpkg\\installed\\x64-windows\\include\nSET LIB=%LIB%;C:\\Users\\my_user\\dev\\vcpkg\\installed\\x64-windows\\lib\n```\n5. `cargo build`\n\n### Windows, Linux and macOS with vcpkg\n\nAnother method of getting the development libraries is with [vcpkg][vcpkg]. To set up a project to build a static binary on Windows (MSVC), Linux or macOS that is buildable like this:\n```sh\ncargo install cargo-vcpkg\ncargo vcpkg build\ncargo build\n```\n\nadd the following your `Cargo.toml`:\n\n```toml\n[dependencies.sdl2]\nversion = \"0.37\"\ndefault-features = false\nfeatures = [\"ttf\",\"image\",\"gfx\",\"mixer\",\"static-link\",\"use-vcpkg\"]\n\n[package.metadata.vcpkg]\ndependencies = [\"sdl2\", \"sdl2-image[libjpeg-turbo,tiff,libwebp]\", \"sdl2-ttf\", \"sdl2-gfx\", \"sdl2-mixer\"]\ngit = \"https://github.com/microsoft/vcpkg\"\nrev = \"2024.05.24\" # release 2024.05.24 # to check for a new one, check https://github.com/microsoft/vcpkg/releases\n\n[package.metadata.vcpkg.target]\nx86_64-pc-windows-msvc = { triplet = \"x64-windows-static-md\" }\n```\n\nMore information on the `cargo vcpkg` tool is [here][cargo-vcpkg].\n\n# Installation\n\nIf you're using [cargo][crates] to manage your project, you can\ndownload through Crates.io:\n\n```toml\n    [dependencies]\n    sdl2 = \"0.37\"\n```\n\nAlternatively, pull it from GitHub to obtain the latest version from master\n\n```toml\n    [dependencies.sdl2]\n    git = \"https://github.com/rust-sdl2/rust-sdl2\"\n```\n\nOtherwise, clone this repo and run [cargo][crates]\n\n```\ncargo build\n```\n\nYou can enable features such as ttf, image, gfx and mixer by\nadding this instead:\n\n```toml\n    [dependencies.sdl2]\n    version = \"0.37\"\n    default-features = false\n    features = [\"ttf\",\"image\",\"gfx\",\"mixer\"]\n```\n\nThose features need their respective libraries, which\ncan be found at these locations : (the install process\nis the same as SDL2)\n\n* [image, ttf, mixer](https://www.libsdl.org/projects/)\n* [gfx](http://sourceforge.net/projects/sdl2gfx/)\n\n## What about sdl2\\_net ?\n\nAs of now, sdl2\\_net is meaningless compared to what other crates\nsuch as `serde` and `bincode` can offer.\nWe highly recommend using those to develop anything UDP or TCP\nrelated (along with futures or TCP/UDP from the standard library).\n\nIf you still want an implementation of sdl2\\_net, you can try to\nadd it in this repo as a feature via a Pull Request. A somewhat\noutdated version of this binding can be found\n[here](https://github.com/Limvot/rust-sdl2_net)\n\n# Demo\n\nWe have several simple example projects included:\n\n\u003e cargo run --example demo\n\nYou can see the full list in the `examples/` folder. Some examples require some features, you can enable them like so:\n\n\u003e cargo run --example gfx-demo --features \"gfx\"\n\nReplace \"gfx\" by the feature(s) needed for the example you want.\n\n# About the `unsafe_textures` feature\n\nIn the `sdl2::render` module, `Texture` has by default lifetimes to prevent it from out-living its parent `TextureCreator`.\nThese lifetimes are sometimes too hard to deal with in Rust, and so you have the option to enable the `unsafe_textures` feature.\n\nThis removes the lifetimes on the `Texture`s, at the cost of optional manual memory management. If you want to manually destroy\nthe `Texture`s you use, you can call the `destroy` method of your `Texture`s, but beware that *it should not* be called if none of\nthe parents (`Canvas` or `TextureCreator`) are alive. If you do not call this method, the memory will simply be freed when\nthe last `Canvas` or the last `TextureCreator` will be freed.\n\nThere is no online documentation for this feature, however you can build it yourself in your project by enabling the feature in your\nCargo.toml, running `cargo doc` and accessing `target/doc/sdl2/index.html` via a browser.\n\n# Generating sdl2-sys with bindgen\n\nThe 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,\nyou may sometimes face trouble when using platform-specific features of SDL2, for instance the WindowManager category.\n\nThe feature \"use-bindgen\" allows you to avoid this limitation by generating the proper bindings depending on your target. It will take\nthe headers based on what `pkg-config` outputs (if you enabled the feature \"use-pkg-config\") and generate bindings based on them.\nIf you don't have pkg-config or disabled the feature, it will try to get the headers in `SDL-2.0.8/include` of this crate instead.\n\nIf somehow you have your own headers that you want to use (use a beta version, an older version, ...),\nyou can set the environment variable \"SDL2_INCLUDE_PATH\" and those headers will be used by bindgen instead.\n\n# Using sdl2-sys to provide SDL2 headers/library\n\nIf you are creating a `*-sys` crate for a library which requires SDL2, you can use `sdl2-sys` to provide both the compiled library\nand the headers for SDL2. \n\nFollow the following process to get the header directory. In the `Cargo.toml` for your crate, add `sdl2-sys` as a dependency (not a build-dependency).\nCargo will then provide your build script with an environment variable `DEP_SDL2_INCLUDE` which is populated with the include directory for SDL2.\nIf there is more than one directory, they are combined with `:` as a separator. Pass these directories to whatever is building your C/C++.\n\nOnce everything is linked together, there will be a single copy of SDL2 (the one provided by `sdl2-sys`) for all C, C++, and Rust code.\n\nFor more discussion see the corresponding [issue][dep-sdl2-include-issue]\n\n# OpenGL\n\nThere are two ways to use OpenGL:\n\n* As a backend for sdl2::render, where everything is done for you by sdl2. It is the default for linux devices.\n* Manually, using only sdl2 as a \"shell\" for your window (akin to `glutin` and `winit` crates), and still use sdl2's joystick, events, audio, text input, ect capabilities.\n\nIf you want to use OpenGL, you also need the\n[gl-rs][gl-rs] package. If you're using\n[cargo][crates], just add these lines to your Cargo.toml:\n\n```toml\n    [dependencies.gl]\n    git = \"https://github.com/bjz/gl-rs\"\n```\n\nYou have two options to use OpenGL with sdl2:\n\n* Use OpenGL with Canvas and use sdl2::render \n* Use OpenGL directly on the Window \"shell\" and use manual OpenGL calls to render something\n\n## Use sdl2::render\n\nFirst, find the OpenGL driver from SDL:\n\n```rust\nfn find_sdl_gl_driver() -\u003e Option\u003cu32\u003e {\n    for (index, item) in sdl2::render::drivers().enumerate() {\n        if item.name == \"opengl\" {\n            return Some(index as u32);\n        }\n    }\n    None\n}\n\nfn main() {\n    let sdl_context = sdl2::init().unwrap();\n    let video_subsystem = sdl_context.video().unwrap();\n    let window = video_subsystem.window(\"Window\", 800, 600)\n        .opengl() // this line DOES NOT enable opengl, but allows you to create/get an OpenGL context from your window.\n        .build()\n        .unwrap();\n    let canvas = window.into_canvas()\n        .index(find_sdl_gl_driver().unwrap())\n        .build()\n        .unwrap();\n\n    // ...\n}\n```\n\nIf you don't plan to use OpenGL calls via the [gl-rs][gl-rs] crate, you can stop here. SDL2 will automatically use the OpenGL backend\n\nIf you plan to have your own calls intertwined with the sdl2 calls, you need to use the context of your canvas first:\n\n```rust\n\n// initialization\ngl::load_with(|name| video_subsystem.gl_get_proc_address(name) as *const _);\n\n// sdl::render creates a context for you, if you use a Canvas you need to use it.\ncanvas.window().gl_set_context_to_current();\n\n// ... in the main loop ...\nunsafe {\n    gl::ClearColor(0.6, 0.0, 0.8, 1.0);\n    gl::Clear(gl::COLOR_BUFFER_BIT);\n}\ncanvas.present();\n```\n\nBe wary though, sdl2 has its own internal state which you should avoid messing with.\nAvoid using manual OpenGL in the middle of SDL2 calls, or make sure to restore the previous state.\n\n## Use OpenGL calls manually\n\n```rust\nextern crate sdl2;\nextern crate gl;\n\nuse sdl2::event::Event;\nuse sdl2::keyboard::Keycode;\nuse sdl2::video::GLProfile;\n\nfn main() {\n    let sdl_context = sdl2::init().unwrap();\n    let video_subsystem = sdl_context.video().unwrap();\n    \n    let gl_attr = video_subsystem.gl_attr();\n    gl_attr.set_context_profile(GLProfile::Core);\n    gl_attr.set_context_version(3, 3);\n\n    let window = video_subsystem.window(\"Window\", 800, 600)\n        .opengl()\n        .build()\n        .unwrap();\n\n    // Unlike the other example above, nobody created a context for your window, so you need to create one.\n    let ctx = window.gl_create_context().unwrap();\n    gl::load_with(|name| video_subsystem.gl_get_proc_address(name) as *const _);\n    \n    debug_assert_eq!(gl_attr.context_profile(), GLProfile::Core);\n    debug_assert_eq!(gl_attr.context_version(), (3, 3));\n\n    let mut event_pump = sdl_context.event_pump().unwrap();\n\n    'running: loop {\n        unsafe {\n            gl::ClearColor(0.6, 0.0, 0.8, 1.0);\n            gl::Clear(gl::COLOR_BUFFER_BIT);\n        }\n\n        window.gl_swap_window();\n        for event in event_pump.poll_iter() {\n            match event {\n                Event::Quit {..} | Event::KeyDown { keycode: Some(Keycode::Escape), .. } =\u003e {\n                    break 'running\n                },\n                _ =\u003e {}\n            }\n        }\n        ::std::thread::sleep(::std::time::Duration::new(0, 1_000_000_000u32 / 60));\n    }\n}\n```\n\nAs mentionned above, this method is useful when you don't care about sdl2's render capabilities, but you do care about\nits audio, controller and other neat features that sdl2 has.\n\nYou don't have to worry about messing with the state intertwined with sdl2 or a version you don't like: SDL2 will never\ncall any OpenGL function outside the `render` module.\n\n# Vulkan\n\nTo use Vulkan, you need a Vulkan library for Rust. This example uses the\n[Vulkano](https://github.com/vulkano-rs/vulkano) library. Other libraries may use different data\ntypes for raw Vulkan object handles. The procedure to interface SDL2's Vulkan functions with these\nwill be different for each one.\n\nFirst, make sure you enable the [`raw-window-handle`](#support-for-raw-window-handle) feature.\n\n```rust\nextern crate sdl2;\nextern crate vulkano;\n\nuse sdl2::event::Event;\nuse sdl2::keyboard::Keycode;\nuse vulkano::instance::{Instance, InstanceCreateInfo, InstanceExtensions};\nuse vulkano::swapchain::Surface;\nuse vulkano::VulkanLibrary;\n\nfn main() {\n    let sdl_context = sdl2::init().unwrap();\n    let video_subsystem = sdl_context.video().unwrap();\n\n    let window = video_subsystem\n        .window(\"Window Title - My Vulkano-SDL2 application\", 1024, 768)\n        .vulkan()\n        .build()\n        .unwrap();\n\n    let instance_extensions =\n        InstanceExtensions::from_iter(window.vulkan_instance_extensions().unwrap());\n\n    let instance = Instance::new(\n        VulkanLibrary::new().unwrap(),\n        InstanceCreateInfo {\n            enabled_extensions: instance_extensions,\n            ..Default::default()\n        },\n    )\n    .unwrap();\n\n    // SAFETY: Be sure not to drop the `window` before the `Surface` or vulkan `Swapchain`!\n    // (SIGSEGV otherwise)\n    let surface = unsafe { Surface::from_window_ref(instance.clone(), \u0026window) };\n\n    let mut event_pump = sdl_context.event_pump().unwrap();\n\n    'running: loop {\n        for event in event_pump.poll_iter() {\n            match event {\n                Event::Quit { .. }\n                | Event::KeyDown {\n                    keycode: Some(Keycode::Escape),\n                    ..\n                } =\u003e {\n                    break 'running;\n                }\n                _ =\u003e {}\n            }\n        }\n        ::std::thread::sleep(::std::time::Duration::new(0, 1_000_000_000u32 / 60));\n    }\n}\n```\n\n# Support for raw-window-handle\n\n`raw-window-handle` can be enabled using the feature name:\n\n```toml\n[dependencies.sdl2]\nversion = \"0.37\"\nfeatures = [\"raw-window-handle\"]\n```\n\nAn example working with [`wgpu`](https://crates.io/crates/wgpu) is also available:\n\n```bash\ncargo run --example raw-window-handle-with-wgpu --features raw-window-handle\n```\n\n### sdl2 with raw-window-handle on macOS:\n\nOn macOS the `RawWindowHandle.ns_view` field is returned null. Libraries consuming the `RawWindowHandle` (such as \n`wgpu`) should determine a sane default for `ns_view`. If they do not, please file an issue with the associated \nproject.\n\n### raw-window-handle on Android\n\nOn some platforms, including Android, SDL2 tries to create the OpenGL context by itself even without creating\na renderer. This can manifest in errors like `VK_ERROR_NATIVE_WINDOW_IN_USE_KHR` when initializing Vulkan or GLES.\nAdd the following code before creating a window to fix the errors:\n```rust\nsdl2::hint::set(\"SDL_VIDEO_EXTERNAL_CONTEXT\", \"1\")\n```\n\n# When things go wrong\nRust, and Rust-SDL2, are both still heavily in development, and you may run\ninto teething issues when using this. Before panicking, check that you're using\nthe latest version of both Rust and Cargo, check that you've updated Rust-SDL2\nto the latest version, and run `cargo clean`. If that fails, please let us know\non the issue tracker.\n\n# Contributing\n\nAny Pull Request is welcome, however small your contribution may be ! There are, however, conditions to contribute:\n\n* 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.\n* 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**.\n* Minor changes, breaking changes and new features added via Pull Request must be added in the [changelog][changelog] file. It is now **mandatory** 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.\n\n[changelog]: ./changelog.md\n[crates-io-badge]: https://img.shields.io/crates/v/sdl2.svg\n[crates-io-url]: https://crates.io/crates/sdl2\n[workflows-ci-img]: https://github.com/Rust-SDL2/rust-sdl2/actions/workflows/CI.yml/badge.svg?branch=master\n[workflows-ci]: https://github.com/Rust-SDL2/rust-sdl2/actions/workflows/CI.yml\n[early-sdl]: https://github.com/brson/rust-sdl\n[homebrew]: http://brew.sh/\n[crates]: http://crates.io/\n[examples]: https://github.com/jdeseno/rs-sdl2-examples\n[dep-sdl2-include-issue]: https://github.com/Rust-SDL2/rust-sdl2/pull/968\n[gl-rs]: https://github.com/bjz/gl-rs\n[pdev-issue]: https://github.com/PistonDevelopers/rust-empty/issues/175\n[vcpkg]: https://github.com/microsoft/vcpkg\n[cargo-vcpkg]: https://crates.io/crates/cargo-vcpkg\n[cargo-vcpkg-usage]: #Windows,-Linux-and-macOS-with-vcpkg\n","funding_links":[],"categories":["Libraries","Rust","库 Libraries","库","Bindings"],"sub_categories":["Game development","游戏开发 Game development","游戏开发"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FRust-SDL2%2Frust-sdl2","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FRust-SDL2%2Frust-sdl2","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FRust-SDL2%2Frust-sdl2/lists"}