SDL3: The Modern Callback System SDL3: Современная система Callbacks
Learn how to use SDL_AppIterate and SDL_AppEvent for WebAssembly and Mobile compatibility. Узнайте, как использовать SDL_AppIterate и SDL_AppEvent для совместимости с WebAssembly и мобильными платформами.
while loop. It is required for Emscripten (Web) and highly recommended for mobile power efficiency.
Примечание: Этот подход заменяет традиционный цикл while. Он необходим для Emscripten (Web) и рекомендуется для мобильных устройств.
1. Project Configuration (CMakeLists.txt) 1. Конфигурация проекта (CMakeLists.txt)
CMakeLists.txt (C)
set(CMAKE_BUILD_TYPE "Debug")
cmake_minimum_required(VERSION 3.21)
project(rectangle-sdl3-c)
set(SDL3_DIR "C:/libs/SDL3-devel-3.4.8-mingw/lib/cmake/SDL3")
find_package(SDL3 REQUIRED)
add_executable(app)
target_sources(app
PRIVATE
src/main.c
)
target_link_libraries(app PRIVATE SDL3::SDL3)
target_link_options(app PRIVATE -mconsole)
CMakeLists.txt (C++)
set(CMAKE_BUILD_TYPE "Debug")
cmake_minimum_required(VERSION 3.21)
project(rectangle-sdl3-cpp)
set(SDL3_DIR "C:/libs/SDL3-devel-3.4.8-mingw/lib/cmake/SDL3")
find_package(SDL3 REQUIRED)
add_executable(app)
target_sources(app
PRIVATE
src/main.cpp
)
target_link_libraries(app PRIVATE SDL3::SDL3)
target_link_options(app PRIVATE -mconsole)
2. Source Code (The Callback Structure) 2. Исходный код (Структура Callback)
main.c / main.cpp
#define SDL_MAIN_USE_CALLBACKS 1 // Use callback functions instead of main()
#include <SDL3/SDL.h>
#include <SDL3/SDL_main.h>
// We will use this renderer to draw into this window every frame
static SDL_Window *window = NULL;
static SDL_Renderer *renderer = NULL;
// This function runs once at startup
SDL_AppResult SDL_AppInit(void **appstate, int argc, char *argv[])
{
if (!SDL_Init(SDL_INIT_VIDEO))
{
SDL_Log("Couldn't initialize SDL: %s", SDL_GetError());
return SDL_APP_FAILURE;
}
if (!SDL_CreateWindowAndRenderer("SDL3 Rectangles", 500, 500, SDL_WINDOW_RESIZABLE, &window, &renderer))
{
SDL_Log("Couldn't create window/renderer: %s", SDL_GetError());
return SDL_APP_FAILURE;
}
SDL_SetRenderVSync(renderer, 1);
return SDL_APP_CONTINUE; // Continue program execution!
}
// This function runs whenever a new event occurs (mouse input, key presses, etc.)
SDL_AppResult SDL_AppEvent(void *appstate, SDL_Event *event)
{
if (event->type == SDL_EVENT_QUIT)
{
return SDL_APP_SUCCESS; // Terminate the program, reporting success to the OS
}
return SDL_APP_CONTINUE; // Continue program execution!
}
// This function runs once per frame and is the heart of the program
SDL_AppResult SDL_AppIterate(void *appstate)
{
SDL_SetRenderDrawColor(renderer, 38, 43, 51, 255);
// Clear the window with the draw color
SDL_RenderClear(renderer);
SDL_FRect rect;
rect.x = 100;
rect.y = 50;
rect.w = 200;
rect.h = 60;
SDL_SetRenderDrawColor(renderer, 220, 80, 80, SDL_ALPHA_OPAQUE);
SDL_RenderFillRect(renderer, &rect);
// Present the freshly cleared result to the screen
SDL_RenderPresent(renderer);
return SDL_APP_CONTINUE; // Continue program execution!
}
// This function runs once upon shutdown
void SDL_AppQuit(void *appstate, SDL_AppResult result)
{
// SDL will clean up the window and renderer for us
}
3. Why use this? 3. Зачем это использовать?
The SDL_AppIterate function is called by the OS whenever it is ready to render a frame. This allows browsers to pause your game when the tab is inactive and mobile phones to save battery.
Функция SDL_AppIterate вызывается ОС всякий раз, когда она готова к отрисовке кадра. Это позволяет браузерам приостанавливать игру, когда вкладка неактивна, а мобильным телефонам — экономить заряд батареи.
Support My Work Поддержать проект
If these tutorials helped you, consider buying me a coffee! Если эти туториалы вам помогли, вы можете поддержать автора.
Sberbank
Direct transfer via phone number Перевод по номеру телефона
Bybit (USDT TRC20)
Support via Cryptocurrency Поддержка криптовалютой