proof-engine 0.2.1

Real-time graphics from math: glyphs and particles moved by ODEs, strange attractors and force fields, drawn with HDR bloom on OpenGL.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
#![allow(dead_code, unused_variables, unused_imports, unused_mut, unused_parens, non_snake_case, unreachable_patterns, unused_assignments, unused_labels, unused_doc_comments, private_interfaces, clippy::all)]

//! # Proof Engine
//!
//! A Rust engine for real-time graphics where every point, glyph and
//! particle on screen is moved by a real equation: an ODE, a force field, a
//! spring, a noise function.
//!
//! <img src="https://raw.githubusercontent.com/Mattbusel/proof-engine/main/assets/gifs/strange_attractors.gif" width="100%" alt="Seven strange attractors, each 1,500 points integrated with RK4">
//!
//! ## The math runs without a window
//!
//! The integrators, attractors, fields and [`MathFunction`]s are plain Rust
//! and can be used on their own. This example runs as a doc test:
//!
//! ```rust
//! use proof_engine::math::attractors::{rk4_step, AttractorType};
//! use proof_engine::prelude::Vec3;
//!
//! // Two Lorenz states that start 0.0001 apart...
//! let mut a = Vec3::new(1.0, 1.0, 1.0);
//! let mut b = Vec3::new(1.0001, 1.0, 1.0);
//! for _ in 0..6000 {
//!     a = rk4_step(AttractorType::Lorenz, a, 0.005);
//!     b = rk4_step(AttractorType::Lorenz, b, 0.005);
//! }
//! // ...are far apart after 30 simulated seconds: that is chaos.
//! assert!((a - b).length() > 1.0);
//! ```
//!
//! ## Open a window and draw
//!
//! The `quickstart` example, in full. It needs a GPU with OpenGL 3.3, so it
//! is compiled here but not run:
//!
//! ```rust,no_run
//! use proof_engine::math::attractors::rk4_step;
//! use proof_engine::prelude::*;
//! use proof_engine::render::ui_layer::UiParticle;
//!
//! let mut engine = ProofEngine::new(EngineConfig::default());
//! let mut points: Vec<Vec3> = (0..5000)
//!     .map(|i| Vec3::new(1.0 + i as f32 * 4e-4, 1.0, 1.0))
//!     .collect();
//!
//! engine.run_ui(move |engine, dt| {
//!     for p in points.iter_mut() {
//!         *p = rk4_step(AttractorType::Lorenz, *p, dt);
//!     }
//!     let (w, h) = engine.render_size();
//!     let (cx, cy, s) = (w as f32 / 2.0, h as f32 / 2.0, h as f32 / 60.0);
//!     let color = Vec4::new(0.5, 1.2, 1.6, 1.0);
//!     let dots = points
//!         .iter()
//!         .map(|p| UiParticle::new(cx + p.x * s, cy - (p.z - 25.0) * s, 3.0, 3.0, '●', color))
//!         .collect();
//!     engine.ui.draw_particles(dots);
//! });
//! ```
//!
//! ## Where to look
//!
//! - [`ProofEngine`]: the window and main loop. [`ProofEngine::run`] for 3D
//!   glyph scenes, [`ProofEngine::run_ui`] for screen-space games and plots.
//! - [`EngineConfig`] and [`config::RenderConfig`]: window size, bloom,
//!   tonemap, grain and every other post-processing setting.
//! - [`Glyph`] and [`ProofEngine::spawn_glyph`]: the basic on-screen object.
//! - [`ForceField`], [`MathFunction`] and [`math::attractors`]: the math.
//! - [`render::ui_layer::UiParticle`]: fast screen-space points, as above.
//! - [`prelude`]: the common imports in one line.
//!
//! Every example in the repository can save its own frames to disk with the
//! `PROOF_SHOT` environment variables; see the
//! [README](https://github.com/Mattbusel/proof-engine#capture-frames-from-any-program).

pub mod math;
pub mod glyph;
pub mod entity;
pub mod particle;
pub mod scene;
pub mod render;
pub mod audio;
pub mod integration;
pub mod input;
pub mod config;
pub mod tween;
pub mod debug;
pub mod ui;
pub mod timeline;
pub mod procedural;
pub mod physics;
pub mod combat;
pub mod spatial;
pub mod effects;
pub mod anim;
pub mod animation;
pub mod ai;
pub mod networking;
pub mod replay;
pub mod scripting;
pub mod terrain;
pub mod ecs;
pub mod editor;
pub mod asset;
pub mod save;
pub mod character;
pub mod dsp;
pub mod game;
pub mod profiler;
pub mod vfx;
pub mod netcode;
pub mod network;
pub mod world;
pub mod crafting;
pub mod pathfinding;
pub mod economy;
pub mod behavior;
pub mod weather;
pub mod deferred;
pub mod shader_graph;
pub mod surfaces;
pub mod rendergraph;
pub mod compute;
pub mod lighting;
pub mod number_theory;
pub mod graph;
pub mod topology;
pub mod stochastic;
pub mod ml;
pub mod wgpu_backend;
pub mod geometry;
pub mod symbolic;
pub mod solver;
pub mod fractal;
pub mod metaball;
pub mod worldgen;
pub mod ecology;
pub mod narrative;
pub mod electromagnetic;
pub mod relativistic;
pub mod quantum;
pub mod svogi;
pub mod curves;
pub mod nishita_sky;
pub mod volumetric_fog;
pub mod tiled_lighting;
mod capture;

pub use config::EngineConfig;
pub use math::{MathFunction, ForceField, Falloff, AttractorType};
pub use glyph::{Glyph, RenderLayer, BlendMode};
pub use entity::AmorphousEntity;
pub use particle::{MathParticle, ParticleInteraction};
pub use scene::SceneGraph;
pub use render::camera::ProofCamera;
pub use input::{InputState, Key};
pub use render::pipeline::FrameStats;
pub use audio::AudioEvent;

/// The main engine struct. Create once, run forever.
pub struct ProofEngine {
    pub config: EngineConfig,
    pub scene: SceneGraph,
    pub camera: ProofCamera,
    pub input: InputState,
    /// Screen-space UI, in pixel coordinates. Cleared at the start of every
    /// frame by `run_ui`, so games redraw it immediate-mode style.
    pub ui: render::ui_layer::UiLayer,
    /// Transient screen effects: shockwaves, flashes, light shafts. Fire and
    /// forget; ticked and uploaded by `run_ui` every frame.
    pub fx: render::screen_fx::ScreenFx,
    /// GPU density entities queued for this frame. Drained after the render.
    density_queue: Vec<particle::gpu_density::GpuDensityEntityData>,
    /// The particle budget per density entity, set by `init_gpu_density`.
    density_budget: u32,
    /// Optional audio engine — None if no output device is available.
    pub audio: Option<audio::AudioEngine>,
    // Internal render pipeline (initialized lazily when run() is called)
    pipeline: Option<render::Pipeline>,
}

impl ProofEngine {
    pub fn new(mut config: EngineConfig) -> Self {
        if let Some((w, h)) = capture::window_size() {
            config.window_width = w;
            config.window_height = h;
        }
        let audio = if config.audio.enabled {
            audio::AudioEngine::try_new()
        } else {
            None
        };
        Self {
            camera: ProofCamera::new(&config),
            scene: SceneGraph::new(),
            input: InputState::new(),
            ui: render::ui_layer::UiLayer::new(
                config.window_width as f32,
                config.window_height as f32,
            ),
            fx: render::screen_fx::ScreenFx::new(),
            density_queue: Vec::new(),
            density_budget: 0,
            audio,
            config,
            pipeline: None,
        }
    }

    /// Turn on GPU density entities with a per-entity particle budget.
    ///
    /// The budget is capped at
    /// [`MAX_PARTICLES_PER_ENTITY`](particle::gpu_density::MAX_PARTICLES_PER_ENTITY):
    /// past that there are more particles than pixels and the picture stops
    /// improving while the frame time keeps climbing. Asking for more is
    /// fine; you get the cap and a log line.
    pub fn init_gpu_density(&mut self, particles: u32) {
        let cap = particle::gpu_density::MAX_PARTICLES_PER_ENTITY;
        if particles > cap {
            log::info!("gpu density: {particles} particles requested, drawing {cap} per entity");
        }
        self.density_budget = particles.min(cap);
    }

    /// Draw a density entity this frame. Call every frame it should show.
    pub fn queue_gpu_density_entity(&mut self, entity: particle::gpu_density::GpuDensityEntityData) {
        self.density_queue.push(entity);
    }

    /// Send an audio event. No-op if audio is unavailable.
    pub fn emit_audio(&self, event: audio::AudioEvent) {
        if let Some(ref a) = self.audio {
            a.emit(event);
        }
    }

    /// Run the engine. Calls `update` every frame with elapsed seconds.
    /// Blocks until the window is closed.
    pub fn run<F>(&mut self, mut update: F)
    where
        F: FnMut(&mut ProofEngine, f32),
    {
        self.run_with_overlay(move |engine, dt, _gl| {
            update(engine, dt);
        });
    }

    /// Run the engine with an overlay callback.
    /// The overlay callback receives the glow GL context reference and is called
    /// AFTER scene rendering but BEFORE buffer swap — perfect for egui.
    pub fn run_with_overlay<F>(&mut self, mut update: F)
    where
        F: FnMut(&mut ProofEngine, f32, &glow::Context),
    {
        let pipeline = render::Pipeline::init(&self.config);
        self.pipeline = Some(pipeline);
        let mut capture = capture::Capture::from_env();
        let fixed_dt = capture::fixed_dt();

        let mut last = std::time::Instant::now();
        loop {
            let now = std::time::Instant::now();
            let dt = fixed_dt.unwrap_or_else(|| now.duration_since(last).as_secs_f32().min(0.1));
            last = now;

            // Poll input
            if let Some(ref mut p) = self.pipeline {
                if !p.poll_events(&mut self.input) {
                    break;
                }
            }

            // Step force fields and physics
            self.scene.tick(dt);

            // User update (logic only — no GL calls here)
            // We pass a dummy gl ref for the logic phase; the real painting
            // happens after the scene render.
            let gl_ptr = self.pipeline.as_ref().map(|p| p.gl() as *const glow::Context);

            // Sync render config so runtime changes (particle_multiplier, bloom, etc.)
            // take effect this frame.
            if let Some(ref mut p) = self.pipeline {
                p.update_render_config(&self.config.render);
            }

            // Render scene first
            if let Some(ref mut p) = self.pipeline {
                p.set_density_entities(&self.density_queue, self.density_budget);
                p.render(&self.scene, &self.camera);
            }
            self.density_queue.clear();
            self.fx.lights.clear();

            // NOW paint the overlay (egui) on top of the rendered scene
            if let Some(ptr) = gl_ptr {
                let gl_ref = unsafe { &*ptr };
                update(self, dt, gl_ref);
            }

            // PROOF_SHOT: read the finished frame back before it is swapped away.
            if let Some(ref mut c) = capture {
                if c.after_draw(self) {
                    break;
                }
            }

            // Honour a quit asked for during the update, as `run_ui` does.
            if self.input.quit_requested {
                break;
            }

            // Swap
            if let Some(ref mut p) = self.pipeline {
                if !p.swap() {
                    break;
                }
            }
        }
    }

    /// Run a UI-driven game.
    ///
    /// Unlike [`run`], `update` is called *before* the scene is drawn, and the
    /// screen-space `ui` layer is painted afterwards. That ordering matters for
    /// a game: what you push this frame is what appears this frame, rather than
    /// showing up one frame late.
    ///
    /// The UI layer is cleared before each `update`, so games redraw it in full
    /// every frame instead of tracking what to erase.
    pub fn run_ui<F>(&mut self, mut update: F)
    where
        F: FnMut(&mut ProofEngine, f32),
    {
        let pipeline = render::Pipeline::init(&self.config);
        self.pipeline = Some(pipeline);

        // Size the UI layer from the framebuffer, which is what the viewport
        // uses; the window's own size can differ on a scaled display.
        let (w, h) = self.render_size();
        self.ui.resize(w as f32, h as f32);

        let mut capture = capture::Capture::from_env();
        let fixed_dt = capture::fixed_dt();

        let mut last = std::time::Instant::now();
        let mut last_size = (w, h);
        loop {
            let now = std::time::Instant::now();
            let dt = fixed_dt.unwrap_or_else(|| now.duration_since(last).as_secs_f32().min(0.1));
            last = now;

            if let Some(ref mut p) = self.pipeline {
                if !p.poll_events(&mut self.input) {
                    break;
                }
            }

            // Keep the UI projection matched to the framebuffer.
            let size = self.render_size();
            if size != last_size {
                last_size = size;
                self.ui.resize(size.0 as f32, size.1 as f32);
            }

            self.scene.tick(dt);

            // Game logic and UI construction, both before anything is drawn.
            self.ui.begin_frame();
            update(self, dt);

            // Honour a quit asked for during the update.
            //
            // `request_quit` used to set a flag that nothing read, so a game's
            // own Quit menu did nothing at all and the only way out was the
            // window's close button. The check goes here, after the update and
            // before the render, so the frame that asked to quit is the last
            // one and nothing half-drawn reaches the screen.
            if self.input.quit_requested {
                break;
            }

            // Trauma decays here. It used to be added and never ticked in
            // this loop, so the first hit left the camera shaking forever.
            self.camera.shake.tick(dt);
            self.fx.tick(dt);

            if let Some(ref mut p) = self.pipeline {
                p.update_render_config(&self.config.render);
                p.set_density_entities(&self.density_queue, self.density_budget);
                // The scene, then the UI's world pass into the same buffer,
                // then post-processing over both.
                p.render_frame(&self.scene, &self.camera, Some(&self.ui), &self.fx);
                // The HUD, painted after post-processing so it stays sharp.
                p.render_ui(&self.ui);
            }
            self.density_queue.clear();
            self.fx.lights.clear();

            if let Some(ref mut c) = capture {
                if c.after_draw(self) {
                    break;
                }
            }

            if let Some(ref mut p) = self.pipeline {
                if !p.swap() {
                    break;
                }
            }
        }
    }

    /// Add a force field to the scene.
    pub fn add_field(&mut self, field: ForceField) -> scene::FieldId {
        self.scene.add_field(field)
    }

    /// Remove a force field.
    pub fn remove_field(&mut self, id: scene::FieldId) {
        self.scene.remove_field(id)
    }

    /// Spawn a glyph into the scene.
    pub fn spawn_glyph(&mut self, glyph: Glyph) -> glyph::GlyphId {
        self.scene.spawn_glyph(glyph)
    }

    /// Spawn an amorphous entity, creating its formation glyphs.
    pub fn spawn_entity(&mut self, mut entity: AmorphousEntity) -> entity::EntityId {
        // If no formation was specified, generate a default diamond
        if entity.formation.is_empty() {
            use entity::formation::Formation;
            let f = Formation::diamond(2);
            entity.formation = f.positions;
            entity.formation_chars = f.chars;
        }
        // Ensure colors are filled (white if unspecified)
        while entity.formation_colors.len() < entity.formation.len() {
            entity.formation_colors.push(glam::Vec4::ONE);
        }
        // Spawn one glyph per formation slot
        for i in 0..entity.formation.len() {
            let offset = entity.formation[i];
            let ch = entity.formation_chars.get(i).copied().unwrap_or('◆');
            let color = entity.formation_colors.get(i).copied().unwrap_or(glam::Vec4::ONE);
            let id = self.scene.spawn_glyph(Glyph {
                character: ch,
                position: entity.position + offset,
                color,
                emission: 0.8,
                glow_color: glam::Vec3::new(color.x, color.y, color.z),
                glow_radius: 1.2,
                mass: entity.entity_mass / entity.formation.len().max(1) as f32,
                layer: RenderLayer::Entity,
                ..Default::default()
            });
            entity.glyph_ids.push(id);
        }
        self.scene.spawn_entity(entity)
    }

    /// Emit a burst of particles at a position.
    pub fn emit_particles(&mut self, emitter: particle::EmitterPreset, origin: glam::Vec3) {
        particle::emit(&mut self.scene, emitter, origin);
    }

    /// Apply trauma (screen shake). 0.0 = none, 1.0 = maximum.
    pub fn add_trauma(&mut self, amount: f32) {
        self.camera.add_trauma(amount);
    }
}

/// Request quit on next frame.
impl ProofEngine {
    pub fn request_quit(&mut self) {
        self.input.quit_requested = true;
    }

    /// Get a reference to the glow GL context (for egui integration).
    /// Returns None if the pipeline hasn't been initialized yet.
    pub fn gl(&self) -> Option<&glow::Context> {
        self.pipeline.as_ref().map(|p| p.gl())
    }

    /// Get the window reference (for egui-winit event processing).
    pub fn window(&self) -> Option<&winit::window::Window> {
        self.pipeline.as_ref().map(|p| p.window())
    }

    /// Get the current window size in pixels.
    pub fn window_size(&self) -> (u32, u32) {
        self.pipeline.as_ref().map(|p| p.window_size()).unwrap_or((1600, 1000))
    }

    /// The framebuffer size, in the same units the viewport uses.
    ///
    /// Screen-space UI must lay out against this, not the window size: on a
    /// scaled display the two differ and the UI ends up magnified.
    pub fn render_size(&self) -> (u32, u32) {
        self.pipeline.as_ref().map(|p| p.render_size()).unwrap_or((1600, 1000))
    }

    /// Write the frame currently on screen to an uncompressed 24-bit BMP.
    ///
    /// The point of this is being able to see what the engine actually drew.
    /// Asking the window manager for a picture of a hardware-accelerated window
    /// is unreliable — it hands back whatever it last cached, which can be a
    /// stale frame or a blank one — so the only trustworthy answer comes from
    /// reading the framebuffer back off the GPU.
    ///
    /// BMP because it needs no compression and therefore no dependency; the
    /// row order matches OpenGL's, so no flip is needed either.
    pub fn save_frame(&self, path: &str) -> std::io::Result<()> {
        use std::io::Write;
        let Some(p) = self.pipeline.as_ref() else {
            return Err(std::io::Error::new(
                std::io::ErrorKind::Other,
                "no pipeline to read from",
            ));
        };
        let (w, h, rgba) = p.read_frame();
        if w == 0 || h == 0 {
            return Err(std::io::Error::new(
                std::io::ErrorKind::Other,
                "empty framebuffer",
            ));
        }

        // Each BMP row is padded to a multiple of four bytes.
        let stride = ((w as usize * 3) + 3) & !3;
        let pixels = stride * h as usize;
        let mut out = Vec::with_capacity(54 + pixels);
        out.extend_from_slice(b"BM");
        out.extend_from_slice(&((54 + pixels) as u32).to_le_bytes());
        out.extend_from_slice(&0u32.to_le_bytes());
        out.extend_from_slice(&54u32.to_le_bytes());
        out.extend_from_slice(&40u32.to_le_bytes());
        out.extend_from_slice(&(w as i32).to_le_bytes());
        out.extend_from_slice(&(h as i32).to_le_bytes());
        out.extend_from_slice(&1u16.to_le_bytes());
        out.extend_from_slice(&24u16.to_le_bytes());
        for _ in 0..6 {
            out.extend_from_slice(&0u32.to_le_bytes());
        }

        for y in 0..h as usize {
            let row = y * w as usize * 4;
            for x in 0..w as usize {
                let i = row + x * 4;
                // BMP stores blue first.
                out.push(rgba[i + 2]);
                out.push(rgba[i + 1]);
                out.push(rgba[i]);
            }
            for _ in 0..(stride - w as usize * 3) {
                out.push(0);
            }
        }

        let mut f = std::fs::File::create(path)?;
        f.write_all(&out)
    }
}

/// Common imports for using Proof Engine.
pub mod prelude {
    pub use crate::{
        ProofEngine, EngineConfig,
        MathFunction, ForceField, Falloff, AttractorType,
        Glyph, RenderLayer, BlendMode,
        AmorphousEntity,
        MathParticle, ParticleInteraction,
        AudioEvent,
        particle::EmitterPreset,
        render::camera::ProofCamera,
        input::{InputState, Key},
        scene::{SceneGraph, FieldId},
        audio::MusicVibe,
        tween::{Tween, Easing, TweenState, Tweens, AnimationGroup},
        tween::easing::Easing as EasingFn,
        tween::keyframe::{KeyframeTrack, Keyframe, CameraPath, ExtrapolateMode},
        tween::sequence::{TweenSequence, TweenTimeline, SequenceBuilder},
        debug::DebugOverlay,
        render::pipeline::FrameStats,
        render::screen_fx::{ScreenFx, ScreenLight, Shockwave},
        render::ui_layer::UiPass,
    };
    // Quat and Mat4 belong here too: the skeleton and animation APIs hand out
    // transforms built from them, so a caller who only has the prelude cannot
    // pose a figure without reaching past it into glam.
    pub use glam::{Mat4, Quat, Vec2, Vec3, Vec4};
}