Foundations

The platform layer

A renderer needs a place to draw and someone to tell it what the user does. In a small demo the renderer opens its own window and reads its own events. In an editor, a map application or a game with its own window library, the application owns the window and the event loop, and the renderer must fit in. This page explains the part between the two: who runs the loop, how a window becomes something the GPU can draw into, why a window has two sizes, and how input travels as a stream of small events. The last part shows how RASM does it.

In short

  • The event loop belongs to one owner. A renderer that is embedded does not run it: the application calls the renderer once per frame.
  • A window reaches the graphics API as a native handle (an HWND, a CAMetalLayer, an X11 window, a Wayland surface). From it, the renderer makes a surface, and from the surface a swapchain.
  • A window has a size in points (mouse positions, UI layout) and a size in pixels (the swapchain). On a HiDPI display they differ. The display also has a scale setting that makes the UI bigger.
  • Input is a stream of events: key down, key up, mouse move, button, wheel, text, focus. Every source, the renderer's own window or the application, sends the same events.
  • A key has a meaning (the letter it types) and a position (where it is). Shortcuts use the meaning, W/A/S/D movement uses the position.
  • The UI looks at each event first. What it captures, a click on a button, typing in a field, does not reach the camera.

1Who runs the event loop

The operating system puts every key press, mouse move and resize into a queue for the window. Somebody must take events out of that queue, again and again, or the window freezes. That repeating code is the event loop, and a program can have only one.

renderer while (running) read events draw application sees no events has its own loop?

The renderer owns the loop. Simple for a demo. But an editor (Qt, a game's own SDL or GLFW loop) already has a loop, and two loops can't both own one window.

application while (open) read events, pass on renderer.frame() renderer applies events, draws one frame

The application owns the loop. It reads its window's events, gives the renderer what it needs, and asks for one frame each time around. The renderer never blocks and never quits by itself.

A good engine offers both: a ready-made window for small programs, and a mode where it only draws. The trick is that both modes feed the renderer the same kind of events, so the code after that point does not know who owns the window.

2From a window to a surface

A graphics API can't draw into "a window". It draws into images that the operating system's window system shows. The program gives the API the window system's own handle, and the API makes a surface from it: the API's view of that window. A swapchain is built on the surface (The swapchain).

window system: handle Windows: HWND (+ HINSTANCE) macOS: CAMetalLayer X11: Display* + window id Wayland: wl_display + wl_surface graphics API: one function each vkCreateWin32SurfaceKHR vkCreateMetalSurfaceEXT vkCreateXlibSurfaceKHR vkCreateWaylandSurfaceKHR surface swap-chain
The handles are plain pointers or numbers. An engine can keep them in one struct with two pointers and a kind, with no window system's types in it, so its public API compiles everywhere. D3D12 takes the HWND itself, Metal the layer itself.
window: lives longer renderer: inside it destroy the renderer first

The window outlives the renderer

The surface points into the window. Destroy the renderer, then the window, never the other way.

one loader instance surface

One loader for both

A window library may load Vulkan for itself. Make the surface from the handle with your own instance, and nothing loads a second copy (The Vulkan loader).

hidden window handle + surface tests the real path, shows nothing

A hidden window is still a window

It has a handle and a surface. A test can render into it and copy the frame back, with nothing on screen, and so check the same path a user's window takes.

3Points, pixels and the scale setting

On a normal display, one point is one pixel. On a HiDPI display (a Retina screen) the window system keeps the old sizes in points, so windows and text keep their size, and draws each point with several pixels. Separately, the user can set a scale (150 % in Windows' settings), which asks programs to draw their UI larger.

400 × 250 points (mouse, UI layout) 800 × 500 pixels (swapchain) = pixels per point = 800 / 400 = 2 OK scale 1.0 OK scale 1.5 the same button, drawn larger: sizes and fonts × scale
Three numbers per window: the size in points, the size in pixels, and the scale setting. Pixels per point sharpen the UI; the scale makes it bigger. Both can change while the program runs, when the window moves to another display.
NumberUsed forChanges when
size in pointsmouse positions, the UI's layoutthe user resizes the window
size in pixelsthe swapchain, render targets, viewportsa resize, or a move to a display with another pixel density
scale settingthe UI's sizes and fontsa move to another display, or the user changes the setting

4Input as a stream of events

Each window system has its own event types. The platform layer turns them into a small set of its own, and everything after it reads only that set. One frame's events form a short list, in the order they happened:

events since the last frame, in order MOVE410, 300 BUTTONleft down MOVE430, 296 MOVE455, 290 KEYW down TEXT"w" WHEELy = +1 UI firsttakes what it captures camera, shortcutsget the rest A held key is state: W stays down until its KEY up event, over many frames.
A key press brings two events: KEY (which key went down) and TEXT (which character it typed, after the layout, Shift and dead keys). Shortcuts and movement read keys; text fields read text.

Some state is kept between frames: which keys are held, where the pointer is, whether a drag runs. Events change that state; a frame reads it. The other way, polling the keyboard's state each frame, misses a press and release that both happen inside one frame, and can't tell which window had the focus.

A key's meaning and its position

US layout Q W E R AZERTY layout A Z E R position: "W" (named after the US layout) meaning on this keyboard: "Z"
One key, two names. The same place on the keyboard types a different letter in each layout.
UseReadWhy
Ctrl+Z, F1, menu keysmeaningThe user presses the letter printed on the key.
W/A/S/D movementpositionThe four keys must stay in a cross, on any layout.
Typingtext eventsOnly the window system knows the character, after Shift and dead keys.

5Who gets the input: the UI's capture

A click on a UI button must press the button, not turn the camera. An immediate-mode UI (Immediate-mode UI) decides this itself at the end of each frame and sets flags: "I want the mouse", "I want the keyboard", "I want text". The rest of the program reads those flags and skips what the UI took. The flags come from the last frame, so the decision is one frame old; nobody notices.

CaseWho gets it
A press over a UI windowThe UI, until the release, even when the pointer leaves the window (a slider drag).
A press outside every UI windowThe camera starts the drag its button map gives the button (an orbit or a pan) and keeps it until that button's release, even over a UI window. The drag follows the moves' dx and dy, and the platform grabs the pointer meanwhile (Platform::setMouseGrab), so the drag goes on past the window's edge.
The wheel over a UI windowThe UI scrolls; the camera does not zoom.
A text field has the focusKeys type into it. Shortcuts like F1 or Escape wait until it lets go.
The window loses the focusNobody: the window will never see the release of a held key or button, so every key counts as up and a drag ends.
Move the pointer, then press the button over the panel and outside it, and drag. The drag is shown in the units the camera uses: divided by the smaller side of the window, y up.

6Pitfalls

The camera turns while you drag a UI slider
The camera does not read the UI's capture flags. Skip a press that the UI wants, and keep a drag with whoever started it.
The camera keeps moving after Alt+Tab
W went down, then the window lost the focus, and the release went to another window. Treat a lost focus as "every key up".
W/A/S/D are in the wrong place for French users
Movement reads the key's meaning. Read its position instead.
Ctrl+Z undoes on the wrong key
The opposite mistake: shortcuts read the position. Read the meaning.
Typing in a text field gives no characters
Some window libraries send text events only after the program asks for them (SDL3's SDL_StartTextInput). Ask when a text field takes the focus, and stop after.
The UI is blurry on a Retina display
It was drawn at one pixel per point. Lay out in points, and draw with the pixels per point.
The UI is tiny on a 4K laptop
The scale setting is ignored. Scale the UI's sizes and fonts by it, and again when the window moves to another display.
A crash when the program closes
The window was destroyed before the renderer, whose surface still pointed into it. Destroy the renderer first.
The embedded renderer quits on Escape
A renderer that owns no window must never end the application's loop. Leave quitting to the owner.

7In RASM

A Renderer has no SDL: it draws into the application's window (RendererConfig::nativeWindow, the native platform) or, without one, into offscreen images (the headless platform). An Engine is a Renderer whose platform EngineConfig::platform picks. SDL opens a window and reads its events. NATIVE draws into the application's window (EngineConfig::nativeWindow), as a Renderer does, and the application runs the loop and sends the input with Renderer::addInputEvent, setWindowSize and setWindowContentScale. HEADLESS has no window (Headless rendering). After the platform, all three look the same: one list of InputEvents, and one NativeWindow for the device.

sources SdlPlatformSDL events → InputEvents the applicationaddInputEvent a headless scriptaddInputEvent inputEventskeeps its capacity getInputEvents pollEventsonce per frame, in order,capture of the last UI frame processUiEventImGuiIO, while it builds applyInputEventF keys, CameraInputState takeCameraInputthe frame's CameraInput SDL's window propertiesor nativeWindow NativeWindowDeviceDesc::window createVulkanSurfacesurface, then swapchain
No ImGui platform backend runs: ImGui is fed by the same events as the camera. What only a window's owner can do, the cursor shape, the clipboard and starting text input, goes back to the Platform; the SDL platform does it, and a NATIVE application reads ImGui's requests itself.
This pageRASM
The application owns the loopA Renderer, or an Engine with PlatformType::NATIVE. running() stays true, Escape does not quit, and NativePlatform::pollEvents reads nothing. The SDL platform keeps the old behaviour for small programs: its own loop, Escape quits.
Native handles in one structNativeWindow: NativeWindowType, two void*, the first pixel size and the content scale. The SDL platform fills the same struct from SDL's window properties (SDL_Metal_CreateView for a CAMetalLayer on macOS), so every window takes the embedder's path.
The surface from the handlecreateVulkanSurface in src/rhi/vulkan/vulkanSurface.cpp, the only file with a window system's types, through volk's vkGetInstanceProcAddr. The instance enables every surface extension the loader has.
Three numbers per windowWindow::width/height (points), pixelWidth/pixelHeight, contentScale. SDL reports all three, also on a move to another display; a NATIVE application calls setWindowSize and setWindowContentScale. A pixel size of 0 skips frames.
One event setInputEvent in rasm/input.h: a type and plain fields, ready for a C API. Mouse positions in points. InputEvent::window names the window (invalid: the main one); only the main window's events reach ImGui, the F keys and the engine's camera.
More windowsRenderer::addWindow(WindowDesc) asks the platform for another window: Platform::createWindow opens an SDL window (WindowDesc::hidden for a script), wraps WindowDesc::native for NATIVE, or makes nothing headless; the engine gives it a WindowHandle (Window::handle, on every platform) and a swapchain (Many views of one scene). SdlPlatform::pollEvents updates every window and tags each event by SDL's window id; a window's close is InputEventType::WINDOW_CLOSE, the main window's stops running(); focus is each window's own. SDL quits with its last window (Window::platformWindow is the SDL_Window). A NATIVE application sends another window's events tagged with its handle, and its size with setWindowSize(window, ...).
Events applied once per frameaddInputEvent queues into Renderer::pendingInputEvents. The first pollEvents of a frame (the application's, else the one in beginFrame) swaps it with Renderer::inputEvents, appends the platform's events and applies them in order. Later calls in the frame leave its input as it is: they queue the window's new events for the next frame and stop running() on a close, so a loop with no frames can end. An event added after the poll waits for the next frame. Both vectors keep their capacity (no allocation in a steady frame, P27). getInputEvents returns the frame's list until the next poll.
Meaning and positionInputEvent::key and physicalKey, one Key enum for both. ImGui and F1–F3 read key; W/A/S/D read physicalKey, which Key::NONE makes the same as key.
The UI's captureUiInputCapture from the last UI frame (readUiInputCapture, public as Renderer::getUiInputCapture): WantCaptureMouse keeps presses and the wheel from the camera, WantCaptureKeyboard W/A/S/D, WantTextInput Escape and F1–F3.
Focus lost: every key upaddCameraInputEvent clears CameraInputState::keysDown and ends the drag on a lost FOCUS; ImGui gets AddFocusEvent.
The input after the platformThe engine moves the camera given to beginFrame with its own CameraInputState, unless the camera's controller is NONE. An application can move its cameras itself: getInputEvents into its own CameraInputState per view, or getCameraInput (Camera controllers).
Ask for text inputupdateUiPlatform calls Platform::setTextInput when WantTextInput changes; SDL starts and stops its text events. Cursor shapes and the clipboard go the same way. The SDL platform also captures the mouse while a button is held.
Scale the UIsetUiScale scales the current style by the ratio of the new Window::contentScale to the old, so the application's colors and sizes stay; ImGui's framebuffer scale is pixels per point.
A hidden window as a test19_embedding --headless opens two hidden SDL windows, makes a Renderer on the first and adds the second, plays a scripted drag, click and typing, and writes frame N of both windows (the second to <out>_window2.png). The drag moves the example's own camera rig, through getInputEvents. verify-change runs it like every example.

Code map

WhatWhere
Public typesInputEvent, Key, MouseButton in include/rasm/input.h; PlatformType, NativeWindow in include/rasm/types.h; Window in include/rasm/window.h
The platformsPlatform in src/platform/platform.h; src/platform/sdlPlatform.cpp, src/platform/nativePlatform.cpp, src/platform/headlessPlatform.cpp
Input state, camera inputInputState (the engine's keys) and applyInputEvent in src/platform/input.cpp; CameraInputState, addCameraInputEvent, takeCameraInput, toInputNdc in src/platform/cameraInput.cpp, public in include/rasm/cameraInput.h
The engine's sideRenderer::pollEvents, addInputEvent, getInputEvents, getUiInputCapture, setWindowSize, setWindowContentScale in src/renderer/renderer.cpp
Dear ImGui's inputprocessUiEvent, updateUiPlatform, setUiScale in src/platform/uiPlatform.cpp; called from src/renderer/ui.cpp
The surfacecreateVulkanSurface in src/rhi/vulkan/vulkanSurface.cpp, called by VulkanDevice::initialize
Exampleexamples/19_embedding/main.cpp: two SDL3 windows of the application's own (the second through addWindow) and a camera it drives, with --headless and --no-window; examples/20_views/main.cpp: a second window the SDL platform opens
Teststests/inputTests.cpp: NDC, areas, drags across frames, the button map, the wheel, the UI's capture, keys by position, focus loss, the F keys, pollEvents once per frame
Rules to keep
  • Every input reaches the engine as an InputEvent. A new platform turns its events into them; it never calls the camera or ImGui itself.
  • No window system's type in a public header or outside src/platform/ and vulkanSurface.cpp.
  • A renderer on a window it does not own never quits by itself.

Still open: the IME window's position (D38), and SDL video drivers without a native handle (D39).

Further reading