rayengine 0.0.1

A small Linux-first Rust game SDK over raylib
Documentation
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
//! Window lifecycle: initialize once, sample input, fixed-update, draw, present.

use crate::{
    assets::{Assets, MaterialId, MeshId, ModelId, ShaderId, SoundId, TextureId, path_string},
    diagnostics::{DiagnosticsConfig, DiagnosticsReport, DrawCounters, RunSettings},
    input::Bindings,
    material::{MaterialDesc, UniformId, UniformValue},
    render::{Frame, rect},
};
use rayengine_core::{
    glam::Vec2,
    input::Input,
    mesh::MeshData,
    time::{FixedClock, Tick},
    ui::{UiActions, UiInput},
    viewport::{ScaleMode, Viewport},
};
use raylib::prelude::*;
use std::{
    fmt,
    path::{Path, PathBuf},
    time::{Duration, Instant},
};

/// SDK setup, asset or I/O failure.
#[derive(Debug)]
pub enum Error {
    /// Invalid game or run configuration.
    Config(String),
    /// Graphics/audio initialization or render target failure.
    Backend(String),
    /// Asset validation/loading failure.
    Asset(String),
    /// Filesystem operation failed.
    Io(std::io::Error),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Config(message) | Self::Backend(message) | Self::Asset(message) => {
                f.write_str(message)
            }
            Self::Io(error) => error.fmt(f),
        }
    }
}
impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        if let Self::Io(error) = self {
            Some(error)
        } else {
            None
        }
    }
}
impl From<std::io::Error> for Error {
    fn from(error: std::io::Error) -> Self {
        Self::Io(error)
    }
}

/// Explicit game defaults. Resizable and high-DPI support are always enabled.
#[derive(Clone, Debug)]
pub struct Config {
    /// Window title.
    pub title: String,
    /// Initial logical window dimensions.
    pub window_size: (u32, u32),
    /// Reference content/UI size. Cameras use world units instead.
    pub reference_size: Vec2,
    /// Viewport fit/expand policy.
    pub scale_mode: ScaleMode,
    /// Fixed simulation updates per second, from 1 to 1000.
    pub fixed_hz: u32,
    /// Maximum simulation updates before rendering a frame.
    pub max_catch_up: u32,
    /// Render framerate cap. Zero is uncapped.
    pub target_fps: u32,
    /// Request display synchronization from the graphics driver.
    pub vsync: bool,
    /// Initialize audio. Disabled until a game requests it.
    pub audio: bool,
    /// Native window-exit key. Defaults to Escape; `None` lets game UI bind
    /// Escape itself. The window close button and `Update::quit` still work.
    pub exit_key: Option<KeyboardKey>,
    /// Background color outside the content viewport.
    pub bar_color: Color,
}

impl Config {
    /// Creates a 960×540 reference view, 1280×720 window, and 120 Hz simulation.
    pub fn new(title: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            window_size: (1280, 720),
            reference_size: Vec2::new(960.0, 540.0),
            scale_mode: ScaleMode::Fit,
            fixed_hz: 120,
            max_catch_up: 8,
            target_fps: 120,
            vsync: true,
            audio: false,
            exit_key: Some(KeyboardKey::KEY_ESCAPE),
            bar_color: Color::new(9, 14, 24, 255),
        }
    }

    /// Validates configuration before invoking the native backend.
    pub fn validate(&self) -> Result<(), Error> {
        if self.title.contains('\0') {
            return Err(Error::Config("window title cannot contain NUL".into()));
        }
        validate_size(self.window_size)?;
        if !self.reference_size.is_finite()
            || self.reference_size.min_element() < 1.0
            || self.reference_size.max_element() > 8192.0
        {
            return Err(Error::Config(
                "reference dimensions must be finite and between 1 and 8192".into(),
            ));
        }
        if !(1..=1000).contains(&self.fixed_hz) || !(1..=1000).contains(&self.max_catch_up) {
            return Err(Error::Config(
                "fixed_hz and max_catch_up must be between 1 and 1000".into(),
            ));
        }
        if self.target_fps > 1000 {
            return Err(Error::Config("target_fps must be 0..=1000".into()));
        }
        Ok(())
    }
}

/// Optional run controls for bounded native rendering smoke checks.
/// This is not the deferred interactive game-testing protocol.
#[derive(Clone, Debug, Default)]
pub struct RunOptions {
    /// Opt-in timings, submission counters and resource sampling. Disabled by default.
    pub diagnostics: Option<DiagnosticsConfig>,
    /// Exit after this many presented frames. `None` means normal interactive play.
    pub frames: Option<u64>,
    /// Save the last presented frame as a PNG.
    pub screenshot: Option<PathBuf>,
    /// Override initial logical window dimensions.
    pub size: Option<(u32, u32)>,
    /// Hide the window; still requires a working native graphics/display context.
    pub hidden: bool,
    /// Disable VSync and the render cap. Useful for rendering measurements.
    pub uncapped: bool,
}

impl RunOptions {
    /// Reads `--frames N`, `--screenshot file.png`, `--size WIDTHxHEIGHT`,
    /// `--hidden`, `--uncapped`, `--diagnostics report.json`, and `--workload ID`.
    /// Either diagnostic flag enables collection. Unknown/incomplete arguments fail.
    pub fn from_env() -> Result<Self, Error> {
        Self::parse(std::env::args().skip(1))
    }

    /// Parses the same run controls from explicit strings.
    pub fn parse(args: impl IntoIterator<Item = String>) -> Result<Self, Error> {
        let mut options = Self::default();
        let mut args = args.into_iter();
        while let Some(arg) = args.next() {
            match arg.as_str() {
                "--frames" => {
                    let value = args
                        .next()
                        .ok_or_else(|| Error::Config("--frames needs a positive count".into()))?;
                    options.frames = Some(
                        value
                            .parse::<u64>()
                            .ok()
                            .filter(|n| *n > 0)
                            .ok_or_else(|| {
                                Error::Config("--frames needs a positive count".into())
                            })?,
                    );
                }
                "--screenshot" => {
                    options.screenshot = Some(
                        args.next()
                            .ok_or_else(|| Error::Config("--screenshot needs a PNG path".into()))?
                            .into(),
                    )
                }
                "--size" => {
                    let value = args
                        .next()
                        .ok_or_else(|| Error::Config("--size needs WIDTHxHEIGHT".into()))?;
                    let (w, h) = value
                        .split_once('x')
                        .ok_or_else(|| Error::Config("--size needs WIDTHxHEIGHT".into()))?;
                    let size = (
                        w.parse()
                            .map_err(|_| Error::Config("invalid width".into()))?,
                        h.parse()
                            .map_err(|_| Error::Config("invalid height".into()))?,
                    );
                    validate_size(size)?;
                    options.size = Some(size);
                }
                "--diagnostics" => {
                    let path = args
                        .next()
                        .ok_or_else(|| Error::Config("--diagnostics needs a JSON path".into()))?;
                    options
                        .diagnostics
                        .get_or_insert_with(|| DiagnosticsConfig::new("unspecified"))
                        .output = Some(path.into());
                }
                "--workload" => {
                    let id = args
                        .next()
                        .ok_or_else(|| Error::Config("--workload needs a stable ID".into()))?;
                    options
                        .diagnostics
                        .get_or_insert_with(|| DiagnosticsConfig::new("unspecified"))
                        .workload = id;
                }
                "--hidden" => options.hidden = true,
                "--uncapped" => options.uncapped = true,
                _ => return Err(Error::Config(format!("unknown run option: {arg}"))),
            }
        }
        if let Some(diagnostics) = &options.diagnostics {
            diagnostics.validate()?;
        }
        if let Some(path) = &options.screenshot {
            if path.extension().and_then(|e| e.to_str()) != Some("png") {
                return Err(Error::Config("screenshot path must end in .png".into()));
            }
            path_string(path)?;
        }
        Ok(options)
    }
}

/// Counters returned after a game exits.
#[derive(Clone, Debug, Default)]
pub struct RunReport {
    /// Optional constant-space performance summary; None when disabled.
    pub diagnostics: Option<DiagnosticsReport>,
    /// Number of presented frames.
    pub frames: u64,
    /// Number of executed simulation ticks.
    pub ticks: u64,
    /// Total time discarded by bounded catch-up.
    pub dropped_time: Duration,
    /// Wall time spent in the game loop, including presentation throttling.
    pub elapsed: Duration,
}

/// Initialization context; asset loading is explicit and errors are recoverable.
pub struct InitContext<'context, 'audio> {
    /// Native raylib handle for advanced resource creation.
    pub raylib: &'context mut RaylibHandle,
    /// Token identifying raylib's owning thread.
    pub thread: &'context RaylibThread,
    /// Assets owned until this game run finishes.
    pub assets: &'context mut Assets<'audio>,
}

impl InitContext<'_, '_> {
    /// Creates an owned material description with borrowed resource dependencies.
    pub fn material(&mut self, desc: MaterialDesc) -> Result<MaterialId, Error> {
        self.assets.create_material(self.raylib, self.thread, desc)
    }
    /// Compiles custom GLSL; None uses raylib's standard mesh vertex shader.
    pub fn shader_from_source(
        &mut self,
        vertex: Option<&str>,
        fragment: &str,
    ) -> Result<ShaderId, Error> {
        self.assets
            .shader_source(self.raylib, self.thread, vertex, fragment)
    }
    /// Loads/caches shader files. None uses the standard mesh vertex shader.
    pub fn shader(
        &mut self,
        vertex: Option<&Path>,
        fragment: impl AsRef<Path>,
    ) -> Result<ShaderId, Error> {
        self.assets
            .load_shader(self.raylib, self.thread, vertex, fragment.as_ref())
    }
    /// Registers a cached binding after checking the active GLSL type.
    pub fn uniform(
        &mut self,
        shader: ShaderId,
        name: &str,
        initial: UniformValue,
    ) -> Result<UniformId, Error> {
        self.assets.uniform(shader, name, initial)
    }

    /// Validates and uploads generated geometry with the default material.
    pub fn mesh(&mut self, data: &MeshData) -> Result<MeshId, Error> {
        self.assets.upload_mesh(self.raylib, self.thread, data)
    }

    /// Replaces generated geometry, preserving its handle and the old mesh on error.
    pub fn replace_mesh(&mut self, id: MeshId, data: &MeshData) -> Result<(), Error> {
        self.assets.replace_mesh(self.thread, id, data)
    }

    /// Loads/caches a texture by canonical path.
    pub fn texture(&mut self, path: impl AsRef<Path>) -> Result<TextureId, Error> {
        self.assets
            .load_texture(self.raylib, self.thread, path.as_ref())
    }
    /// Uploads a CPU image into a new run-owned texture without filesystem I/O.
    /// Does not cache by image identity. The image may be dropped immediately
    /// afterward; explicit unloading permanently invalidates the returned handle.
    pub fn texture_from_image(
        &mut self,
        image: &raylib::prelude::Image,
    ) -> Result<TextureId, Error> {
        self.assets
            .upload_texture_image(self.raylib, self.thread, image)
    }
    /// Loads/caches a model by canonical path.
    pub fn model(&mut self, path: impl AsRef<Path>) -> Result<ModelId, Error> {
        self.assets
            .load_model(self.raylib, self.thread, path.as_ref())
    }
    /// Loads/caches a sound. Requires `Config::audio = true`.
    pub fn sound(&mut self, path: impl AsRef<Path>) -> Result<SoundId, Error> {
        self.assets.load_sound(path.as_ref())
    }
}

/// One fixed update. Gameplay receives actions and timing, never a variable dt.
pub struct Update<'context, 'audio> {
    /// Current fixed tick.
    pub tick: Tick,
    /// Action states. Press/release edges are consumed after this update.
    pub input: &'context Input,
    /// Current viewport, shared with UI and cameras.
    pub viewport: Viewport,
    /// Pointer in UI units, or `None` in bars, while captured, or while unfocused.
    pub pointer: Option<Vec2>,
    /// Whether the window is focused and can accept UI input.
    pub window_focused: bool,
    /// Loaded assets, including sound playback.
    pub assets: &'context Assets<'audio>,
    pub(crate) quit: &'context mut bool,
}

impl Update<'_, '_> {
    /// Samples UI actions using this tick's mapped pointer and window focus.
    pub fn ui_input(&self, actions: UiActions) -> UiInput {
        UiInput::from_actions(self.input, self.pointer, actions, self.window_focused)
    }
    /// Requests exit after the current update batch and final presentation.
    pub fn quit(&mut self) {
        *self.quit = true;
    }
}

/// Shared game lifecycle for 2D, 3D, or mixed games.
pub trait Game {
    /// Chooses the current cursor policy. Re-read before input sampling and after
    /// fixed updates, so opening/closing menus can release/recapture the cursor.
    /// Capture is suspended on focus loss; transition motion is discarded.
    fn cursor_mode(&self) -> CursorMode {
        CursorMode::Free
    }
    /// Declares actions and physical buttons before entering the loop.
    fn bindings(&self) -> Bindings {
        Bindings::new()
    }
    /// Loads resources once, before the first simulation tick.
    fn init(&mut self, _context: &mut InitContext<'_, '_>) -> Result<(), Error> {
        Ok(())
    }
    /// Advances game state by one fixed tick.
    fn fixed_update(&mut self, context: &mut Update<'_, '_>);
    /// Draws world passes and UI. Interpolate state using `frame.alpha`.
    fn draw(&mut self, frame: &mut Frame<'_, '_>);
}

/// Game-owned cursor policy, applied by the runner while the window is focused.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum CursorMode {
    /// Visible cursor that can leave the window.
    #[default]
    Free,
    /// Hidden cursor with unbounded relative motion for first-person look.
    Captured,
}

#[derive(Default)]
struct CursorState {
    focused: bool,
    captured: bool,
    discard_motion: bool,
}

impl CursorState {
    fn sync(&mut self, mode: CursorMode, focused: bool) -> bool {
        let capture = focused && mode == CursorMode::Captured;
        let changed = capture != self.captured;
        self.discard_motion |= changed || focused != self.focused;
        self.focused = focused;
        self.captured = capture;
        changed
    }

    fn take_motion(&mut self) -> bool {
        let discard = std::mem::take(&mut self.discard_motion);
        self.focused && !discard
    }

    #[cfg(test)]
    fn update(&mut self, mode: CursorMode, focused: bool) -> (bool, bool) {
        let changed = self.sync(mode, focused);
        (changed, self.take_motion())
    }
}

fn sync_cursor(
    raylib: &mut RaylibHandle,
    state: &mut CursorState,
    mode: CursorMode,
    focused: bool,
) {
    if state.sync(mode, focused) {
        if state.captured {
            raylib.disable_cursor();
        } else {
            raylib.enable_cursor();
        }
    }
}

/// Owns game configuration and executes the prescribed lifecycle.
pub struct App {
    config: Config,
    options: RunOptions,
}

impl App {
    /// Builds a runner. Configuration is validated by [`Self::run`].
    pub fn new(config: Config) -> Self {
        Self {
            config,
            options: RunOptions::default(),
        }
    }
    /// Applies optional bounded-run and screenshot controls.
    pub fn with_options(mut self, options: RunOptions) -> Self {
        self.options = options;
        self
    }

    /// Opens raylib and runs the game on this thread.
    ///
    /// Native window creation can panic if the display or graphics driver is
    /// unavailable, following raylib-rs behavior. CPU-only tests use `rayengine-core`.
    /// Only one raylib window may exist in a process at a time.
    pub fn run(self, game: impl Game) -> Result<RunReport, Error> {
        let Self {
            mut config,
            options,
        } = self;
        if let Some(size) = options.size {
            config.window_size = size;
        }
        config.validate()?;
        if let Some(diagnostics) = &options.diagnostics {
            diagnostics.validate()?;
        }
        if options.frames == Some(0) {
            return Err(Error::Config("frame limit must be positive".into()));
        }
        if let Some(path) = &options.screenshot {
            if path.extension().and_then(|e| e.to_str()) != Some("png") {
                return Err(Error::Config("screenshot path must end in .png".into()));
            }
            path_string(path)?;
            if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
                std::fs::create_dir_all(parent)?;
            }
        }
        let mut builder = raylib::init();
        builder
            .size(config.window_size.0 as i32, config.window_size.1 as i32)
            .title(&config.title)
            .resizable()
            .highdpi()
            .log_level(TraceLogLevel::LOG_WARNING);
        if config.vsync && !options.uncapped {
            builder.vsync();
        }
        if options.hidden {
            builder.hidden().always_run();
        }
        let (mut raylib, thread) = builder.build();
        raylib.set_exit_key(config.exit_key);
        raylib.set_target_fps(if options.uncapped {
            0
        } else {
            config.target_fps
        });
        let audio = if config.audio {
            Some(RaylibAudio::init_audio_device().map_err(|e| Error::Backend(e.to_string()))?)
        } else {
            None
        };
        let mut assets = Assets::new(audio.as_ref());
        // This binding drops the game before assets, audio, and the window even
        // on early returns. Game-owned native resources also remain context-safe.
        let mut game = game;
        let bindings = game.bindings();
        let mut input = Input::with_capacity(bindings.capacity());
        game.init(&mut InitContext {
            raylib: &mut raylib,
            thread: &thread,
            assets: &mut assets,
        })?;
        let mut cursor = CursorState::default();
        let mut target: Option<RenderTexture2D> = None;
        let mut target_size = (0, 0);
        let mut clock = FixedClock::new(config.fixed_hz, config.max_catch_up);
        let start = Instant::now();
        let mut previous_frame = start;
        let mut report = RunReport {
            diagnostics: options.diagnostics.as_ref().map(|diagnostics| {
                DiagnosticsReport::new(
                    diagnostics,
                    RunSettings {
                        backend: if cfg!(target_os = "windows") {
                            "glfw-win32"
                        } else if cfg!(target_os = "macos") {
                            "glfw-cocoa"
                        } else if cfg!(all(unix, not(target_vendor = "apple")))
                            && cfg!(feature = "wayland")
                        {
                            "glfw-x11+wayland"
                        } else if cfg!(all(unix, not(target_vendor = "apple"))) {
                            "glfw-x11"
                        } else {
                            "glfw"
                        },
                        os: std::env::consts::OS,
                        arch: std::env::consts::ARCH,
                        sdk_version: env!("CARGO_PKG_VERSION"),
                        window_size: config.window_size,
                        reference_size: config.reference_size.to_array(),
                        scale_mode: match config.scale_mode {
                            ScaleMode::Fit => "fit",
                            ScaleMode::Expand => "expand",
                            ScaleMode::IntegerFit => "integer-fit",
                        },
                        fixed_hz: config.fixed_hz,
                        max_catch_up: config.max_catch_up,
                        target_fps: if options.uncapped {
                            0
                        } else {
                            config.target_fps
                        },
                        vsync: config.vsync && !options.uncapped,
                        render_size: (0, 0),
                    },
                    assets.resource_counts(),
                )
            }),
            ..RunReport::default()
        };
        let mut quit = false;
        while !quit
            && !raylib.window_should_close()
            && options.frames.is_none_or(|limit| report.frames < limit)
        {
            let now = Instant::now();
            let elapsed = now.duration_since(previous_frame);
            previous_frame = now;
            let window = Vec2::new(
                raylib.get_screen_width() as f32,
                raylib.get_screen_height() as f32,
            );
            let view = Viewport::new(window, config.reference_size, config.scale_mode);
            if raylib.is_window_minimized() || view.is_none() {
                sync_cursor(&mut raylib, &mut cursor, game.cursor_mode(), false);
                input.release_all();
                // Keep backend event polling alive, but pause simulation while minimized.
                raylib
                    .begin_drawing(&thread)
                    .clear_background(config.bar_color);
                std::thread::sleep(Duration::from_millis(16));
                continue;
            }
            let view = view.expect("non-minimized viewport");
            let window_focused = raylib.is_window_focused();
            sync_cursor(&mut raylib, &mut cursor, game.cursor_mode(), window_focused);
            bindings.sample(&raylib, &mut input);
            if cursor.take_motion() {
                let delta = raylib.get_mouse_delta();
                input.add_pointer_delta(Vec2::new(delta.x, delta.y));
            }
            let mouse = raylib.get_mouse_position();
            let plan = clock.advance(elapsed);
            report.dropped_time += plan.dropped;
            if let Some(metrics) = &mut report.diagnostics {
                metrics.dropped_ns = metrics
                    .dropped_ns
                    .saturating_add(plan.dropped.as_nanos().min(u128::from(u64::MAX)) as u64);
            }
            for step in 0..plan.steps {
                let update_start = report.diagnostics.as_ref().map(|_| Instant::now());
                game.fixed_update(&mut Update {
                    tick: Tick {
                        index: plan.first_tick + u64::from(step),
                        dt: clock.step().as_secs_f32(),
                    },
                    input: &input,
                    viewport: view,
                    pointer: (window_focused && !cursor.captured)
                        .then(|| view.screen_to_ui(Vec2::new(mouse.x, mouse.y)))
                        .flatten(),
                    window_focused,
                    assets: &assets,
                    quit: &mut quit,
                });
                if let Some(metrics) = &mut report.diagnostics {
                    metrics
                        .update
                        .record(update_start.expect("diagnostics enabled").elapsed());
                    metrics.updates = metrics.updates.saturating_add(1);
                }
                input.consume_edges();
                sync_cursor(&mut raylib, &mut cursor, game.cursor_mode(), window_focused);
                report.ticks += 1;
                if quit {
                    break;
                }
            }
            let render_start = report.diagnostics.as_ref().map(|_| Instant::now());
            let dpi = Vec2::new(
                raylib.get_render_width() as f32,
                raylib.get_render_height() as f32,
            ) / window;
            let size = if config.scale_mode == ScaleMode::IntegerFit {
                (
                    config.reference_size.x.round() as u32,
                    config.reference_size.y.round() as u32,
                )
            } else {
                view.render_size(dpi)
            };
            if size != target_size {
                // Resize only when required; the old target drops while GL is alive.
                let new_target = raylib
                    .load_render_texture(&thread, size.0, size.1)
                    .map_err(|e| Error::Backend(e.to_string()))?;
                new_target.texture().set_texture_filter(
                    &thread,
                    if config.scale_mode == ScaleMode::IntegerFit {
                        TextureFilter::TEXTURE_FILTER_POINT
                    } else {
                        TextureFilter::TEXTURE_FILTER_BILINEAR
                    },
                );
                target = Some(new_target);
                target_size = size;
            }
            let target = target.as_mut().expect("created target");
            let draws = {
                let mut frame = Frame {
                    counters: report.diagnostics.as_ref().map(|_| DrawCounters::default()),
                    raylib: &mut raylib,
                    thread: &thread,
                    target,
                    assets: &mut assets,
                    viewport: view,
                    alpha: plan.alpha,
                    index: report.frames,
                };
                frame.clear(Color::BLACK);
                game.draw(&mut frame);
                frame.draw_counters()
            };
            if let Some(metrics) = &mut report.diagnostics {
                metrics
                    .render
                    .record(render_start.expect("diagnostics enabled").elapsed());
            }
            let present_start = report.diagnostics.as_ref().map(|_| Instant::now());
            {
                let mut draw = raylib.begin_drawing(&thread);
                draw.clear_background(config.bar_color);
                draw.draw_texture_pro(
                    target.texture(),
                    Rectangle::new(0.0, 0.0, size.0 as f32, -(size.1 as f32)),
                    rect(rayengine_core::collision::Aabb2 {
                        min: view.origin,
                        max: view.origin + view.size,
                    }),
                    Vector2::zero(),
                    0.0,
                    Color::WHITE,
                );
            }
            if let Some(metrics) = &mut report.diagnostics {
                metrics
                    .present
                    .record(present_start.expect("diagnostics enabled").elapsed());
                metrics.settings.render_size = size;
                metrics.record_frame(draws.unwrap_or_default(), assets.resource_counts());
                metrics.frame.record(now.elapsed());
            }
            report.frames += 1;
        }
        if let Some(path) = &options.screenshot {
            let image = raylib.load_image_from_screen(&thread);
            let png = image
                .export_image_to_memory(".png")
                .map_err(|e| Error::Backend(e.to_string()))?;
            std::fs::write(path, &*png)?;
        }
        report.elapsed = start.elapsed();
        if let Some((path, metrics)) = options
            .diagnostics
            .as_ref()
            .and_then(|d| d.output.as_ref())
            .zip(report.diagnostics.as_ref())
        {
            if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
                std::fs::create_dir_all(parent)?;
            }
            let file = std::fs::File::create(path)?;
            let mut writer = std::io::BufWriter::new(file);
            metrics
                .write_json(&mut writer)
                .map_err(|error| Error::Io(std::io::Error::other(error)))?;
            std::io::Write::flush(&mut writer)?;
        }
        Ok(report)
    }
}

fn validate_size(size: (u32, u32)) -> Result<(), Error> {
    if (1..=8192).contains(&size.0) && (1..=8192).contains(&size.1) {
        Ok(())
    } else {
        Err(Error::Config(
            "window dimensions must be between 1 and 8192".into(),
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn capture_releases_on_focus_loss_and_ignores_motion_at_focus_transitions() {
        let mut state = CursorState::default();
        assert_eq!(state.update(CursorMode::Captured, false), (false, false));
        assert_eq!(state.update(CursorMode::Captured, true), (true, false));
        assert!(state.captured);
        assert_eq!(state.update(CursorMode::Captured, true), (false, true));
        assert_eq!(state.update(CursorMode::Captured, false), (true, false));
        assert!(!state.captured);
        assert_eq!(state.update(CursorMode::Captured, true), (true, false));
        assert_eq!(state.update(CursorMode::Captured, true), (false, true));
        let mut free = CursorState::default();
        assert_eq!(free.update(CursorMode::Free, true), (false, false));
        assert_eq!(free.update(CursorMode::Free, true), (false, true));
        assert!(!free.captured);
    }

    #[test]
    fn menu_transitions_discard_motion_even_when_changed_between_samples() {
        let mut state = CursorState::default();
        assert!(state.sync(CursorMode::Captured, true));
        assert!(!state.take_motion());
        assert!(state.take_motion());
        assert!(state.sync(CursorMode::Free, true));
        assert!(!state.captured);
        assert!(state.sync(CursorMode::Captured, true));
        assert!(!state.take_motion()); // Open/close between samples still discarded.
        assert!(state.take_motion());
        assert!(state.sync(CursorMode::Captured, false));
        assert!(!state.take_motion());
        assert!(state.sync(CursorMode::Captured, true));
        assert!(!state.take_motion());
        assert!(state.take_motion());
    }

    #[test]
    fn bad_configuration_is_rejected_before_opening_window() {
        let mut config = Config::new("test");
        config.fixed_hz = 0;
        assert!(config.validate().is_err());
        config.fixed_hz = 120;
        config.reference_size.x = f32::NAN;
        assert!(config.validate().is_err());
        config.reference_size.x = 960.0;
        config.title = "bad\0title".into();
        assert!(config.validate().is_err());
    }

    #[test]
    fn run_arguments_are_strict_and_bounded() {
        let parse = |args: &[&str]| RunOptions::parse(args.iter().map(|s| s.to_string()));
        let options = parse(&[
            "--frames",
            "10",
            "--size",
            "800x600",
            "--screenshot",
            "frame.png",
            "--hidden",
        ])
        .unwrap();
        assert_eq!(options.frames, Some(10));
        assert_eq!(options.size, Some((800, 600)));
        assert!(options.hidden);
        for args in [
            &["--frames", "0"][..],
            &["--frames"],
            &["--size", "0x2"],
            &["--screenshot", "out.jpg"],
            &["--wat"],
        ] {
            assert!(parse(args).is_err());
        }
    }

    #[test]
    #[ignore = "requires a native display and OpenGL context; scripts/native_smoke.sh"]
    fn native_render_smoke() {
        use rayengine_core::{
            camera::{Camera2D as EngineCamera2D, Camera3D as EngineCamera3D},
            collision::{Aabb2, Aabb3},
            glam::Vec3,
        };
        let directory =
            std::env::temp_dir().join(format!("rayengine-render-smoke-{}", std::process::id()));
        std::fs::create_dir(&directory).unwrap();
        let png = Image::gen_image_color(8, 8, Color::GREEN)
            .export_image_to_memory(".png")
            .unwrap();
        std::fs::write(directory.join("green.png"), &*png).unwrap();
        std::fs::write(
            directory.join("triangle.obj"),
            "v -1 0 0\nv 1 0 0\nv 0 2 0\nf 1 2 3\n",
        )
        .unwrap();

        struct Probe {
            directory: PathBuf,
            texture: Option<TextureId>,
            model: Option<ModelId>,
        }
        impl Game for Probe {
            fn init(&mut self, context: &mut InitContext<'_, '_>) -> Result<(), Error> {
                let path = self.directory.join("green.png");
                let first = context.texture(&path)?;
                assert_eq!(first, context.texture(&path)?);
                context.assets.unload_texture(first);
                let fresh = context.texture(&path)?;
                assert_ne!(fresh, first);
                assert!(context.assets.texture(first).is_none());
                let image = Image::gen_image_color(8, 8, Color::GREEN);
                let generated = context.texture_from_image(&image)?;
                assert_eq!(context.assets.texture(generated).unwrap().width, 8);
                context.assets.unload_texture(generated);
                let replacement = context.texture_from_image(&image)?;
                assert_ne!(replacement, generated);
                assert!(context.assets.texture(generated).is_none());
                context.assets.unload_texture(fresh);
                // The CPU image is dropped after init; the uploaded texture survives.
                self.texture = Some(replacement);
                let path = self.directory.join("triangle.obj");
                let model = context.model(&path)?;
                assert_eq!(model, context.model(&path)?);
                context.assets.unload_model(model);
                let fresh_model = context.model(&path)?;
                assert_ne!(fresh_model, model);
                assert!(context.assets.model(model).is_none());
                self.model = Some(fresh_model);
                assert!(context.texture(self.directory.join("missing.png")).is_err());
                assert!(context.sound(self.directory.join("missing.wav")).is_err());
                Ok(())
            }
            fn fixed_update(&mut self, _: &mut Update<'_, '_>) {}
            fn draw(&mut self, frame: &mut Frame<'_, '_>) {
                frame.clear(Color::WHITE);
                assert!((frame.viewport.aspect() - 16.0 / 9.0).abs() < 0.0001);
                if frame.index == 0 {
                    frame.world_2d(EngineCamera2D::default(), |canvas| {
                        assert!(canvas.texture(
                            self.texture.unwrap(),
                            Aabb2::from_center(Vec2::ZERO, Vec2::splat(100.0)),
                            Color::WHITE
                        ));
                    });
                } else {
                    frame.world_3d(EngineCamera3D::default(), |canvas| {
                        canvas.cube(
                            Aabb3::from_center(Vec3::ZERO, Vec3::splat(2.0)),
                            Color::BLUE,
                        );
                        assert!(canvas.model(
                            self.model.unwrap(),
                            Vec3::new(3.0, 0.0, 0.0),
                            1.0,
                            Color::RED
                        ));
                    });
                }
                frame.ui(|ui| {
                    ui.rectangle(
                        Aabb2 {
                            min: Vec2::splat(10.0),
                            max: Vec2::splat(60.0),
                        },
                        Color::RED,
                    )
                });
                let mut image = frame.target.texture().load_image().unwrap();
                image.flip_vertical();
                let center = image.get_color(image.width / 2, image.height / 2);
                if frame.index == 0 {
                    assert_eq!(center, Color::GREEN, "2D texture probe");
                } else {
                    assert!(
                        center.b > center.r.saturating_add(40),
                        "3D cube probe: {center:?}"
                    );
                }
                let ui_pixel = image.get_color(
                    (image.width as f32 * 30.0 / frame.viewport.logical_size.x) as i32,
                    (image.height as f32 * 30.0 / frame.viewport.logical_size.y) as i32,
                );
                assert!(
                    ui_pixel.r > 180 && ui_pixel.g < 100,
                    "scaled UI probe: {ui_pixel:?}"
                );
                if frame.index == 0 {
                    frame.raylib.set_window_size(800, 1000);
                }
                if frame.index == 2 {
                    assert_eq!(frame.raylib.get_screen_width(), 800);
                    assert_eq!(frame.raylib.get_screen_height(), 1000);
                    assert!(frame.viewport.origin.y > 200.0);
                }
            }
        }
        let mut config = Config::new("rayengine native render probe");
        config.window_size = (960, 540);
        config.vsync = false;
        let screenshot = directory.join("absolute-path.png");
        let report = App::new(config)
            .with_options(RunOptions {
                frames: Some(3),
                hidden: true,
                screenshot: Some(screenshot.clone()),
                ..RunOptions::default()
            })
            .run(Probe {
                directory: directory.clone(),
                texture: None,
                model: None,
            })
            .unwrap();
        assert_eq!(report.frames, 3);
        assert!(
            std::fs::read(&screenshot)
                .unwrap()
                .starts_with(b"\x89PNG\r\n\x1a\n")
        );
        std::fs::remove_dir_all(directory).unwrap();
    }
}

#[cfg(test)]
mod ui_tests;

#[cfg(test)]
mod diagnostics_tests;