### Get Display for Window Example Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_GetDisplayForWindow.md This example demonstrates how to initialize SDL, create a window, retrieve the display ID for that window using SDL_GetDisplayForWindow, and log the display name. It requires SDL_INIT_VIDEO and should only be called on the main thread. ```c #include #include #include int main(int argc, char** argv) { if (!SDL_Init(SDL_INIT_VIDEO)) { SDL_Log("Unable to initialize SDL: %s", SDL_GetError()); return 0; } SDL_Window* window = SDL_CreateWindow("My Window", 640, 480, 0); if(window == NULL) { SDL_Log("Unable to create window: %s", SDL_GetError()); return 0; } SDL_DisplayID display_id = SDL_GetDisplayForWindow(window); SDL_Log("Window created on display '%s'", SDL_GetDisplayName(display_id)); SDL_DestroyWindow(window); return 0; } ``` -------------------------------- ### Create a Renderer for a Window Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_CreateRenderer.md This example demonstrates the basic setup for an SDL application, including window creation, renderer creation, loading a BMP image, rendering it, and handling the event loop. It shows how to initialize SDL, create a window and renderer, load and display a texture, and properly clean up resources. ```c #include #include int main(int argc, char *argv[]) { SDL_Window *win = NULL; SDL_Renderer *renderer = NULL; SDL_Texture *bitmapTex = NULL; SDL_Surface *bitmapSurface = NULL; int width = 320, height = 240; bool loopShouldStop = false; SDL_Init(SDL_INIT_VIDEO); win = SDL_CreateWindow("Hello World", width, height, 0); renderer = SDL_CreateRenderer(win, NULL); bitmapSurface = SDL_LoadBMP("img/hello.bmp"); bitmapTex = SDL_CreateTextureFromSurface(renderer, bitmapSurface); SDL_DestroySurface(bitmapSurface); while (!loopShouldStop) { SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_EVENT_QUIT: loopShouldStop = true; break; } } SDL_RenderClear(renderer); SDL_RenderTexture(renderer, bitmapTex, NULL, NULL); SDL_RenderPresent(renderer); } SDL_DestroyTexture(bitmapTex); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(win); SDL_Quit(); return 0; } ``` -------------------------------- ### SDL2 Audio Playback with Callback Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/README-migration.md This example demonstrates the traditional SDL2 method for playing audio using a callback function. It shows how to define a callback, set desired audio specifications, open an audio device, and start playback. ```c void SDLCALL MyAudioCallback(void *userdata, Uint8 * stream, int len) { /* Calculate a little more audio here, maybe using `userdata`, write it to `stream` */ } /* ...somewhere near startup... */ SDL_AudioSpec my_desired_audio_format; SDL_zero(my_desired_audio_format); my_desired_audio_format.format = AUDIO_S16; my_desired_audio_format.channels = 2; my_desired_audio_format.freq = 44100; my_desired_audio_format.samples = 1024; my_desired_audio_format.callback = MyAudioCallback; my_desired_audio_format.userdata = &my_audio_callback_user_data; SDL_AudioDeviceID my_audio_device = SDL_OpenAudioDevice(NULL, 0, &my_desired_audio_format, NULL, 0); SDL_PauseAudioDevice(my_audio_device, 0); ``` -------------------------------- ### Build SDL2_gfx for Android Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/Android.md Specific example for downloading, configuring, and installing SDL2_gfx for the Android cross-compilation environment. Includes disabling MMX for broader compatibility. ```bash VERSION=1.0.3 wget http://www.ferzkopp.net/Software/SDL2_gfx/SDL2_gfx-$VERSION.tar.gz tar xf SDL2_gfx-$VERSION.tar.gz mv SDL2_gfx-$VERSION/ SDL2_gfx/ cd SDL2_gfx/ mkdir cross-android/ && cd cross-android/ ../configure --host=arm-linux-androideabi --prefix=$NDK_STANDALONE/sysroot/usr \ --disable-shared --disable-mmx make -j$(nproc) make install ``` -------------------------------- ### Enable SDL Examples with CMake Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/README-cmake.md Add this option to the initial CMake command to build SDL example programs. Examples can be run from the build/examples/ directory. ```sh cmake -S . -B build -DSDL_EXAMPLES=ON ``` -------------------------------- ### Get Number of Displays Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_GetDisplays.md This example demonstrates how to initialize SDL, retrieve the number of connected displays and their IDs, log the count, and then free the allocated display ID array. Ensure SDL is initialized with SDL_INIT_VIDEO before calling this function. ```c #include #include #include int main(int argc, char** argv) { if (!SDL_Init(SDL_INIT_VIDEO)) { SDL_Log("Unable to initialize SDL: %s", SDL_GetError()); return 0; } int num_displays; SDL_DisplayID *displays = SDL_GetDisplays(&num_displays); SDL_Log("Found %d display(s)", num_displays); SDL_free(displays); return 0; } ``` -------------------------------- ### Build and Install SDL on Windows with CMake Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/README-cmake.md Use these commands to build and install SDL on Windows. Ensure you are in the SDL source directory. The installation prefix is set to C:/SDL. ```sh cmake -S . -B build cmake --build build --config RelWithDebInfo cmake --install build --config RelWithDebInfo --prefix C:/SDL ``` -------------------------------- ### Build and Install SDL on UNIX with CMake Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/README-cmake.md Use these commands to build and install SDL on UNIX-like systems. Assumes you are in the SDL source directory. Installation prefix is /usr/local. ```sh cmake -S . -B build cmake --build build sudo cmake --install build --prefix /usr/local ``` -------------------------------- ### Install Java Development Kit and Android SDK Tools Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/Android.md Installs the OpenJDK 17, Ant, and Android SDK platform tools. Ensure you have a minimal Java environment set up. ```bash sudo apt install openjdk-17-jdk ant android-sdk-platform-tools-common ``` -------------------------------- ### Example: Defining SDL_AUDIO_S32LE Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_DEFINE_AUDIO_FORMAT.md An example demonstrating how to use SDL_DEFINE_AUDIO_FORMAT to define the SDL_AUDIO_S32LE format, which represents signed 32-bit little-endian audio. ```c SDL_DEFINE_AUDIO_FORMAT(1, 0, 0, 32) ``` -------------------------------- ### Build SDL3 with MinGW-w64 and CMake Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/README-windows.md Commands to configure, build, and install SDL3 using CMake with a MinGW-w64 toolchain file. Ensure CMake, Ninja, and Git are installed. ```sh mkdir build cmake -S . -B build -G Ninja -DCMAKE_TOOLCHAIN_FILE=build-scripts/cmake-toolchain-mingw64-x86_64.cmake cmake --build build --parallel cmake --install build --prefix C:/Libraries ``` -------------------------------- ### Build, Install, and Start a Test with CMake Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/README-android.md A convenience CMake target 'build-install-start-testsprite' that automates the process of building, installing, and starting a specific test. This simplifies the testing workflow. ```bash cmake --build . --target build-install-start-testsprite ``` -------------------------------- ### SDL_GetJoystickGUID Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/CategoryAPIFunction.md Gets the GUID of a joystick. ```APIDOC ## SDL_GetJoystickGUID ### Description Gets the GUID of a joystick. ### Function Signature ```c SDL_JoystickGUID SDL_GetJoystickGUID(SDL_Joystick *joystick) ``` ### Parameters #### Path Parameters - **joystick** (SDL_Joystick*) - Required - The joystick to query. ### Return Value Returns the GUID of the joystick. ``` -------------------------------- ### Create Window and Renderer Example Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_CreateWindowAndRenderer.md This example demonstrates how to initialize SDL, create a window and renderer using SDL_CreateWindowAndRenderer, load a BMP image, create a texture, and then enter a basic event loop to display the texture. It includes cleanup of SDL resources. ```c #include #include int main(int argc, char *argv[]) { SDL_Window *window; SDL_Renderer *renderer; SDL_Surface *surface; SDL_Texture *texture; SDL_Event event; if (!SDL_Init(SDL_INIT_VIDEO)) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s", SDL_GetError()); return 3; } if (!SDL_CreateWindowAndRenderer("Hello SDL", 320, 240, SDL_WINDOW_RESIZABLE, &window, &renderer)) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window and renderer: %s", SDL_GetError()); return 3; } surface = SDL_LoadBMP("sample.bmp"); if (!surface) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create surface from image: %s", SDL_GetError()); return 3; } texture = SDL_CreateTextureFromSurface(renderer, surface); if (!texture) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create texture from surface: %s", SDL_GetError()); return 3; } SDL_DestroySurface(surface); while (1) { SDL_PollEvent(&event); if (event.type == SDL_EVENT_QUIT) { break; } SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0x00); SDL_RenderClear(renderer); SDL_RenderTexture(renderer, texture, NULL, NULL); SDL_RenderPresent(renderer); } SDL_DestroyTexture(texture); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return 0; } ``` -------------------------------- ### SDL_GetJoystickGUIDInfo Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/CategoryAPIFunction.md Gets information about a joystick GUID. ```APIDOC ## SDL_GetJoystickGUIDInfo ### Description Gets information about a joystick GUID, such as the vendor, product, and type. ### Function Signature ```c SDL_bool SDL_GetJoystickGUIDInfo(SDL_JoystickGUID guid, Uint16* vendor, Uint16* product, Uint16* version, Uint32* type) ``` ### Parameters #### Path Parameters - **guid** (SDL_JoystickGUID) - Required - The GUID of the joystick. - **vendor** (Uint16*) - Output - Pointer to store the vendor ID. - **product** (Uint16*) - Output - Pointer to store the product ID. - **version** (Uint16*) - Output - Pointer to store the product version. - **type** (Uint32*) - Output - Pointer to store the joystick type. ### Return Value Returns SDL_TRUE on success, SDL_FALSE if the GUID is invalid or the information is not available. ``` -------------------------------- ### Importing External Wayland Surface with Qt 6 Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/README-wayland.md This example demonstrates how to initialize SDL to use an existing wl_display from Qt, create a QWindow, obtain its wl_surface, and then create an SDL_Window that wraps this external surface. Ensure the Qt window is not flagged as DPI-aware to avoid protocol violations. ```c++ #include #include #include #include int main(int argc, char *argv[]) { int ret = -1; int done = 0; SDL_PropertiesID props; SDL_Event e; SDL_Window *sdlWindow = NULL; SDL_Renderer *sdlRenderer = NULL; struct wl_display *display = NULL; struct wl_surface *surface = NULL; /* Initialize Qt */ QApplication qtApp(argc, argv); QWindow qtWindow; /* The windowing system must be Wayland. */ if (QApplication::platformName() != "wayland") { goto exit; } { /* Get the wl_display object from Qt */ QNativeInterface::QWaylandApplication *qtWlApp = qtApp.nativeInterface(); display = qtWlApp->display(); if (!display) { goto exit; } } /* Set SDL to use the existing wl_display object from Qt and initialize. */ SDL_SetPointerProperty(SDL_GetGlobalProperties(), SDL_PROP_GLOBAL_VIDEO_WAYLAND_WL_DISPLAY_POINTER, display); SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS); /* Create a basic, frameless QWindow */ qtWindow.setFlags(Qt::FramelessWindowHint); qtWindow.setGeometry(0, 0, 640, 480); qtWindow.show(); { /* Get the native wl_surface backing resource for the window */ QPlatformNativeInterface *qtNative = qtApp.platformNativeInterface(); surface = (struct wl_surface *)qtNative->nativeResourceForWindow("surface", &qtWindow); if (!surface) { goto exit; } } /* Create a window that wraps the wl_surface from the QWindow. * Qt objects should not be flagged as DPI-aware or protocol violations will result. */ props = SDL_CreateProperties(); SDL_SetPointerProperty(props, SDL_PROP_WINDOW_CREATE_WAYLAND_WL_SURFACE_POINTER, surface); SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_OPENGL_BOOLEAN, true); SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, 640); SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER, 480); sdlWindow = SDL_CreateWindowWithProperties(props); SDL_DestroyProperties(props); if (!sdlWindow) { goto exit; } /* Create a renderer */ sdlRenderer = SDL_CreateRenderer(sdlWindow, NULL); if (!sdlRenderer) { goto exit; } ``` -------------------------------- ### SDL_GetJoystickGUIDForID Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/CategoryAPIFunction.md Gets the GUID of a joystick from its instance ID. ```APIDOC ## SDL_GetJoystickGUIDForID ### Description Gets the GUID of a joystick given its instance ID. ### Function Signature ```c SDL_JoystickGUID SDL_GetJoystickGUIDForID(SDL_JoystickID instance_id) ``` ### Parameters #### Path Parameters - **instance_id** (SDL_JoystickID) - Required - The instance ID of the joystick. ### Return Value Returns the GUID of the joystick, or an invalid GUID if the ID is invalid. ``` -------------------------------- ### MIX_PROP_PLAY_START_ORDER_NUMBER Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3_mixer/CategoryAPI.md Gets or sets the playback start order. ```APIDOC ## MIX_PROP_PLAY_START_ORDER_NUMBER ### Description Gets or sets the playback start order. ### Parameters This property can be read or written to. ### Return Value Returns the current start order value. ``` -------------------------------- ### Create and Use a Color Cursor Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_CreateColorCursor.md This example demonstrates initializing SDL, creating a window and renderer, loading a BMP image as an SDL_Surface, creating a color cursor from the surface, setting the cursor, and running a basic event loop until quit. It includes error handling and cleanup. ```c #include int main(int argc, char *argv[]) { SDL_Window *window = NULL; SDL_Renderer *renderer = NULL; SDL_Surface *surface = NULL; SDL_Cursor *cursor = NULL; bool error = true; if (!SDL_Init(SDL_INIT_VIDEO)) { goto exit; } if (!SDL_CreateWindowAndRenderer("Hello SDL", 640, 480, 0, &window, &renderer)) { goto exit; } surface = SDL_LoadBMP((1 < argc) ? argv[1] : "cursor.bmp"); if (!surface) { goto exit; } cursor = SDL_CreateColorCursor(surface, 0, 0); if (!cursor) { goto exit; } SDL_SetCursor(cursor); SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255); while (true) { SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_EVENT_MOUSE_BUTTON_UP: case SDL_EVENT_QUIT: error = false; goto exit; } } SDL_RenderClear(renderer); SDL_RenderPresent(renderer); } exit: if (error) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "%s", SDL_GetError()); } if (cursor) { SDL_DestroyCursor(cursor); } if (surface) { SDL_DestroySurface(surface); } if (renderer) { SDL_DestroyRenderer(renderer); } if (window) { SDL_DestroyWindow(window); } SDL_Quit(); return error; } ``` -------------------------------- ### MIX_PROP_PLAY_START_MILLISECOND_NUMBER Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3_mixer/CategoryAPI.md Gets or sets the starting millisecond for playback. ```APIDOC ## MIX_PROP_PLAY_START_MILLISECOND_NUMBER ### Description Gets or sets the starting millisecond for playback. ### Parameters This property can be read or written to. ### Return Value Returns the current start millisecond value. ``` -------------------------------- ### Create an SDL3 Window Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_CreateWindow.md This example demonstrates the basic usage of SDL_CreateWindow to create a window. It includes SDL initialization, window creation with a title, dimensions, and flags, a simple event loop to keep the window open, and proper cleanup. ```c #include #include int main(int argc, char* argv[]) { SDL_Window *window; bool done = false; SDL_Init(SDL_INIT_VIDEO); window = SDL_CreateWindow( "An SDL3 window", 640, 480, SDL_WINDOW_OPENGL ); if (window == NULL) { SDL_LogError(SDL_LOG_CATEGORY_ERROR, "Could not create window: %s\n", SDL_GetError()); return 1; } while (!done) { SDL_Event event; while (SDL_PollEvent(&event)) { if (event.type == SDL_EVENT_QUIT) { done = true; } } } SDL_DestroyWindow(window); SDL_Quit(); return 0; } ``` -------------------------------- ### MIX_PROP_PLAY_START_FRAME_NUMBER Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3_mixer/CategoryAPI.md Gets or sets the starting frame for playback. ```APIDOC ## MIX_PROP_PLAY_START_FRAME_NUMBER ### Description Gets or sets the starting frame for playback. ### Parameters This property can be read or written to. ### Return Value Returns the current start frame value. ``` -------------------------------- ### SDL_GetMemoryFunctions Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/CategoryStdinc.md Gets the currently installed memory allocation functions. ```APIDOC ## SDL_GetMemoryFunctions ### Description Gets the currently installed memory allocation functions. ### Signature `void SDL_GetMemoryFunctions(SDL_malloc_func *malloc_func, SDL_calloc_func *calloc_func, SDL_realloc_func *realloc_func, SDL_free_func *free_func);` ``` -------------------------------- ### Iterate and Log Joystick Information in SDL3 Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/README-migration.md This example demonstrates how to initialize the joystick subsystem, retrieve a list of available joysticks using their instance IDs, and log their names, paths, vendor, and product IDs. It ensures proper cleanup by quitting the subsystem after use. ```c { if (SDL_InitSubSystem(SDL_INIT_JOYSTICK)) { int i, num_joysticks; SDL_JoystickID *joysticks = SDL_GetJoysticks(&num_joysticks); if (joysticks) { for (i = 0; i < num_joysticks; ++i) { SDL_JoystickID instance_id = joysticks[i]; const char *name = SDL_GetJoystickNameForID(instance_id); const char *path = SDL_GetJoystickPathForID(instance_id); SDL_Log("Joystick %" SDL_PRIu32 ": %s%s%s VID 0x%.4x, PID 0x%.4x", instance_id, name ? name : "Unknown", path ? ", " : "", path ? path : "", SDL_GetJoystickVendorForID(instance_id), SDL_GetJoystickProductForID(instance_id)); } SDL_free(joysticks); } SDL_QuitSubSystem(SDL_INIT_JOYSTICK); } } ``` -------------------------------- ### MIX_PROP_PLAY_LOOP_START_MILLISECOND_NUMBER Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3_mixer/CategoryAPI.md Gets or sets the starting millisecond for loop playback. ```APIDOC ## MIX_PROP_PLAY_LOOP_START_MILLISECOND_NUMBER ### Description Gets or sets the starting millisecond for loop playback. ### Parameters This property can be read or written to. ### Return Value Returns the current loop start millisecond value. ``` -------------------------------- ### Initial SDL Android Project Setup Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/Android.md Commands to perform an initial setup for an SDL Android project using the androidbuild.sh script. This step is primarily for configuring the build environment, even if the actual build fails. ```bash cd /usr/src/SDL3/ #git checkout -- . # remove traces of previous builds cd build-scripts/ # edit androidbuild.sh and modify $ANDROID update project --target android-XX ./androidbuild.sh org.libsdl /dev/null # doesn't matter if the actual build fails, it's just for setup cd ../build/org.liblibsdl/ rm -rf jni/src/ ``` -------------------------------- ### Opening and Using an Audio Device Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_OpenAudioDevice.md This example demonstrates how to open a default audio playback device with specific audio settings (format, channels, frequency), check for errors, resume audio playback, delay for a duration, and finally close the audio device. ```APIDOC ## SDL_OpenAudioDevice ### Description Opens a specific audio device for playing or recording audio. ### Parameters #### Path Parameters - **iscapture** (int) - Required - Non-zero to indicate a recording device, 0 for a playback device. - **devicename** (const char *) - Optional - The name of the device to open, or NULL for the default device. - **desired** (const SDL_AudioSpec *) - Required - A pointer to a `SDL_AudioSpec` structure describing the desired audio format, frequency, channels, etc. This structure will be filled with the actual audio device parameters upon successful opening. ### Returns On success, returns a non-zero audio device ID. On failure, returns 0. The specific failure reason can be found by calling [SDL_GetError()](SDL_GetError). ### Example ```c SDL_AudioSpec want, have; SDL_AudioDeviceID dev; SDL_memset(&want, 0, sizeof(want)); /* or SDL_zero(want) */ want.format = SDL_AUDIO_F32; want.channels = 2; want.freq = 48000; dev = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &want); if (dev == 0) { SDL_Log("Failed to open audio: %s", SDL_GetError()); } else { SDL_ResumeAudioDevice(dev); /* start audio playing. */ SDL_Delay(5000); // let device play for 5 seconds SDL_CloseAudioDevice(dev); } ``` ### See Also - [SDL_CloseAudioDevice](SDL_CloseAudioDevice) - [SDL_GetAudioDeviceFormat](SDL_GetAudioDeviceFormat) - [SDL_GetError](SDL_GetError) - [SDL_ResumeAudioDevice](SDL_ResumeAudioDevice) - [SDL_Delay](SDL_Delay) ``` -------------------------------- ### Start testsprite executable with CMake Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/README-android.md Start the 'testsprite' executable on the Android device using the 'start-testsprite' CMake target. This assumes the test has been built and installed. ```bash cmake --build . --target start-testsprite ``` -------------------------------- ### Example Gamepad Mapping String Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_AddGamepadMapping.md This is an example of a valid mapping string for a gamepad. The format is "GUID,name,mapping", where mappings specify buttons, hats, and axes. ```c "341a3608000000000000504944564944,Afterglow PS3 Controller,a:b1,b:b2,y:b3,x:b0,start:b9,guide:b12,back:b8,dpup:h0.1,dpleft:h0.8,dpdown:h0.4,dpright:h0.2,leftshoulder:b4,rightshoulder:b5,leftstick:b10,rightstick:b11,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:b6,righttrigger:b7" ``` -------------------------------- ### SDL3 App Initialization with Callbacks Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/AppFreezeDuringDrag.md Demonstrates initializing an SDL3 application using the main callback functions, enabling code execution even during window resize or move operations. Ensure SDL_MAIN_USE_CALLBACKS is defined before including SDL_main.h. ```c #include #define SDL_MAIN_USE_CALLBACKS #include SDL_Window* g_window; SDL_Renderer* g_renderer; SDL_FRect g_rect = { 100.f, 100.f, 100.f, 100.f }; SDL_AppResult SDL_AppInit(void** appstate, int argc, char** argv) { SDL_CreateWindowAndRenderer("Test", 300, 300, SDL_WINDOW_RESIZABLE, &g_window, &g_renderer); return SDL_APP_CONTINUE; } ``` -------------------------------- ### Example: Initializing and Using a Subsystem with SDL_InitState Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_InitState.md Demonstrates how to use SDL_InitState to manage the initialization and shutdown of a system or subsystem. Ensure SDL_SetInitialized is called before leaving initialization or shutdown functions. ```c static SDL_InitState init; bool InitSystem(void) { if (!SDL_ShouldInit(&init)) { // The system is initialized return true; } // At this point, you should not leave this function without calling SDL_SetInitialized() bool initialized = DoInitTasks(); SDL_SetInitialized(&init, initialized); return initialized; } bool UseSubsystem(void) { if (SDL_ShouldInit(&init)) { // Error, the subsystem isn't initialized SDL_SetInitialized(&init, false); return false; } // Do work using the initialized subsystem return true; } void QuitSystem(void) { if (!SDL_ShouldQuit(&init)) { // The system is not initialized return; } // At this point, you should not leave this function without calling SDL_SetInitialized() DoQuitTasks(); SDL_SetInitialized(&init, false); } ``` -------------------------------- ### Extract Minor Version with SDL_VERSIONNUM_MINOR Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_VERSIONNUM_MINOR.md Use this macro to get the minor version number from a version integer. For example, 1002003 will yield 2. ```c #define SDL_VERSIONNUM_MINOR(version) (((version) / 1000) % 1000) ``` -------------------------------- ### Initialize SDL Renderer and Render Loop Source: https://context7.com/libsdl-org/sdlwiki/llms.txt Sets up a hardware-accelerated 2D renderer and demonstrates the basic render loop: clear, draw, and present. Pass NULL to SDL_CreateRenderer to let SDL auto-select the best driver. ```c #include #include int main(int argc, char *argv[]) { SDL_Init(SDL_INIT_VIDEO); SDL_Window *win = SDL_CreateWindow("Renderer Demo", 640, 480, 0); SDL_Renderer *renderer = SDL_CreateRenderer(win, NULL); // NULL = auto-select driver if (!renderer) { SDL_LogError(SDL_LOG_CATEGORY_ERROR, "Renderer creation failed: %s", SDL_GetError()); return 1; } // Load a bitmap texture from disk SDL_Surface *surf = SDL_LoadBMP("sprite.bmp"); SDL_Texture *tex = SDL_CreateTextureFromSurface(renderer, surf); SDL_DestroySurface(surf); SDL_FRect dst = { 100.0f, 100.0f, 64.0f, 64.0f }; // x, y, w, h bool running = true; while (running) { SDL_Event ev; while (SDL_PollEvent(&ev)) { if (ev.type == SDL_EVENT_QUIT) running = false; } SDL_SetRenderDrawColor(renderer, 30, 30, 30, 255); // dark grey background SDL_RenderClear(renderer); // fill with draw color SDL_RenderTexture(renderer, tex, NULL, &dst); // draw texture at dst rect SDL_RenderPresent(renderer); // swap buffers / present frame } SDL_DestroyTexture(tex); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(win); SDL_Quit(); return 0; } ``` -------------------------------- ### Create a system tray with a quit button Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_CreateTray.md This example demonstrates how to create a system tray icon with a context menu that includes a 'Quit' button. It initializes SDL, creates the tray with a tooltip, sets up a menu and a button with a callback to post a quit event, and runs the main event loop. The video subsystem is required for this functionality. This function should only be called on the main thread. ```c #include #include void callback_quit(void *userdata, SDL_TrayEntry *invoker) { SDL_Event e; e.type = SDL_EVENT_QUIT; SDL_PushEvent(&e); } int main(int argc, char *argv[]) { SDL_Tray *tray; SDL_TrayMenu *menu; SDL_TrayEntry *entry; SDL_Event e; SDL_Init(SDL_INIT_VIDEO); // Create the entry in the system tray. A regular app will want to provide // an SDL_Surface instead of NULL. tray = SDL_CreateTray(NULL, "My tray"); // Create a context menu for the tray. menu = SDL_CreateTrayMenu(tray); // Create a button in the context menu. entry = SDL_InsertTrayEntryAt(menu, -1, "Quit", SDL_TRAYENTRY_BUTTON); // Set the callback for the button SDL_SetTrayEntryCallback(entry, callback_quit, NULL); // Run the main loop... while (SDL_WaitEvent(&e)) { if (e.type == SDL_EVENT_QUIT) { break; } } // No need to destroy anything other than the tray itself - the rest is // destroyed automatically. SDL_DestroyTray(tray); SDL_Quit(); return 0; } ``` -------------------------------- ### Get Nanoseconds Since Initialization Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_GetTicksNS.md Call this function to retrieve the elapsed time in nanoseconds since SDL started. It is safe to call from any thread. ```c Uint64 nanoseconds = SDL_GetTicksNS(); ``` -------------------------------- ### Initialize and Query Displays in SDL3 Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/README-migration.md Use SDL_InitSubSystem() with SDL_INIT_VIDEO for initialization and SDL_GetDisplays() to retrieve display information. SDL_free() must be called on the returned display array. ```c { if (SDL_InitSubSystem(SDL_INIT_VIDEO)) { int i, num_displays = 0; SDL_DisplayID *displays = SDL_GetDisplays(&num_displays); if (displays) { for (i = 0; i < num_displays; ++i) { SDL_DisplayID instance_id = displays[i]; const char *name = SDL_GetDisplayName(instance_id); SDL_Log("Display %" SDL_PRIu32 ": %s", instance_id, name ? name : "Unknown"); } SDL_free(displays); } SDL_QuitSubSystem(SDL_INIT_VIDEO); } } ``` -------------------------------- ### Extract Micro Version Number Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_VERSIONNUM_MICRO.md Use this macro to get the micro version number from a combined version integer. For example, 1002003 becomes 3. ```c #define SDL_VERSIONNUM_MICRO(version) ((version) % 1000) ``` -------------------------------- ### SDL3 Audio Playback with SDL_QueueAudio Migration Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/README-migration.md This example illustrates migrating from SDL2's SDL_QueueAudio to SDL3's SDL_AudioStream for audio playback. It shows how to open an audio device stream without a callback and then queue audio data in the main loop. ```c /* ...somewhere near startup... */ const SDL_AudioSpec spec = { SDL_AUDIO_S16, 2, 44100 }; SDL_AudioStream *stream = SDL_OpenAudioDeviceStream(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &spec, NULL, NULL); SDL_ResumeAudioDevice(SDL_GetAudioStreamDevice(stream)); /* ...in your main loop... */ /* calculate a little more audio into `buf`, add it to `stream` */ SDL_PutAudioStreamData(stream, buf, buflen); ``` -------------------------------- ### Build SDL Example Program Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/HowToReportBugs.md Compile a simple SDL example program using a C compiler. Ensure you are in the SDL source directory and have SDL headers and libraries available. ```bash cd SDL cc -o clear examples/renderer/01-clear/clear.c -Iinclude -lSDL3 ``` -------------------------------- ### Example Usage of SDL_AUDIO_BYTESIZE Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_AUDIO_BYTESIZE.md Demonstrates how to use SDL_AUDIO_BYTESIZE to get the byte size of a specific audio format. For instance, SDL_AUDIO_S16 format results in 2 bytes. ```c SDL_AUDIO_BYTESIZE(SDL_AUDIO_S16) ``` -------------------------------- ### Create Software Renderer for a Surface Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_CreateSoftwareRenderer.md This example demonstrates how to initialize SDL, create a window and its surface, and then create a software renderer associated with that surface using SDL_CreateSoftwareRenderer. It includes error handling for initialization, window creation, and renderer creation. The code then enters a loop to draw a chessboard pattern and handle events until the application quits. ```c #include #include SDL_Window *window; SDL_Renderer *renderer; int done; void DrawChessBoard(SDL_Renderer *renderer) { int row = 0, column = 0, x = 0; SDL_FRect rect; SDL_Rect darea; /* Get the Size of drawing surface */ SDL_GetRenderViewport(renderer, &darea); SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF); SDL_RenderClear(renderer); for (; row < 8; row++) { column = row % 2; x = column; for (; column < 4 + (row % 2); column++) { SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0xFF); rect.w = (float)darea.w / 8; rect.h = (float)darea.h / 8; rect.x = x * rect.w; rect.y = row * rect.h; x = x + 2; SDL_RenderFillRect(renderer, &rect); } } SDL_RenderPresent(renderer); } void loop() { SDL_Event e; while (SDL_PollEvent(&e)) { if (e.type == SDL_EVENT_QUIT) { done = 1; return; } if ((e.type == SDL_EVENT_KEY_DOWN) && (e.key.key == SDLK_ESCAPE)) { done = 1; return; } } DrawChessBoard(renderer); /* Got everything on rendering surface, now Update the drawing image on window screen */ SDL_UpdateWindowSurface(window); } int main(int argc, char *argv[]) { SDL_Surface *surface; /* Initialize SDL */ if (!SDL_Init(SDL_INIT_VIDEO)) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_Init fail : %s\n", SDL_GetError()); return 1; } /* Create window and renderer for given surface */ window = SDL_CreateWindow("Chess Board", 640, 480, 0); if (!window) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Window creation fail : %s\n", SDL_GetError()); return 1; } surface = SDL_GetWindowSurface(window); renderer = SDL_CreateSoftwareRenderer(surface); if (!renderer) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Render creation for surface fail : %s\n", SDL_GetError()); return 1; } /* Draw the Image on rendering surface */ done = 0; while (!done) { loop(); } SDL_Quit(); return 0; } ``` -------------------------------- ### MIX_PROP_PLAY_LOOP_START_MILLISECOND_NUMBER Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3_mixer/MIX_PROP_PLAY_LOOP_START_MILLISECOND_NUMBER.md This property is related to setting the loop start point in milliseconds for audio playback. For detailed usage and examples, please refer to the MIX_PlayTrack function documentation. ```APIDOC ## MIX_PROP_PLAY_LOOP_START_MILLISECOND_NUMBER ### Description This property is used in conjunction with audio playback functions to specify the starting point of a loop in milliseconds. It allows for precise control over looping behavior. ### Related Function Refer to [MIX_PlayTrack](MIX_PlayTrack) for detailed usage and examples. ``` -------------------------------- ### Log Display Names using SDL3 Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_GetDisplayName.md This example demonstrates how to initialize SDL, retrieve a list of all connected displays, and then iterate through them to log the name of each display using SDL_GetDisplayName. Ensure SDL is initialized with SDL_INIT_VIDEO before calling this function. This function should only be called on the main thread. ```c #include #include #include int main(int argc, char** argv) { if (!SDL_Init(SDL_INIT_VIDEO)) { SDL_Log("Unable to initialize SDL: %s", SDL_GetError()); return 0; } int num_displays; SDL_DisplayID *displays = SDL_GetDisplays(&num_displays); for(int i = 0; i < num_displays; i++) { SDL_Log("Found display named '%s'", SDL_GetDisplayName(displays[i])); } SDL_free(displays); return 0; } ``` -------------------------------- ### Extract Major Version using SDL_VERSIONNUM_MAJOR Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_VERSIONNUM_MAJOR.md Use this macro to get the major version number from a combined version integer. For example, 1002003 (representing 1.2.3) will yield 1. ```c #define SDL_VERSIONNUM_MAJOR(version) ((version) / 1000000) ``` -------------------------------- ### Enumerate Display Properties Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_EnumerateProperties.md This example demonstrates how to enumerate and log the properties of each display connected to the system. It initializes SDL, retrieves display information, and then uses SDL_EnumerateProperties with a custom callback function to process each property. ```c #include #include #include static void my_enumerate_properties_callback(void *userdata, SDL_PropertiesID props, const char *name) { SDL_PropertyType prop_type = SDL_GetPropertyType(props, name); switch (prop_type) { case SDL_PROPERTY_TYPE_POINTER: SDL_Log("%s is a pointer poperty", name); break; case SDL_PROPERTY_TYPE_STRING: SDL_Log( "%s is a string property with value %s", name, SDL_GetStringProperty(props, name, "")); break; case SDL_PROPERTY_TYPE_NUMBER: SDL_Log("%s is a number property with value %"SDL_PRIs64, name, SDL_GetNumberProperty(props, name, 0)); break; case SDL_PROPERTY_TYPE_FLOAT: SDL_Log("%s is a float property with value %f", name, SDL_GetFloatProperty(props, name, 0.0f)); break; case SDL_PROPERTY_TYPE_BOOLEAN: SDL_Log( "%s is a boolean property with value %d", name, SDL_GetBooleanProperty(props, name, false)); break; case SDL_PROPERTY_TYPE_INVALID: default: SDL_Log("%s is an invalid property", name); break; } } int main(int argc, char** argv) { if (!SDL_Init(SDL_INIT_VIDEO)) { SDL_Log("Unable to initialize SDL: %s", SDL_GetError()); return 0; } SDL_Log("SDL initialized"); int num_displays; SDL_DisplayID *displays = SDL_GetDisplays(&num_displays); SDL_Log("Found %d displays.", num_displays); for(int i = 0; i < num_displays; i++) { SDL_PropertiesID prop_id = SDL_GetDisplayProperties(displays[i]); SDL_Log("Display %d has properties ID %d", i, prop_id); if(!SDL_EnumerateProperties(prop_id, my_enumerate_properties_callback, NULL)) { SDL_Log("Error enumerating properties: %s.", SDL_GetError()); } } SDL_free(displays); return 0; } ``` -------------------------------- ### Peeking Events with Event Range in SDL3 Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL12MigrationGuide.md SDL3 uses event ranges instead of masks for SDL_PeepEvents. This example demonstrates peeking for mouse button down events using the start and end of the event type range. ```c SDL_PeepEvents(&event, 1, SDL_GETEVENT, SDL_EVENT_MOUSE_BUTTON_DOWN, SDL_EVENT_MOUSE_BUTTON_DOWN); ``` -------------------------------- ### SDL3 Audio Stream Callback Example Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL12MigrationGuide.md Demonstrates the SDL3 approach using SDL_AudioStream for handling audio data, which abstracts format conversion and resampling. ```c static void SDLCALL my_audio_callback(void *userdata, SDL_AudioStream *stream, int additional_amount, int total_amount) { /* fill `stream` with `additional_amount` bytes of data */ /* any amount of audio can be added, but we need `additional_amount` right now! This number can vary between calls! */ SDL_PutAudioStreamData(stream, my_audio_data, additional_amount); } /* somewhere near startup... */ SDL_AudioSpec spec; spec.freq = 22050; spec.format = SDL_AUDIO_S16SYS; spec.channels = 2; SDL_AudioStream *stream = SDL_OpenAudioDeviceStream(SDL_AUDIO_DEVICE_DEFAULT_OUTPUT, &spec, my_audio_callback, whatever); if (!stream) { /* oh no, we failed, report an error and quit. */ } SDL_UnpauseAudioDeviceStream(stream); /* at the end of the program ... */ SDL_DestroyAudioStream(stream); ``` -------------------------------- ### SDL 1.2 Audio Callback Example Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL12MigrationGuide.md Illustrates the traditional SDL 1.2 audio callback mechanism for filling audio buffers. ```c static void SDLCALL my_audio_callback(void *userdata, Uint8 *stream, int len) { /* fill `stream` with `len` bytes of data */ memcpy(stream, my_audio_data, len); } /* somewhere near startup... */ SDL_AudioSpec spec; spec.freq = 22050; spec.format = AUDIO_S16SYS; spec.channels = 2; spec.samples = 1024; spec.callback = my_audio_callback; spec.userdata = whatever; if (SDL_OpenAudio(&spec, NULL) == -1) { /* oh no, we failed, report an error and quit. */ } SDL_PauseAudio(0); /* now the callback will start. */ /* at the end of the program ... */ SDL_CloseAudio(); ``` -------------------------------- ### Broadcasting to Condition Variables Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_BroadcastCondition.md This example demonstrates how to use SDL_BroadcastCondition to wake up multiple threads waiting on a condition. It shows the setup for mutexes and condition variables, threads waiting on the condition, and a thread that modifies the condition and then broadcasts to all waiting threads. ```c // BEWARE: This code example was migrated from the SDL2 Wiki, by only updating the names. bool condition = false; SDL_Mutex *lock; SDL_Condition *cond; lock = SDL_CreateMutex(); cond = SDL_CreateCondition(); Thread_A: SDL_LockMutex(lock); while (!condition) { SDL_WaitCondition(cond, lock); } SDL_UnlockMutex(lock); Thread_B: SDL_LockMutex(lock); while (!condition) { SDL_WaitCondition(cond, lock); } SDL_UnlockMutex(lock); Thread_C: SDL_LockMutex(lock); /* ... */ condition = true; /* ... */ SDL_BroadcastCondition(cond); SDL_UnlockMutex(lock); SDL_DestroyCondition(cond); SDL_DestroyMutex(lock); ``` -------------------------------- ### Get Android JNI Environment and Call Java Method Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_GetAndroidJNIEnv.md This C++ example demonstrates how to obtain the JNI environment and the Android activity instance to call a custom Java method. It includes manual cleanup of local references, which is crucial when the native function is the entry point of the application. ```cpp #include #include // This example requires C++ and a custom Java method named "void showHome()" // Calls the void showHome() method of the Java instance of the activity. void showHome(void) { // retrieve the JNI environment. JNIEnv* env = (JNIEnv*)SDL_GetAndroidJNIEnv(); // retrieve the Java instance of the SDLActivity jobject activity = (jobject)SDL_GetAndroidActivity(); // find the Java class of the activity. It should be SDLActivity or a subclass of it. jclass clazz(env->GetObjectClass(activity)); // find the identifier of the method to call jmethodID method_id = env->GetMethodID(clazz, "showHome", "()V"); // effectively call the Java method env->CallVoidMethod(activity, method_id); // clean up the local references. env->DeleteLocalRef(activity); env->DeleteLocalRef(clazz); // Warning (and discussion of implementation details of SDL for Android): // Local references are automatically deleted if a native function called // from Java side returns. For SDL this native function is main() itself. // Therefore references need to be manually deleted because otherwise the // references will first be cleaned if main() returns (application exit). } ```