### 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; } ``` -------------------------------- ### Start Android Tests Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/README-android.md Launch installed tests directly from the build environment or perform a full build-install-start cycle. ```bash cmake --build . --target start-testsprite ``` ```bash cmake --build . --target build-install-start-testsprite ``` -------------------------------- ### 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; } ``` -------------------------------- ### Build an SDL example program Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/HowToReportBugs.md A command-line example for compiling a single SDL example file using a C compiler. ```bash cd SDL cc -o clear examples/renderer/01-clear/clear.c -Iinclude -lSDL3 ``` -------------------------------- ### 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 ``` -------------------------------- ### 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) ``` -------------------------------- ### SDL XR Manifest Example Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/README-xr.md This path points to an example XR manifest template provided by SDL. It includes Khronos OpenXR requirements and configurable Meta Quest support. ```cmake test/android/cmake/AndroidManifest.xr.xml.cmake ``` -------------------------------- ### Creating a Window and Renderer Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_CreateWindowAndRenderer.md A complete example demonstrating the initialization of SDL, creation of a window and renderer, and a basic rendering loop. ```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; } ``` -------------------------------- ### 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" ``` -------------------------------- ### Creating a window with properties Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_CreateWindowWithProperties.md Demonstrates initializing SDL, setting window properties, and creating a window using SDL_CreateWindowWithProperties. ```c // Example program // Use SDL3 to create a window with properties #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_PropertiesID props = SDL_CreateProperties(); if(props == 0) { SDL_Log("Unable to create properties: %s", SDL_GetError()); return 0; } // Assume the following calls succeed SDL_SetStringProperty(props, SDL_PROP_WINDOW_CREATE_TITLE_STRING, "My Window"); SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_RESIZABLE_BOOLEAN, true); SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, 640); SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER, 480); SDL_Window *window = SDL_CreateWindowWithProperties(props); if(window == NULL) { SDL_Log("Unable to create window: %s", SDL_GetError()); return 0; } // A game loop goes here SDL_DestroyWindow(window); SDL_DestroyProperties(props); return 0; } ``` -------------------------------- ### 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) ``` -------------------------------- ### SDL2 Audio Callback Setup Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/README-migration.md Standard audio initialization pattern using a callback in SDL2. ```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); ``` -------------------------------- ### 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(); ``` -------------------------------- ### 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; } ``` -------------------------------- ### 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) ``` -------------------------------- ### 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; } ``` -------------------------------- ### 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) ``` -------------------------------- ### 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. ``` -------------------------------- ### Run the executable on Windows Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3_net/INTRO-cmake.md Navigate to the build directory and execute the binary on Windows. ```sh cd build/Debug ./hello ``` -------------------------------- ### 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) ``` -------------------------------- ### 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/ ``` -------------------------------- ### 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); ``` -------------------------------- ### 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) ``` -------------------------------- ### 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). } ``` -------------------------------- ### 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); } ``` -------------------------------- ### Disable SDL documentation installation Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/README-cmake.md Use `-DSDL_INSTALL_DOCS=OFF` to prevent the SDL documentation from being installed. This can reduce the size of the installed package. ```bash -DSDL_INSTALL_DOCS=OFF ``` -------------------------------- ### 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; } ``` -------------------------------- ### 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; } ``` -------------------------------- ### Initialize Video Window in SDL 1.2 Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL12MigrationGuide.md Example of setting the window caption and video mode using the legacy SDL 1.2 API. ```c SDL_WM_SetCaption("My Game Window", "game"); SDL_Surface *screen = SDL_SetVideoMode(640, 480, 0, SDL_FULLSCREEN | SDL_OPENGL); ``` -------------------------------- ### Disable SDL install target Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/README-cmake.md Set `-DSDL_DISABLE_INSTALL=ON` to prevent CMake from creating an install target for SDL. This is useful in environments where installation is not desired or handled separately. ```bash -DSDL_DISABLE_INSTALL=ON ``` -------------------------------- ### Build and Install SDL on macOS with CMake Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/README-cmake.md Use these commands to build and install SDL on macOS, with support for multiple architectures. Installation prefix is set to ~/SDL. ```sh cmake -S . -B build -DSDL_FRAMEWORK=ON -DCMAKE_OSX_ARCHITECTURES="arm64;x86_64" cmake --build build cmake --install build --prefix ~/SDL ``` -------------------------------- ### 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; } ``` -------------------------------- ### Enable installation of SDL test programs Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/README-cmake.md Set `-DSDL_INSTALL_TESTS=ON` to include the SDL test programs in the installation process. This allows users to easily run tests after installation. ```bash -DSDL_INSTALL_TESTS=ON ``` -------------------------------- ### 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; } ``` -------------------------------- ### Build Other Dependencies for Cross-Compilation Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/Android.md General example for configuring and building other libraries (e.g., SDL2_gfx) for the Android toolchain. Static builds are recommended for simplicity. ```bash mkdir cross-android/ && cd cross-android/ ../configure --host=arm-linux-androideabi --prefix=$NDK_STANDALONE/sysroot/usr \ --with-some-option --enable-another-option \ --disable-shared make -j$(nproc) make install ``` -------------------------------- ### Install APK to SD Card Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/Android.md Installs an Android application package (APK) directly to the SD card. Use this if internal storage is full or causing installation failures. ```bash adb install -s bin/app-debug.apk ``` -------------------------------- ### Example Usage of SDL_INIT_INTERFACE Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_INIT_INTERFACE.md Demonstrates how to declare an interface structure, initialize it using SDL_INIT_INTERFACE, and then set its function pointers. ```c SDL_IOStreamInterface iface; SDL_INIT_INTERFACE(&iface); // Fill in the interface function pointers with your implementation iface.seek = ... stream = SDL_OpenIO(&iface, NULL); ``` -------------------------------- ### SDL_StringToGUID Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_StringToGUID.md Converts a string representation of a GUID into an SDL_GUID structure. It takes a constant character pointer to the GUID string as input and returns an SDL_GUID structure. Note that this function performs no error checking; invalid GUID strings will result in a non-useful GUID without any error indication. ```APIDOC ## SDL_StringToGUID ### Description Converts a string representation of a GUID into an SDL_GUID structure. ### Syntax ```c SDL_GUID SDL_StringToGUID(const char *pchGUID); ``` ### Parameters #### Path Parameters - **pchGUID** (const char *) - Required - string containing an ASCII representation of a GUID. ### Return Value ([SDL_GUID]) Returns a [SDL_GUID](SDL_GUID) structure. ### Remarks Performs no error checking. If this function is given a string containing an invalid GUID, the function will silently succeed, but the GUID generated will not be useful. ### Thread Safety It is safe to call this function from any thread. ### Version This function is available since SDL 3.2.0. ``` -------------------------------- ### Install and Uninstall Android APKs Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/README-android.md Manage the installation and removal of test APKs on the connected Android device. ```bash cmake --build . --target install-testsprite ``` ```bash cmake --build . --target install-sdl-test-apks ``` ```bash cmake --build . --target uninstall-sdl-test-apks ``` -------------------------------- ### Install a macOS application bundle Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/README-macos.md Use this install-exec-hook rule in your Makefile.am to copy the generated application bundle to the system applications directory. ```make install-exec-hook: APP_NAME_bundle rm -rf $(DESTDIR)$(prefix)/Applications/APP_NAME.app mkdir -p $(DESTDIR)$(prefix)/Applications/ cp -r $< /$(DESTDIR)$(prefix)Applications/ ``` -------------------------------- ### Install and run evtest for joystick debugging Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/README-linux.md Installs and executes the evtest utility to identify joystick device paths. ```bash sudo apt-get install evtest sudo evtest cat /dev/input/event/XX ``` -------------------------------- ### Registering and Pushing a User Event Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_UserEvent.md This example demonstrates how to register a new user event type, create an SDL_Event, populate its user event fields, and push it onto the event queue. Ensure the event type is successfully registered before proceeding. ```c extern Sint32 my_event_code; extern void *significant_data; extern void *some_other_data; const Uint32 myEventType = SDL_RegisterEvents(1); if (myEventType != 0) { SDL_Event event; SDL_zero(event); event.type = myEventType; event.user.code = my_event_code; event.user.data1 = significant_data; event.user.data2 = some_other_data; SDL_PushEvent(&event); } ``` -------------------------------- ### Install build dependencies on Arch Linux Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/README-linux.md Installs the required development libraries to enable all SDL3 features on Arch Linux. ```bash sudo pacman -S alsa-lib cmake hidapi ibus jack libdecor libthai fribidi libgl libpulse libusb libx11 libxcursor libxext libxfixes libxi libxinerama libxkbcommon libxrandr libxrender libxss libxtst mesa ninja pipewire sndio vulkan-driver vulkan-headers wayland wayland-protocols ``` -------------------------------- ### Install build dependencies on openSUSE Tumbleweed Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/README-linux.md Installs the required development libraries to enable all SDL3 features on openSUSE Tumbleweed. ```bash sudo zypper in libunwind-devel libusb-1_0-devel Mesa-libGL-devel libxkbcommon-devel libdrm-devel \ libgbm-devel pipewire-devel libpulse-devel sndio-devel Mesa-libEGL-devel alsa-devel xwayland-devel \ wayland-devel wayland-protocols-devel libthai-devel fribidi-devel ``` -------------------------------- ### Install build dependencies on Fedora 35 Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/README-linux.md Installs the required development libraries to enable all SDL3 features on Fedora 35. ```bash sudo dnf install gcc git-core make cmake \ alsa-lib-devel fribidi-devel pulseaudio-libs-devel pipewire-devel \ libX11-devel libXext-devel libXrandr-devel libXcursor-devel libXfixes-devel \ libXi-devel libXScrnSaver-devel libXtst-devel dbus-devel ibus-devel \ systemd-devel mesa-libGL-devel libxkbcommon-devel mesa-libGLES-devel \ mesa-libEGL-devel vulkan-devel wayland-devel wayland-protocols-devel \ libdrm-devel mesa-libgbm-devel libusb1-devel libdecor-devel \ pipewire-jack-audio-connection-kit-devel libthai-devel ``` -------------------------------- ### Install build dependencies on Ubuntu 18.04 Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/README-linux.md Installs the required development libraries to enable all SDL3 features on Ubuntu 18.04. ```bash sudo apt-get install build-essential git make \ pkg-config cmake ninja-build gnome-desktop-testing libasound2-dev libpulse-dev \ libaudio-dev libfribidi-dev libjack-dev libsndio-dev libx11-dev libxext-dev \ libxrandr-dev libxcursor-dev libxfixes-dev libxi-dev libxss-dev libxtst-dev \ libxkbcommon-dev libdrm-dev libgbm-dev libgl1-mesa-dev libgles2-mesa-dev \ libegl1-mesa-dev libdbus-1-dev libibus-1.0-dev libudev-dev libthai-dev libusb-1.0-0-dev ``` -------------------------------- ### Initialize and Play Simple Rumble Effect Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/CategoryHaptic.md Demonstrates how to initialize the haptic subsystem, open a device, and play a simple rumble effect at 50% strength for 2 seconds. Ensure the haptic device is available and supports rumble. ```c SDL_Haptic *haptic = NULL; // Open the device SDL_HapticID *haptics = SDL_GetHaptics(NULL); if (haptics) { haptic = SDL_OpenHaptic(haptics[0]); SDL_free(haptics); } if (haptic == NULL) return; // Initialize simple rumble if (!SDL_InitHapticRumble(haptic)) return; // Play effect at 50% strength for 2 seconds if (!SDL_PlayHapticRumble(haptic, 0.5, 2000)) return; SDL_Delay(2000); // Clean up SDL_CloseHaptic(haptic); ``` -------------------------------- ### Example Usage of SDL_ELF_NOTE_DLOPEN Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_ELF_NOTE_DLOPEN.md Illustrates how to use the SDL_ELF_NOTE_DLOPEN macro to declare a dependency on the libpng library. ```APIDOC ## Example Usage ### Description This example shows how to use the `SDL_ELF_NOTE_DLOPEN` macro to declare a dependency on the 'png' feature, specifying its description, priority, and the associated shared library name. ### Macro Call ```c SDL_ELF_NOTE_DLOPEN( "png", "Support for loading PNG images using libpng (required for APNG)", SDL_ELF_NOTE_DLOPEN_PRIORITY_RECOMMENDED, "libpng12.so.0" ) ``` ### Remarks A trailing semicolon is not needed after the macro invocation. ``` -------------------------------- ### Build SDL3 for PSVita Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/README-vita.md Use this command to configure, build, and install SDL3 for the PSVita. Ensure vitasdk and cmake are installed. ```sh cmake -S. -Bbuild -DCMAKE_TOOLCHAIN_FILE=${VITASDK}/share/vita.toolchain.cmake -DCMAKE_BUILD_TYPE=Release cmake --build build cmake --install build ``` -------------------------------- ### SDL_AppInit Function Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/README-main-functions.md This function is called once before anything else. It handles initial application setup and returns an SDL_AppResult to determine the application's next step. ```APIDOC ## SDL_AppInit ```c SDL_AppResult SDL_AppInit(void **appstate, int argc, char **argv); ``` This will be called _once_ before anything else. argc/argv work like they always do. If this returns SDL_APP_CONTINUE, the app runs. If it returns SDL_APP_FAILURE, the app calls SDL_AppQuit and terminates with an exit code that reports an error to the platform. If it returns SDL_APP_SUCCESS, the app calls SDL_AppQuit and terminates with an exit code that reports success to the platform. This function should not go into an infinite mainloop; it should do any one-time startup it requires and then return. If you want to, you can assign a pointer to `*appstate`, and this pointer will be made available to you in later functions calls in their `appstate` parameter. This allows you to avoid global variables, but is totally optional. If you don't set this, the pointer will be NULL in later function calls. ``` -------------------------------- ### Install pkg-config and Symlink Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/Android.md Installs pkg-config into the toolchain and creates a symlink for autoconf to detect it. This is crucial for managing library dependencies. ```bash VERSION=0.9.12 cd /usr/src/ wget http://rabbit.dereferenced.org/~nenolod/distfiles/pkgconf-$VERSION.tar.gz tar xf pkgconf-$VERSION.tar.gz cd pkgconf-$VERSION/ mkdir native-android/ && cd native-android/ ../configure --prefix=$NDK_STANDALONE/sysroot/usr make -j$(nproc) make install ln -s ../sysroot/usr/bin/pkgconf $NDK_STANDALONE/bin/arm-linux-androideabi-pkg-config mkdir $NDK_STANDALONE/sysroot/usr/lib/pkgconfig/ ``` -------------------------------- ### Example Usage with Multiple Library Versions Source: https://github.com/libsdl-org/sdlwiki/blob/main/SDL3/SDL_ELF_NOTE_DLOPEN.md Demonstrates how to use SDL_ELF_NOTE_DLOPEN to declare support for multiple versions of a library, such as different SDL versions. ```APIDOC ## Example Usage with Multiple Library Versions ### Description This example illustrates how to declare support for multiple versions of a library, in this case, different versions of SDL, using the `SDL_ELF_NOTE_DLOPEN` macro. The macro allows listing multiple shared object names for a single feature. ### Macro Call ```c // Our app supports SDL1, SDL2, and SDL3 by dynamically loading them SDL_ELF_NOTE_DLOPEN( "SDL", "Create windows through SDL video backend", SDL_ELF_NOTE_DLOPEN_PRIORITY_REQUIRED, "libSDL-1.2.so.0", "libSDL2-2.0.so.0", "libSDL3.so.0" ) ``` ### Remarks This approach is useful when an application needs to be compatible with or dynamically load different versions of the same library. ```