Skip to main content

proof_engine/render/
pipeline.rs

1//! Render pipeline — glutin 0.32 / winit 0.30 window + OpenGL 3.3 Core context,
2//! instanced glyph batch rendering, and the full multi-pass post-processing pipeline
3//! (bloom, chromatic aberration, film grain, vignette, scanlines) wired through
4//! `PostFxPipeline` so that `RenderConfig` actually controls runtime behaviour.
5//!
6//! # Post-processing flow
7//!
8//! ```text
9//! GlyphPass (to scene FBO, dual attachments)
10//!   └─ color    ──┐
11//!   └─ emission ──┤
12//!                 ├─ PostFxPipeline::run(RenderConfig)
13//!                 │   ├─ Bloom H-blur
14//!                 │   ├─ Bloom V-blur   (×2 for softness)
15//!                 │   └─ Composite: scene + bloom + CA + grain + vignette → screen
16//!                 └─► Default framebuffer
17//! ```
18
19use std::num::NonZeroU32;
20use std::ffi::CString;
21use std::time::{Duration, Instant};
22
23use glutin::config::ConfigTemplateBuilder;
24use glutin::context::{ContextApi, ContextAttributesBuilder, NotCurrentGlContext,
25                      PossiblyCurrentContext, Version};
26use glutin::display::{GetGlDisplay, GlDisplay};
27use glutin::surface::{GlSurface, Surface, WindowSurface};
28use glutin_winit::{DisplayBuilder, GlWindow};
29use glow::HasContext;
30use raw_window_handle::HasWindowHandle;
31use winit::dpi::LogicalSize;
32use winit::event::{ElementState, Event, MouseButton, MouseScrollDelta, WindowEvent};
33use winit::event_loop::EventLoop;
34use winit::keyboard::{KeyCode, PhysicalKey};
35use winit::platform::pump_events::{EventLoopExtPumpEvents, PumpStatus};
36use winit::window::Window;
37use glam::{Mat4, Vec2, Vec3};
38use bytemuck::cast_slice;
39
40use crate::config::{EngineConfig, RenderConfig};
41use crate::scene::Scene;
42use crate::render::camera::ProofCamera;
43use crate::render::postfx::PostFxPipeline;
44use crate::input::{InputState, Key};
45use crate::glyph::atlas::FontAtlas;
46use crate::glyph::batch::GlyphInstance;
47use crate::render::ui_layer::UiLayer;
48use crate::render::screen_fx::ScreenFx;
49use crate::particle::gpu_density::{GpuDensityEntityData, GpuDensityRenderer};
50
51// ── Glyph vertex shader ────────────────────────────────────────────────────────
52
53const VERT_SRC: &str = r#"
54#version 330 core
55
56layout(location = 0) in vec2  v_pos;
57layout(location = 1) in vec2  v_uv;
58
59layout(location = 2)  in vec3  i_position;
60layout(location = 3)  in vec2  i_scale;
61layout(location = 4)  in float i_rotation;
62layout(location = 5)  in vec4  i_color;
63layout(location = 6)  in float i_emission;
64layout(location = 7)  in vec3  i_glow_color;
65layout(location = 8)  in float i_glow_radius;
66layout(location = 9)  in vec2  i_uv_offset;
67layout(location = 10) in vec2  i_uv_size;
68// x: 1.0 for a fill (ground, panel) that must not cast shadow.
69layout(location = 11) in vec2  i_flags;
70
71uniform mat4 u_view_proj;
72// Oversampling: each base instance is rendered u_n_copies times.
73// vertex_attrib_divisor is set to u_n_copies so all copies share the same
74// instance attributes. gl_InstanceID / u_n_copies selects the base particle;
75// gl_InstanceID % u_n_copies selects the copy and drives the jitter hash.
76uniform uint u_n_copies;
77
78out vec2  f_uv;
79out vec4  f_color;
80out float f_emission;
81out vec3  f_glow_color;
82out float f_glow_radius;
83out float f_fill;
84
85// Hash matching the CPU hf(seed, v) function — same constants, same bit ops.
86float hf(uint seed, uint v) {
87    uint n = seed * 374761393u + v * 668265263u;
88    n ^= (n >> 13u);
89    n *= 0x5851F42Du;
90    n ^= (n >> 16u);
91    return float(n & 0x00FFFFFFu) / float(0x01000000u);
92}
93
94void main() {
95    float c = cos(i_rotation);
96    float s = sin(i_rotation);
97    vec2 rotated = vec2(
98        v_pos.x * c - v_pos.y * s,
99        v_pos.x * s + v_pos.y * c
100    ) * i_scale;
101
102    // Per-copy position jitter — only active when oversampling.
103    // Seeds mirror the CPU oversampling: seed = real_id*17 + copy_id, slots 30/31.
104    vec3 jitter = vec3(0.0);
105    if (u_n_copies > 1u) {
106        uint real_id = uint(gl_InstanceID) / u_n_copies;
107        uint copy_id = uint(gl_InstanceID) % u_n_copies;
108        uint jseed   = real_id * 17u + copy_id;
109        jitter = vec3(
110            (hf(jseed, 30u) - 0.5) * i_scale.x * 0.70,
111            (hf(jseed, 31u) - 0.5) * i_scale.y * 0.70,
112            0.0
113        );
114    }
115
116    gl_Position = u_view_proj * vec4(i_position + jitter + vec3(rotated, 0.0), 1.0);
117    gl_Position.y = -gl_Position.y;  // FBO renders upside-down relative to screen
118
119    f_uv         = i_uv_offset + v_uv * i_uv_size;
120    // Divide alpha and emission by n_copies so n_copies additive contributions
121    // sum to the same luminance as a single unscaled instance.
122    float inv_n  = 1.0 / float(u_n_copies);
123    f_color      = vec4(i_color.rgb, i_color.a * inv_n);
124    f_emission   = i_emission * inv_n;
125    f_glow_color = i_glow_color;
126    f_glow_radius = i_glow_radius;
127    f_fill        = i_flags.x;
128}
129"#;
130
131/// Glyph fragment shader -- SDF rendering with outline, glow halo, and drop shadow.
132///
133/// The atlas stores Signed Distance Field values:
134///   128/255 = edge, >128 = inside, <128 = outside.
135///
136/// `o_color`    -> COLOR_ATTACHMENT0 -- blended scene color
137/// `o_emission` -> COLOR_ATTACHMENT1 -- bloom input
138const FRAG_SRC: &str = r#"
139#version 330 core
140
141in vec2  f_uv;
142in vec4  f_color;
143in float f_emission;
144in vec3  f_glow_color;
145in float f_glow_radius;
146in float f_fill;
147
148uniform sampler2D u_atlas;
149
150layout(location = 0) out vec4 o_color;
151layout(location = 1) out vec4 o_emission;
152// Coverage of matter, for the light map's shadows. Fills write none, and
153// cover whatever was under them.
154layout(location = 2) out vec4 o_occluder;
155
156void main() {
157    float dist = texture(u_atlas, f_uv).r;
158
159    // SDF thresholds (in normalized distance, 0.5 = edge)
160    float edge     = 0.5;
161    float softness = 0.08; // edge softness (antialiasing)
162
163    // Core glyph alpha (sharp edge with antialiasing)
164    float alpha = smoothstep(edge - softness, edge + softness, dist);
165
166    // Outline: a band just outside the edge
167    float outline_width = 0.06;
168    float outline_alpha = smoothstep(edge - outline_width - softness, edge - outline_width, dist)
169                        * (1.0 - smoothstep(edge - softness * 0.5, edge + softness * 0.5, dist));
170    vec3 outline_color = f_glow_color * 0.6;
171
172    // Glow halo: soft falloff outside the glyph
173    float glow_size  = 0.15 + f_glow_radius * 0.05;
174    float glow_alpha = smoothstep(edge - glow_size - 0.1, edge - 0.02, dist) * (1.0 - alpha);
175    glow_alpha *= clamp(f_glow_radius * 0.3, 0.0, 0.5);
176
177    // Drop shadow (offset sample)
178    vec2 shadow_offset = vec2(0.003, -0.004);
179    float shadow_dist = texture(u_atlas, f_uv + shadow_offset).r;
180    float shadow_alpha = smoothstep(edge - softness, edge + softness, shadow_dist) * 0.2;
181
182    // Discard if nothing visible
183    float total_alpha = max(max(alpha, outline_alpha), max(glow_alpha, shadow_alpha));
184    if (total_alpha < 0.01) discard;
185
186    // Composite layers
187    float em = clamp(f_emission * 0.5, 0.0, 1.0);
188    vec3 base_col = mix(f_color.rgb, f_glow_color, em);
189
190    // Shadow (darkest layer)
191    vec3 col = vec3(0.0);
192    float a = shadow_alpha * f_color.a * 0.3;
193
194    // Glow halo (behind outline)
195    col = mix(col, f_glow_color * 0.5, glow_alpha);
196    a = max(a, glow_alpha * f_color.a * 0.4);
197
198    // Outline
199    col = mix(col, outline_color, outline_alpha);
200    a = max(a, outline_alpha * f_color.a * 0.7);
201
202    // Core fill (on top)
203    col = mix(col, base_col, alpha);
204    a = max(a, alpha * f_color.a);
205
206    o_color = vec4(col, a);
207
208    // Emission for bloom
209    float bloom_strength = clamp(f_emission - 0.3, 0.0, 1.0);
210    float glow_boost = clamp(f_glow_radius * 0.15, 0.0, 0.8);
211    float em_alpha = max(alpha, glow_alpha * 0.5) * f_color.a;
212    o_emission = vec4(f_glow_color * (bloom_strength + glow_boost), em_alpha);
213    o_occluder = vec4(alpha * f_color.a * (1.0 - f_fill), 0.0, 0.0, a);
214}
215"#;
216
217// ── Unit quad geometry ─────────────────────────────────────────────────────────
218
219/// Unit quad: 6 vertices (2 CCW triangles), each: [pos_x, pos_y, uv_x, uv_y]
220#[rustfmt::skip]
221const QUAD_VERTS: [f32; 24] = [
222    -0.5,  0.5,  0.0, 1.0,
223    -0.5, -0.5,  0.0, 0.0,
224     0.5,  0.5,  1.0, 1.0,
225    -0.5, -0.5,  0.0, 0.0,
226     0.5, -0.5,  1.0, 0.0,
227     0.5,  0.5,  1.0, 1.0,
228];
229
230// ── FrameStats ─────────────────────────────────────────────────────────────────
231
232/// Per-frame rendering statistics.
233#[derive(Clone, Debug, Default)]
234pub struct FrameStats {
235    /// Frames per second (rolling average over 60 frames).
236    pub fps:              f32,
237    /// Time of last frame in seconds.
238    pub dt:               f32,
239    /// Number of glyphs drawn this frame.
240    pub glyph_count:      usize,
241    /// Number of particles drawn this frame.
242    pub particle_count:   usize,
243    /// Number of draw calls this frame.
244    pub draw_calls:       u32,
245    /// Total frame number since engine start.
246    pub frame_number:     u64,
247}
248
249/// Rolling FPS calculator over N frames.
250struct FpsCounter {
251    samples:   [f32; 60],
252    head:      usize,
253    filled:    bool,
254}
255
256impl FpsCounter {
257    fn new() -> Self { Self { samples: [0.016; 60], head: 0, filled: false } }
258
259    fn push(&mut self, dt: f32) {
260        self.samples[self.head] = dt.max(f32::EPSILON);
261        self.head = (self.head + 1) % 60;
262        if self.head == 0 { self.filled = true; }
263    }
264
265    fn fps(&self) -> f32 {
266        let count = if self.filled { 60 } else { self.head.max(1) };
267        let avg_dt: f32 = self.samples[..count].iter().sum::<f32>() / count as f32;
268        1.0 / avg_dt
269    }
270}
271
272// ── Pipeline ───────────────────────────────────────────────────────────────────
273
274/// The main render pipeline.
275///
276/// Created once by `ProofEngine::new()` and kept alive for the duration of the game.
277/// Owns the window, OpenGL context, shader programs, font atlas, glyph VAO, and
278/// the post-processing pipeline.
279#[allow(dead_code)]
280pub struct Pipeline {
281    // ── Runtime info ──────────────────────────────────────────────────────────
282    pub width:   u32,
283    pub height:  u32,
284    pub stats:   FrameStats,
285    running:     bool,
286
287    // ── Config snapshot (not a reference — the engine owns EngineConfig) ──────
288    render_config: RenderConfig,
289
290    // ── Windowing ────────────────────────────────────────────────────────────
291    event_loop: EventLoop<()>,
292    window:     Window,
293    surface:    Surface<WindowSurface>,
294    context:    PossiblyCurrentContext,
295
296    // ── OpenGL glyph pass ─────────────────────────────────────────────────────
297    gl:            glow::Context,
298    program:       glow::Program,
299    vao:           glow::VertexArray,
300    quad_vbo:      glow::Buffer,
301    instance_vbo:  glow::Buffer,
302    atlas_tex:     glow::Texture,
303    loc_view_proj: glow::UniformLocation,
304    loc_n_copies:  Option<glow::UniformLocation>,
305
306    // ── Post-processing pipeline (the real deal — reads RenderConfig) ─────────
307    postfx: PostFxPipeline,
308
309    // ── Font atlas ────────────────────────────────────────────────────────────
310    atlas: FontAtlas,
311
312    // ── Screen-space UI pass ──────────────────────────────────────────────────
313    // Builds instances from a UiLayer's draw queue and paints them in pixel
314    // coordinates after post-processing, so panels and text stay crisp.
315    ui_renderer: super::ui_layer_renderer::UiLayerRenderer,
316    /// Whether `render_frame` already built this frame's UI instances, so
317    /// `render_ui` need not build them again.
318    ui_prepared: bool,
319
320    // ── GPU density entities ──────────────────────────────────────────────────
321    /// Created the first time an entity is queued.
322    density: Option<GpuDensityRenderer>,
323    density_entities: Vec<GpuDensityEntityData>,
324    density_budget: u32,
325
326    // ── SVOGI Global Illumination ───────────────────────────────────────────
327    pub svogi: crate::svogi::integration::CascadedSvogi,
328
329    // ── Volumetric fog ──────────────────────────────────────────────────────
330    pub fog: crate::volumetric_fog::VolumetricFogPipeline,
331
332    // ── CPU-side glyph batch ──────────────────────────────────────────────────
333    instances: Vec<GlyphInstance>,
334
335    // ── Timing ────────────────────────────────────────────────────────────────
336    fps_counter:  FpsCounter,
337    frame_start:  Instant,
338    scene_time:   f32,
339
340    // ── Mouse state ───────────────────────────────────────────────────────────
341    mouse_pos:      Vec2,
342    mouse_pos_prev: Vec2,
343    /// Normalized device coordinates (NDC) of the mouse cursor.
344    mouse_ndc:      Vec2,
345
346    // ── Raw events for external consumers (egui) ────────────────────────────
347    /// Raw winit WindowEvents collected during poll_events, drained by consumers.
348    pub raw_window_events: Vec<winit::event::WindowEvent>,
349}
350
351impl Pipeline {
352    /// Initialize window, OpenGL 3.3 Core context, shader programs, font atlas, and PostFxPipeline.
353    pub fn init(config: &EngineConfig) -> Self {
354        // ── 1. winit EventLoop ────────────────────────────────────────────────
355        let event_loop = EventLoop::new().expect("EventLoop::new");
356
357        // ── 2. Window attributes (winit 0.30 API) ─────────────────────────────
358        let window_attrs = Window::default_attributes()
359            .with_title(&config.window_title)
360            .with_inner_size(LogicalSize::new(config.window_width, config.window_height))
361            .with_resizable(true);
362
363        // ── 3. GL config via DisplayBuilder (glutin-winit 0.5) ────────────────
364        let template = ConfigTemplateBuilder::new()
365            .with_alpha_size(8)
366            .with_depth_size(0);
367
368        let display_builder = DisplayBuilder::new()
369            .with_window_attributes(Some(window_attrs));
370
371        let (window, gl_config) = display_builder
372            .build(&event_loop, template, |mut configs| {
373                configs.next().expect("no suitable GL config found")
374            })
375            .expect("DisplayBuilder::build failed");
376
377        let window = window.expect("window was not created");
378        let display = gl_config.display();
379
380        // ── 4. OpenGL context — try 4.3 (compute shaders) then fall back to 3.3 ─
381        let raw_handle = window.window_handle().unwrap().as_raw();
382        let ctx_attrs_43 = ContextAttributesBuilder::new()
383            .with_context_api(ContextApi::OpenGl(Some(Version::new(4, 3))))
384            .build(Some(raw_handle));
385        let ctx_attrs_33 = ContextAttributesBuilder::new()
386            .with_context_api(ContextApi::OpenGl(Some(Version::new(3, 3))))
387            .build(Some(raw_handle));
388
389        let not_current = unsafe {
390            display.create_context(&gl_config, &ctx_attrs_43)
391                   .unwrap_or_else(|_| {
392                       display.create_context(&gl_config, &ctx_attrs_33)
393                              .expect("create_context failed (both GL 4.3 and 3.3)")
394                   })
395        };
396
397        // ── 5. Window surface ─────────────────────────────────────────────────
398        let size = window.inner_size();
399        let w = size.width.max(1);
400        let h = size.height.max(1);
401
402        let surface_attrs = window
403            .build_surface_attributes(Default::default())
404            .expect("build_surface_attributes failed");
405
406        let surface = unsafe {
407            display.create_window_surface(&gl_config, &surface_attrs)
408                   .expect("create_window_surface failed")
409        };
410
411        // ── 6. Make current ───────────────────────────────────────────────────
412        let context = not_current.make_current(&surface)
413                                 .expect("make_current failed");
414        if config.render.vsync {
415            use glutin::surface::SwapInterval;
416            if let Err(e) = surface.set_swap_interval(
417                &context,
418                SwapInterval::Wait(NonZeroU32::new(1).unwrap()),
419            ) {
420                log::warn!("vsync unavailable: {e}");
421            }
422        }
423
424        // ── 7. glow context from proc address ─────────────────────────────────
425        let gl = unsafe {
426            glow::Context::from_loader_function(|sym| {
427                let sym_c = CString::new(sym).unwrap();
428                display.get_proc_address(sym_c.as_c_str()) as *const _
429            })
430        };
431
432        // ── 8. Compile glyph program ──────────────────────────────────────────
433        let program = unsafe { compile_program(&gl, VERT_SRC, FRAG_SRC) };
434        let loc_view_proj = unsafe {
435            gl.get_uniform_location(program, "u_view_proj")
436              .expect("uniform u_view_proj not found")
437        };
438        let loc_n_copies = unsafe {
439            gl.get_uniform_location(program, "u_n_copies")
440        };
441        unsafe {
442            gl.use_program(Some(program));
443            if let Some(loc) = gl.get_uniform_location(program, "u_atlas") {
444                gl.uniform_1_i32(Some(&loc), 0);
445            }
446            // Default: no oversampling
447            if let Some(ref loc) = loc_n_copies {
448                gl.uniform_1_u32(Some(loc), 1u32);
449            }
450        }
451
452        // ── 9. Geometry: VAO + VBOs ───────────────────────────────────────────
453        let (vao, quad_vbo, instance_vbo) = unsafe { setup_vao(&gl) };
454
455        // ── 10. Font atlas ────────────────────────────────────────────────────
456        let atlas     = FontAtlas::build(config.render.font_size as f32);
457        let atlas_tex = unsafe { upload_atlas(&gl, &atlas) };
458
459        // ── 11. PostFxPipeline — dual-attachment FBOs + bloom shaders ────────
460        let postfx = unsafe { PostFxPipeline::new(&gl, w, h, config.render.render_scale) };
461
462        // ── 12. Global GL state ───────────────────────────────────────────────
463        unsafe {
464            gl.enable(glow::BLEND);
465            gl.blend_func(glow::SRC_ALPHA, glow::ONE_MINUS_SRC_ALPHA);
466            gl.clear_color(0.02, 0.02, 0.05, 1.0);
467            gl.viewport(0, 0, w as i32, h as i32);
468        }
469
470        log::info!(
471            "Pipeline ready — {}×{} — font atlas {}×{} ({} chars) — PostFxPipeline wired",
472            w, h, atlas.width, atlas.height, atlas.uvs.len()
473        );
474
475        Self {
476            width: w, height: h,
477            stats: FrameStats::default(),
478            running: true,
479            render_config: config.render.clone(),
480            event_loop, window, surface, context,
481            gl, program, vao, quad_vbo, instance_vbo, atlas_tex, loc_view_proj, loc_n_copies,
482            postfx,
483            atlas,
484            ui_renderer: super::ui_layer_renderer::UiLayerRenderer::new(),
485            ui_prepared: false,
486            density: None,
487            density_entities: Vec::new(),
488            density_budget: 0,
489            instances: Vec::with_capacity(8192),
490            fps_counter: FpsCounter::new(),
491            frame_start: Instant::now(),
492            scene_time: 0.0,
493            mouse_pos: Vec2::ZERO,
494            mouse_pos_prev: Vec2::ZERO,
495            mouse_ndc: Vec2::ZERO,
496            raw_window_events: Vec::new(),
497            svogi: crate::svogi::integration::CascadedSvogi::new(3, 64, 50.0),
498            fog: crate::volumetric_fog::VolumetricFogPipeline::new(
499                crate::volumetric_fog::FogPresets::combat()
500            ),
501        }
502    }
503
504    /// Hand over this frame's GPU density entities and the particle budget
505    /// each is drawn with. They are drawn into the scene after the glyph
506    /// pass, so they bloom and grade with everything else.
507    pub fn set_density_entities(&mut self, entities: &[GpuDensityEntityData], budget: u32) {
508        self.density_entities.clear();
509        self.density_entities.extend_from_slice(entities);
510        self.density_budget = budget;
511        if !self.density_entities.is_empty() && self.density.is_none() {
512            self.density = Some(unsafe { GpuDensityRenderer::new(&self.gl) });
513        }
514    }
515
516    /// Update the render config used by the PostFx pipeline this frame.
517    /// Call from `ProofEngine::run()` whenever the config changes.
518    pub fn update_render_config(&mut self, config: &RenderConfig) {
519        let old_scale = self.render_config.render_scale;
520        self.render_config = config.clone();
521        // A change of render scale is a change of target size.
522        if (config.render_scale - old_scale).abs() > 1e-4 {
523            unsafe { self.postfx.resize(&self.gl, self.width, self.height, config.render_scale); }
524        }
525    }
526
527    /// Poll window events and update `InputState`. Returns false on quit.
528    pub fn poll_events(&mut self, input: &mut InputState) -> bool {
529        input.clear_frame();
530        self.mouse_pos_prev = self.mouse_pos;
531
532        let mut should_exit = false;
533        let mut resize:     Option<(u32, u32)>  = None;
534        let mut key_events: Vec<(KeyCode, bool)> = Vec::new();
535        let mut mouse_moved:     Option<(f64, f64)> = None;
536        let mut mouse_buttons:   Vec<(MouseButton, bool)> = Vec::new();
537        let mut scroll_delta:    f32 = 0.0;
538
539        self.raw_window_events.clear();
540
541        #[allow(deprecated)]
542        let status = self.event_loop.pump_events(Some(Duration::ZERO), |event, elwt| {
543            match event {
544                Event::WindowEvent { event: we, .. } => match we {
545                    WindowEvent::CloseRequested => {
546                        should_exit = true;
547                        elwt.exit();
548                    }
549                    WindowEvent::Resized(s) => {
550                        resize = Some((s.width, s.height));
551                    }
552                    WindowEvent::KeyboardInput { event: key_ev, .. } => {
553                        if let PhysicalKey::Code(kc) = key_ev.physical_key {
554                            let pressed = key_ev.state == ElementState::Pressed;
555                            key_events.push((kc, pressed));
556                        }
557                    }
558                    WindowEvent::CursorMoved { position, .. } => {
559                        mouse_moved = Some((position.x, position.y));
560                    }
561                    WindowEvent::MouseInput { button, state, .. } => {
562                        let pressed = state == ElementState::Pressed;
563                        mouse_buttons.push((button, pressed));
564                    }
565                    WindowEvent::MouseWheel { delta, .. } => {
566                        scroll_delta += match delta {
567                            MouseScrollDelta::LineDelta(_, y) => y,
568                            MouseScrollDelta::PixelDelta(d)   => d.y as f32 / 40.0,
569                        };
570                    }
571                    _ => {}
572                }
573                _ => {}
574            }
575        });
576
577        // ── Apply resize ───────────────────────────────────────────────────────
578        if let Some((w, h)) = resize {
579            if w > 0 && h > 0 {
580                self.surface.resize(
581                    &self.context,
582                    NonZeroU32::new(w).unwrap(),
583                    NonZeroU32::new(h).unwrap(),
584                );
585                unsafe { self.gl.viewport(0, 0, w as i32, h as i32); }
586                self.width  = w;
587                self.height = h;
588                input.window_resized = Some((w, h));
589                unsafe { self.postfx.resize(&self.gl, w, h, self.render_config.render_scale); }
590            }
591        }
592
593        // ── Apply key events ───────────────────────────────────────────────────
594        for (kc, pressed) in key_events {
595            if let Some(key) = keycode_to_engine(kc) {
596                if pressed {
597                    input.keys_pressed.insert(key);
598                    input.keys_just_pressed.insert(key);
599                } else {
600                    input.keys_pressed.remove(&key);
601                    input.keys_just_released.insert(key);
602                }
603            }
604        }
605
606        // ── Apply mouse events ─────────────────────────────────────────────────
607        if let Some((x, y)) = mouse_moved {
608            self.mouse_pos = Vec2::new(x as f32, y as f32);
609            input.mouse_x = x as f32;
610            input.mouse_y = y as f32;
611            // Compute NDC: x/y ∈ [0, width/height] → [-1, 1]
612            let w = self.width.max(1) as f32;
613            let h = self.height.max(1) as f32;
614            self.mouse_ndc = Vec2::new(
615                (x as f32 / w) * 2.0 - 1.0,
616                1.0 - (y as f32 / h) * 2.0,
617            );
618            input.mouse_ndc = self.mouse_ndc;
619            input.mouse_delta = self.mouse_pos - self.mouse_pos_prev;
620        }
621
622        for (button, pressed) in mouse_buttons {
623            match button {
624                MouseButton::Left   => {
625                    if pressed { input.mouse_left_just_pressed  = true; }
626                    else       { input.mouse_left_just_released = true; }
627                    input.mouse_left = pressed;
628                }
629                MouseButton::Right  => {
630                    if pressed { input.mouse_right_just_pressed  = true; }
631                    else       { input.mouse_right_just_released = true; }
632                    input.mouse_right = pressed;
633                }
634                MouseButton::Middle => {
635                    if pressed { input.mouse_middle_just_pressed = true; }
636                    input.mouse_middle = pressed;
637                }
638                _ => {}
639            }
640        }
641
642        input.scroll_delta = scroll_delta;
643
644        // ── Exit check ─────────────────────────────────────────────────────────
645        if should_exit || matches!(status, PumpStatus::Exit(_)) {
646            self.running = false;
647        }
648        self.running
649    }
650
651    /// Collect all visible glyphs + particles from the scene, upload to the GPU,
652    /// and execute the full multi-pass rendering pipeline.
653    pub fn render(&mut self, scene: &Scene, camera: &ProofCamera) {
654        let fx = ScreenFx::default();
655        self.render_frame(scene, camera, None, &fx);
656    }
657
658    /// Render the scene, the UI layer's world pass, and post-processing.
659    ///
660    /// With `ui` given, its world-pass commands are painted into the HDR
661    /// scene buffer after the 3D glyphs and before post-processing, so they
662    /// bloom, grade and shake with the scene; its HUD-pass commands are
663    /// built here and painted by [`render_ui`](Self::render_ui) afterwards.
664    /// `fx` supplies the frame's shockwaves, flash and light-shaft source.
665    pub fn render_frame(
666        &mut self,
667        scene: &Scene,
668        camera: &ProofCamera,
669        ui: Option<&UiLayer>,
670        fx: &ScreenFx,
671    ) {
672        // ── Frame timing ───────────────────────────────────────────────────────
673        let now = Instant::now();
674        let dt  = now.duration_since(self.frame_start).as_secs_f32().min(0.1);
675        self.frame_start = now;
676        self.scene_time  = scene.time;
677
678        self.fps_counter.push(dt);
679        self.stats.fps          = self.fps_counter.fps();
680        self.stats.dt           = dt;
681        self.stats.frame_number += 1;
682
683        // ── Build camera matrices ──────────────────────────────────────────────
684        let pos    = camera.position.position();
685        let tgt    = camera.target.position();
686        let fov    = camera.fov.position;
687        let aspect = if self.height > 0 { self.width as f32 / self.height as f32 } else { 1.0 };
688        let view      = Mat4::look_at_rh(pos, tgt, Vec3::Y);
689        let proj      = Mat4::perspective_rh_gl(fov.to_radians(), aspect, camera.near, camera.far);
690        let view_proj = proj * view;
691
692        // ── Update SVOGI (voxelize scene, inject light, propagate) ───────────
693        if self.render_config.global_illumination {
694            use crate::svogi::inject::{LightSource, DirectionalLight, PointLight};
695            let sun = LightSource::Directional(DirectionalLight {
696                direction: Vec3::new(-0.5, 1.0, 0.8).normalize(),
697                color: Vec3::new(0.8, 0.75, 0.65),
698                intensity: 1.0,
699            });
700            let mut all_lights = vec![sun];
701            // Inject emissive glyphs as point lights
702            let mut emissive_count = 0;
703            for (_, glyph) in scene.glyphs.iter() {
704                if glyph.emission > 0.5 && emissive_count < 50 {
705                    all_lights.push(LightSource::Point(PointLight {
706                        position: glyph.position,
707                        color: glyph.glow_color,
708                        intensity: glyph.emission * 0.3,
709                        radius: glyph.glow_radius * 2.0,
710                    }));
711                    emissive_count += 1;
712                }
713            }
714            self.svogi.update(dt, &[], &all_lights, &[]);
715        }
716
717        // ── Update volumetric fog ─────────────────────────────────────────────
718        if self.render_config.volumetric_fog {
719            use crate::volumetric_fog::FogLight;
720            let inv_vp = view_proj.inverse();
721            let fog_lights = vec![
722                FogLight::Directional {
723                    direction: Vec3::new(-0.3, -0.8, -0.5).normalize(),
724                    color: Vec3::new(0.6, 0.55, 0.5),
725                    intensity: 0.5,
726                },
727            ];
728            self.fog.update(dt, &inv_vp, pos, &fog_lights, &[]);
729        }
730
731        // ── Build glyph batch ──────────────────────────────────────────────────
732        self.instances.clear();
733        let mut glyph_count    = 0;
734        let mut particle_count = 0;
735
736        // Glyphs sorted by render layer (entity < particle < UI)
737        for (_, glyph) in scene.glyphs.iter() {
738            if !glyph.visible { continue; }
739            let life_scale = if let Some(ref f) = glyph.life_function {
740                f.evaluate(scene.time, 0.0)
741            } else {
742                1.0
743            };
744            let uv = self.atlas.uv_for(glyph.character);
745
746            // Apply distance fog: glyphs further from camera fade toward fog color
747            let dist = (glyph.position - pos).length();
748            let fog_density = 0.003; // very subtle
749            let fog_factor = (-dist * fog_density).exp(); // 1.0 = no fog, 0.0 = fully fogged
750            let fog_color = [0.03f32, 0.04, 0.06]; // dark blue-ish fog
751            let mut color = glyph.color.to_array();
752            color[0] = color[0] * fog_factor + fog_color[0] * (1.0 - fog_factor);
753            color[1] = color[1] * fog_factor + fog_color[1] * (1.0 - fog_factor);
754            color[2] = color[2] * fog_factor + fog_color[2] * (1.0 - fog_factor);
755            color[3] *= fog_factor.max(0.1); // alpha also fades but not to zero
756            let emission_fogged = glyph.emission * fog_factor;
757
758            self.instances.push(GlyphInstance {
759                position:    glyph.position.to_array(),
760                scale:       [glyph.scale.x * life_scale, glyph.scale.y * life_scale],
761                rotation:    glyph.rotation,
762                color,
763                emission:    emission_fogged,
764                glow_color:  glyph.glow_color.to_array(),
765                glow_radius: glyph.glow_radius * fog_factor,
766                uv_offset:   uv.offset(),
767                uv_size:     uv.size(),
768                _pad:        [0.0; 2],
769            });
770            glyph_count += 1;
771        }
772
773        for particle in scene.particles.iter() {
774            let g = &particle.glyph;
775            if !g.visible { continue; }
776            let uv = self.atlas.uv_for(g.character);
777            // Apply fog to particles too
778            let dist = (g.position - pos).length();
779            let fog_factor = (-dist * 0.003).exp();
780            let fog_color = [0.03f32, 0.04, 0.06];
781            let mut color = g.color.to_array();
782            color[0] = color[0] * fog_factor + fog_color[0] * (1.0 - fog_factor);
783            color[1] = color[1] * fog_factor + fog_color[1] * (1.0 - fog_factor);
784            color[2] = color[2] * fog_factor + fog_color[2] * (1.0 - fog_factor);
785            color[3] *= fog_factor.max(0.1);
786
787            self.instances.push(GlyphInstance {
788                position:    g.position.to_array(),
789                scale:       [g.scale.x, g.scale.y],
790                rotation:    g.rotation,
791                color,
792                emission:    g.emission * fog_factor,
793                glow_color:  g.glow_color.to_array(),
794                glow_radius: g.glow_radius * fog_factor,
795                uv_offset:   uv.offset(),
796                uv_size:     uv.size(),
797                _pad:        [0.0; 2],
798            });
799            particle_count += 1;
800        }
801
802        self.stats.glyph_count    = glyph_count;
803        self.stats.particle_count = particle_count;
804        self.stats.draw_calls     = 0;
805
806        // ── World-pass UI ──────────────────────────────────────────────────────
807        //
808        // Built once here for both passes. The world pass is projected in
809        // screen pixels like the HUD, then shifted by the camera's trauma so
810        // a blow moves the world and not the interface.
811        let mut world_proj = None;
812        if let Some(ui) = ui {
813            self.ui_renderer.build_instances(ui, &self.atlas);
814            self.ui_prepared = true;
815            if self.render_config.world_ui_in_scene && self.ui_renderer.world_count() > 0 {
816                let trauma = camera.shake.trauma.clamp(0.0, 1.0);
817                let amp = trauma * trauma * self.render_config.shake_pixels;
818                let t = self.scene_time;
819                let shake = Vec3::new((t * 47.3).sin() * amp, (t * 31.7).cos() * amp, 0.0);
820                world_proj = Some(ui.world_projection() * Mat4::from_translation(shake));
821            }
822        }
823
824        // ── Execute render passes ──────────────────────────────────────────────
825        unsafe { self.execute_render_passes(view_proj, world_proj, fx); }
826    }
827
828    /// Paint a screen-space UI layer on top of the finished frame.
829    ///
830    /// Runs after post-processing and writes straight to the default
831    /// framebuffer, so panels and text are not smeared by bloom, chromatic
832    /// aberration or grain — a HUD has to stay readable.
833    ///
834    /// Call once per frame, after `render`, before `swap`.
835    pub fn render_ui(&mut self, ui: &super::ui_layer::UiLayer) {
836        let prepared = std::mem::replace(&mut self.ui_prepared, false);
837        if ui.command_count() == 0 {
838            return;
839        }
840        if !prepared {
841            self.ui_renderer.build_instances(ui, &self.atlas);
842        }
843        let proj = ui.projection();
844        // With the world pass switched off, its commands paint here instead,
845        // under the HUD, which is how the layer behaved before it existed.
846        if !self.render_config.world_ui_in_scene && self.ui_renderer.world_count() > 0 {
847            unsafe { self.draw_ui_pass(proj, true) };
848            self.stats.draw_calls += 1;
849        }
850        if self.ui_renderer.glyph_count() == 0 {
851            return;
852        }
853        unsafe { self.draw_ui_pass(proj, false) };
854        self.stats.draw_calls += 1;
855    }
856
857    /// Upload and draw one of the UI instance buffers, straight to the
858    /// screen, with an orthographic projection. `world` picks the world-pass
859    /// buffer; otherwise the HUD buffer.
860    unsafe fn draw_ui_pass(&mut self, proj: Mat4, world: bool) {
861        let gl = &self.gl;
862        let (bytes, count) = if world {
863            (self.ui_renderer.world_bytes(), self.ui_renderer.world_count())
864        } else {
865            (self.ui_renderer.glyph_bytes(), self.ui_renderer.glyph_count())
866        };
867
868        // Straight to the screen: post-processing has already composited.
869        gl.bind_framebuffer(glow::FRAMEBUFFER, None);
870        gl.viewport(0, 0, self.width as i32, self.height as i32);
871
872        // UI is 2D and ordered by draw call, so depth testing would only cause
873        // z-fighting between overlapping panels.
874        gl.disable(glow::DEPTH_TEST);
875        gl.enable(glow::BLEND);
876        gl.blend_func(glow::SRC_ALPHA, glow::ONE_MINUS_SRC_ALPHA);
877
878        gl.bind_buffer(glow::ARRAY_BUFFER, Some(self.instance_vbo));
879        gl.buffer_data_u8_slice(glow::ARRAY_BUFFER, bytes, glow::DYNAMIC_DRAW);
880
881        gl.use_program(Some(self.program));
882        gl.uniform_matrix_4_f32_slice(Some(&self.loc_view_proj), false, &proj.to_cols_array());
883        // The oversampling trick used by the 3D pass would smear UI text, so
884        // the UI always draws exactly one copy per instance.
885        gl.uniform_1_u32(self.loc_n_copies.as_ref(), 1);
886        gl.active_texture(glow::TEXTURE0);
887        gl.bind_texture(glow::TEXTURE_2D, Some(self.atlas_tex));
888        gl.bind_vertex_array(Some(self.vao));
889        for loc in 2u32..=11 {
890            gl.vertex_attrib_divisor(loc, 1);
891        }
892        gl.draw_arrays_instanced(glow::TRIANGLES, 0, 6, count as i32);
893
894        // Restore state the 3D pass expects on the next frame.
895        gl.enable(glow::DEPTH_TEST);
896    }
897
898    /// Swap back buffer to screen. Returns false on window close.
899    pub fn swap(&mut self) -> bool {
900        if let Err(e) = self.surface.swap_buffers(&self.context) {
901            log::error!("swap_buffers failed: {e}");
902            self.running = false;
903        }
904        self.running
905    }
906
907    // ── Public accessors for editor/egui integration ──────────────────────────
908
909    /// Get a reference to the raw glow OpenGL context.
910    /// Used by egui-glow to render UI on top of the scene.
911    pub fn gl(&self) -> &glow::Context {
912        &self.gl
913    }
914
915    /// Get the window reference (for egui-winit event processing).
916    pub fn window(&self) -> &Window {
917        &self.window
918    }
919
920    /// The framebuffer size the viewport is actually set to.
921    ///
922    /// This is what screen-space passes must project against. On a scaled
923    /// display it can differ from the window's logical size, and projecting
924    /// against the wrong one magnifies the whole UI.
925    pub fn render_size(&self) -> (u32, u32) {
926        (self.width, self.height)
927    }
928
929    /// Read the frame that is currently on screen back off the GPU.
930    ///
931    /// Returns `(width, height, rgba)` with the bottom row first, which is how
932    /// OpenGL stores it. Call this after everything for the frame has been
933    /// drawn and before the buffers are swapped, or the read comes back empty.
934    pub fn read_frame(&self) -> (u32, u32, Vec<u8>) {
935        let (w, h) = (self.width, self.height);
936        let mut buf = vec![0u8; (w as usize) * (h as usize) * 4];
937        unsafe {
938            let gl = &self.gl;
939            gl.bind_framebuffer(glow::FRAMEBUFFER, None);
940            gl.read_buffer(glow::BACK);
941            gl.pixel_store_i32(glow::PACK_ALIGNMENT, 1);
942            gl.read_pixels(
943                0,
944                0,
945                w as i32,
946                h as i32,
947                glow::RGBA,
948                glow::UNSIGNED_BYTE,
949                glow::PixelPackData::Slice(Some(&mut buf)),
950            );
951        }
952        (w, h, buf)
953    }
954
955    /// Get the current window size.
956    pub fn window_size(&self) -> (u32, u32) {
957        let size = self.window.inner_size();
958        (size.width, size.height)
959    }
960
961    // ── Private render pass execution ─────────────────────────────────────────
962
963    unsafe fn execute_render_passes(
964        &mut self,
965        view_proj: Mat4,
966        world_proj: Option<Mat4>,
967        fx: &ScreenFx,
968    ) {
969        let gl = &self.gl;
970
971        // ── Pass 0: clear the HDR scene targets ────────────────────────────────
972        //
973        // At render scale, which may differ from the window. A dark
974        // blue-black ground rather than pure black, so the vignette and the
975        // dither have something to work against.
976        let (sw, sh) = self.postfx.scene_size();
977        gl.bind_framebuffer(glow::FRAMEBUFFER, Some(self.postfx.scene_fbo));
978        gl.viewport(0, 0, sw as i32, sh as i32);
979        gl.clear_color(0.02, 0.025, 0.04, 1.0);
980        gl.clear(glow::COLOR_BUFFER_BIT);
981        // The occluder buffer starts empty rather than at the ground colour.
982        gl.clear_buffer_f32_slice(glow::COLOR, 2, &[0.0, 0.0, 0.0, 0.0]);
983        gl.enable(glow::BLEND);
984        gl.blend_func(glow::SRC_ALPHA, glow::ONE_MINUS_SRC_ALPHA);
985
986        // ── Pass 1: Render glyphs ────────────────────────────────────────────
987
988        if !self.instances.is_empty() {
989            // Upload instance data
990            gl.bind_buffer(glow::ARRAY_BUFFER, Some(self.instance_vbo));
991            gl.buffer_data_u8_slice(
992                glow::ARRAY_BUFFER,
993                cast_slice(self.instances.as_slice()),
994                glow::DYNAMIC_DRAW,
995            );
996
997            // Oversampling: each base instance is rendered n_copies times.
998            // vertex_attrib_divisor = n_copies → all n_copies share the same
999            // attribute data. The vertex shader uses gl_InstanceID to derive
1000            // the copy index and compute per-copy position jitter.
1001            let n_copies = self.render_config.particle_multiplier
1002                .ceil().max(1.0) as u32;
1003
1004            gl.use_program(Some(self.program));
1005            gl.uniform_matrix_4_f32_slice(
1006                Some(&self.loc_view_proj),
1007                false,
1008                &view_proj.to_cols_array(),
1009            );
1010            gl.uniform_1_u32(self.loc_n_copies.as_ref(), n_copies);
1011            gl.active_texture(glow::TEXTURE0);
1012            gl.bind_texture(glow::TEXTURE_2D, Some(self.atlas_tex));
1013            gl.bind_vertex_array(Some(self.vao));
1014            // Set attribute divisor to n_copies so each base instance repeats
1015            // n_copies times before advancing to the next instance in the VBO.
1016            for loc in 2u32..=11 {
1017                gl.vertex_attrib_divisor(loc, n_copies);
1018            }
1019            gl.draw_arrays_instanced(
1020                glow::TRIANGLES, 0, 6,
1021                (self.instances.len() as u32 * n_copies) as i32,
1022            );
1023            self.stats.draw_calls += 1;
1024        }
1025
1026        // ── Pass 1a: GPU density entities ──────────────────────────────────────
1027        //
1028        // Millions of particles derived on the GPU from a few bones. Into
1029        // the same HDR targets, before the world pass so screen-space matter
1030        // can stand in front of them.
1031        if let Some(ref mut density) = self.density {
1032            if !self.density_entities.is_empty() {
1033                let draws = density.draw(
1034                    gl,
1035                    &self.density_entities,
1036                    self.density_budget,
1037                    &view_proj,
1038                    (sw, sh),
1039                    self.scene_time,
1040                );
1041                self.stats.draw_calls += draws;
1042                self.stats.particle_count += density.drawn as usize;
1043            }
1044        }
1045
1046        // ── Pass 1b: the UI layer's world pass ─────────────────────────────────
1047        //
1048        // Same program, same instance layout, projected in screen pixels
1049        // rather than through the camera, into the same HDR targets. From
1050        // here on the post-processing cannot tell it from the 3D scene.
1051        if let Some(wp) = world_proj {
1052            let count = self.ui_renderer.world_count();
1053            if count > 0 {
1054                gl.bind_buffer(glow::ARRAY_BUFFER, Some(self.instance_vbo));
1055                gl.buffer_data_u8_slice(
1056                    glow::ARRAY_BUFFER,
1057                    self.ui_renderer.world_bytes(),
1058                    glow::DYNAMIC_DRAW,
1059                );
1060                gl.use_program(Some(self.program));
1061                gl.uniform_matrix_4_f32_slice(
1062                    Some(&self.loc_view_proj),
1063                    false,
1064                    &wp.to_cols_array(),
1065                );
1066                // One copy per instance: the oversampling jitter is sized for
1067                // the 3D scene and would smear pixel-placed matter.
1068                gl.uniform_1_u32(self.loc_n_copies.as_ref(), 1);
1069                gl.active_texture(glow::TEXTURE0);
1070                gl.bind_texture(glow::TEXTURE_2D, Some(self.atlas_tex));
1071                gl.bind_vertex_array(Some(self.vao));
1072                for loc in 2u32..=11 {
1073                    gl.vertex_attrib_divisor(loc, 1);
1074                }
1075                gl.draw_arrays_instanced(glow::TRIANGLES, 0, 6, count as i32);
1076                self.stats.draw_calls += 1;
1077            }
1078        }
1079
1080        // ── Passes 2+: bloom, composite, anti-aliasing ─────────────────────────
1081        let draws = self.postfx.run(
1082            gl, &self.render_config, fx, self.width, self.height, self.scene_time,
1083        );
1084        self.stats.draw_calls += draws;
1085    }
1086}
1087
1088// ── GL helper functions ────────────────────────────────────────────────────────
1089
1090/// Compile a vertex + fragment shader pair into a linked GL program.
1091unsafe fn compile_program(gl: &glow::Context, vert_src: &str, frag_src: &str) -> glow::Program {
1092    let vs = gl.create_shader(glow::VERTEX_SHADER).expect("create vertex shader");
1093    gl.shader_source(vs, vert_src);
1094    gl.compile_shader(vs);
1095    if !gl.get_shader_compile_status(vs) {
1096        let log = gl.get_shader_info_log(vs);
1097        panic!("Vertex shader compile error:\n{log}");
1098    }
1099
1100    let fs = gl.create_shader(glow::FRAGMENT_SHADER).expect("create fragment shader");
1101    gl.shader_source(fs, frag_src);
1102    gl.compile_shader(fs);
1103    if !gl.get_shader_compile_status(fs) {
1104        let log = gl.get_shader_info_log(fs);
1105        panic!("Fragment shader compile error:\n{log}");
1106    }
1107
1108    let prog = gl.create_program().expect("create shader program");
1109    gl.attach_shader(prog, vs);
1110    gl.attach_shader(prog, fs);
1111    gl.link_program(prog);
1112    if !gl.get_program_link_status(prog) {
1113        let log = gl.get_program_info_log(prog);
1114        panic!("Shader link error:\n{log}");
1115    }
1116
1117    gl.detach_shader(prog, vs);
1118    gl.detach_shader(prog, fs);
1119    gl.delete_shader(vs);
1120    gl.delete_shader(fs);
1121    prog
1122}
1123
1124/// Create VAO with per-vertex quad data (locations 0–1) and per-instance data (locations 2–10).
1125unsafe fn setup_vao(gl: &glow::Context) -> (glow::VertexArray, glow::Buffer, glow::Buffer) {
1126    let vao = gl.create_vertex_array().expect("create vao");
1127    gl.bind_vertex_array(Some(vao));
1128
1129    // ── Quad geometry VBO ─────────────────────────────────────────────────────
1130    let quad_vbo = gl.create_buffer().expect("create quad_vbo");
1131    gl.bind_buffer(glow::ARRAY_BUFFER, Some(quad_vbo));
1132    gl.buffer_data_u8_slice(glow::ARRAY_BUFFER, cast_slice(&QUAD_VERTS), glow::STATIC_DRAW);
1133    // location 0: vec2 v_pos  (offset 0, stride 16)
1134    gl.vertex_attrib_pointer_f32(0, 2, glow::FLOAT, false, 16, 0);
1135    gl.enable_vertex_attrib_array(0);
1136    // location 1: vec2 v_uv   (offset 8, stride 16)
1137    gl.vertex_attrib_pointer_f32(1, 2, glow::FLOAT, false, 16, 8);
1138    gl.enable_vertex_attrib_array(1);
1139
1140    // ── Instance VBO (per-glyph data) ─────────────────────────────────────────
1141    let instance_vbo = gl.create_buffer().expect("create instance_vbo");
1142    gl.bind_buffer(glow::ARRAY_BUFFER, Some(instance_vbo));
1143
1144    let stride = std::mem::size_of::<GlyphInstance>() as i32;
1145
1146    // Macro: set up an instanced float attribute.
1147    macro_rules! inst_attr {
1148        ($loc:expr, $count:expr, $off:expr) => {{
1149            gl.vertex_attrib_pointer_f32($loc, $count, glow::FLOAT, false, stride, $off);
1150            gl.enable_vertex_attrib_array($loc);
1151            gl.vertex_attrib_divisor($loc, 1); // advance once per instance
1152        }};
1153    }
1154
1155    inst_attr!(2,  3,  0);  // i_position   vec3   @ byte 0
1156    inst_attr!(3,  2, 12);  // i_scale      vec2   @ byte 12
1157    inst_attr!(4,  1, 20);  // i_rotation   float  @ byte 20
1158    inst_attr!(5,  4, 24);  // i_color      vec4   @ byte 24
1159    inst_attr!(6,  1, 40);  // i_emission   float  @ byte 40
1160    inst_attr!(7,  3, 44);  // i_glow_color vec3   @ byte 44
1161    inst_attr!(8,  1, 56);  // i_glow_radius float @ byte 56
1162    inst_attr!(9,  2, 60);  // i_uv_offset  vec2   @ byte 60
1163    inst_attr!(10, 2, 68);  // i_uv_size    vec2   @ byte 68
1164    inst_attr!(11, 2, 76);  // i_flags      vec2   @ byte 76 (the former padding)
1165
1166    (vao, quad_vbo, instance_vbo)
1167}
1168
1169/// Upload a FontAtlas as an R8 GL texture and return the handle.
1170unsafe fn upload_atlas(gl: &glow::Context, atlas: &FontAtlas) -> glow::Texture {
1171    let tex = gl.create_texture().expect("create atlas texture");
1172    gl.bind_texture(glow::TEXTURE_2D, Some(tex));
1173    gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, 1);
1174    gl.tex_image_2d(
1175        glow::TEXTURE_2D, 0, glow::R8 as i32,
1176        atlas.width as i32, atlas.height as i32,
1177        0, glow::RED, glow::UNSIGNED_BYTE,
1178        glow::PixelUnpackData::Slice(Some(&atlas.pixels)),
1179    );
1180    gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MIN_FILTER, glow::LINEAR as i32);
1181    gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MAG_FILTER, glow::LINEAR as i32);
1182    gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_WRAP_S, glow::CLAMP_TO_EDGE as i32);
1183    gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_WRAP_T, glow::CLAMP_TO_EDGE as i32);
1184    tex
1185}
1186
1187// ── KeyCode → engine Key mapping ──────────────────────────────────────────────
1188
1189/// Map a winit `KeyCode` to the engine's `Key` enum. Returns `None` for unknown keys.
1190fn keycode_to_engine(kc: KeyCode) -> Option<Key> {
1191    Some(match kc {
1192        KeyCode::KeyA => Key::A, KeyCode::KeyB => Key::B, KeyCode::KeyC => Key::C,
1193        KeyCode::KeyD => Key::D, KeyCode::KeyE => Key::E, KeyCode::KeyF => Key::F,
1194        KeyCode::KeyG => Key::G, KeyCode::KeyH => Key::H, KeyCode::KeyI => Key::I,
1195        KeyCode::KeyJ => Key::J, KeyCode::KeyK => Key::K, KeyCode::KeyL => Key::L,
1196        KeyCode::KeyM => Key::M, KeyCode::KeyN => Key::N, KeyCode::KeyO => Key::O,
1197        KeyCode::KeyP => Key::P, KeyCode::KeyQ => Key::Q, KeyCode::KeyR => Key::R,
1198        KeyCode::KeyS => Key::S, KeyCode::KeyT => Key::T, KeyCode::KeyU => Key::U,
1199        KeyCode::KeyV => Key::V, KeyCode::KeyW => Key::W, KeyCode::KeyX => Key::X,
1200        KeyCode::KeyY => Key::Y, KeyCode::KeyZ => Key::Z,
1201        KeyCode::Digit1 => Key::Num1, KeyCode::Digit2 => Key::Num2,
1202        KeyCode::Digit3 => Key::Num3, KeyCode::Digit4 => Key::Num4,
1203        KeyCode::Digit5 => Key::Num5, KeyCode::Digit6 => Key::Num6,
1204        KeyCode::Digit7 => Key::Num7, KeyCode::Digit8 => Key::Num8,
1205        KeyCode::Digit9 => Key::Num9, KeyCode::Digit0 => Key::Num0,
1206        KeyCode::ArrowUp    => Key::Up,    KeyCode::ArrowDown  => Key::Down,
1207        KeyCode::ArrowLeft  => Key::Left,  KeyCode::ArrowRight => Key::Right,
1208        KeyCode::Enter | KeyCode::NumpadEnter => Key::Enter,
1209        KeyCode::Escape     => Key::Escape,
1210        KeyCode::Space      => Key::Space,
1211        KeyCode::Backspace  => Key::Backspace,
1212        KeyCode::Tab        => Key::Tab,
1213        KeyCode::ShiftLeft   => Key::LShift,  KeyCode::ShiftRight   => Key::RShift,
1214        KeyCode::ControlLeft => Key::LCtrl,   KeyCode::ControlRight => Key::RCtrl,
1215        KeyCode::AltLeft     => Key::LAlt,    KeyCode::AltRight     => Key::RAlt,
1216        KeyCode::F1  => Key::F1,  KeyCode::F2  => Key::F2,  KeyCode::F3  => Key::F3,
1217        KeyCode::F4  => Key::F4,  KeyCode::F5  => Key::F5,  KeyCode::F6  => Key::F6,
1218        KeyCode::F7  => Key::F7,  KeyCode::F8  => Key::F8,  KeyCode::F9  => Key::F9,
1219        KeyCode::F10 => Key::F10, KeyCode::F11 => Key::F11, KeyCode::F12 => Key::F12,
1220        KeyCode::Slash        => Key::Slash,
1221        KeyCode::Backslash    => Key::Backslash,
1222        KeyCode::Period       => Key::Period,
1223        KeyCode::Comma        => Key::Comma,
1224        KeyCode::Semicolon    => Key::Semicolon,
1225        KeyCode::Quote        => Key::Quote,
1226        KeyCode::BracketLeft  => Key::LBracket,
1227        KeyCode::BracketRight => Key::RBracket,
1228        KeyCode::Minus        => Key::Minus,
1229        KeyCode::Equal        => Key::Equals,
1230        KeyCode::Backquote    => Key::Backtick,
1231        KeyCode::PageUp       => Key::PageUp,
1232        KeyCode::PageDown     => Key::PageDown,
1233        KeyCode::Home         => Key::Home,
1234        KeyCode::End          => Key::End,
1235        KeyCode::Insert       => Key::Insert,
1236        KeyCode::Delete       => Key::Delete,
1237        _ => return None,
1238    })
1239}