Plugin reference

sdl2

Direct SDL2 — windows, rendering, textures, input, and audio.

57 functionsnamespace sdl2source plugins/sdl2/Sdl2Plugin.c

Introduction

The sdl2 plugin provides the full surface of the SDL2 multimedia library: you can open a window, do pixel-level 2D graphics (rectangles, lines, textures), read events (keyboard, mouse, window close), play audio (WAV files or a synthesized tone), and load images as textures (BMP by itself; PNG/JPG/WebP through the sdl2_image adapter and a pixel packet). The plugin is handle-based: window, texture, WAV, and audio resources receive an integer identifier (a handle) that further operations refer to them by.

SDL2 at runtime

The plugin loads SDL2 at run time, not at build time: it opens the library when it is loaded (before the script starts) and refuses to start the script if SDL2 is missing, naming the file to copy into the runtime folder. LoadTexture loads BMP, which SDL2 itself decodes; PNG, JPG and WebP come through the separate sdl2_image adapter as a pixel packet that TextureFromPixels turns into a texture — one library per plugin, the blob as the interface between them.

Relationship to the opengl plugin

The sdl2 and opengl plugins can be used in parallel, but with different purposes: opengl provides a high-level 3D demonstration scene (rotating cube, textures, gl.* fixed-pipeline wrappers), and sdl2 provides the SDL2-based API for 2D graphics, audio, and events. The two have their OWN windows and state; you generally choose one or the other for your script, depending on whether you need 3D rendering or 2D multimedia.

Loading the plugin

plugin "builtin:print";
plugin "../plugins/sdl2/Sdl2Plugin";

A typical flow — 2D window and drawing

i32 $win;
sdl.Init();
$win = sdl.OpenWindow("Demo", 800, 600);
while (sdl.PollQuit() == 0)
{
    sdl.Clear($win, 20, 20, 30);
    sdl.FillRect($win, 100, 100, 200, 150, 255, 80, 80);
    sdl.Present($win);
}
sdl.CloseWindow($win);
sdl.Quit();

What to know about every function (the basics)

  • The SDL2-requiring verbs automatically initialize SDL2 on the first call (Init/OpenWindow/Ticks/Delay/PumpEvents/PollEvent/PollQuit/OpenAudio/LoadWav/PlayWav/LoadTexture).

  • Window, texture, WAV, and audio resources receive a positive handle, which must be freed with the matching Close*.

  • The color components in 2D drawing are integers from 0..255 (R, G, B); the alpha channel in SetTextureAlpha is also 0..255.

  • Event handling has two modes: the SYNCHRONOUS PollEvent + Event* getters (on the main thread), or the ASYNCHRONOUS SetEventCallback (a background callback that subscribes to events).

  • An error (stopping the script) is caused by a wrong argument count or type, an invalid handle, and a failed SDL2 initialization.

How to read the signatures

windowId is the handle of an open window, textureId of a texture, audioId of an audio device, wavId of a loaded WAV file. The type after the -> arrow is the return type. For example, sdl2.OpenWindow(title, width, height) -> int takes a string and two integers and returns a window handle.

Lifecycle and timing

Initializing and shutting down the SDL2 subsystems, plus timing helpers (elapsed time, waiting).

Initialisation

The plugin opens the SDL2 library when it is loaded (a missing SDL2 refuses the script before it starts). SDL’s subsystems come up per subsystem, at the first verb that needs one: window, event and texture verbs bring up video and the timer, the audio verbs bring up audio, Ticks/Delay the timer. A script that only draws therefore runs on a machine with no audio driver, and one that only plays runs without a display. sdl2.Init() is optional — it asks for all three at once, an early check; sdl2.Quit() is optional too, the plugin quits SDL at shutdown. sdl2.SetVideoDriver / sdl2.SetAudioDriver select the driver for that subsystem’s first initialisation, so call them before the first window or audio verb. sdl2.TryOpenAudio answers 0 when there is no audio subsystem at all, like “no device”.

sdl2.Init

sdl.Init() -> int

Initializes the SDL2 video, audio, and timer subsystems (if not yet initialized). Optional: every verb brings up the subsystems it needs; an explicit Init asks for all three at once and reveals at the start if one of them is unavailable.

Parameters

This function takes no arguments.

Return value

1 on success. A missing SDL2 or a failed Init causes a runtime error.

Example
printf("%d\n", sdl.Init());
Output after running
1
When to use

When you want the early check (video, audio and timer all at once) at the top of the program. Not required: a window verb brings up video on its own, an audio verb brings up audio.

sdl2.Quit

sdl.Quit() -> int

Shuts down the SDL2 subsystems and releases the pending resources (windows, textures, audio).

Parameters

This function takes no arguments.

Return value

Always 1.

Example
printf("%d\n", sdl.Quit());
Output after running
1
When to use

Optional at the end of the program (the plugin quits SDL2 at shutdown). Open windows/textures/audio devices close automatically, but it is worth freeing them with your own Close* calls first, so the order is traceable.

sdl2.Ticks

sdl.Ticks() -> int

Returns the milliseconds elapsed since SDL2 started.

Parameters

This function takes no arguments.

Return value

The number of elapsed milliseconds.

Example
printf("%d\n", sdl.Ticks());
Output after running
(an increasing millisecond value)
When to use

For simple time measurements or frame timing: the difference between two Ticks values gives the length of the given interval. Finer-grained and monotonic (not jumping back) compared to NowText.

sdl2.Delay

sdl.Delay(ms) -> int

Waits for the given milliseconds (suspends the script).

Parameters
Parameter Type Description
ms int The wait time in milliseconds (non-negative).
Return value

The given value (ms). A negative value causes a runtime error.

Example
printf("%d\n", sdl.Delay(16));
Output after running
16
When to use

For frame pacing (for example 16 ms of waiting after each frame for ~60 fps), or for simple pausing. More accurate than many platforms' sleep, and gentler on the CPU.

Window and 2D drawing

Opening, closing a window, querying its size; drawing rectangles, lines, and presenting the drawing.

sdl2.OpenWindow

sdl.OpenWindow(title, width, height) -> int

Opens an SDL2 window with the given title and size, and returns a window handle.

Parameters
Parameter Type Description
title string The window title.
width int The window width in pixels.
height int The window height in pixels.
Return value

The window handle (a positive integer). A failed opening causes a runtime error.

Example
i32 $win;
$win = sdl.OpenWindow("Demo", 800, 600);
// ... drawing + event handling ...
sdl.CloseWindow($win);
Output after running
(the window handle by which you call the rest of the 2D
operations)
When to use

The first step of every 2D display. You pass the returned handle to Clear/FillRect/DrawLine/Present and the texture-drawing calls. Always close it at the end.

sdl2.CloseWindow

sdl.CloseWindow(windowId) -> int

Closes the window and releases its associated resources.

Parameters
Parameter Type Description
windowId int The window handle to close.
Return value

1 on success.

Example
sdl.CloseWindow($win);
Output after running
1
When to use

When a window is no longer needed, or the program stops. Close the textures bound to it separately first (CloseTexture), so the order is clean.

sdl2.WindowWidth

sdl.WindowWidth(windowId) -> int

Returns the window's current width in pixels.

Parameters
Parameter Type Description
windowId int The window handle.
Return value

The width in pixels.

Example
printf("%d\n", sdl.WindowWidth($win));
Output after running
800
When to use

To query the window size — for example to fit the layout to the current size (after a user resize). WindowHeight is its height counterpart.

sdl2.WindowHeight

sdl.WindowHeight(windowId) -> int

Returns the window's current height in pixels.

Parameters
Parameter Type Description
windowId int The window handle.
Return value

The height in pixels.

Example
printf("%d\n", sdl.WindowHeight($win));
Output after running
600
When to use

The counterpart of WindowWidth: together they give the current window size.

sdl2.Clear

sdl.Clear(windowId, r, g, b) -> int

Clears the whole window area with the given RGB color.

Parameters
Parameter Type Description
windowId int The window handle.
r int Red (0..255).
g int Green (0..255).
b int Blue (0..255).
Return value

1 on success.

Example
sdl.Clear($win, 20, 20, 30);
Output after running
(paints the window background dark blue)
When to use

The first drawing step of every frame: setting the background color. After it come FillRect/DrawLine/DrawTexture calls, then Present displays the whole image.

sdl2.FillRect

sdl.FillRect(windowId, x, y, width, height, r, g, b) -> int

Draws a filled rectangle at the given position, size, and color.

Parameters
Parameter Type Description
windowId int The window handle.
x int The upper-left corner's X coordinate.
y int The upper-left corner's Y coordinate.
width int The rectangle width.
height int The rectangle height.
r int Red (0..255).
g int Green (0..255).
b int Blue (0..255).
Return value

1 on success.

Example
sdl.FillRect($win, 100, 100, 200, 150, 255, 80, 80);
Output after running
(a red rectangle at the given place)
When to use

For UI elements (buttons, panels, background blocks), game tiles, or simple graphical elements. The coordinate system starts from the upper-left corner, growing downward/rightward.

sdl2.DrawLine

sdl.DrawLine(windowId, x1, y1, x2, y2, r, g, b) -> int

Draws a straight line between two points with the given color.

Parameters
Parameter Type Description
windowId int The window handle.
x1 int The start point's X coordinate.
y1 int The start point's Y coordinate.
x2 int The end point's X coordinate.
y2 int The end point's Y coordinate.
r int Red (0..255).
g int Green (0..255).
b int Blue (0..255).
Return value

1 on success.

Example
sdl.DrawLine($win, 0, 0, 800, 600, 255, 255, 255);
Output after running
(a white diagonal line)
When to use

For sketching, helper grids, contours, or simple geometric shapes. The lines are one pixel thick.

sdl2.Present

sdl.Present(windowId) -> int

Displays all the pending drawings on the window (swapping the back buffer with the front).

Parameters
Parameter Type Description
windowId int The window handle.
Return value

1 on success.

Example
sdl.Clear($win, 0, 0, 0);
sdl.FillRect($win, 10, 10, 50, 50, 255, 0, 0);
sdl.Present($win);
Output after running
(the image becomes visible)
When to use

The last step of every frame: only after this call does the drawn image appear. You typically use the Clear → Draw* → Present trio in a loop.

Event handling (synchronous)

Synchronous processing of the window's events (keyboard, mouse, quit) on the main thread, and querying the last event's data.

sdl2.PumpEvents

sdl.PumpEvents() -> int

Fills the SDL2 internal event queue with operating-system events (without taking one).

Parameters

This function takes no arguments.

Return value

1 on success.

Example
sdl.PumpEvents();
Output after running
(SDL2's internal queue is refreshed)
When to use

Usually need not be called explicitly — PollEvent / PollQuit does this automatically. It can be useful if you do not call Poll for a long time and want to make sure the window does not freeze.

sdl2.PollEvent

sdl.PollEvent() -> int

Takes a pending event from the SDL2 queue and updates the state returned by the Event* getters.

Parameters

This function takes no arguments.

Return value

The event type code (for example QUIT, KEYDOWN, MOUSEMOTION), or 0 if there was no event.

Example
i32 $t;
$t = sdl.PollEvent();
if ($t > 0) { printf("event: %d, key=%d\n", $t,
    sdl.EventKeyCode()); }
Output after running
(0, or the event's type code and data)
When to use

In the main loop: in every iteration you take one event, or get 0. The Event* getters give the data of the most recent event (key code, mouse position, wheel, etc.).

sdl2.PollQuit

sdl.PollQuit() -> int

Checks whether a QUIT event has arrived (the window or the application was closed).

Parameters

This function takes no arguments.

Return value

1 if a QUIT event arrived; otherwise 0.

Example
while (sdl.PollQuit() == 0)
{
    // ... frame ...
}
Output after running
0
When to use

As the main loop condition, the simplest pattern: while there is no QUIT, the program runs. You take other events (key, mouse) meanwhile with PollEvent.

sdl2.PushQuitEvent

sdl.PushQuitEvent() -> int

Programmatically pushes a QUIT event into the SDL2 queue.

Parameters

This function takes no arguments.

Return value

1 on success.

Example
sdl.PushQuitEvent(); // the next PollQuit will return 1
Output after running
1
When to use

For triggering exit from the script's own code (for example on a button press): the next PollQuit gives 1 and the main loop stops. Cleaner than closing the window from outside.

sdl2.EventKeyCode

sdl.EventKeyCode() -> int

The last keyboard event's key code.

Parameters

This function takes no arguments.

Return value

The key code (or 0 if there has been no keyboard event yet).

Example
printf("%d\n", sdl.EventKeyCode());
Output after running
0
When to use

After PollEvent, if a KEYDOWN/KEYUP-type event arrived: it gives the pressed (or released) key code. The KeyCode function gives you a comparison code by name.

sdl2.EventMouseX

sdl.EventMouseX() -> int

The X coordinate of the last mouse event.

Parameters

This function takes no arguments.

Return value

The X value (or 0 if there has been no mouse event yet).

Example
printf("%d\n", sdl.EventMouseX());
Output after running
0
When to use

After MOUSEMOTION/MOUSEBUTTONDOWN/UP: the X coordinate of the mouse position. EventMouseY gives its counterpart.

sdl2.EventMouseY

sdl.EventMouseY() -> int

The Y coordinate of the last mouse event.

Parameters

This function takes no arguments.

Return value

The Y value (or 0 if there has been no mouse event yet).

Example
printf("%d\n", sdl.EventMouseY());
Output after running
0
When to use

The counterpart of EventMouseX: together they give the exact mouse position.

sdl2.EventMouseButton

sdl.EventMouseButton() -> int

The button identifier of the last mouse button event.

Parameters

This function takes no arguments.

Return value

The button identifier (1=left, 2=middle, 3=right), or 0 if there has been no such event.

Example
printf("%d\n", sdl.EventMouseButton());
Output after running
0
When to use

After MOUSEBUTTONDOWN/UP: which button was clicked. Comparable with the MouseLeftButton/Middle/Right constants.

sdl2.EventWheelX

sdl.EventWheelX() -> int

The horizontal (X-direction) value of the last wheel event.

Parameters

This function takes no arguments.

Return value

The wheel X direction (positive or negative), or 0.

Example
printf("%d\n", sdl.EventWheelX());
Output after running
0
When to use

For tracking horizontal scrolling or sideways button movement (rare, but some mice support it).

sdl2.EventWheelY

sdl.EventWheelY() -> int

The vertical (Y-direction) value of the last wheel event.

Parameters

This function takes no arguments.

Return value

The wheel Y direction (positive=forward, negative=back), or 0.

Example
printf("%d\n", sdl.EventWheelY());
Output after running
0
When to use

For tracking the most common mouse wheel scrolling (vertical) — for zoom, scrolling, list selection.

Event handling (asynchronous callback)

You register a script-level callback function that SDL2's background thread invokes for every event. The main thread's state is shown by the probes (Active/Delivered/Dropped/HasReply).

sdl2.SetEventCallback

sdl.SetEventCallback(callback, timeoutMs) -> int

Sets a script-level callback to be invoked for every incoming event (with an event blob).

Parameters
Parameter Type Description
callback string The name of the script function to call (it takes an event blob and may give a reply).
timeoutMs int The wait timeout in milliseconds for the callback's reply.
Return value

1 on success.

Example
sdl.SetEventCallback("onEvent", 50);
// i32 onEvent(blob $packet) { ... return(0); }
Output after running
(the callback runs for every event)
When to use

For event-driven programming: the background thread automatically notifies you of every event. More convenient than the PollEvent loop if event processing is costly or needs asynchronous logic.

sdl2.ClearEventCallback

sdl.ClearEventCallback() -> int

Removes the configured event callback.

Parameters

This function takes no arguments.

Return value

1 on success.

Example
sdl.ClearEventCallback();
Output after running
1
When to use

When you want to switch from the callback pattern to the synchronous Poll* pattern, or end event handling.

sdl2.EventCallbackActive

sdl.EventCallbackActive() -> int

Tells whether there is an active event callback.

Parameters

This function takes no arguments.

Return value

1 if there is; otherwise 0.

Example
printf("%d\n", sdl.EventCallbackActive());
Output after running
0
When to use

For a check: whether a callback is enabled, before registering another or turning off the existing one.

sdl2.EventCallbackDelivered

sdl.EventCallbackDelivered() -> int

Returns how many events the background thread has delivered to the callback so far.

Parameters

This function takes no arguments.

Return value

The number of delivered events.

Example
printf("%d\n", sdl.EventCallbackDelivered());
Output after running
0
When to use

For diagnostics: you can watch how many events the callback has actually processed (since the start of the run).

sdl2.EventCallbackDropped

sdl.EventCallbackDropped() -> int

Returns how many events the background thread has dropped (because the callback did not finish in time).

Parameters

This function takes no arguments.

Return value

The number of dropped events.

Example
printf("%d\n", sdl.EventCallbackDropped());
Output after running
0
When to use

For performance monitoring: if there are frequent drops, the callback is slower than the configured timeoutMs. You can raise timeoutMs or rewrite the callback to be faster.

sdl2.HasEventCallbackReply

sdl.HasEventCallbackReply() -> int

Tells whether there is a pending reply (reply blob) from the callback.

Parameters

This function takes no arguments.

Return value

1 if there is; otherwise 0.

Example
if (sdl.HasEventCallbackReply() == 1) { /* take */ }
Output after running
0
When to use

Before calling TakeEventCallbackReply: you check whether there is something to take. The callback can reply to the event, which the main thread takes this way.

sdl2.TakeEventCallbackReply

sdl.TakeEventCallbackReply() -> blob

Takes a pending callback reply into the main thread.

Parameters

This function takes no arguments.

Return value

The reply blob (empty if there is none).

Example
blob $reply[256];
if (sdl.HasEventCallbackReply() == 1) { $reply =
    sdl.TakeEventCallbackReply(); }
Output after running
(the callback's reply)
When to use

For taking data sent from the async callback to the main thread. The callback can dictate, at script level, what blob it replies with — for example sending the pressed key back to the main thread for its own processing.

Input (constants)

Key name → key code conversion, and the constants of the mouse buttons. These verbs do not require SDL2 initialization — they can be safely run.

sdl2.KeyCode

sdl.KeyCode(name) -> int

Converts a key name (or a single character) into a key code.

Parameters
Parameter Type Description
name string The key name: a single 0-9/a-z character, or one of these names: Return, Enter, Escape, Space, Tab, Backspace, Left, Right, Up, Down (case-insensitive).
Return value

The key code. An unknown name causes a runtime error.

Example
printf("%d\n", sdl.KeyCode("Return"));
printf("%d\n", sdl.KeyCode("a"));
Output after running
13
97
When to use

For key comparison: you can compare the value returned by EventKeyCode after PollEvent with this. Letters are normalized to lowercase (KeyCode("A") == KeyCode("a") == 97).

sdl2.MouseLeftButton

sdl.MouseLeftButton() -> int

Returns the identifier of the left mouse button (a constant).

Parameters

This function takes no arguments.

Return value

1.

Example
printf("%d\n", sdl.MouseLeftButton());
Output after running
1
When to use

For a more readable comparison of the value returned by EventMouseButton: if (sdl2.EventMouseButton() == sdl2.MouseLeftButton()).

sdl2.MouseMiddleButton

sdl.MouseMiddleButton() -> int

Returns the identifier of the middle mouse button (a constant).

Parameters

This function takes no arguments.

Return value

2.

Example
printf("%d\n", sdl.MouseMiddleButton());
Output after running
2
When to use

For recognizing a click with the wheel button (usually pressing the wheel).

sdl2.MouseRightButton

sdl.MouseRightButton() -> int

Returns the identifier of the right mouse button (a constant).

Parameters

This function takes no arguments.

Return value

3.

Example
printf("%d\n", sdl.MouseRightButton());
Output after running
3
When to use

For recognizing a local (context) menu or a secondary action.

Audio

Opening an audio device, loading and playing WAV files, and a synthesized tone.

sdl2.OpenAudio

sdl.OpenAudio(sampleRate) -> int

Opens an audio device with the given sample rate (and returns an audio handle).

Parameters
Parameter Type Description
sampleRate int The sample rate in hertz (typically 44100 or 48000).
Return value

The audio handle (a positive integer). A failed opening or a missing audio device causes a runtime error.

Example
i32 $audio;
$audio = sdl.OpenAudio(44100);
// ... LoadWav + PlayWav or PlayTone ...
sdl.CloseAudio($audio);
Output after running
(the audio handle by which you play sound)
When to use

The first step of sound playback. If the audio device is not available (for example in a server environment), TryOpenAudio is the failure-free alternative.

sdl2.TryOpenAudio

sdl.TryOpenAudio(sampleRate) -> int

Tries to open an audio device, but with a missing device it does not fail — it returns 0.

Parameters
Parameter Type Description
sampleRate int The sample rate in hertz.
Return value

The audio handle if it succeeded; 0 if the device is not available.

Example
i32 $audio;
$audio = sdl.TryOpenAudio(44100);
if ($audio > 0) { /* have sound */ }
Output after running
(handle or 0)
When to use

For optional sound support: if audio is available, use it; if not, the program continues silently. Excellent in a server or headless environment.

sdl2.CloseAudio

sdl.CloseAudio(audioId) -> int

Closes the audio device and releases its resources.

Parameters
Parameter Type Description
audioId int The audio handle.
Return value

1 on success.

Example
sdl.CloseAudio($audio);
Output after running
1
When to use

At the end of audio use — releases the device for other applications. Close the WAVs loaded with LoadWav separately first.

sdl2.StopAudio

sdl.StopAudio(audioId) -> int

Stops the currently playing sound on the given audio device.

Parameters
Parameter Type Description
audioId int The audio handle.
Return value

1 on success.

Example
sdl.StopAudio($audio);
Output after running
1
When to use

If you want to play another sound, or playback must stop on user request. The audio device stays open; only the active sound is cut off.

sdl2.LoadWav

sdl.LoadWav(audioId, path) -> int

Loads a WAV file for the given audio device, and returns a WAV handle.

Parameters
Parameter Type Description
audioId int The target audio handle.
path string The WAV file path.
Return value

The WAV handle (a positive integer). A missing file or a wrong format causes a runtime error.

Example
i32 $wav;
$wav = sdl.LoadWav($audio, "sounds/click.wav");
Output after running
(the WAV handle by which you play the sound)
When to use

For loading sound effects. A loaded WAV can be played multiple times with PlayWav; free it with CloseWav at the end.

sdl2.CloseWav

sdl.CloseWav(wavId) -> int

Releases the memory of a loaded WAV file.

Parameters
Parameter Type Description
wavId int The WAV handle.
Return value

1 on success.

Example
sdl.CloseWav($wav);
Output after running
1
When to use

Close every WAV belonging to a LoadWav when no longer needed — otherwise memory can pile up.

sdl2.PlayWav

sdl.PlayWav(wavId, repeatCount, volumePercent) -> int

Plays a loaded WAV with the given repeat count and volume percent.

Parameters
Parameter Type Description
wavId int The WAV handle.
repeatCount int How many times to play (0 = once; -1 = infinite).
volumePercent int The volume between 0..100.
Return value

1 on success.

Example
sdl.PlayWav($wav, 0, 80); // once, at 80% volume
Output after running
(the WAV is heard)
When to use

For sound effects (click, collision, notification). For longer background music, use infinite repeat (-1), and stop it with StopAudio when needed.

sdl2.PlayTone

sdl.PlayTone(audioId, frequencyHz, durationMs, volumePercent) ->
int

Plays a simple sine tone at the given frequency, duration, and volume.

Parameters
Parameter Type Description
audioId int The audio handle.
frequencyHz int The tone frequency in hertz (e.g. 440 = A4).
durationMs int The tone duration in milliseconds.
volumePercent int The volume between 0..100.
Return value

1 on success.

Example
sdl.PlayTone($audio, 440, 500, 70); // A4, 500 ms, 70%
Output after running
(a half-second A4 tone)
When to use

For feedback sounds (beep, bell, chirp), or for simple melodic signals without a WAV file. By chaining several tones in time, a tune can also be made.

Textures

Loading images as textures (BMP by itself, any other format through the sdl2_image adapter and TextureFromPixels), drawing textures on the window, resizing, rotating, and transparency.

sdl2.LoadTexture

sdl.LoadTexture(windowId, path) -> int

Loads a BMP image as a texture for the given window; returns a texture handle. SDL2 itself decodes BMP; for PNG, JPG or WebP use TextureFromPixels with a packet from the sdl2_image adapter.

Parameters
Parameter Type Description
windowId int The window handle the texture belongs to.
path string The BMP file path.
Return value

The texture handle (a positive integer). On error, a runtime error.

Example
i32 $tex;
$tex = sdl.LoadTexture($win, "sprite.bmp");
Output after running
(the texture handle)
When to use

For loading BMP sprites, icons, backgrounds with nothing but SDL2 installed. Other formats: sdl2.TextureFromPixels($win, sdl2image.Load(path)).

sdl2.CloseTexture

sdl.CloseTexture(textureId) -> int

Releases the memory of a texture.

Parameters
Parameter Type Description
textureId int The texture handle.
Return value

1 on success.

Example
sdl.CloseTexture($tex);
Output after running
1
When to use

Close every loaded texture when no longer needed. Before the window's CloseWindow, close all the textures belonging to it.

sdl2.TextureWidth

sdl.TextureWidth(textureId) -> int

Returns the texture width in pixels.

Parameters
Parameter Type Description
textureId int The texture handle.
Return value

The width in pixels.

Example
printf("%d\n", sdl.TextureWidth($tex));
Output after running
(the texture width)
When to use

To query the loaded image's actual size — for example so you can center it or rescale it to a given size.

sdl2.TextureHeight

sdl.TextureHeight(textureId) -> int

Returns the texture height in pixels.

Parameters
Parameter Type Description
textureId int The texture handle.
Return value

The height in pixels.

Example
printf("%d\n", sdl.TextureHeight($tex));
Output after running
(the texture height)
When to use

The counterpart of TextureWidth: together they give the texture's actual size.

sdl2.DrawTexture

sdl.DrawTexture(textureId, x, y) -> int

Draws the texture on the window at the given position, at its original size.

Parameters
Parameter Type Description
textureId int The texture handle.
x int The target upper-left corner's X coordinate.
y int The target upper-left corner's Y coordinate.
Return value

1 on success.

Example
sdl.DrawTexture($tex, 100, 50);
Output after running
(the texture appears at the given place)
When to use

The most common texture drawing: places it at the original size. If you need another size, DrawTextureRect; for rotation/flip, DrawTextureEx.

sdl2.DrawTextureRect

sdl.DrawTextureRect(textureId, x, y, width, height) -> int

Draws the texture at the given position and size (scaled).

Parameters
Parameter Type Description
textureId int The texture handle.
x int The target X coordinate.
y int The target Y coordinate.
width int The target width.
height int The target height.
Return value

1 on success.

Example
sdl.DrawTextureRect($tex, 50, 50, 200, 100);
Output after running
(the texture is stretched to 200×100)
When to use

For drawing that requires a size change: enlarging an icon, using an image as a filled background, or resizing a UI element.

sdl2.SetTextureColor

sdl.SetTextureColor(textureId, r, g, b) -> int

Sets the texture's color modulator (multiplies the displayed colors).

Parameters
Parameter Type Description
textureId int The texture handle.
r int Red modulator (0..255; 255 = unchanged).
g int Green modulator (0..255).
b int Blue modulator (0..255).
Return value

1 on success.

Example
sdl.SetTextureColor($tex, 128, 255, 128); // greenish tint
Output after running
(the texture takes a greenish tint)
When to use

For color effects on a texture (red flash on damage, dampened color with a gray shade). The values multiply the texture's original colors: 255 = unchanged, 128 = half intensity.

sdl2.SetTextureAlpha

sdl.SetTextureAlpha(textureId, alpha) -> int

Sets the texture's transparency (alpha multiplier).

Parameters
Parameter Type Description
textureId int The texture handle.
alpha int The alpha value 0..255 (0 = fully transparent, 255 = opaque).
Return value

1 on success.

Example
sdl.SetTextureAlpha($tex, 128); // half transparent
Output after running
(the texture becomes half transparent)
When to use

For fade-in/fade-out animations, or transparent UI elements (for example a panel that half-covers the background).

sdl2.DrawTexturePart

sdl.DrawTexturePart(textureId, srcX, srcY, srcWidth, srcHeight, dstX,
dstY, dstWidth, dstHeight) -> int

Draws a rectangular slice of the texture onto a rectangular slice of the window (source → destination mapping).

Parameters
Parameter Type Description
textureId int The texture handle.
srcX int The source rectangle's X on the texture.
srcY int The source rectangle's Y on the texture.
srcWidth int The source rectangle width.
srcHeight int The source rectangle height.
dstX int The target X on the window.
dstY int The target Y on the window.
dstWidth int The target width (scaling possible).
dstHeight int The target height (scaling possible).
Return value

1 on success.

Example
// drawing the 2nd cell (32..63, 0..31) from a 32x32 sprite sheet
sdl.DrawTexturePart($sheet, 32, 0, 32, 32, 100, 100, 32, 32);
Output after running
(a piece of the sprite sheet is visible)
When to use

For sprite sheets: cutting a given character, tile, or animation frame from a large image. The source and destination rectangles are independent, so scaling is also possible at the same time.

sdl2.DrawTextureEx

sdl.DrawTextureEx(textureId, x, y, width, height, angleDeg, flipX,
flipY) -> int

Draws the texture rotated and/or flipped, at the given position and size.

Parameters
Parameter Type Description
textureId int The texture handle.
x int The target X coordinate.
y int The target Y coordinate.
width int The target width.
height int The target height.
angleDeg int Rotation angle in degrees (around the center).
flipX int Horizontal flip (0 or 1).
flipY int Vertical flip (0 or 1).
Return value

1 on success.

Example
sdl.DrawTextureEx($tex, 100, 100, 64, 64, 45, 0, 0); // rotated by 45
degrees
Output after running
(the texture appears rotated)
When to use

For a rotating or flipped sprite (for example a character that looks right or left with flipX). The rotation happens around the rectangle's center.

sdl2.SetVideoDriver

sdl.SetVideoDriver(driver) -> int

Selects SDL's video driver before the first window verb (or sdl2.Init) — it sets SDL_VIDEODRIVER for this process. "dummy" gives a window and a software renderer with no display at all — headless tests, CI, servers; any other name SDL accepts works (x11, wayland, windows, …).

Parameters
NameTypeMeaning
driverstringSDL video driver name, 1–64 characters
Return value

1 on success.

Example
sdl.SetVideoDriver("dummy");
sdl.Init();
i32 $W = sdl.OpenWindow("headless", 64, 48);
When to use

To run window and texture code where there is no display. Call it before the first window verb (or sdl2.Init); once video is up it has no effect.

sdl2.SetAudioDriver

sdl.SetAudioDriver(driver) -> int

Selects SDL's audio driver before the first audio verb (or sdl2.Init) — SDL_AUDIODRIVER. "dummy" plays into nothing, so audio code runs on machines without a sound device.

Parameters
NameTypeMeaning
driverstringSDL audio driver name, 1–64 characters
Return value

1 on success.

Example
sdl.SetAudioDriver("dummy");
sdl.Init();
When to use

Headless runs and tests; before the first audio verb (or sdl2.Init).

sdl2.CreateStreamingTexture

sdl.CreateStreamingTexture(windowId, width, height, format) -> int

Creates a texture that is refilled from frame packets (sdl2.UpdateTexture) instead of loaded from a file. "rgba" takes RGBA8 packets; "yuv420p" creates an IYUV texture that takes planar YUV packets and lets the GPU convert to RGB while drawing — pair it with ffmpeg.SetOutputFormat("yuv420p") and no colour conversion happens on the CPU anywhere between the decoder and the screen. The returned handle works with every DrawTexture* verb and CloseTexture.

Parameters
NameTypeMeaning
windowIdintwindow handle from sdl2.OpenWindow
widthinttexture width in pixels (1–16384)
heightinttexture height in pixels (1–16384)
formatstring"rgba" or "yuv420p"
Return value

The texture handle (> 0).

Example
i32 $Tex = sdl.CreateStreamingTexture($W, 640, 360, "yuv420p");
When to use

Video and live frames. Match the format and size to the packets you will upload; a mismatch is refused by sdl2.UpdateTexture.

sdl2.UpdateTexture

sdl.UpdateTexture(textureId, $Packet) -> int

Uploads one OMVF frame packet into a streaming texture: RGBA8 packets through SDL_UpdateTexture, YUV420P packets plane by plane through SDL_UpdateYUVTexture. The packet may be the callback's lent ref blob straight from the ffmpeg plugin — nothing is copied on the script side. The packet's format and size must match the texture's.

Parameters
NameTypeMeaning
textureIdinthandle from sdl2.CreateStreamingTexture
$Packetbloban OMVF frame packet (RGBA8 or YUV420P)
Return value

1 on success; a runtime error when the blob is not an OMVF packet, or its format/size does not match the texture.

Example
callback i32 OnVideoFrame(ref blob $Packet)
{
    sdl.UpdateTexture($VideoTexture, $Packet);
    return 1;
}
When to use

In the frame callback of ffmpeg.DecodeNext / PollNext; then draw the texture each frame. See Examples/sdl2_ffmpeg_yuv_demo.dom.

sdl2.TextureFromPixels

sdl.TextureFromPixels(windowId, $Packet) -> int

Creates a texture of the packet's size and fills it from an OMVF RGBA8 pixel packet — the packet sdl2image.Load, image.Load or any other producer gives. One call where LoadTexture stood for PNG files; alpha blending is enabled like LoadTexture.

Parameters
NameTypeDescription
windowIdintthe window whose renderer owns the texture
$Packetbloban OMVF RGBA8 pixel packet (64-byte header, then width*height*4 bytes)
Return value

The texture identifier (> 0).

Example
i32 $Tex = sdl.TextureFromPixels($W, sdl2image.Load("logo.png"));
sdl.DrawTexture($Tex, 10, 10);
When to use

Whenever the image comes from the sdl2_image adapter (PNG, JPG, WebP), from the built-in image plugin, or from your own pixel source; the blob is the interface between the plugins, so the same packet can also go to gl.UpdateTexture or to a file.

sdl2.DrawPixels

sdl.DrawPixels(windowId, x, y, $Packet) -> int

Draws an OMVF RGBA8 pixel packet onto the window’s renderer at (x, y) in the packet’s own size, alpha-blended, and keeps nothing — a texture is created, copied and destroyed inside the call. The one-shot counterpart of TextureFromPixels, for a producer that renders on demand.

Parameters
NameTypeDescription
windowIdintthe window to draw on
x, yinttop-left corner; partly off-window is fine
$Packetbloban OMVF RGBA8 pixel packet
Return value

1. A blob that is not an RGBA8 packet is a runtime error.

Example
sdl.DrawPixels($W, 10, 10, sdl2ttf.RenderText($Font, "Score 12", 255, 255, 255));
When to use

Text or any image that changes every frame — the sdl2_ttf adapter’s RenderText is the typical source. For something drawn every frame unchanged, keep a texture (TextureFromPixels + DrawTexture) instead of re-uploading it.