ferravex_render/
lib.rs

1//! Original immediate/retained renderer and platform ABI. Game code, input, geometry and
2//! scheduling live in Rust; hosts only bind OS events and GPU submission.
3pub use ferravex_math::{Color, Mat4, Quat, Rect, Vec2, Vec3, Vec4, vec2, vec3, vec4};
4use std::{
5    cell::RefCell,
6    collections::BTreeSet,
7    future::Future,
8    pin::Pin,
9    task::{Context, Poll, Waker},
10};
11pub mod ao;
12pub mod audio;
13pub mod canvas;
14#[cfg(feature = "content")]
15pub mod content;
16pub mod demo;
17pub mod effects;
18mod font;
19mod font_modern;
20pub mod icons;
21pub use font::{BitmapFontMetrics, BitmapTextMetrics, FontMeasureError};
22pub mod input;
23pub mod juice;
24pub mod lighting;
25pub mod material;
26pub mod mesh;
27#[cfg(not(target_arch = "wasm32"))]
28pub mod native;
29pub mod post;
30pub mod preferences;
31pub mod retained;
32pub mod shaders;
33pub mod shapes;
34pub mod skinning;
35#[cfg(test)]
36mod specimen;
37pub mod status;
38pub mod storage;
39pub mod text;
40pub mod ui;
41pub mod visibility;
42pub use ferravex_core::telemetry;
43pub use ferravex_graphics::Look;
44
45pub mod prelude {
46    pub use crate::post::{PostFx, post_fx_hud_begin, set_post_fx};
47    pub use crate::{
48        BLACK, BLUE, Camera, Camera2D, Camera3D, Color, Conf, DARKGRAY, Font, GRAY, GREEN, KeyCode,
49        LIGHTGRAY, Mat4, Mesh, MouseButton, ORANGE, Quat, RED, Rect, TextDimensions, TextParams,
50        Touch, TouchPhase, Vec2, Vec3, Vec4, Vertex, WHITE, YELLOW, clear_background, draw_circle,
51        draw_circle_lines, draw_cube, draw_ellipse, draw_line, draw_line_3d, draw_mesh,
52        draw_mesh_transformed, draw_poly, draw_rectangle, draw_rectangle_lines, draw_text,
53        draw_text_ex, draw_triangle, get_default_font, get_frame_time, get_screen_data, get_time,
54        is_key_down, is_key_pressed, is_mouse_button_down, is_mouse_button_pressed, measure_text,
55        mouse_delta_position, mouse_position, mouse_wheel, next_frame, screen_dpi_scale,
56        screen_height, screen_width, set_camera, set_cursor_grab, set_default_camera, show_mouse,
57        simulate_mouse_with_touch, touches, vec2, vec3, vec4,
58    };
59}
60pub const WHITE: Color = Color::new(1., 1., 1., 1.);
61pub const BLACK: Color = Color::new(0., 0., 0., 1.);
62pub const RED: Color = Color::new(0.9, 0.2, 0.2, 1.);
63pub const GREEN: Color = Color::new(0.2, 0.8, 0.3, 1.);
64pub const BLUE: Color = Color::new(0.2, 0.4, 0.9, 1.);
65pub const YELLOW: Color = Color::new(1., 0.85, 0.2, 1.);
66pub const GRAY: Color = Color::new(0.5, 0.5, 0.5, 1.);
67pub const DARKGRAY: Color = Color::new(0.2, 0.2, 0.2, 1.);
68pub const LIGHTGRAY: Color = Color::new(0.8, 0.8, 0.8, 1.);
69pub const ORANGE: Color = Color::new(1., 0.5, 0.2, 1.);
70#[derive(Clone, Debug)]
71pub struct Conf {
72    pub window_title: String,
73    pub window_width: i32,
74    pub window_height: i32,
75    pub high_dpi: bool,
76    pub sample_count: i32,
77}
78impl Default for Conf {
79    fn default() -> Self {
80        window_conf("Ferravex")
81    }
82}
83pub fn window_conf(title: &str) -> Conf {
84    Conf {
85        window_title: title.into(),
86        window_width: 1280,
87        window_height: 800,
88        high_dpi: true,
89        sample_count: 4,
90    }
91}
92#[derive(Clone, Debug, Default)]
93pub struct Mesh {
94    pub vertices: Vec<Vertex>,
95    pub indices: Vec<u16>,
96    pub texture: Option<()>,
97}
98#[repr(C)]
99#[derive(Clone, Copy, Debug)]
100pub struct Vertex {
101    pub position: Vec3,
102    pub uv: Vec2,
103    pub color: [u8; 4],
104    pub normal: Vec4,
105}
106impl Vertex {
107    pub fn new2(position: Vec3, uv: Vec2, color: Color) -> Self {
108        Self {
109            position,
110            uv,
111            color: color.to_rgba(),
112            normal: Vec4::Y,
113        }
114    }
115}
116#[repr(C)]
117#[derive(Clone, Copy, Debug)]
118pub struct Batch {
119    pub start: u32,
120    pub count: u32,
121    pub depth: bool,
122}
123#[derive(Clone, Copy, Debug)]
124pub struct Camera2D {
125    pub target: Vec2,
126    pub zoom: Vec2,
127    pub offset: Vec2,
128    pub rotation: f32,
129}
130impl Default for Camera2D {
131    fn default() -> Self {
132        Self {
133            target: Vec2::ZERO,
134            zoom: Vec2::ONE,
135            offset: Vec2::ZERO,
136            rotation: 0.,
137        }
138    }
139}
140impl Camera2D {
141    pub fn from_display_rect(r: Rect) -> Self {
142        Self {
143            target: r.center(),
144            zoom: vec2(2. / r.w, 2. / r.h),
145            ..Self::default()
146        }
147    }
148}
149#[derive(Clone, Copy, Debug)]
150pub struct Camera3D {
151    pub position: Vec3,
152    pub target: Vec3,
153    pub up: Vec3,
154    pub fovy: f32,
155    pub aspect: Option<f32>,
156    pub z_near: f32,
157    pub z_far: f32,
158}
159impl Default for Camera3D {
160    fn default() -> Self {
161        Self {
162            position: vec3(0., 5., 10.),
163            target: Vec3::ZERO,
164            up: Vec3::Y,
165            fovy: 45f32.to_radians(),
166            aspect: None,
167            z_near: 0.1,
168            z_far: 1000.,
169        }
170    }
171}
172pub trait Camera {
173    fn matrix(&self, w: f32, h: f32) -> Mat4;
174    fn depth(&self) -> bool;
175    fn position(&self) -> Option<Vec3> {
176        None
177    }
178}
179impl Camera for Camera2D {
180    fn matrix(&self, _: f32, _: f32) -> Mat4 {
181        Mat4::from_translation(self.offset.extend(0.))
182            * Mat4::from_scale(vec3(self.zoom.x, -self.zoom.y, 1.))
183            * Mat4::from_rotation_z(-self.rotation.to_radians())
184            * Mat4::from_translation((-self.target).extend(0.))
185    }
186    fn depth(&self) -> bool {
187        false
188    }
189}
190impl Camera for Camera3D {
191    fn position(&self) -> Option<Vec3> {
192        Some(self.position)
193    }
194    fn matrix(&self, w: f32, h: f32) -> Mat4 {
195        Mat4::perspective_rh_gl(
196            self.fovy,
197            self.aspect.unwrap_or(w / h),
198            self.z_near,
199            self.z_far,
200        ) * Mat4::look_at_rh(self.position, self.target, self.up)
201    }
202    fn depth(&self) -> bool {
203        true
204    }
205}
206#[derive(Clone, Copy, Debug, PartialEq, Eq)]
207#[repr(u32)]
208pub enum KeyCode {
209    F1 = 0xffbe,
210    F2 = 0xffbf,
211    F3 = 0xffc0,
212    F4 = 0xffc1,
213    F5 = 0xffc2,
214    F6 = 0xffc3,
215    Space = 32,
216    A = 97,
217    B = 98,
218    C = 99,
219    D = 100,
220    E = 101,
221    F = 102,
222    G = 103,
223    H = 104,
224    I = 105,
225    J = 106,
226    K = 107,
227    L = 108,
228    M = 109,
229    N = 110,
230    O = 111,
231    P = 112,
232    Q = 113,
233    R = 114,
234    S = 115,
235    T = 116,
236    U = 117,
237    V = 118,
238    W = 119,
239    X = 120,
240    Y = 121,
241    Z = 122,
242    Key0 = 48,
243    Key1 = 49,
244    Key2 = 50,
245    Key3 = 51,
246    Key4 = 52,
247    Escape = 0xff1b,
248    Enter = 0xff0d,
249    Tab = 0xff09,
250    Backspace = 0xff08,
251    Left = 0xff51,
252    Up = 0xff52,
253    Right = 0xff53,
254    Down = 0xff54,
255    LeftShift = 0xffe1,
256    RightShift = 0xffe2,
257    LeftControl = 0xffe3,
258    RightControl = 0xffe4,
259}
260#[derive(Clone, Copy, Debug)]
261#[repr(u32)]
262pub enum MouseButton {
263    Left = 1,
264    Middle = 2,
265    Right = 3,
266}
267#[derive(Clone, Copy, Debug, PartialEq, Eq)]
268pub enum TouchPhase {
269    Started,
270    Moved,
271    Stationary,
272    Ended,
273    Cancelled,
274}
275#[derive(Clone, Copy, Debug)]
276pub struct Touch {
277    pub id: u64,
278    pub position: Vec2,
279    pub phase: TouchPhase,
280}
281struct State {
282    w: u32,
283    h: u32,
284    dt: f32,
285    dpi: f32,
286    graphics_reset: bool,
287    time: f64,
288    matrix: Mat4,
289    depth: bool,
290    frustum: Option<ferravex_graphics::Frustum>,
291    shadow_frustum: Option<ferravex_graphics::Frustum>,
292    eye: Option<Vec3>,
293    visibility: visibility::VisibilitySettings,
294    visibility_stats: visibility::VisibilityStats,
295    clear: Color,
296    vertices: Vec<[f32; 8]>,
297    batches: Vec<Batch>,
298    retained: retained::Frame,
299    effect_stats: effects::EffectStats,
300    lighting: Option<shaders::LitSettings>,
301    shader: Option<material::ShaderMaterial>,
302    shader_params: [f32; 16],
303    presentation: preferences::Preferences,
304    pending_presentation: Option<preferences::Preferences>,
305    details_open: bool,
306    details_error: bool,
307    resolution: u8,
308    performance: performance::Runtime,
309    shadow_detail: u8,
310    light_detail: u8,
311    look: Look,
312    look_override: Option<Look>,
313    world_colors: bool,
314    post: post::PostFx,
315    post_override: Option<post::PostFx>,
316    post_hud: bool,
317    glow: bool,
318    quality: lighting::Quality,
319    authored_quality: lighting::Quality,
320    preferred_quality: Option<lighting::Quality>,
321    quality_override: Option<lighting::Quality>,
322    points: Vec<lighting::PointLight>,
323    sun: Option<lighting::SunShadow>,
324    input: input::PlatformInput,
325    input_enabled: bool,
326    controls_open: bool,
327    keys: BTreeSet<u32>,
328    pressed: BTreeSet<u32>,
329    buttons: BTreeSet<u32>,
330    touch_buttons: BTreeSet<u32>,
331    clicks: BTreeSet<u32>,
332    mouse: Vec2,
333    delta: Vec2,
334    wheel: f32,
335    wheel_x: f32,
336    touches: Vec<Touch>,
337    grab: bool,
338    visible: bool,
339    touch_mouse: bool,
340    #[cfg(not(target_arch = "wasm32"))]
341    screenshots: Vec<String>,
342    future: Option<Pin<Box<dyn Future<Output = ()>>>>,
343    autoplay: bool,
344    frame: u64,
345    in_frame: bool,
346}
347impl Default for State {
348    fn default() -> Self {
349        let mut s = Self {
350            w: 1280,
351            h: 800,
352            dt: 1. / 60.,
353            dpi: 1.,
354            graphics_reset: false,
355            time: 0.,
356            matrix: Mat4::IDENTITY,
357            depth: false,
358            frustum: None,
359            shadow_frustum: None,
360            eye: None,
361            visibility: Default::default(),
362            visibility_stats: Default::default(),
363            clear: BLACK,
364            vertices: Vec::new(),
365            batches: Vec::new(),
366            retained: retained::Frame::default(),
367            effect_stats: effects::EffectStats::default(),
368            lighting: None,
369            shader: None,
370            shader_params: [0.; 16],
371            presentation: Default::default(),
372            pending_presentation: None,
373            details_open: false,
374            details_error: false,
375            resolution: 0,
376            performance: performance::Runtime::default(),
377            shadow_detail: 0,
378            light_detail: 0,
379            look: Look::Authored,
380            look_override: None,
381            world_colors: false,
382            post: post::PostFx::off(),
383            post_override: None,
384            post_hud: false,
385            glow: false,
386            quality: Default::default(),
387            authored_quality: Default::default(),
388            preferred_quality: None,
389            quality_override: None,
390            points: Vec::new(),
391            sun: None,
392            input: Default::default(),
393            input_enabled: false,
394            controls_open: false,
395            keys: BTreeSet::new(),
396            pressed: BTreeSet::new(),
397            buttons: BTreeSet::new(),
398            touch_buttons: BTreeSet::new(),
399            clicks: BTreeSet::new(),
400            mouse: Vec2::ZERO,
401            delta: Vec2::ZERO,
402            wheel: 0.,
403            wheel_x: 0.,
404            touches: Vec::new(),
405            grab: false,
406            visible: true,
407            touch_mouse: true,
408            #[cfg(not(target_arch = "wasm32"))]
409            screenshots: Vec::new(),
410            future: None,
411            autoplay: false,
412            frame: 0,
413            in_frame: false,
414        };
415        s.default_camera();
416        s
417    }
418}
419impl State {
420    fn effective_shadow_detail(&self) -> u8 {
421        if self.presentation.adaptive {
422            let level = self.performance.budget.level();
423            if level >= 3 {
424                return 1;
425            }
426            if level >= 1
427                && (self.shadow_detail == 3
428                    || self.shadow_detail == 0 && self.quality == lighting::Quality::High)
429            {
430                return 2;
431            }
432        }
433        self.shadow_detail
434    }
435    fn refresh_environment(&mut self) {
436        self.retained.environment.update_details(
437            &self.points,
438            self.sun,
439            self.quality,
440            self.eye,
441            self.effective_shadow_detail(),
442            self.light_detail,
443        );
444        // All mesh submissions share the current light volume. Extract and
445        // normalize its six planes once per environment update, not per draw.
446        self.shadow_frustum = self.retained.environment.frustum();
447    }
448    fn submit(
449        &mut self,
450        mesh: &retained::ResidentMesh,
451        model: Mat4,
452        bounds: ferravex_graphics::Bounds,
453        skin: Option<&skinning::SkinPalette>,
454    ) -> bool {
455        let visible = self.test_visibility(bounds, model);
456        let casts = self.depth
457            && mesh.is_opaque()
458            && self.shader.as_ref().is_none_or(|m| {
459                m.0.options.blend == material::BlendMode::Opaque && m.0.options.casts_shadows
460            })
461            && self
462                .shadow_frustum
463                .is_some_and(|f| f.intersects_bounds(bounds, model));
464        if !visible && !casts {
465            return false;
466        }
467        let recorded = self.retained.record_style(
468            mesh,
469            model,
470            self.matrix,
471            self.depth,
472            retained::DrawStyle {
473                light: self.lighting,
474                look: if self.world_colors {
475                    self.look_override.unwrap_or(self.look)
476                } else {
477                    Look::Authored
478                },
479                material: self.shader.as_ref(),
480                params: self.shader_params,
481                shadow_only: !visible,
482                skip_shadow: !casts,
483                skin,
484            },
485        );
486        visible && recorded
487    }
488    fn test_visibility(&mut self, bounds: ferravex_graphics::Bounds, model: Mat4) -> bool {
489        let result = visibility::classify(bounds, model, self.frustum, self.eye, self.visibility);
490        self.visibility_stats.record(result);
491        result == visibility::Visibility::Visible
492    }
493    fn default_camera(&mut self) {
494        self.matrix = Mat4::orthographic_rh_gl(0., self.w as f32, self.h as f32, 0., -1., 1.);
495        self.depth = false;
496        self.world_colors = false;
497        self.frustum = None;
498        self.eye = None;
499    }
500    fn push(&mut self, vertices: impl IntoIterator<Item = (Vec3, Vec3, Color)>, model: Mat4) {
501        let iter = vertices.into_iter();
502        let (lower, _) = iter.size_hint();
503        if lower > 0 {
504            self.vertices.reserve(lower);
505        }
506        let start = self.vertices.len() as u32;
507        let apply_look = self
508            .world_colors
509            .then(|| self.look_override.unwrap_or(self.look))
510            .filter(|&look| look != ferravex_graphics::Look::Authored);
511        if let Some(lighting) = self.lighting {
512            let normal_matrix = model
513                .try_inverse()
514                .map(|m| m.transpose())
515                .unwrap_or(Mat4::IDENTITY);
516            let mat = self.matrix;
517            for (p, n, mut c) in iter {
518                let p = model.transform_point3(p);
519                c = lighting.shade_vertex(p, normal_matrix.transform_vector3(n), c);
520                if let Some(look) = apply_look {
521                    c = look.shade(c);
522                }
523                let v = mat.x_axis * p.x + mat.y_axis * p.y + mat.z_axis * p.z + mat.w_axis;
524                self.vertices.push([v.x, v.y, v.z, v.w, c.r, c.g, c.b, c.a]);
525            }
526        } else {
527            let mvp = if model == Mat4::IDENTITY {
528                self.matrix
529            } else {
530                self.matrix * model
531            };
532            if let Some(look) = apply_look {
533                for (p, _, c) in iter {
534                    let c = look.shade(c);
535                    let v = mvp.x_axis * p.x + mvp.y_axis * p.y + mvp.z_axis * p.z + mvp.w_axis;
536                    self.vertices.push([v.x, v.y, v.z, v.w, c.r, c.g, c.b, c.a]);
537                }
538            } else {
539                for (p, _, c) in iter {
540                    let v = mvp.x_axis * p.x + mvp.y_axis * p.y + mvp.z_axis * p.z + mvp.w_axis;
541                    self.vertices.push([v.x, v.y, v.z, v.w, c.r, c.g, c.b, c.a]);
542                }
543            }
544        }
545        let count = self.vertices.len() as u32 - start;
546        if count == 0 {
547            return;
548        }
549        self.record_immediate(start, count, self.depth);
550    }
551    /// Effective post tier and accessibility-capped settings for this state.
552    fn post_effective(&self) -> (post::PostTier, post::PostFx) {
553        let fx = self.post_override.unwrap_or(self.post);
554        let adaptive = self
555            .presentation
556            .adaptive
557            .then(|| self.performance.budget.level());
558        let tier = post::tier(
559            &fx,
560            self.quality_override.or(self.preferred_quality),
561            self.authored_quality,
562            adaptive,
563        );
564        let policy = preferences::feedback_policy();
565        (tier, post::accessible(fx, policy.reduced_flash()))
566    }
567    /// Record the frame's single world/HUD post boundary when post is active.
568    fn post_boundary(&mut self) -> bool {
569        if self.post_hud || self.post_effective().0 == post::PostTier::Off {
570            return false;
571        }
572        self.post_hud = true;
573        self.retained
574            .commands
575            .push(retained::Command { kind: 4, index: 0 });
576        true
577    }
578    /// Automatic boundary when world colors end (`set_default_camera` or
579    /// `set_world_colors(false)`), unless the game disabled `auto_hud`.
580    fn post_auto_boundary(&mut self) {
581        if self.world_colors && self.post_override.unwrap_or(self.post).auto_hud {
582            self.post_boundary();
583        }
584    }
585    /// Records identity-model geometry such as 2D shapes, HUD text and 3D lines.
586    ///
587    /// Produces the same vertices as `push(.., Mat4::IDENTITY)` without the
588    /// per-vertex model/normal transforms or inverse; an unlit color is graded once.
589    #[inline(never)]
590    fn push_flat(
591        &mut self,
592        points: impl ExactSizeIterator<Item = Vec3>,
593        normal: Vec3,
594        color: Color,
595    ) {
596        if points.len() == 0 {
597            return;
598        }
599        self.reserve_vertices(points.len());
600        let start = self.vertices.len() as u32;
601        let look = self.world_look();
602        let matrix = self.matrix;
603        let vertex = |p: Vec3, c: Color| {
604            let v = matrix * p.extend(1.);
605            [v.x, v.y, v.z, v.w, c.r, c.g, c.b, c.a]
606        };
607        match self.lighting {
608            None => {
609                let c = look.map_or(color, |look| look.shade(color));
610                self.vertices.extend(points.map(|p| vertex(p, c)));
611            }
612            Some(l) => self.vertices.extend(points.map(|p| {
613                let c = l.shade_vertex(p, normal, color);
614                vertex(p, look.map_or(c, |look| look.shade(c)))
615            })),
616        }
617        let count = self.vertices.len() as u32 - start;
618        self.record_immediate(start, count, self.depth);
619    }
620    /// Grows vertex storage to a power-of-two capacity, the same sequence as
621    /// per-vertex pushes, so frame-to-frame peaks rarely reallocate.
622    fn reserve_vertices(&mut self, count: usize) {
623        let needed = self.vertices.len() + count;
624        if needed > self.vertices.capacity() {
625            self.vertices
626                .reserve_exact(needed.next_power_of_two() - self.vertices.len());
627        }
628    }
629    /// The world palette applied to immediate colors, if any.
630    fn world_look(&self) -> Option<Look> {
631        self.world_colors
632            .then(|| self.look_override.unwrap_or(self.look))
633    }
634    /// [`State::push_flat`] for screen-plane points with a +Z normal. Kept out of
635    /// line: every 2D primitive shares one copy of the vertex loop.
636    #[inline(never)]
637    fn push_flat_2d(&mut self, points: &[Vec2], color: Color) {
638        if self.lighting.is_some() {
639            return self.push_flat(points.iter().map(|p| p.extend(0.)), Vec3::Z, color);
640        }
641        if points.is_empty() {
642            return;
643        }
644        self.reserve_vertices(points.len());
645        let start = self.vertices.len() as u32;
646        let c = self.world_look().map_or(color, |look| look.shade(color));
647        // `matrix * (x, y, 0, 1)` without the zero z column. Only the sign of
648        // an exactly zero coordinate can differ from the general product.
649        let (x, y, w) = (self.matrix.x_axis, self.matrix.y_axis, self.matrix.w_axis);
650        self.vertices.extend(points.iter().map(|p| {
651            let v = x * p.x + y * p.y + w;
652            [v.x, v.y, v.z, v.w, c.r, c.g, c.b, c.a]
653        }));
654        self.record_immediate(start, points.len() as u32, self.depth);
655    }
656    fn record_immediate(&mut self, start: u32, count: u32, depth: bool) {
657        if self.glow {
658            // Additive, non-depth-writing effect batch; see `post::with_glow`.
659            let flags = depth as u32 | 2 | 4;
660            if let Some(last) = self.retained.effects.last_mut().filter(|b| {
661                b.flags == flags && self.retained.commands.last().is_some_and(|c| c.kind == 2)
662            }) {
663                last.count += count;
664            } else {
665                self.retained.commands.push(retained::Command {
666                    kind: 2,
667                    index: self.retained.effects.len() as u32,
668                });
669                self.retained.effects.push(effects::EffectBatch {
670                    start,
671                    count,
672                    flags,
673                });
674            }
675            return;
676        }
677        if let Some(last) = self.batches.last_mut().filter(|b| {
678            b.depth == depth && self.retained.commands.last().is_some_and(|c| c.kind == 0)
679        }) {
680            last.count += count;
681        } else {
682            self.retained.commands.push(retained::Command {
683                kind: 0,
684                index: self.batches.len() as u32,
685            });
686            self.batches.push(Batch {
687                start,
688                count,
689                depth,
690            });
691        }
692    }
693}
694thread_local! {static STATE:RefCell<State>=RefCell::new(State::default());}
695fn read<T>(f: impl FnOnce(&State) -> T) -> T {
696    STATE.with(|s| f(&s.borrow()))
697}
698fn edit<T>(f: impl FnOnce(&mut State) -> T) -> T {
699    STATE.with(|s| f(&mut s.borrow_mut()))
700}
701pub fn set_camera(camera: &impl Camera) {
702    edit(|s| {
703        s.matrix = camera.matrix(s.w as f32, s.h as f32);
704        s.depth = camera.depth();
705        s.world_colors = true;
706        s.eye = camera.position();
707        if s.eye.is_some() {
708            s.refresh_environment();
709        }
710        s.frustum = if s.depth {
711            ferravex_graphics::Frustum::from_matrix(
712                s.matrix,
713                ferravex_graphics::ClipDepth::NegativeOneToOne,
714            )
715        } else {
716            None
717        };
718    });
719}
720/// Select a palette for world draws. Default-camera HUD drawing stays authored.
721pub fn set_look(look: Look) {
722    edit(|s| s.look = look);
723}
724pub fn look() -> Look {
725    read(|s| s.look_override.unwrap_or(s.look))
726}
727/// Explicit world/HUD boundary for games drawing in screen coordinates.
728/// Turning world colors off is also the post-processing HUD boundary; see [`post`].
729pub fn set_world_colors(enabled: bool) {
730    edit(|s| {
731        if !enabled {
732            s.post_auto_boundary();
733        }
734        s.world_colors = enabled
735    });
736}
737/// Restore the screen-space HUD camera. After a world camera this is also the
738/// post-processing HUD boundary; see [`post`].
739pub fn set_default_camera() {
740    edit(|s| {
741        s.post_auto_boundary();
742        s.default_camera();
743    })
744}
745pub fn set_lighting(settings: Option<shaders::LitSettings>) {
746    edit(|s| s.lighting = settings)
747}
748pub fn clear_background(c: Color) {
749    edit(|s| {
750        s.clear = c;
751        s.vertices.clear();
752        s.batches.clear();
753        s.retained.clear();
754        s.post_hud = false;
755        s.effect_stats = effects::EffectStats::default();
756        s.points.clear();
757        s.sun = None;
758        s.refresh_environment();
759        s.visibility_stats = Default::default();
760    });
761}
762pub fn draw_mesh(m: &Mesh) {
763    draw_mesh_transformed(m, Mat4::IDENTITY)
764}
765/// Submit an immutable mesh snapshot. Compatible adjacent draws share one instanced call.
766/// Returns false when culled, for invalid transforms or a full frame instance budget.
767pub(crate) fn set_shader(shader: Option<material::ShaderMaterial>, params: [f32; 16]) {
768    edit(|s| {
769        s.shader = shader;
770        s.shader_params = params;
771    });
772}
773pub fn draw_resident(mesh: &retained::ResidentMesh, model: Mat4) -> bool {
774    edit(|s| {
775        let bounds = s
776            .shader
777            .as_ref()
778            .map_or(mesh.bounds(), |m| m.padded(mesh.bounds()));
779        s.submit(mesh, model, bounds, None)
780    })
781}
782/// Submit a hidden opaque caster, for example a first-person character body.
783pub fn draw_shadow(mesh: &retained::ResidentMesh, model: Mat4) -> bool {
784    draw_shadow_pose(mesh, model, mesh.bounds(), None)
785}
786/// Record a GPU-skinned mesh using conservative deformed bounds. Position and
787/// inverse-transpose normal palettes are copied into this frame; later palette
788/// edits cannot change already recorded draws or their matching shadow pass.
789pub fn draw_skinned(
790    mesh: &skinning::SkinnedMesh,
791    model: Mat4,
792    palette: &skinning::SkinPalette,
793) -> bool {
794    let Ok(bounds) = mesh.bounds(palette) else {
795        return false;
796    };
797    edit(|s| {
798        let bounds = s.shader.as_ref().map_or(bounds, |m| m.padded(bounds));
799        s.submit(mesh.resident(), model, bounds, Some(palette))
800    })
801}
802/// Draw an animated first-person prop over world geometry, without casting or
803/// receiving world shadows. Uses the current perspective and lighting; call
804/// after world draws. It never changes the camera or following draw state.
805pub fn draw_skinned_viewmodel(
806    mesh: &skinning::SkinnedMesh,
807    model: Mat4,
808    palette: &skinning::SkinPalette,
809) -> bool {
810    if mesh.bounds(palette).is_err() {
811        return false;
812    }
813    edit(|s| {
814        s.retained.record_style(
815            mesh.resident(),
816            model,
817            s.matrix,
818            false,
819            retained::DrawStyle {
820                light: s.lighting,
821                look: if s.world_colors {
822                    s.look_override.unwrap_or(s.look)
823                } else {
824                    Look::Authored
825                },
826                material: s.shader.as_ref(),
827                params: s.shader_params,
828                skip_shadow: true,
829                skin: Some(palette),
830                ..Default::default()
831            },
832        )
833    })
834}
835pub fn draw_skinned_shadow(
836    mesh: &skinning::SkinnedMesh,
837    model: Mat4,
838    palette: &skinning::SkinPalette,
839) -> bool {
840    let Ok(bounds) = mesh.bounds(palette) else {
841        return false;
842    };
843    draw_shadow_pose(mesh.resident(), model, bounds, Some(palette))
844}
845fn draw_shadow_pose(
846    mesh: &retained::ResidentMesh,
847    model: Mat4,
848    bounds: ferravex_graphics::Bounds,
849    skin: Option<&skinning::SkinPalette>,
850) -> bool {
851    edit(|s| {
852        let bounds = s.shader.as_ref().map_or(bounds, |m| m.padded(bounds));
853        if !s.depth
854            || !mesh.is_opaque()
855            || s.shader.as_ref().is_some_and(|m| {
856                !m.0.options.casts_shadows || m.0.options.blend != material::BlendMode::Opaque
857            })
858            || !s
859                .shadow_frustum
860                .is_some_and(|f| f.intersects_bounds(bounds, model))
861        {
862            return false;
863        }
864        s.retained.record_style(
865            mesh,
866            model,
867            s.matrix,
868            s.depth,
869            retained::DrawStyle {
870                light: s.lighting,
871                look: Look::Authored,
872                material: s.shader.as_ref(),
873                params: s.shader_params,
874                shadow_only: true,
875                skip_shadow: false,
876                skin,
877            },
878        )
879    })
880}
881pub fn set_quality(quality: lighting::Quality) {
882    edit(|s| {
883        s.authored_quality = quality;
884        s.quality = s
885            .quality_override
886            .or(s.preferred_quality)
887            .unwrap_or(quality);
888        s.refresh_environment();
889    });
890}
891/// User preference overrides authored quality; explicit env/URL overrides win.
892pub fn set_quality_preference(quality: Option<lighting::Quality>) {
893    edit(|s| {
894        s.preferred_quality = quality;
895        s.quality = s.quality_override.or(quality).unwrap_or(s.authored_quality);
896        s.refresh_environment();
897    });
898}
899/// Independent presentation detail overrides. Zero follows device/preset defaults.
900pub fn set_fidelity(resolution: u8, shadows: u8, lights: u8) -> bool {
901    if resolution > 5 || shadows > 3 || lights > 4 {
902        return false;
903    }
904    edit(|s| {
905        s.resolution = resolution;
906        s.shadow_detail = shadows;
907        s.light_detail = lights;
908        s.refresh_environment();
909    });
910    true
911}
912pub fn quality() -> lighting::Quality {
913    read(|s| s.quality)
914}
915/// Effective shadow tier, including the independent player detail override.
916pub fn shadow_quality() -> lighting::Quality {
917    read(|s| match s.effective_shadow_detail() {
918        1 => lighting::Quality::Low,
919        2 => lighting::Quality::Medium,
920        3 => lighting::Quality::High,
921        _ => s.quality,
922    })
923}
924pub fn set_point_lights(lights: &[lighting::PointLight]) -> Result<(), &'static str> {
925    if lights.len() > lighting::MAX_POINT_LIGHTS || lights.iter().any(|l| !l.valid()) {
926        return Err("invalid point lights or capacity exceeded");
927    }
928    edit(|s| {
929        s.points.clear();
930        s.points.extend_from_slice(lights);
931        s.refresh_environment();
932    });
933    Ok(())
934}
935pub fn set_sun_shadow(sun: Option<lighting::SunShadow>) -> Result<(), &'static str> {
936    if sun.is_some_and(|s| !s.valid()) {
937        return Err("invalid sun shadow");
938    }
939    edit(|s| {
940        s.sun = sun;
941        s.refresh_environment();
942    });
943    Ok(())
944}
945fn quality_override(quality: lighting::Quality) {
946    edit(|s| {
947        s.quality_override = Some(quality);
948        s.quality = quality;
949        s.refresh_environment();
950    });
951}
952pub fn set_visibility(settings: visibility::VisibilitySettings) -> bool {
953    if !settings.valid() {
954        return false;
955    }
956    edit(|s| s.visibility = settings);
957    true
958}
959pub fn visibility_stats() -> visibility::VisibilityStats {
960    read(|s| s.visibility_stats)
961}
962pub fn draw_lod(
963    chain: &visibility::LodChain,
964    model: Mat4,
965    state: &mut visibility::LodState,
966) -> bool {
967    edit(|s| {
968        let distance = s.eye.map_or(0., |eye| {
969            visibility::distance_to_bounds(chain.bounds(), model, eye)
970        });
971        let mesh = chain.select(distance, state);
972        let bounds = s
973            .shader
974            .as_ref()
975            .map_or(chain.bounds(), |m| m.padded(chain.bounds()));
976        s.submit(mesh, model, bounds, None)
977    })
978}
979pub fn draw_mesh_transformed(m: &Mesh, model: Mat4) {
980    edit(|s| {
981        s.push(
982            m.indices
983                .as_chunks::<3>()
984                .0
985                .iter()
986                .filter_map(|[a, b, c]| {
987                    let v = [
988                        m.vertices.get(*a as usize)?,
989                        m.vertices.get(*b as usize)?,
990                        m.vertices.get(*c as usize)?,
991                    ];
992                    v.iter()
993                        .all(|v| v.position.is_finite() && v.normal.is_finite())
994                        .then_some(v)
995                })
996                .flatten()
997                .map(|v| {
998                    (
999                        v.position,
1000                        v.normal.truncate(),
1001                        Color::from_rgba(v.color[0], v.color[1], v.color[2], v.color[3]),
1002                    )
1003                }),
1004            model,
1005        )
1006    })
1007}
1008pub fn draw_triangle(a: Vec2, b: Vec2, c: Vec2, color: Color) {
1009    edit(|s| s.push_flat_2d(&[a, b, c], color))
1010}
1011/// Two triangles `(a, b, d)` and `(d, b, e)`, as drawn by [`draw_rectangle`].
1012fn rectangle_vertices(x: f32, y: f32, w: f32, h: f32) -> [Vec2; 6] {
1013    let a = vec2(x, y);
1014    let b = vec2(x + w, y);
1015    let d = vec2(x, y + h);
1016    let e = vec2(x + w, y + h);
1017    [a, b, d, d, b, e]
1018}
1019pub fn draw_rectangle(x: f32, y: f32, w: f32, h: f32, c: Color) {
1020    edit(|s| s.push_flat_2d(&rectangle_vertices(x, y, w, h), c))
1021}
1022/// Two triangles covering a segment of the given width, as drawn by [`draw_line`].
1023fn line_vertices(x1: f32, y1: f32, x2: f32, y2: f32, width: f32) -> [Vec2; 6] {
1024    let a = vec2(x1, y1);
1025    let b = vec2(x2, y2);
1026    let d = (b - a).normalize_or_zero();
1027    let n = vec2(-d.y, d.x) * width * 0.5;
1028    [a + n, a - n, b + n, b + n, a - n, b - n]
1029}
1030pub fn draw_line(x1: f32, y1: f32, x2: f32, y2: f32, width: f32, c: Color) {
1031    edit(|s| s.push_flat_2d(&line_vertices(x1, y1, x2, y2, width), c))
1032}
1033pub fn draw_rectangle_lines(x: f32, y: f32, w: f32, h: f32, t: f32, c: Color) {
1034    let mut points = [Vec2::ZERO; 24];
1035    for (chunk, line) in points.as_chunks_mut::<6>().0.iter_mut().zip([
1036        line_vertices(x, y, x + w, y, t),
1037        line_vertices(x + w, y, x + w, y + h, t),
1038        line_vertices(x + w, y + h, x, y + h, t),
1039        line_vertices(x, y + h, x, y, t),
1040    ]) {
1041        *chunk = line;
1042    }
1043    edit(|s| s.push_flat_2d(&points, c))
1044}
1045/// Unit `(cos, sin)` pairs for the start and end angle of each [`draw_circle`]
1046/// wedge, computed once with exactly the expressions [`draw_poly`] uses.
1047fn circle_ring() -> &'static [[Vec2; 2]; 32] {
1048    static RING: std::sync::OnceLock<[[Vec2; 2]; 32]> = std::sync::OnceLock::new();
1049    RING.get_or_init(|| {
1050        std::array::from_fn(|i| {
1051            let (a, b) = poly_angles(0., i as u8, 32);
1052            [vec2(a.cos(), a.sin()), vec2(b.cos(), b.sin())]
1053        })
1054    })
1055}
1056fn poly_angles(rotation: f32, i: u8, sides: u8) -> (f32, f32) {
1057    let a = rotation.to_radians() + i as f32 * std::f32::consts::TAU / sides as f32;
1058    (a, a + std::f32::consts::TAU / sides as f32)
1059}
1060pub fn draw_poly(x: f32, y: f32, sides: u8, r: f32, rotation: f32, c: Color) {
1061    const CHUNK: usize = 32;
1062    let sides = sides.max(3);
1063    let center = vec2(x, y);
1064    let ring = (sides == 32 && rotation == 0.).then(circle_ring);
1065    let mut points = [Vec2::ZERO; CHUNK * 3];
1066    edit(|s| {
1067        for first in (0..sides).step_by(CHUNK) {
1068            let last = sides.min(first.saturating_add(CHUNK as u8));
1069            for (i, chunk) in (first..last).zip(points.as_chunks_mut::<3>().0) {
1070                let [a, b] = ring.map_or_else(
1071                    || {
1072                        let (a, b) = poly_angles(rotation, i, sides);
1073                        [vec2(a.cos(), a.sin()), vec2(b.cos(), b.sin())]
1074                    },
1075                    |ring| ring[i as usize],
1076                );
1077                *chunk = [
1078                    center,
1079                    vec2(x + r * a.x, y + r * a.y),
1080                    vec2(x + r * b.x, y + r * b.y),
1081                ];
1082            }
1083            s.push_flat_2d(&points[..(last - first) as usize * 3], c);
1084        }
1085    })
1086}
1087pub fn draw_circle(x: f32, y: f32, r: f32, c: Color) {
1088    draw_poly(x, y, 32, r, 0., c)
1089}
1090/// Unit points at `i * TAU / 40` for `i` in `0..=40`, shared by every outline.
1091fn outline_ring() -> &'static [Vec2; 41] {
1092    static RING: std::sync::OnceLock<[Vec2; 41]> = std::sync::OnceLock::new();
1093    RING.get_or_init(|| {
1094        std::array::from_fn(|i| {
1095            let a = i as f32 * std::f32::consts::TAU / 40.;
1096            vec2(a.cos(), a.sin())
1097        })
1098    })
1099}
1100pub fn draw_circle_lines(x: f32, y: f32, r: f32, t: f32, c: Color) {
1101    let ring = outline_ring();
1102    let mut points = [Vec2::ZERO; 40 * 6];
1103    for (i, chunk) in points.as_chunks_mut::<6>().0.iter_mut().enumerate() {
1104        let (a, b) = (ring[i], ring[i + 1]);
1105        *chunk = line_vertices(x + r * a.x, y + r * a.y, x + r * b.x, y + r * b.y, t);
1106    }
1107    edit(|s| s.push_flat_2d(&points, c))
1108}
1109/// Fan triangles for an ellipse rim sampled at the closed `units` ring.
1110fn ellipse_fan(x: f32, y: f32, rx: f32, ry: f32, rotation: f32, units: &[Vec2], out: &mut [Vec2]) {
1111    let angle = rotation.to_radians();
1112    let (sin, cos) = (angle.sin(), angle.cos());
1113    let point = |u: Vec2| {
1114        let p = vec2(rx * u.x, ry * u.y);
1115        vec2(x + p.x * cos - p.y * sin, y + p.x * sin + p.y * cos)
1116    };
1117    let mut prev = point(units[0]);
1118    for (chunk, &u) in out.as_chunks_mut::<3>().0.iter_mut().zip(&units[1..]) {
1119        let next = point(u);
1120        *chunk = [vec2(x, y), prev, next];
1121        prev = next;
1122    }
1123}
1124/// Filled ellipse of radii `rx`/`ry` rotated by `rotation` degrees, as a
1125/// 32-segment fan (96 vertices). The rim directions come from a shared table.
1126pub fn draw_ellipse(x: f32, y: f32, rx: f32, ry: f32, rotation: f32, c: Color) {
1127    let mut points = [Vec2::ZERO; 32 * 3];
1128    if let Some(table) = shapes::unit_circle(32) {
1129        // The closing point keeps its historical exact `TAU` evaluation.
1130        let mut units = [Vec2::ZERO; 33];
1131        units[..32].copy_from_slice(&table[..32]);
1132        units[32] = vec2(std::f32::consts::TAU.cos(), std::f32::consts::TAU.sin());
1133        ellipse_fan(x, y, rx, ry, rotation, &units, &mut points);
1134    }
1135    edit(|s| s.push_flat_2d(&points, c))
1136}
1137/// [`draw_ellipse`] with its segment count chosen from the on-screen size:
1138/// from 8 segments for a few-pixel blob shadow to 64 for a large ellipse, the
1139/// same curve density as [`shapes`] (2–16 segments per quarter turn). Emits
1140/// at most 192 vertices; non-finite input draws nothing.
1141///
1142/// ```
1143/// use ferravex_render::{Color, draw_ellipse_adaptive, input::host_frame};
1144/// host_frame(1. / 60., 320, 200, || {
1145///     // A small contact shadow uses far fewer than draw_ellipse's 96 vertices.
1146///     draw_ellipse_adaptive(160., 120., 6., 2.5, 0., Color::new(0., 0., 0., 0.4));
1147///     draw_ellipse_adaptive(160., 80., 140., 60., 10., Color::from_hex(0x5bd5d8));
1148/// });
1149/// ```
1150pub fn draw_ellipse_adaptive(x: f32, y: f32, rx: f32, ry: f32, rotation: f32, c: Color) {
1151    if ![x, y, rx, ry, rotation].iter().all(|v| v.is_finite()) {
1152        return;
1153    }
1154    edit(|s| {
1155        let px = shapes::Sink::device_pixel_of(s);
1156        let n = shapes::curve_segments(rx.abs().max(ry.abs()) / px).max(8);
1157        let Some(units) = shapes::unit_circle(n) else {
1158            return;
1159        };
1160        let mut points = [Vec2::ZERO; 64 * 3];
1161        let points = &mut points[..n * 3];
1162        ellipse_fan(x, y, rx, ry, rotation, units, points);
1163        s.push_flat_2d(points, c)
1164    })
1165}
1166pub fn draw_line_3d(a: Vec3, b: Vec3, c: Color) {
1167    let d = (b - a).normalize_or_zero();
1168    let n = d
1169        .cross(if d.y.abs() < 0.9 { Vec3::Y } else { Vec3::X })
1170        .normalize_or_zero()
1171        * 0.015;
1172    edit(|s| {
1173        s.push_flat(
1174            [a + n, a - n, b + n, b + n, a - n, b - n].into_iter(),
1175            Vec3::Y,
1176            c,
1177        )
1178    });
1179}
1180/// Distinct `(size, color)` cuboids [`draw_cube`] keeps resident between calls.
1181const CUBE_CACHE: usize = 64;
1182/// Draws an axis-aligned resident cuboid.
1183///
1184/// Recently used size/color combinations reuse one resident mesh, so a steady
1185/// scene neither allocates nor re-uploads geometry each frame. At most 64
1186/// combinations stay cached (oldest replaced first); continuously varying sizes
1187/// still work, at the cost of a fresh mesh per new combination.
1188///
1189/// ```
1190/// use ferravex_render::{draw_cube, vec3, WHITE};
1191/// draw_cube(vec3(0., 1., 0.), vec3(1., 2., 1.), None, WHITE);
1192/// ```
1193pub fn draw_cube(position: Vec3, size: Vec3, _texture: Option<()>, color: Color) {
1194    type Key = [u32; 7];
1195    thread_local! {
1196        static CUBES: RefCell<(usize, Vec<(Key, mesh::Mesh3d)>)> =
1197            const { RefCell::new((0, Vec::new())) };
1198    }
1199    let key: Key = [size.x, size.y, size.z, color.r, color.g, color.b, color.a].map(f32::to_bits);
1200    let model = Mat4::from_rotation_translation(Quat::IDENTITY, position);
1201    CUBES.with(|cubes| {
1202        let mut cubes = cubes.borrow_mut();
1203        let (next, entries) = &mut *cubes;
1204        let index = match entries.iter().position(|(k, _)| *k == key) {
1205            Some(index) => index,
1206            None => {
1207                let entry = (key, mesh::Mesh3d::cuboid(size, color));
1208                if entries.len() < CUBE_CACHE {
1209                    entries.push(entry);
1210                    entries.len() - 1
1211                } else {
1212                    let index = *next;
1213                    *next = (index + 1) % CUBE_CACHE;
1214                    entries[index] = entry;
1215                    index
1216                }
1217            }
1218        };
1219        entries[index].1.draw_transformed(model);
1220    });
1221}
1222#[derive(Clone, Copy, Debug, Default)]
1223pub struct Font;
1224impl Font {
1225    pub fn populate_font_cache(&self, _chars: &[char], _size: u16) { /* Static glyphs need no atlas allocation. */
1226    }
1227}
1228pub fn get_default_font() -> Font {
1229    Font
1230}
1231#[derive(Clone, Copy, Debug)]
1232pub struct TextParams {
1233    pub font_size: u16,
1234    pub font_scale: f32,
1235    pub color: Color,
1236}
1237impl Default for TextParams {
1238    fn default() -> Self {
1239        Self {
1240            font_size: 20,
1241            font_scale: 1.,
1242            color: WHITE,
1243        }
1244    }
1245}
1246#[derive(Clone, Copy, Debug, Default)]
1247pub struct TextDimensions {
1248    pub width: f32,
1249    pub height: f32,
1250    pub offset_y: f32,
1251}
1252pub fn measure_text(t: &str, _font: Option<&Font>, size: u16, scale: f32) -> TextDimensions {
1253    let px = size as f32 * scale / 8.;
1254    TextDimensions {
1255        width: t.chars().count() as f32 * 6. * px,
1256        height: 7. * px,
1257        offset_y: 7. * px,
1258    }
1259}
1260pub fn draw_text(t: &str, x: f32, y: f32, size: f32, c: Color) -> TextDimensions {
1261    draw_text_ex(
1262        t,
1263        x,
1264        y,
1265        TextParams {
1266            font_size: 8,
1267            font_scale: size / 8.,
1268            color: c,
1269        },
1270    )
1271}
1272/// Draws classic 5×7 bitmap text with its baseline at `y`: one quad per
1273/// horizontal run of lit font pixels in each glyph row, each exactly one font
1274/// pixel tall. Coverage is identical to one quad per lit pixel with fewer
1275/// vertices. Use [`text::draw_text_styled`] with [`text::FontFace::Classic`]
1276/// for the same letters with vertically merged geometry, shadows and outlines.
1277///
1278/// ```
1279/// use ferravex_render::{TextParams, WHITE, draw_text_ex, input::host_frame};
1280/// let size = host_frame(1. / 60., 320, 120, || {
1281///     draw_text_ex("HUD 42", 8., 40., TextParams { font_size: 16, font_scale: 1., color: WHITE })
1282/// });
1283/// assert_eq!((size.width, size.height), (72., 14.));
1284/// ```
1285pub fn draw_text_ex(t: &str, mut x: f32, y: f32, p: TextParams) -> TextDimensions {
1286    let px = p.font_size as f32 * p.font_scale / 8.;
1287    // One stream borrow and batch record per string.
1288    edit(|s| {
1289        let mut sink = shapes::Sink::new(s);
1290        for c in t.chars() {
1291            for (row, bits) in font::glyph(c.to_ascii_uppercase()).into_iter().enumerate() {
1292                let top = y - 7. * px + row as f32 * px;
1293                // Maximal runs of set bits, left to right (bit 4 is column 0).
1294                let mut bits = bits & 0x1f;
1295                while bits != 0 {
1296                    let start = bits.leading_zeros() as usize - 3;
1297                    let len = (!(bits << (start + 3))).leading_zeros() as usize;
1298                    // Edges use the per-pixel arithmetic: left of the first
1299                    // pixel, and the last pixel's left plus one pixel.
1300                    let left = x + start as f32 * px;
1301                    let right = x + (start + len - 1) as f32 * px + px;
1302                    sink.rect_edges(left, top, right, top + px, p.color);
1303                    bits &= !(((1u8 << len) - 1) << (5 - start - len));
1304                }
1305            }
1306            x += 6. * px;
1307        }
1308    });
1309    measure_text(t, None, p.font_size, p.font_scale)
1310}
1311pub fn screen_width() -> f32 {
1312    read(|s| s.w as f32)
1313}
1314pub fn screen_height() -> f32 {
1315    read(|s| s.h as f32)
1316}
1317pub fn screen_dpi_scale() -> f32 {
1318    read(|s| s.dpi)
1319}
1320/// Hosts supply framebuffer pixels per logical input/UI pixel.
1321pub fn set_display_scale(scale: f32) {
1322    edit(|s| {
1323        s.dpi = if scale.is_finite() && scale > 0. {
1324            scale.clamp(0.5, 4.)
1325        } else {
1326            1.
1327        }
1328    });
1329}
1330/// Rebuild GPU caches on the next host frame without restarting game state.
1331pub fn request_graphics_reset() {
1332    edit(|s| s.graphics_reset = true);
1333}
1334
1335pub fn get_frame_time() -> f32 {
1336    read(|s| s.dt)
1337}
1338pub fn get_time() -> f64 {
1339    read(|s| s.time)
1340}
1341pub fn is_key_down(k: KeyCode) -> bool {
1342    read(|s| !s.controls_open && s.keys.contains(&(k as u32)))
1343}
1344pub fn is_key_pressed(k: KeyCode) -> bool {
1345    read(|s| !s.controls_open && s.pressed.contains(&(k as u32)))
1346}
1347pub fn is_mouse_button_down(k: MouseButton) -> bool {
1348    read(|s| {
1349        !s.controls_open
1350            && (s.buttons.contains(&(k as u32)) || s.touch_buttons.contains(&(k as u32)))
1351    })
1352}
1353pub fn is_mouse_button_pressed(k: MouseButton) -> bool {
1354    read(|s| !s.controls_open && s.clicks.contains(&(k as u32)))
1355}
1356pub fn mouse_position() -> (f32, f32) {
1357    read(|s| s.mouse.into())
1358}
1359pub fn mouse_delta_position() -> Vec2 {
1360    read(|s| -s.delta / vec2(s.w as f32, s.h as f32))
1361}
1362pub fn mouse_wheel() -> (f32, f32) {
1363    read(|s| (s.wheel_x, s.wheel))
1364}
1365pub fn touches() -> Vec<Touch> {
1366    read(|s| {
1367        if s.controls_open {
1368            Vec::new()
1369        } else {
1370            s.touches.clone()
1371        }
1372    })
1373}
1374pub fn set_cursor_grab(grab: bool) {
1375    edit(|s| s.grab = grab)
1376}
1377pub fn simulate_mouse_with_touch(enabled: bool) {
1378    edit(|s| s.touch_mouse = enabled)
1379}
1380pub fn show_mouse(visible: bool) {
1381    edit(|s| s.visible = visible)
1382}
1383pub struct ScreenImage;
1384pub fn get_screen_data() -> ScreenImage {
1385    ScreenImage
1386}
1387impl ScreenImage {
1388    /// Captures this frame after GPU submission, including draws queued before this call.
1389    #[cfg(not(target_arch = "wasm32"))]
1390    pub fn export_png(&self, path: &str) {
1391        edit(|s| {
1392            if s.screenshots.len() < 8 {
1393                s.screenshots.push(path.into());
1394            }
1395        });
1396    }
1397}
1398pub async fn next_frame() {
1399    struct Yield(bool);
1400    impl Future for Yield {
1401        type Output = ();
1402        fn poll(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<()> {
1403            if self.0 {
1404                Poll::Ready(())
1405            } else {
1406                self.0 = true;
1407                Poll::Pending
1408            }
1409        }
1410    }
1411    Yield(false).await
1412}
1413pub fn start(conf: Conf, future: impl Future<Output = ()> + 'static) {
1414    audio::reset();
1415    edit(|s| {
1416        *s = State::default();
1417        s.w = conf.window_width.max(1) as u32;
1418        s.h = conf.window_height.max(1) as u32;
1419        s.default_camera();
1420        s.future = Some(Box::pin(future));
1421    });
1422}
1423fn begin_host_frame(dt: f32, w: u32, h: u32) {
1424    edit(|s| {
1425        assert!(!s.in_frame, "one input/render frame at a time");
1426        s.in_frame = true;
1427        s.dt = if dt.is_finite() {
1428            dt.clamp(0., 0.1)
1429        } else {
1430            0.
1431        };
1432        s.time += s.dt as f64;
1433        s.w = w.max(1);
1434        s.h = h.max(1);
1435        s.vertices.clear();
1436        s.batches.clear();
1437        s.retained.clear();
1438        s.post_hud = false;
1439        s.glow = false;
1440        s.effect_stats = effects::EffectStats::default();
1441        s.points.clear();
1442        s.sun = None;
1443        s.refresh_environment();
1444        s.visibility_stats = Default::default();
1445        s.default_camera();
1446    });
1447}
1448fn frame(dt: f32, w: u32, h: u32) -> bool {
1449    begin_host_frame(dt, w, h);
1450    let mut future = edit(|s| s.future.take());
1451    let finished = future.as_mut().is_none_or(|f| {
1452        f.as_mut()
1453            .poll(&mut Context::from_waker(Waker::noop()))
1454            .is_ready()
1455    });
1456    edit(|s| {
1457        s.future = future;
1458    });
1459    end_host_frame();
1460    !finished
1461}
1462fn end_host_frame() {
1463    let dt = read(|s| s.dt);
1464    audio::end_frame(dt);
1465    edit(|s| {
1466        s.retained.finalize();
1467        let (tier, fx) = s.post_effective();
1468        let motion = preferences::feedback_policy().reduced_motion();
1469        s.retained.post = post::pack(tier, &fx, s.frame, motion, s.dpi);
1470        s.frame += 1;
1471        s.in_frame = false;
1472        s.pressed.clear();
1473        s.clicks.clear();
1474        s.input.finish_frame();
1475        s.delta = Vec2::ZERO;
1476        s.wheel = 0.;
1477        s.wheel_x = 0.;
1478        if !s.touches.is_empty() {
1479            let mut ended = [0_u64; 64];
1480            let mut len = 0;
1481            for touch in &s.touches {
1482                if matches!(touch.phase, TouchPhase::Ended | TouchPhase::Cancelled) {
1483                    ended[len] = touch.id;
1484                    len += 1;
1485                }
1486            }
1487            s.touches.retain(|touch| !ended[..len].contains(&touch.id));
1488        }
1489        for t in &mut s.touches {
1490            t.phase = TouchPhase::Stationary;
1491        }
1492    });
1493}
1494fn clear_held(s: &mut State) {
1495    s.keys.clear();
1496    s.pressed.clear();
1497    s.buttons.clear();
1498    s.touch_buttons.clear();
1499    s.clicks.clear();
1500    s.touches.clear();
1501    s.delta = Vec2::ZERO;
1502    s.wheel = 0.;
1503    s.wheel_x = 0.;
1504}
1505fn focus(focused: bool) {
1506    edit(|s| {
1507        s.input.focus(focused);
1508        if !focused {
1509            clear_held(s);
1510        }
1511    });
1512    if !focused {
1513        audio::focus_lost();
1514    }
1515}
1516fn key(code: u32, down: bool) {
1517    if code == 0 || code > u16::MAX as u32 {
1518        return;
1519    }
1520    edit(|s| {
1521        if s.keys.contains(&code) == down {
1522            return;
1523        }
1524        if !s.input.push(input::PlatformEvent::Value(
1525            input::InputCode::Key(code as u16),
1526            f32::from(down),
1527        )) {
1528            clear_held(s);
1529            return;
1530        }
1531        if down {
1532            if s.keys.len() < input::MAX_ACTIVE_CODES {
1533                s.keys.insert(code);
1534                s.pressed.insert(code);
1535            }
1536        } else {
1537            s.keys.remove(&code);
1538        }
1539    });
1540}
1541fn button(code: u32, down: bool) {
1542    button_source(code, down, false)
1543}
1544fn button_source(code: u32, down: bool, touch: bool) {
1545    if !(1..=5).contains(&code) {
1546        return;
1547    }
1548    edit(|s| {
1549        if !s.input.focused || s.input.overflow {
1550            clear_held(s);
1551            return;
1552        }
1553        let held = if touch { &s.touch_buttons } else { &s.buttons };
1554        if held.contains(&code) == down {
1555            return;
1556        }
1557        if !touch
1558            && (!s.input.push(input::PlatformEvent::PointerPosition(s.mouse))
1559                || !s.input.push(input::PlatformEvent::Value(
1560                    input::InputCode::Mouse(code as u8),
1561                    f32::from(down),
1562                )))
1563        {
1564            clear_held(s);
1565            return;
1566        }
1567        let held = if touch {
1568            &mut s.touch_buttons
1569        } else {
1570            &mut s.buttons
1571        };
1572        if down {
1573            held.insert(code);
1574            s.clicks.insert(code);
1575        } else {
1576            held.remove(&code);
1577        }
1578    });
1579}
1580fn pointer(x: f32, y: f32, dx: f32, dy: f32) {
1581    if ![x, y, dx, dy]
1582        .iter()
1583        .all(|v| v.is_finite() && v.abs() <= 1e6)
1584    {
1585        return;
1586    }
1587    edit(|s| {
1588        if (dx != 0. || dy != 0.)
1589            && !s
1590                .input
1591                .push(input::PlatformEvent::MouseMotion(vec2(dx, dy)))
1592        {
1593            clear_held(s);
1594            return;
1595        }
1596        s.mouse = vec2(x, y);
1597        s.delta += vec2(dx, dy);
1598    });
1599}
1600fn wheel(delta: f32) {
1601    wheel_axis(1, delta)
1602}
1603fn wheel_axis(axis: u8, delta: f32) {
1604    if !delta.is_finite() || axis > 1 {
1605        return;
1606    }
1607    edit(|s| {
1608        let delta = delta.clamp(-1000., 1000.);
1609        if !s.input.push(input::PlatformEvent::Value(
1610            input::InputCode::Wheel(axis),
1611            delta,
1612        )) {
1613            clear_held(s);
1614            return;
1615        }
1616        if axis == 0 {
1617            s.wheel_x += delta;
1618        } else {
1619            s.wheel += delta;
1620        }
1621    });
1622}
1623fn touch(id: u64, phase: u32, x: f32, y: f32) {
1624    if !x.is_finite() || !y.is_finite() {
1625        return;
1626    }
1627    edit(|s| {
1628        let position = vec2(x, y);
1629        if position.abs().max_element() > 1e6 {
1630            return;
1631        }
1632        let event = ferravex_play::input::touch::Event {
1633            id,
1634            position,
1635            phase: match phase {
1636                0 => ferravex_play::input::touch::Phase::Start,
1637                1 => ferravex_play::input::touch::Phase::Move,
1638                2 => ferravex_play::input::touch::Phase::End,
1639                _ => ferravex_play::input::touch::Phase::Cancel,
1640            },
1641        };
1642        if !s.input.push(input::PlatformEvent::Touch(event)) {
1643            clear_held(s);
1644            return;
1645        }
1646        if phase == 1
1647            && let Some(t) = s
1648                .touches
1649                .iter_mut()
1650                .find(|t| t.id == id && t.phase == TouchPhase::Started)
1651        {
1652            t.position = position;
1653            return;
1654        }
1655        let preserve_start = phase == 2
1656            && s.touches
1657                .iter()
1658                .any(|t| t.id == id && t.phase == TouchPhase::Started);
1659        if !preserve_start {
1660            s.touches.retain(|t| t.id != id);
1661        }
1662        if s.touches.len() < 64 {
1663            s.touches.push(Touch {
1664                id,
1665                position,
1666                phase: match phase {
1667                    0 => TouchPhase::Started,
1668                    1 => TouchPhase::Moved,
1669                    2 => TouchPhase::Ended,
1670                    _ => TouchPhase::Cancelled,
1671                },
1672            });
1673        }
1674    });
1675}
1676pub mod performance;
1677#[cfg(not(target_arch = "wasm32"))]
1678mod runner;
1679#[cfg(not(target_arch = "wasm32"))]
1680pub fn run(conf: Conf, future: impl Future<Output = ()> + 'static) {
1681    #[cfg(target_os = "ios")]
1682    native::ios::launch(conf, future);
1683    #[cfg(not(target_os = "ios"))]
1684    {
1685        let mut runner = runner::Runner::new(conf, future)
1686            .unwrap_or_else(|e| panic!("Ferravex native platform: {e}"));
1687        while runner.step() {
1688            if runner.suspended() {
1689                std::thread::sleep(std::time::Duration::from_millis(10));
1690            }
1691        }
1692    }
1693}
1694#[macro_export]
1695macro_rules! game {
1696    ($conf:path,$game:path) => {
1697        #[cfg(not(target_arch = "wasm32"))]
1698        #[global_allocator]
1699        static FERRAVEX_ALLOCATOR: $crate::telemetry::TrackingAllocator =
1700            $crate::telemetry::TrackingAllocator;
1701        #[cfg(not(target_arch = "wasm32"))]
1702        pub fn run() {
1703            $crate::run($conf(), $game());
1704        }
1705        #[cfg(target_arch = "wasm32")]
1706        #[unsafe(no_mangle)]
1707        pub extern "C" fn ferravex_init() {
1708            $crate::start($conf(), $game());
1709        }
1710    };
1711}
1712#[cfg(target_arch = "wasm32")]
1713mod wasm {
1714    use super::*;
1715    #[unsafe(no_mangle)]
1716    pub extern "C" fn ferravex_feedback_preferences(motion: u32, flash: u32) -> u32 {
1717        preferences::apply_feedback_flags(motion, flash)
1718    }
1719    /// Version 1: (version=1, finite text_scale in 1..=2, contrast=0|1).
1720    /// Returns exactly 1 on acceptance, 0 on rejection; session-local UI only.
1721    #[unsafe(no_mangle)]
1722    pub extern "C" fn ferravex_ui_preferences_v1(
1723        version: u32,
1724        text_scale: f32,
1725        contrast: u32,
1726    ) -> u32 {
1727        preferences::apply_ui_snapshot_v1(version, text_scale, contrast)
1728    }
1729    #[unsafe(no_mangle)]
1730    pub extern "C" fn ferravex_display_scale(scale: f32) {
1731        set_display_scale(scale);
1732    }
1733    #[unsafe(no_mangle)]
1734    pub extern "C" fn ferravex_take_graphics_reset() -> u32 {
1735        edit(|s| u32::from(std::mem::take(&mut s.graphics_reset)))
1736    }
1737    #[unsafe(no_mangle)]
1738    pub extern "C" fn ferravex_light_environment() -> *const lighting::Environment {
1739        read(|s| &s.retained.environment as *const lighting::Environment)
1740    }
1741    #[unsafe(no_mangle)]
1742    pub extern "C" fn ferravex_details_get(field: u32) -> u32 {
1743        read(|s| match field {
1744            0 => s.presentation.quality.map_or(0, |q| q as u32 + 1),
1745            1 => s.presentation.resolution as u32,
1746            2 => s.presentation.shadows as u32,
1747            3 => s.presentation.lights as u32,
1748            4 => s.presentation.look as u32,
1749            5 => s.details_error as u32,
1750            6 => u32::from(s.presentation.adaptive),
1751            _ => u32::MAX,
1752        })
1753    }
1754    #[unsafe(no_mangle)]
1755    pub extern "C" fn ferravex_details_set(field: u32, value: u32) -> u32 {
1756        edit(|s| {
1757            let mut p = s.presentation;
1758            match field {
1759                0 if value <= 3 => p.quality = value.checked_sub(1).map(|q| q as u8),
1760                1 if value <= 5 => p.resolution = value as u8,
1761                2 if value <= 3 => p.shadows = value as u8,
1762                3 if value <= 4 => p.lights = value as u8,
1763                4 if value <= 3 => p.look = value as u8,
1764                6 if value <= 1 => p.adaptive = value != 0,
1765                _ => return 0,
1766            };
1767            s.presentation = p;
1768            s.pending_presentation = Some(p);
1769            1
1770        })
1771    }
1772    #[unsafe(no_mangle)]
1773    pub extern "C" fn ferravex_details_open(open: u32) {
1774        edit(|s| s.details_open = open != 0);
1775    }
1776    #[unsafe(no_mangle)]
1777    pub extern "C" fn ferravex_resolution() -> u32 {
1778        read(|s| s.resolution as u32)
1779    }
1780    #[unsafe(no_mangle)]
1781    pub extern "C" fn ferravex_shadow_detail() -> u32 {
1782        shadow_quality() as u32 + 1
1783    }
1784    #[unsafe(no_mangle)]
1785    pub extern "C" fn ferravex_visual_look() -> u32 {
1786        look() as u32
1787    }
1788    #[unsafe(no_mangle)]
1789    pub extern "C" fn ferravex_visual_quality() -> u32 {
1790        quality() as u32
1791    }
1792    #[unsafe(no_mangle)]
1793    pub extern "C" fn ferravex_look_override(value: u32) -> u32 {
1794        let Some(look) = Look::from_index(value) else {
1795            return 0;
1796        };
1797        edit(|s| s.look_override = Some(look));
1798        1
1799    }
1800    #[unsafe(no_mangle)]
1801    pub extern "C" fn ferravex_quality_override(value: u32) -> u32 {
1802        let q = match value {
1803            0 => lighting::Quality::Low,
1804            1 => lighting::Quality::Medium,
1805            2 => lighting::Quality::High,
1806            _ => return 0,
1807        };
1808        quality_override(q);
1809        1
1810    }
1811
1812    #[unsafe(no_mangle)]
1813    pub extern "C" fn ferravex_retained_batch_count() -> u32 {
1814        read(|s| s.retained.batches.len() as u32)
1815    }
1816    #[unsafe(no_mangle)]
1817    pub extern "C" fn ferravex_culled_count() -> u32 {
1818        let s = visibility_stats();
1819        s.frustum_culled + s.distance_culled
1820    }
1821    #[unsafe(no_mangle)]
1822    pub extern "C" fn ferravex_visible_count() -> u32 {
1823        visibility_stats().visible
1824    }
1825    /// Resolved post-processing block (28 f32, see `post`); index 0 is the tier.
1826    #[unsafe(no_mangle)]
1827    pub extern "C" fn ferravex_post_frame() -> *const f32 {
1828        read(|s| s.retained.post.as_ptr())
1829    }
1830    /// Session preset override: 0 off, 1 subtle, 2 neon, 3 warm-film, 4 crt;
1831    /// 255 clears it. Returns 1 on success.
1832    #[unsafe(no_mangle)]
1833    pub extern "C" fn ferravex_post_override(index: u32) -> u32 {
1834        let value = if index == 255 {
1835            None
1836        } else if let Some(fx) = post::PostFx::from_index(index) {
1837            Some(fx)
1838        } else {
1839            return 0;
1840        };
1841        edit(|s| s.post_override = value);
1842        1
1843    }
1844    #[unsafe(no_mangle)]
1845    pub extern "C" fn ferravex_commands() -> *const retained::Command {
1846        read(|s| s.retained.commands.as_ptr())
1847    }
1848    #[unsafe(no_mangle)]
1849    pub extern "C" fn ferravex_command_count() -> u32 {
1850        read(|s| s.retained.commands.len() as u32)
1851    }
1852    #[unsafe(no_mangle)]
1853    pub extern "C" fn ferravex_sprite_batches() -> *const effects::SpriteBatch {
1854        read(|s| s.retained.sprite_batches.as_ptr())
1855    }
1856    #[unsafe(no_mangle)]
1857    pub extern "C" fn ferravex_sprite_batch_count() -> u32 {
1858        read(|s| s.retained.sprite_batches.len() as u32)
1859    }
1860    #[unsafe(no_mangle)]
1861    pub extern "C" fn ferravex_sprite_instances() -> *const [f32; 16] {
1862        read(|s| s.retained.sprites.as_ptr())
1863    }
1864    #[unsafe(no_mangle)]
1865    pub extern "C" fn ferravex_sprite_instance_count() -> u32 {
1866        read(|s| s.retained.sprites.len() as u32)
1867    }
1868    #[unsafe(no_mangle)]
1869    pub extern "C" fn ferravex_effect_batches() -> *const effects::EffectBatch {
1870        read(|s| s.retained.effects.as_ptr())
1871    }
1872    #[unsafe(no_mangle)]
1873    pub extern "C" fn ferravex_effect_batch_count() -> u32 {
1874        read(|s| s.retained.effects.len() as u32)
1875    }
1876    #[unsafe(no_mangle)]
1877    pub extern "C" fn ferravex_effect_vertex_count() -> u32 {
1878        effects::stats().vertices
1879    }
1880    #[unsafe(no_mangle)]
1881    pub extern "C" fn ferravex_retained_batches() -> *const retained::RetainedBatch {
1882        read(|s| s.retained.batches.as_ptr())
1883    }
1884    #[unsafe(no_mangle)]
1885    pub extern "C" fn ferravex_retained_instances() -> *const [f32; 28] {
1886        read(|s| s.retained.instances.as_ptr())
1887    }
1888    #[unsafe(no_mangle)]
1889    pub extern "C" fn ferravex_retained_instance_count() -> u32 {
1890        read(|s| s.retained.instances.len() as u32)
1891    }
1892    #[unsafe(no_mangle)]
1893    pub extern "C" fn ferravex_mesh_vertices(id: u32) -> *const [f32; 10] {
1894        retained::geometry(id).map_or(std::ptr::null(), |m| m.vertices.as_ptr())
1895    }
1896    #[unsafe(no_mangle)]
1897    pub extern "C" fn ferravex_mesh_skin(id: u32) -> *const [f32; 8] {
1898        retained::geometry(id)
1899            .and_then(|m| m.skin.as_ref().map(|v| v.as_ptr()))
1900            .unwrap_or(std::ptr::null())
1901    }
1902    #[unsafe(no_mangle)]
1903    pub extern "C" fn ferravex_skin_matrices() -> *const [f32; 16] {
1904        read(|s| s.retained.skin_matrices.as_ptr())
1905    }
1906    #[unsafe(no_mangle)]
1907    pub extern "C" fn ferravex_skin_normals() -> *const [f32; 9] {
1908        read(|s| s.retained.skin_normals.as_ptr())
1909    }
1910    #[unsafe(no_mangle)]
1911    pub extern "C" fn ferravex_skin_joint_count() -> u32 {
1912        read(|s| s.retained.skin_matrices.len() as u32)
1913    }
1914    #[unsafe(no_mangle)]
1915    pub extern "C" fn ferravex_mesh_vertex_count(id: u32) -> u32 {
1916        retained::geometry(id).map_or(0, |m| m.vertices.len() as u32)
1917    }
1918    #[unsafe(no_mangle)]
1919    pub extern "C" fn ferravex_frame(dt: f32, w: u32, h: u32) -> u32 {
1920        frame(dt, w, h) as u32
1921    }
1922    #[unsafe(no_mangle)]
1923    pub extern "C" fn ferravex_vertices() -> *const [f32; 8] {
1924        read(|s| s.vertices.as_ptr())
1925    }
1926    #[unsafe(no_mangle)]
1927    pub extern "C" fn ferravex_vertex_count() -> u32 {
1928        read(|s| s.vertices.len() as u32)
1929    }
1930    #[unsafe(no_mangle)]
1931    pub extern "C" fn ferravex_batches() -> *const Batch {
1932        read(|s| s.batches.as_ptr())
1933    }
1934    #[unsafe(no_mangle)]
1935    pub extern "C" fn ferravex_batch_count() -> u32 {
1936        read(|s| s.batches.len() as u32)
1937    }
1938    #[unsafe(no_mangle)]
1939    pub extern "C" fn ferravex_clear(channel: u32) -> f32 {
1940        read(|s| [s.clear.r, s.clear.g, s.clear.b, s.clear.a][channel.min(3) as usize])
1941    }
1942    #[unsafe(no_mangle)]
1943    pub extern "C" fn ferravex_key(code: u32, down: u32) {
1944        key(code, down != 0)
1945    }
1946    #[unsafe(no_mangle)]
1947    pub extern "C" fn ferravex_button(code: u32, down: u32) {
1948        button(code, down != 0)
1949    }
1950    #[unsafe(no_mangle)]
1951    pub extern "C" fn ferravex_pointer(x: f32, y: f32, dx: f32, dy: f32) {
1952        pointer(x, y, dx, dy)
1953    }
1954    #[unsafe(no_mangle)]
1955    pub extern "C" fn ferravex_wheel(delta: f32) {
1956        wheel(delta);
1957    }
1958    #[unsafe(no_mangle)]
1959    pub extern "C" fn ferravex_wheel_axis(axis: u32, delta: f32) {
1960        if axis < 2 {
1961            wheel_axis(axis as u8, delta);
1962        }
1963    }
1964    #[unsafe(no_mangle)]
1965    pub extern "C" fn ferravex_blur() {
1966        focus(false)
1967    }
1968    #[unsafe(no_mangle)]
1969    pub extern "C" fn ferravex_focus(value: u32) {
1970        focus(value != 0)
1971    }
1972    #[unsafe(no_mangle)]
1973    pub extern "C" fn ferravex_touch_button(code: u32, down: u32) {
1974        button_source(code, down != 0, true)
1975    }
1976    #[unsafe(no_mangle)]
1977    pub extern "C" fn ferravex_touch_pointer(x: f32, y: f32) {
1978        if x.is_finite() && y.is_finite() {
1979            edit(|s| s.mouse = vec2(x, y));
1980        }
1981    }
1982    #[unsafe(no_mangle)]
1983    pub extern "C" fn ferravex_pad_connected(index: u32, connected: u32) {
1984        edit(|s| s.input.pad_connected(index as usize, connected != 0));
1985    }
1986    #[unsafe(no_mangle)]
1987    pub extern "C" fn ferravex_pad_axis(index: u32, axis: u32, value: f32) {
1988        edit(|s| s.input.pad_axis(index as usize, axis as usize, value));
1989    }
1990    #[unsafe(no_mangle)]
1991    pub extern "C" fn ferravex_pad_button(index: u32, button: u32, value: f32) {
1992        edit(|s| s.input.pad_button(index as usize, button as usize, value));
1993    }
1994    #[unsafe(no_mangle)]
1995    pub extern "C" fn ferravex_controls_open() -> u32 {
1996        read(|s| s.controls_open as u32)
1997    }
1998    #[unsafe(no_mangle)]
1999    pub extern "C" fn ferravex_input_settings() {
2000        edit(|s| s.input.settings_requested = true);
2001    }
2002    #[unsafe(no_mangle)]
2003    pub extern "C" fn ferravex_touch_mouse() -> u32 {
2004        read(|s| s.touch_mouse as u32)
2005    }
2006    #[unsafe(no_mangle)]
2007    pub extern "C" fn ferravex_grab() -> u32 {
2008        read(|s| s.grab as u32)
2009    }
2010    #[unsafe(no_mangle)]
2011    pub extern "C" fn ferravex_touch(id: u32, phase: u32, x: f32, y: f32) {
2012        touch(id as u64, phase, x, y);
2013    }
2014    #[unsafe(no_mangle)]
2015    pub extern "C" fn ferravex_autoplay(enabled: u32) {
2016        edit(|s| s.autoplay = enabled != 0)
2017    }
2018}
2019pub fn autoplay_enabled() -> bool {
2020    read(|s| s.autoplay)
2021}
2022
2023#[cfg(test)]
2024mod tests {
2025    use super::*;
2026    fn reset() {
2027        edit(|s| *s = State::default());
2028    }
2029    #[test]
2030    fn world_palette_leaves_hud_and_viewmodel_shadow_state_unchanged() {
2031        reset();
2032        set_look(Look::Ink);
2033        let color = Color::new(0.8, 0.5, 0.2, 1.);
2034        set_world_colors(true);
2035        draw_rectangle(0., 0., 8., 8., color);
2036        set_default_camera();
2037        draw_rectangle(16., 0., 8., 8., color);
2038        read(|s| {
2039            let first = &s.vertices[0];
2040            let hud = &s.vertices[6];
2041            let expected = Look::Ink.shade(color).to_array();
2042            assert_eq!(first[4..], expected);
2043            assert_eq!(hud[4..], color.to_array());
2044        });
2045        let source = mesh::Mesh3d::cuboid(Vec3::ONE, color);
2046        let skin = skinning::SkinnedMesh::new(
2047            &source.mesh,
2048            &vec![skinning::SkinWeights::rigid(0); source.mesh.vertices.len()],
2049            1,
2050        )
2051        .unwrap();
2052        let palette = skinning::SkinPalette::new(&[Mat4::IDENTITY.to_cols_array()]).unwrap();
2053        set_camera(&Camera3D::default());
2054        assert!(draw_skinned_viewmodel(&skin, Mat4::IDENTITY, &palette));
2055        read(|s| {
2056            let b = s.retained.batches.last().unwrap();
2057            assert_eq!(b.depth & 1, 0);
2058            assert_eq!(b.depth & 24, 24);
2059            assert!(s.depth);
2060        });
2061    }
2062    #[test]
2063    fn camera_culled_meshes_remain_available_to_the_shadow_pass() {
2064        reset();
2065        set_quality(lighting::Quality::High);
2066        set_sun_shadow(Some(lighting::SunShadow {
2067            extent: 30.,
2068            ..Default::default()
2069        }))
2070        .unwrap();
2071        set_camera(&Camera3D {
2072            position: vec3(0., 0., 5.),
2073            target: Vec3::ZERO,
2074            z_far: 20.,
2075            ..Default::default()
2076        });
2077        let mesh = mesh::Mesh3d::cuboid(Vec3::ONE, WHITE);
2078        assert!(!draw_resident(
2079            mesh.resident(),
2080            Mat4::from_translation(Vec3::X * 10.)
2081        ));
2082        read(|s| {
2083            assert_eq!(s.retained.batches.len(), 1);
2084            assert_ne!(s.retained.batches[0].depth & 32, 0);
2085            assert_eq!(s.retained.batches[0].depth & 8, 0);
2086        });
2087    }
2088    #[test]
2089    fn shadow_visibility_refreshes_when_lighting_settings_change() {
2090        reset();
2091        set_camera(&Camera3D::default());
2092        set_quality(lighting::Quality::High);
2093        let mesh = mesh::Mesh3d::cuboid(Vec3::ONE, WHITE);
2094        let sun = lighting::SunShadow {
2095            extent: 4.,
2096            depth: 20.,
2097            ..Default::default()
2098        };
2099        set_sun_shadow(Some(sun)).unwrap();
2100        assert!(draw_shadow(mesh.resident(), Mat4::IDENTITY));
2101        set_sun_shadow(Some(lighting::SunShadow {
2102            center: Vec3::X * 100.,
2103            ..sun
2104        }))
2105        .unwrap();
2106        assert!(!draw_shadow(mesh.resident(), Mat4::IDENTITY));
2107        set_sun_shadow(Some(sun)).unwrap();
2108        assert!(draw_shadow(mesh.resident(), Mat4::IDENTITY));
2109        set_fidelity(0, 1, 0);
2110        assert!(!draw_shadow(mesh.resident(), Mat4::IDENTITY));
2111        set_fidelity(0, 0, 0);
2112        assert!(draw_shadow(mesh.resident(), Mat4::IDENTITY));
2113        clear_background(BLACK);
2114        assert!(!draw_shadow(mesh.resident(), Mat4::IDENTITY));
2115    }
2116    #[test]
2117    fn shared_camera_culls_residents_and_default_ui_camera_does_not() {
2118        reset();
2119        let mesh = mesh::Mesh3d::cuboid(Vec3::ONE, WHITE);
2120        set_camera(&Camera3D {
2121            position: vec3(0., 0., 5.),
2122            target: Vec3::ZERO,
2123            z_far: 20.,
2124            ..Default::default()
2125        });
2126        assert!(draw_resident(mesh.resident(), Mat4::IDENTITY));
2127        assert!(!draw_resident(
2128            mesh.resident(),
2129            Mat4::from_translation(Vec3::X * 100.)
2130        ));
2131        let stats = visibility_stats();
2132        assert_eq!(
2133            (stats.tested, stats.visible, stats.frustum_culled),
2134            (2, 1, 1)
2135        );
2136        assert!(!set_visibility(visibility::VisibilitySettings {
2137            max_distance: Some(-1.),
2138            ..Default::default()
2139        }));
2140        set_default_camera();
2141        assert!(draw_resident(
2142            mesh.resident(),
2143            Mat4::from_translation(Vec3::X * 100.)
2144        ));
2145    }
2146    #[test]
2147    fn frame_yields_once_and_keeps_game_local_state() {
2148        reset();
2149        let ticks = std::rc::Rc::new(std::cell::Cell::new(0));
2150        let count = ticks.clone();
2151        start(Conf::default(), async move {
2152            for _ in 0..3 {
2153                count.set(count.get() + 1);
2154                next_frame().await;
2155            }
2156        });
2157        for expected in 1..=3 {
2158            assert!(frame(1. / 60., 640, 480));
2159            assert_eq!(ticks.get(), expected);
2160        }
2161        assert!(!frame(1. / 60., 640, 480));
2162        assert_eq!(ticks.get(), 3);
2163    }
2164    #[test]
2165    fn key_edges_survive_until_poll_and_release_on_blur() {
2166        reset();
2167        key(97, true);
2168        key(97, true);
2169        assert!(is_key_down(KeyCode::A));
2170        assert!(is_key_pressed(KeyCode::A));
2171        start(Conf::default(), async {
2172            assert!(is_key_pressed(KeyCode::D));
2173            next_frame().await;
2174            assert!(!is_key_pressed(KeyCode::D));
2175            assert!(is_key_down(KeyCode::D));
2176        });
2177        key(100, true);
2178        assert!(frame(0.01, 1280, 800));
2179        assert!(!frame(0.01, 1280, 800));
2180        key(100, false);
2181        assert!(!is_key_down(KeyCode::D));
2182    }
2183    #[test]
2184    fn screen_camera_projects_top_left_and_bottom_right() {
2185        reset();
2186        edit(|s| {
2187            s.w = 640;
2188            s.h = 480;
2189            s.default_camera()
2190        });
2191        read(|s| {
2192            assert!(
2193                s.matrix
2194                    .project_point3(Vec3::ZERO)
2195                    .abs_diff_eq(vec3(-1., 1., 0.), 1e-6)
2196            );
2197            assert!(
2198                s.matrix
2199                    .project_point3(vec3(640., 480., 0.))
2200                    .abs_diff_eq(vec3(1., -1., 0.), 1e-6)
2201            );
2202        });
2203        let c = Camera2D::from_display_rect(Rect::new(10., 20., 100., 50.));
2204        let m = c.matrix(640., 480.);
2205        assert!(
2206            m.project_point3(vec3(10., 20., 0.))
2207                .abs_diff_eq(vec3(-1., 1., 0.), 1e-6)
2208        );
2209    }
2210    #[test]
2211    fn draws_batch_only_adjacent_depth_modes_and_retain_their_camera() {
2212        reset();
2213        draw_rectangle(0., 0., 20., 20., WHITE);
2214        set_camera(&Camera3D::default());
2215        draw_triangle(Vec2::ZERO, Vec2::X, Vec2::Y, RED);
2216        set_default_camera();
2217        draw_triangle(Vec2::ZERO, Vec2::X, Vec2::Y, BLUE);
2218        read(|s| {
2219            assert_eq!(s.vertices.len(), 12);
2220            assert_eq!(
2221                s.batches
2222                    .iter()
2223                    .map(|b| (b.start, b.count, b.depth))
2224                    .collect::<Vec<_>>(),
2225                [(0, 6, false), (6, 3, true), (9, 3, false)]
2226            );
2227            assert_eq!(std::mem::size_of::<Batch>(), 12);
2228            assert_eq!(std::mem::offset_of!(Batch, depth), 8);
2229        });
2230    }
2231    #[test]
2232    fn fast_touch_taps_preserve_start_and_end_without_sticking() {
2233        reset();
2234        start(Conf::default(), async {
2235            next_frame().await;
2236        });
2237        touch(7, 0, 10., 20.);
2238        touch(7, 1, 12., 22.);
2239        assert_eq!(touches()[0].phase, TouchPhase::Started);
2240        touch(7, 2, 12., 22.);
2241        assert_eq!(touches().len(), 2);
2242        frame(f32::NAN, 640, 480);
2243        assert!(touches().is_empty());
2244        assert_eq!(get_frame_time(), 0.);
2245        assert!(get_time().is_finite());
2246        touch(8, 0, 10., 20.);
2247        touch(8, 3, 10., 20.);
2248        assert_eq!(touches().len(), 1);
2249        assert_eq!(touches()[0].phase, TouchPhase::Cancelled);
2250        pointer(f32::NAN, 0., 0., 0.);
2251        assert!(read(|s| s.mouse.is_finite()));
2252    }
2253    #[test]
2254    fn invalid_mesh_triangles_cannot_corrupt_adjacent_batches() {
2255        reset();
2256        let v = Vertex::new2(Vec3::ZERO, Vec2::ZERO, WHITE);
2257        draw_mesh(&Mesh {
2258            vertices: vec![v; 3],
2259            indices: vec![0, 1, 9, 0, 1, 2, 0],
2260            texture: None,
2261        });
2262        read(|s| {
2263            assert_eq!(s.vertices.len(), 3);
2264            assert_eq!(s.batches[0].count, 3);
2265        });
2266    }
2267    #[test]
2268    fn nonuniform_scale_uses_inverse_transpose_for_normals() {
2269        reset();
2270        set_lighting(Some(shaders::LitSettings {
2271            ambient: 0.,
2272            light_direction: Vec3::Y,
2273            fog_start: 1e5,
2274            fog_end: 2e5,
2275            ..Default::default()
2276        }));
2277        let n = vec3(1., 1., 0.).normalize();
2278        let model = Mat4::from_scale(vec3(4., 0.5, 1.));
2279        edit(|s| s.push([(Vec3::ZERO, n, WHITE); 3], model));
2280        read(|s| {
2281            assert!(s.vertices[0][4] > 0.99);
2282        });
2283    }
2284    /// The original per-triangle primitive formulas through the generic
2285    /// `push(.., Mat4::IDENTITY)` path; the batched fast path must match them.
2286    mod reference {
2287        use super::*;
2288        pub fn triangle(a: Vec2, b: Vec2, c: Vec2, color: Color) {
2289            edit(|s| {
2290                s.push(
2291                    [a, b, c].map(|p| (p.extend(0.), Vec3::Z, color)),
2292                    Mat4::IDENTITY,
2293                )
2294            })
2295        }
2296        pub fn rectangle(x: f32, y: f32, w: f32, h: f32, c: Color) {
2297            let (a, b, d, e) = (
2298                vec2(x, y),
2299                vec2(x + w, y),
2300                vec2(x, y + h),
2301                vec2(x + w, y + h),
2302            );
2303            triangle(a, b, d, c);
2304            triangle(d, b, e, c);
2305        }
2306        pub fn line(x1: f32, y1: f32, x2: f32, y2: f32, width: f32, c: Color) {
2307            let a = vec2(x1, y1);
2308            let b = vec2(x2, y2);
2309            let d = (b - a).normalize_or_zero();
2310            let n = vec2(-d.y, d.x) * width * 0.5;
2311            triangle(a + n, a - n, b + n, c);
2312            triangle(b + n, a - n, b - n, c);
2313        }
2314        pub fn rectangle_lines(x: f32, y: f32, w: f32, h: f32, t: f32, c: Color) {
2315            line(x, y, x + w, y, t, c);
2316            line(x + w, y, x + w, y + h, t, c);
2317            line(x + w, y + h, x, y + h, t, c);
2318            line(x, y + h, x, y, t, c);
2319        }
2320        pub fn poly(x: f32, y: f32, sides: u8, r: f32, rotation: f32, c: Color) {
2321            let sides = sides.max(3);
2322            for i in 0..sides {
2323                let a = rotation.to_radians() + i as f32 * std::f32::consts::TAU / sides as f32;
2324                let b = a + std::f32::consts::TAU / sides as f32;
2325                triangle(
2326                    vec2(x, y),
2327                    vec2(x + r * a.cos(), y + r * a.sin()),
2328                    vec2(x + r * b.cos(), y + r * b.sin()),
2329                    c,
2330                );
2331            }
2332        }
2333        pub fn circle_lines(x: f32, y: f32, r: f32, t: f32, c: Color) {
2334            for i in 0..40 {
2335                let a = i as f32 * std::f32::consts::TAU / 40.;
2336                let b = (i + 1) as f32 * std::f32::consts::TAU / 40.;
2337                line(
2338                    x + r * a.cos(),
2339                    y + r * a.sin(),
2340                    x + r * b.cos(),
2341                    y + r * b.sin(),
2342                    t,
2343                    c,
2344                );
2345            }
2346        }
2347        pub fn ellipse(x: f32, y: f32, rx: f32, ry: f32, rotation: f32, c: Color) {
2348            let angle = rotation.to_radians();
2349            let point = |a: f32| {
2350                let p = vec2(rx * a.cos(), ry * a.sin());
2351                vec2(
2352                    x + p.x * angle.cos() - p.y * angle.sin(),
2353                    y + p.x * angle.sin() + p.y * angle.cos(),
2354                )
2355            };
2356            for i in 0..32 {
2357                triangle(
2358                    vec2(x, y),
2359                    point(i as f32 * std::f32::consts::TAU / 32.),
2360                    point((i + 1) as f32 * std::f32::consts::TAU / 32.),
2361                    c,
2362                );
2363            }
2364        }
2365        pub fn line_3d(a: Vec3, b: Vec3, c: Color) {
2366            let d = (b - a).normalize_or_zero();
2367            let n = d
2368                .cross(if d.y.abs() < 0.9 { Vec3::Y } else { Vec3::X })
2369                .normalize_or_zero()
2370                * 0.015;
2371            edit(|s| {
2372                s.push(
2373                    [a + n, a - n, b + n, b + n, a - n, b - n].map(|p| (p, Vec3::Y, c)),
2374                    Mat4::IDENTITY,
2375                )
2376            });
2377        }
2378    }
2379    /// Recorded immediate vertices and `(start, count, depth)` batches.
2380    type Recorded = (Vec<[f32; 8]>, Vec<(u32, u32, bool)>);
2381    fn primitive_scene(fast: bool) -> Recorded {
2382        reset();
2383        let c = Color::new(0.8, 0.45, 0.2, 0.9);
2384        let scene = |configure: &dyn Fn()| {
2385            configure();
2386            if fast {
2387                draw_triangle(vec2(1., 2.), vec2(30.5, 4.), vec2(9., 17.25), c);
2388                draw_rectangle(10.5, 20.25, 33., 7.75, c);
2389                draw_line(3., 4., 90., 41.5, 2.5, c);
2390                draw_line(5., 5., 5., 5., 1., c);
2391                draw_rectangle_lines(4., 8., 50., 30., 1.5, c);
2392                draw_circle(100.3, 60.7, 12.9, c);
2393                draw_poly(40., 40., 6, 9., 30., c);
2394                draw_poly(40., 40., 200, 9., 0., c);
2395                draw_poly(40., 40., 2, 9., 0., c);
2396                draw_poly(40., 40., 32, 9., 12., c);
2397                draw_circle_lines(70., 30., 15.5, 1.25, c);
2398                draw_ellipse(55., 66., 20., 9., 33., c);
2399                draw_line_3d(vec3(0., 0., 0.), vec3(1., 2., 3.), c);
2400                draw_line_3d(vec3(0., 0., 0.), vec3(0., 4., 0.), c);
2401            } else {
2402                reference::triangle(vec2(1., 2.), vec2(30.5, 4.), vec2(9., 17.25), c);
2403                reference::rectangle(10.5, 20.25, 33., 7.75, c);
2404                reference::line(3., 4., 90., 41.5, 2.5, c);
2405                reference::line(5., 5., 5., 5., 1., c);
2406                reference::rectangle_lines(4., 8., 50., 30., 1.5, c);
2407                reference::poly(100.3, 60.7, 32, 12.9, 0., c);
2408                reference::poly(40., 40., 6, 9., 30., c);
2409                reference::poly(40., 40., 200, 9., 0., c);
2410                reference::poly(40., 40., 2, 9., 0., c);
2411                reference::poly(40., 40., 32, 9., 12., c);
2412                reference::circle_lines(70., 30., 15.5, 1.25, c);
2413                reference::ellipse(55., 66., 20., 9., 33., c);
2414                reference::line_3d(vec3(0., 0., 0.), vec3(1., 2., 3.), c);
2415                reference::line_3d(vec3(0., 0., 0.), vec3(0., 4., 0.), c);
2416            }
2417        };
2418        scene(&|| set_default_camera());
2419        scene(&|| {
2420            set_camera(&Camera3D::default());
2421            set_look(Look::Ink);
2422            set_world_colors(true);
2423        });
2424        scene(&|| {
2425            set_camera(&Camera3D::default());
2426            set_lighting(Some(shaders::LitSettings::default()));
2427        });
2428        scene(&|| {
2429            set_world_colors(false);
2430            set_lighting(None);
2431            set_default_camera();
2432        });
2433        read(|s| {
2434            (
2435                s.vertices.clone(),
2436                s.batches
2437                    .iter()
2438                    .map(|b| (b.start, b.count, b.depth))
2439                    .collect(),
2440            )
2441        })
2442    }
2443    #[test]
2444    fn adaptive_ellipses_scale_segments_with_size_and_stay_on_the_rim() {
2445        let draw = |rx: f32, ry: f32| {
2446            reset();
2447            input::host_frame(1. / 60., 800, 600, || {
2448                draw_ellipse_adaptive(400., 300., rx, ry, 30., WHITE)
2449            });
2450            read(|s| s.vertices.clone())
2451        };
2452        let small = draw(3., 2.);
2453        let large = draw(380., 150.);
2454        assert_eq!(small.len(), 12 * 3, "a blob shadow needs few segments");
2455        assert_eq!(large.len(), 64 * 3, "large ellipses get the densest rim");
2456        // Every rim vertex satisfies the rotated ellipse equation.
2457        let (sin, cos) = 30_f32.to_radians().sin_cos();
2458        for v in &large {
2459            let p = vec2((v[0] + 1.) * 400., (1. - v[1]) * 300.) - vec2(400., 300.);
2460            let local = vec2(p.x * cos + p.y * sin, -p.x * sin + p.y * cos);
2461            let e = (local.x / 380.).powi(2) + (local.y / 150.).powi(2);
2462            assert!(p.length() < 1e-3 || (e - 1.).abs() < 1e-3, "{e}");
2463        }
2464        assert!(draw(f32::NAN, 2.).is_empty());
2465    }
2466    #[test]
2467    fn batched_primitives_match_the_per_triangle_reference_exactly() {
2468        let (fast, fast_batches) = primitive_scene(true);
2469        let (slow, slow_batches) = primitive_scene(false);
2470        assert_eq!(fast.len(), slow.len());
2471        assert_eq!(fast_batches, slow_batches);
2472        for (i, (a, b)) in fast.iter().zip(&slow).enumerate() {
2473            // `==` also equates the +0/-0 an identity product can introduce.
2474            assert_eq!(a, b, "vertex {i}");
2475        }
2476    }
2477}