1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
// Copyright 2026 Joseph Anthony Abbott III
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! The OS layer of the Nadir engine: a window and its events, gamepads,
//! OpenGL contexts, audio output, the user's folders, an error dialog and a
//! precise sleep, with one safe API on Linux, Windows and macOS.
//!
//! # Where it fits
//!
//! This crate wraps the raw declarations of [`nadir_sys`], and is where the
//! rest of Nadir meets the operating system, through one API that is the
//! same on every system. `nadir-gfx` draws through its [`GlContext`],
//! `nadir-input` reads its [`Event`]s, and `nadir_engine` opens the window
//! with it and runs the main loop. A game reaches it through `nadir_engine`, which re-exports
//! [`Event`] as `nadir::Event` and, with its own `dev` feature, the
//! allocation counter. Depend on this crate directly for a window and its
//! events without the rest of the engine.
//!
//! # The window
//!
//! - [`Platform::new`] opens the window that a [`WindowConfig`] describes:
//! its title, its size and smallest size in logical pixels, whether it can
//! be resized, whether it starts fullscreen, and vsync.
//! - [`Platform::pump_events`] appends the [`Event`]s that arrived since the
//! last call, and does not wait for any. Call it once a frame.
//! - [`Platform::window_size`] is the inside of the window in physical
//! pixels, and [`Platform::scale_factor`] the physical pixels a logical
//! one covers.
//! - [`Platform::set_fullscreen`], [`Platform::set_title`] and
//! [`Platform::set_cursor_visible`] change the window.
//! - [`Platform::set_modal_frame_callback`] sets what runs while the system
//! holds the event loop, and `pump_events` does not return: while Windows
//! drags or resizes the window, and while macOS resizes it. The callback
//! gets a [`ModalFrame`] with the size and the scale factor, so that the
//! game can run frames meanwhile. Linux never calls it.
//!
//! # Events
//!
//! An [`Event`] is something that happened to the window, to the keyboard
//! and mouse, or to a gamepad (below), in the order the system reported it:
//!
//! - One [`Event::ScaleFactorChanged`] comes before any other event. On
//! Windows and macOS another comes each time the scale factor changes.
//! - [`Event::CloseRequested`] leaves the window open: the game decides.
//! - [`Event::Key`] names the physical key, a [`nadir_core::Key`], whatever
//! the keyboard layout, and says whether a press is a repeat.
//! - [`Event::Text`] is a character typed, after the key press that typed
//! it: one a character, a composed one included, never a control
//! character, and none for a shortcut. On Linux it comes from an X input
//! method, on Windows from `WM_CHAR`, and on macOS from a key press's
//! `characters`.
//! - [`Event::MouseMoved`] is in physical pixels from the top-left corner of
//! the inside of the window, with y growing downward, on every system.
//! [`Event::MouseWheel`] is in lines.
//! - Right after [`Event::Focused`]`(false)`, every key and button that is
//! down gets a release, so nothing stays held while the window cannot see
//! it go up.
//!
//! # Gamepads
//!
//! - [`Platform::poll_gamepads`] appends what the gamepads did since the
//! last call, without waiting: call it once a frame, beside
//! `pump_events`. Its first call reports the pads already plugged in.
//! - A pad plugged in is [`Event::GamepadConnected`], at rest; what is held
//! on it follows as events. A pad unplugged is put back at rest by events,
//! then [`Event::GamepadDisconnected`]. So the events alone give each
//! pad's state, which [`Platform::gamepad_state`] also gives, as a
//! [`GamepadState`].
//! - A [`GamepadId`] is never given twice: a pad plugged in again is a new
//! one.
//! - [`Event::GamepadButton`] names a [`nadir_core::GamepadButton`] by its
//! place on the pad, with the Xbox pad's names: `A` is the bottom face
//! button on every pad. [`Event::GamepadAxis`] gives a stick's axis from
//! -1 to 1, with +Y down, and a trigger from 0 to 1, raw: dead zones are
//! the input layer's.
//! - Pads are read whether or not the window has the focus.
//!
//! # Drawing
//!
//! - [`Platform::gpu_surface`] gives what the GPU draws the window with: for
//! now always [`GpuSurface::Gl`], an OpenGL context current on the thread
//! that opened the window.
//! - [`GlContext`] looks GL functions up ([`GlContext::get_proc_address`]),
//! shows a frame ([`GlContext::swap_buffers`]) and sets the swap interval.
//! The functions it returns are called through the types of
//! [`nadir_sys::gl`], which is `unsafe`; `nadir-gfx` does that, behind a
//! safe API.
//! - [`create_headless_gl`] makes a [`HeadlessGl`], an OpenGL 3.3 core
//! context that draws only offscreen, into render targets, with no window
//! and no display server: for tests and golden images.
//! - A thread has at most one OpenGL context, the window's or a headless
//! one, and it stays current there until it is dropped. A second fails
//! with [`PlatformError::GlContextExists`]. Each context this crate makes
//! has a [`GlContextId`] ([`GlContext::context_id`]), which says whether
//! the context still exists, so that a user can keep the id in place of a
//! borrow. The stand-in of Windows and macOS (below) has none.
//!
//! # Audio
//!
//! - [`open_audio`] opens the default output device, as an
//! [`AudioOutputConfig`] asks (48 kHz stereo, 30 ms of latency by
//! default), and starts an audio thread that feeds it until the
//! [`AudioStream`] it returns is dropped. [`AudioStream::latency`] is the
//! device's buffer, or `None` while there is no device.
//! - The thread calls an [`AudioRender`], given to `open_audio`, a period
//! at a time: [`AudioRender::render`] fills it, and
//! [`AudioRender::underrun`] hears of each time the device ran dry. It
//! must not block, allocate, free or log, as `nadir-audio`'s mixer does
//! not; a panic in it ends the stream.
//! - A device that stops working, as one unplugged does, or that is not
//! there at the start, is logged, and the thread renders on in time while
//! it tries to open it again once a second, and logs when it has. It logs
//! nothing else.
//! - It needs no window: open it before [`Platform::new`], or without one.
//!
//! # The game's files, errors and timing
//!
//! - [`user_dirs`] works out the folders for the game's settings, saves and
//! logs, as a [`UserDirs`]. It creates none of them. It rejects a studio
//! or game name that some system would refuse as a folder name, on every
//! system, so that a name that works on one works on all.
//! - [`show_error_dialog`] tells the player about an error that stops the
//! game: on stderr, and also in a message box on Windows and an alert on
//! macOS.
//! - [`precise_sleep`] blocks until an [`Instant`](std::time::Instant), for
//! a frame limiter. It sleeps, then spins through the last millisecond,
//! and never returns early.
//!
//! # Examples
//!
//! Open a window and run until it is closed:
//!
//! ```no_run
//! use std::time::{Duration, Instant};
//!
//! use nadir_core::log::{debug, info};
//! use nadir_core::{Key, UVec2};
//! use nadir_platform::{Event, Platform, WindowConfig, precise_sleep};
//!
//! let mut platform = Platform::new(&WindowConfig {
//! title: "My game".to_string(),
//! size: UVec2::new(640, 360),
//! min_size: UVec2::ZERO,
//! resizable: true,
//! fullscreen: false,
//! vsync: true,
//! })?;
//! // Frames to run while Windows drags the window, or macOS resizes it.
//! platform.set_modal_frame_callback(Box::new(|frame| {
//! debug!("a modal frame at {}x{}", frame.size.x, frame.size.y);
//! }));
//! let mut events = Vec::new();
//! let mut fullscreen = false;
//! let mut next_frame = Instant::now();
//! 'run: loop {
//! events.clear();
//! platform.pump_events(&mut events);
//! for &event in &events {
//! match event {
//! Event::CloseRequested => break 'run,
//! Event::Key { key: Key::F11, pressed: true, repeat: false } => {
//! fullscreen = !fullscreen;
//! platform.set_fullscreen(fullscreen);
//! }
//! Event::Resized(size) => info!("now {}x{} physical pixels", size.x, size.y),
//! _ => {}
//! }
//! }
//! next_frame += Duration::from_micros(16_667);
//! precise_sleep(next_frame);
//! }
//! # Ok::<(), nadir_platform::PlatformError>(())
//! ```
//!
//! Draw offscreen, and ask the driver for its name through the GL function
//! types of `nadir-sys`, which a program that does this depends on too:
//!
//! ```no_run
//! use core::ffi::{CStr, c_void};
//! use core::mem;
//!
//! use nadir_platform::{GlContext, create_headless_gl};
//! use nadir_sys::gl::{GL_RENDERER, PFNGLGETSTRINGPROC};
//!
//! let gl = create_headless_gl()?;
//! let pointer = gl.get_proc_address(c"glGetString");
//! assert!(!pointer.is_null());
//! // SAFETY: the pointer is not null, and is `glGetString`, of this type.
//! let get_string =
//! unsafe { mem::transmute::<*const c_void, PFNGLGETSTRINGPROC>(pointer) };
//! // SAFETY: the context is current on this thread, and takes this name.
//! let name = unsafe { get_string(GL_RENDERER) };
//! assert!(!name.is_null());
//! // SAFETY: the string is not null, ends with a NUL, and lives as long as
//! // the context.
//! let renderer = unsafe { CStr::from_ptr(name.cast()) };
//! nadir_core::log::info!("drawing with {}", renderer.to_string_lossy());
//! # Ok::<(), nadir_platform::PlatformError>(())
//! ```
//!
//! # Errors
//!
//! Every call that can fail returns a [`PlatformError`], whose message says
//! what went wrong and, where the player can fix it, how: which library or
//! function is missing, or that a Wayland session needs XWayland turned on.
//! The calls that change the window, such as [`Platform::set_title`],
//! return nothing, and log what fails. [`PlatformError`] is
//! `#[non_exhaustive]`: new kinds of error can join it.
//!
//! # Threads
//!
//! A [`Platform`] stays on the thread that opened it, and so does its OpenGL
//! context. On macOS that must be the main thread: on any other,
//! [`Platform::new`] fails with [`PlatformError::NotMainThread`]. A
//! [`HeadlessGl`] is neither `Send` nor `Sync`.
//!
//! [`open_audio`] starts a thread of its own, `nadir-audio`, which alone
//! calls the [`AudioRender`] and the system's audio functions. The
//! [`AudioStream`] it returns is `Send` and `Sync` on every system, and can
//! be opened and dropped on any thread.
//!
//! # Counting allocations (feature `dev`)
//!
//! With the `dev` feature, the global allocator of every binary that links
//! this crate counts heap allocations, for each thread and for the whole
//! process, so that tests can show that a steady frame allocates nothing.
//! `thread_alloc_counts` and `process_alloc_counts` read the counts, as an
//! `AllocCounts`, and `AllocCounts::since` takes the difference of two
//! readings. No other crate in the binary may declare a global allocator.
//! Turn `dev` on only from a `[features]` table or a `[dev-dependencies]`
//! entry, so that no release build carries it. The counter sees only what
//! goes through Rust's allocator: C libraries that call `malloc`, such as
//! Mesa and Xlib, are not counted.
//!
//! ```
//! # #[cfg(feature = "dev")]
//! # {
//! use std::hint::black_box;
//!
//! use nadir_platform::thread_alloc_counts;
//!
//! let mut numbers: Vec<u32> = Vec::with_capacity(64);
//! let start = thread_alloc_counts();
//! for number in 0..64 {
//! numbers.push(black_box(number));
//! }
//! // The pushes fit the capacity, so nothing was allocated.
//! assert_eq!(thread_alloc_counts().since(start).allocations, 0);
//! # }
//! ```
//!
//! The `headless-test` feature is for the workspace's own tests, which need
//! an EGL driver with OpenGL 3.3 on Linux.
//!
//! # Platforms
//!
//! - **Linux**, on X11: everything above. A Wayland session runs the window
//! through XWayland. Xlib (`libX11.so.6`), EGL (`libEGL.so.1`) and ALSA
//! (`libasound.so.2`) are loaded while the program runs, not linked, so
//! that a machine without them gets [`PlatformError::LibraryNotFound`] or
//! [`PlatformError::MissingSymbols`]. The window's context and
//! [`create_headless_gl`] are OpenGL 3.3 core through EGL; the headless
//! one needs `EGL_MESA_platform_surfaceless`, which Mesa and NVIDIA have.
//! The scale factor is read once, from `Xft.dpi`, when the window opens.
//! Typed text comes from the X input method that `XMODIFIERS` names, or
//! else Xlib's own, which composes from the locale's Compose file.
//! Audio goes to ALSA's `default` device, which PipeWire or PulseAudio
//! usually provides. Gamepads are the kernel's event devices in
//! `/dev/input`, which the desktop's udev rules open to the user at the
//! seat, watched with `inotify` for pads plugged in; the drivers `xpad`,
//! `hid-playstation` and `hid-nintendo` give the standard codes, and an
//! Xbox pad over Bluetooth its own axes, which are read too.
//! - **Windows** 10 and later: a Win32 window, aware of each monitor's DPI,
//! with borderless fullscreen. It builds and passes its tests in CI, and
//! still awaits its checks by hand (roadmap task M1.5). It has no OpenGL
//! context yet (M2.6): [`Platform::gpu_surface`] is a stand-in with no
//! functions, whose swaps fail with [`PlatformError::Unsupported`], and
//! [`create_headless_gl`] returns that error. [`WindowConfig::vsync`] is
//! ignored there for now, and [`open_audio`] returns
//! [`PlatformError::Unsupported`] until M6.4. It reports no gamepads until
//! M8.2.
//! - **macOS** 12 and later: an AppKit window, whose fullscreen is the
//! system's own, in a Space of its own. It builds and passes its tests in
//! CI, and still awaits its checks by hand (M1.6). It has no OpenGL context
//! yet (M2.7): the same stand-in as on Windows, and `vsync` is ignored.
//! Nor has it audio output yet (M6.5), nor gamepads (M8.3).
//! - On any other system, [`Platform::new`], [`user_dirs`],
//! [`create_headless_gl`] and [`open_audio`] return
//! [`PlatformError::Unsupported`].
//!
//! Not built yet on any system: Metal (M10.1), showing a text being
//! composed, noticing that the window was minimized, holding the pointer
//! inside the window, and native Wayland. macOS has no input method for
//! typed text yet.
// One of the three crates allowed to contain `unsafe` (AGENTS.md, rule 3). The
// workspace denies `unsafe_code` everywhere else.
// The README's examples are compiled as doc tests too.
;
use UVec2;
pub use ;
pub use ;
pub use show_error_dialog;
pub use PlatformError;
pub use Event;
pub use ;
pub use ;
pub use ;
pub use precise_sleep;
use Backend;
use Gamepads;
use Backend;
use Gamepads;
use Backend;
use Backend;
/// What window to open.
/// What a modal frame callback is told: see
/// [`Platform::set_modal_frame_callback`].
/// The game's window and its connection to the operating system.
///
/// It stays on the thread that created it. On Linux it holds that thread's
/// OpenGL context, so the thread cannot have another (see [`GlContext`]).