Skip to main content

kalast/py/app/
mod.rs

1pub mod body;
2pub mod frame;
3pub mod config;
4pub mod config_gen;
5pub mod gpu;
6pub mod script;
7pub mod simulation;
8
9use std::{cell::RefCell, rc::Rc};
10
11use pyo3::prelude::*;
12
13/// Write a script's output to the log's script tab, and on to the terminal.
14///
15/// What `sys.stdout` and `sys.stderr` call in the UI app -- see
16/// `kalast.editor.capture_output` -- not something a script calls itself:
17/// `print` already comes here.
18#[pyfunction]
19pub fn script_write(text: &str) {
20    crate::app::gui::script_write(text);
21}
22
23/// Queue a line for the console, as Enter in the log's python tab does --
24/// for tests, which cannot type into it.
25#[pyfunction]
26pub fn console_submit(line: String) {
27    crate::app::gui::console_submit(line);
28}
29
30/// The next line typed at the log's python tab, or `None`.
31///
32/// For `kalast.editor`, which runs them between frames -- not something a
33/// script calls itself.
34#[pyfunction]
35pub fn console_take() -> Option<String> {
36    crate::app::gui::console_take()
37}
38
39/// Ask for completions of `line`, as Tab in the python tab does -- for
40/// tests, which cannot press it.
41#[pyfunction]
42pub fn console_ask_completion(line: String) {
43    crate::app::gui::console_ask_completion(line);
44}
45
46/// The line Tab asked Python to complete, if one is waiting.
47#[pyfunction]
48pub fn console_take_completion() -> Option<String> {
49    crate::app::gui::console_take_completion()
50}
51
52/// Python's answer to a Tab: the line asked about, the part before the word
53/// being completed, and the word's completions.
54#[pyfunction]
55pub fn console_offer(line: String, head: String, matches: Vec<String>) {
56    crate::app::gui::console_offer(line, head, matches);
57}
58
59/// The interpreter scripts run in, `sys.executable`: the script editor's
60/// Python language server resolves imports with it.
61#[pyfunction]
62pub fn editor_set_python(path: String) {
63    crate::app::gui::script::set_python(std::path::PathBuf::from(path));
64}
65
66/// Whether Ctrl+C was pressed at the python tab's prompt since last asked:
67/// the block being collected is to be dropped.
68#[pyfunction]
69pub fn console_take_interrupt() -> bool {
70    crate::app::gui::console_take_interrupt()
71}
72
73/// What running a console line printed, for the python tab.
74#[pyfunction]
75pub fn console_write(text: &str) {
76    crate::app::gui::console_write(text);
77}
78
79/// The python tab's greeting, once: `python`'s version line and where help
80/// is. The `kalast` binary gives it as it starts; this is Python's way in,
81/// when kalast runs under it.
82#[pyfunction]
83pub fn console_greet(version: &str, platform: &str) {
84    crate::app::gui::console_greet(version, platform);
85}
86
87/// Whether the console waits for the rest of a block -- a `for`, a `def` --
88/// so the next line is typed at `...`.
89#[pyfunction]
90pub fn console_set_more(more: bool) {
91    crate::app::gui::console_set_more(more);
92}
93
94#[pyclass(from_py_object, unsendable)]
95#[derive(Clone)]
96pub struct App {
97    /// The engine's app, on the thread that runs its loop. `None` for the
98    /// handle a script gets on the UI app's scripts' thread (`script`): the
99    /// window is the main thread's, and `step()` asks it for a frame.
100    pub inner: Option<Rc<RefCell<crate::app::App>>>,
101    /// Everything a script may touch while the loop runs.
102    ///
103    /// Held beside `inner`, never through it: `start()` borrows `inner` for
104    /// the whole run, so a setter reaching through it would panic.
105    pub shared: crate::locked::Locked<crate::app::Shared>,
106    /// The application's own settings. `App` owns this one.
107    pub config: crate::locked::Locked<crate::app::config::AppConfig>,
108    /// The simulation's settings. `Simulation` owns it; this is a handle.
109    ///
110    /// Held alongside `inner`, not fetched through it. `start()` borrows the
111    /// app mutably for the whole run loop, so a getter that went through
112    /// `inner` would panic from inside a callback -- which is exactly where
113    /// changing a setting is wanted.
114    pub sim_config: crate::locked::Locked<crate::app::config::Config>,
115    pub simulation: crate::locked::Locked<crate::app::simulation::Simulation>,
116}
117
118/// An app's handles on what scripts touch -- everything but the engine's app
119/// itself -- which may cross to the scripts' thread (`script`).
120#[derive(Clone)]
121pub struct Handles {
122    pub shared: crate::locked::Locked<crate::app::Shared>,
123    pub config: crate::locked::Locked<crate::app::config::AppConfig>,
124    pub sim_config: crate::locked::Locked<crate::app::config::Config>,
125    pub simulation: crate::locked::Locked<crate::app::simulation::Simulation>,
126}
127
128impl Handles {
129    pub fn of(app: &crate::app::App) -> Self {
130        Self {
131            shared: app.shared.clone(),
132            config: app.config.clone(),
133            sim_config: app.simulation.borrow().config.clone(),
134            simulation: app.simulation.clone(),
135        }
136    }
137}
138
139impl App {
140    /// A Python handle onto an app that already exists.
141    ///
142    /// For a front door written in Rust that wants to hand a script the app
143    /// it is already showing, rather than one the script makes for itself --
144    /// the same thing `python -m kalast` passes to `editor.run_toplevel`.
145    pub fn wrap(inner: Rc<RefCell<crate::app::App>>) -> Self {
146        let handles = Handles::of(&inner.borrow());
147        Self { inner: Some(inner), ..Self::remote(handles) }
148    }
149
150    /// The handle a script gets on the scripts' thread: the scene's, and no
151    /// window.
152    pub fn remote(handles: Handles) -> Self {
153        Self {
154            inner: None,
155            shared: handles.shared,
156            config: handles.config,
157            sim_config: handles.sim_config,
158            simulation: handles.simulation,
159        }
160    }
161
162    pub fn handles(&self) -> Handles {
163        Handles {
164            shared: self.shared.clone(),
165            config: self.config.clone(),
166            sim_config: self.sim_config.clone(),
167            simulation: self.simulation.clone(),
168        }
169    }
170}
171
172/// What the log's python tab has for Python -- lines typed, a Tab -- run by
173/// `kalast.editor.serve_console` against `app`. Its own errors are the
174/// console's to show; one reaching here is shown there.
175pub(crate) fn serve_console<'py>(py: Python<'py>, app: impl IntoPyObject<'py>) {
176    let served = py
177        .import("kalast.editor")
178        .and_then(|m| m.call_method1("serve_console", (app,)));
179    if let Err(e) = served {
180        crate::app::gui::console_write(&format!("{e}\n"));
181    }
182}
183
184#[pymethods]
185impl App {
186    #[new]
187    fn new() -> Self {
188        Self::wrap(Rc::new(RefCell::new(crate::app::App::new())))
189    }
190
191    #[getter]
192    /// The application's own settings: window size, and panel layout and
193    /// colours as the editor grows.
194    ///
195    /// Not the simulation's -- that is `app.simulation.config`, and it is
196    /// where shading, shadows, axes, the colour bar and export live.
197    fn config(&self) -> config::AppConfig {
198        config::AppConfig {
199            config: self.config.clone(),
200        }
201    }
202
203    #[getter]
204    /// The scene: bodies, camera, Sun, iteration state and HUDs.
205    fn get_simulation(&self) -> simulation::Simulation {
206        // The one on screen: a Rust example the editor loads brings a
207        // simulation of its own, which the window shows and the python tab
208        // has to see (`Shared::shown`). Otherwise the app's own, which a
209        // script's run puts back (`App::begin_script`). Its config through
210        // the handle held beside it while the simulation is borrowed here --
211        // inside a frame, from a callback.
212        let shown = self.shared.borrow().shown.clone();
213        let inner = shown.unwrap_or_else(|| self.simulation.clone());
214        let config = inner.try_borrow().ok().map(|s| s.config.clone());
215        let config = config.unwrap_or_else(|| self.sim_config.clone());
216        simulation::Simulation { inner, config }
217    }
218
219    /// Create the window and run the render loop.
220    ///
221    /// **Blocks until the window closes**, so set everything up before calling it
222    /// and do per-frame work in `before_render`/`after_render`.
223    ///
224    /// Use `step()` instead to keep the loop in your own script.
225    fn start(&self, py: Python<'_>) {
226        match &self.inner {
227            Some(inner) => inner.borrow_mut().start(),
228            // On the scripts' thread the loop is the UI app's: its frames,
229            // a step at a time, until the window closes.
230            None => while script::step(py, self) {},
231        }
232    }
233
234    /// Open the editor: the renderer as one panel in a Blender-style layout.
235    ///
236    /// **Blocks until the window closes**, like `start()`, and runs the same
237    /// loop. The difference is where the scene lands -- into an offscreen
238    /// texture at the viewport panel's size, which the UI samples into the
239    /// centre of the layout, rather than blitted to the swapchain.
240    ///
241    /// `start()` and `step()` are untouched by this: a script run from a
242    /// terminal draws straight to the window as it always has.
243    ///
244    /// ```python
245    /// app = App()
246    /// app.simulation.load_mesh(path=..., mat=numpy.eye(4))
247    /// app.start_editor()
248    /// ```
249    ///
250    /// `python -m kalast` opens it on an empty scene.
251    fn start_editor(&self) {
252        // On the scripts' thread the editor is open already.
253        if let Some(inner) = &self.inner {
254            inner.borrow_mut().start_editor();
255        }
256    }
257
258    /// Install what the editor's `Run` button calls.
259    ///
260    /// A callable taking `(app, source, path)`. `kalast.editor.make_runner()`
261    /// builds the standard one, which executes a script against the app it is
262    /// handed rather than letting it construct a second.
263    ///
264    /// The app arrives as an argument rather than being captured when the
265    /// runner is installed: a script must reach the app through a handle of
266    /// its own, not through the object whose `start_editor` is running.
267    #[setter]
268    /// :pytype: Callable[[str, str], None]
269    fn set_script_runner(&self, py: Python<'_>, callback: Py<PyAny>) -> PyResult<()> {
270        let app = Py::new(py, self.clone())?;
271        self.shared.borrow_mut().script_runner =
272            Some(crate::app::ScriptRunner { callback, app });
273        Ok(())
274    }
275
276    /// Put a script in the editor's buffer, and name the file it came from.
277    ///
278    /// Settable before `start_editor()`, which is when a launcher does it.
279    fn set_script(&self, path: &str, source: &str) {
280        // Straight into `pending_script`: the editor may not exist yet, and
281        // if it does the frame picks this up on its next pass.
282        self.shared.borrow_mut().pending_script =
283            Some((path.to_string(), source.to_string()));
284    }
285
286    /// Run the script in the editor's buffer, as the Play button does.
287    ///
288    /// Takes effect on the next frame, and starts the simulation. Works
289    /// before `start_editor()` as well, which is how `python -m kalast
290    /// script.py --run` opens straight into a running scene.
291    fn run_script(&self) {
292        self.shared.borrow_mut().run_requested = true;
293    }
294
295    /// Read the file named by `set_script`'s path, as the panel's `open`
296    /// button does -- which also builds the scene and holds it at iteration
297    /// 0, so there is something to look at and Step has something to step.
298    fn open_script(&self) {
299        self.shared.borrow_mut().open_requested = true;
300    }
301
302    /// Rebuild the scene from the script and stop at the start, as the
303    /// Restart button does.
304    ///
305    /// The difference from `run_script()` is only what happens afterwards:
306    /// this leaves the simulation paused.
307    fn restart_script(&self) {
308        self.shared.borrow_mut().restart_requested = true;
309    }
310
311    /// Open the editor and run its loop until the window closes.
312    ///
313    /// The loop is `App::run_editor` in the engine -- the same one the
314    /// `kalast` binary runs. This is a binding onto it, not a second
315    /// implementation.
316    ///
317    /// `args` are taken as typed on the command line: `.py` and `.rs` open in
318    /// the script panel, `.obj` loads as a mesh.
319    ///
320    /// `run_script(app, source, path)` is called whenever Play or Restart
321    /// asks for a script, and is the one piece Rust cannot do for itself --
322    /// executing Python needs CPython. Everything else about the loop is in
323    /// the engine. It is called on the scripts' thread, as are the callbacks
324    /// and the python tab: the window goes on while a script works.
325    #[pyo3(signature = (args, run_script))]
326    fn run_editor(&self, py: Python<'_>, args: Vec<String>, run_script: Py<PyAny>) -> PyResult<()> {
327        let Some(inner) = self.inner.clone() else {
328            return Err(pyo3::exceptions::PyRuntimeError::new_err("the UI app is open already"));
329        };
330
331        // Driven a turn at a time rather than handing the loop to
332        // `run_editor`, because that would hold `inner` borrowed for the whole
333        // session -- and an example run in it reaches the app between its
334        // frames. The policy is still the engine's; only the handle is
335        // turned here.
336        inner.borrow_mut().editor_start(&args);
337
338        // Scripts, their callbacks and the python tab on a thread of their
339        // own (`script`), so a slow one holds that thread and not the
340        // window. The loop below never runs Python: it lets go of the
341        // interpreter for the whole session, and the thread takes it.
342        let (main, thread) = crate::app::script::link();
343        let ended = script::spawn(thread, self.handles(), Box::new(move |py, _app| Ok(run_script.clone_ref(py))));
344        inner.borrow_mut().set_script_thread(main);
345
346        let looped = script::OnThisThread(inner.clone());
347        py.detach(move || {
348            let inner = looped.into_inner();
349            loop {
350                let tick = inner.borrow_mut().editor_tick();
351                match tick {
352                    crate::app::EditorTick::Closed => break,
353                    // With the thread, a script and the console are its:
354                    // neither comes back here.
355                    crate::app::EditorTick::Frame
356                    | crate::app::EditorTick::Run { .. }
357                    | crate::app::EditorTick::Console => {}
358                    // A Rust example runs here, holding the flow until its
359                    // loop ends, and the python tab is served between its
360                    // frames -- on the thread, waited for, with nothing of
361                    // ours borrowed.
362                    crate::app::EditorTick::Example { path, release } => {
363                        let mut between = || {
364                            inner.borrow_mut().console_on_thread();
365                        };
366                        crate::app::App::run_example(&inner, &path, release, &mut between);
367                    }
368                }
369            }
370            // The thread ends with its link, letting go of what it made.
371            inner.borrow_mut().end_script_thread();
372            ended.wait(std::time::Duration::from_secs(2));
373        });
374        Ok(())
375    }
376
377    /// Take a script the editor's Play button has asked to run, if any.
378    ///
379    /// Returns `(path, source, paused)` once per request, or `None`.
380    /// `paused` is true when Restart asked -- rebuild the scene and stop at
381    /// the start -- and false for Play, which rebuilds and runs. Call it
382    /// **between** frames and execute what comes back:
383    ///
384    /// ```python
385    /// while app.step():
386    ///     asked = app.take_script_request()
387    ///     if asked:
388    ///         path, source, paused = asked
389    ///         app.simulation.reset()
390    ///         app.simulation.state.is_paused = paused
391    ///         kalast.editor.run_toplevel(app, source, path)
392    /// ```
393    ///
394    /// The frame cannot run a script itself: one that drives its own
395    /// `while app.step():` would be a loop nested inside the frame it is
396    /// trying to drive. Between frames it runs as the program it is,
397    /// whatever shape it has.
398    fn take_script_request(&self) -> Option<(String, String, bool)> {
399        self.shared.borrow_mut().take_script()
400    }
401
402    /// Where the UI last saw the pointer, in egui points, or `None`.
403    ///
404    /// `None` is the usual state of an unfocused window: macOS delivers
405    /// mouse-moved events only to the front application.
406    #[getter]
407    fn pointer(&self) -> Option<(f32, f32)> {
408        self.shared.borrow().pointer
409    }
410
411    /// The size the pointer is measured against, in egui points.
412    #[getter]
413    fn ui_size(&self) -> (f32, f32) {
414        self.shared.borrow().ui_size
415    }
416
417    /// Which panels the last frame drew: `(top, bottom, left, right)`.
418    ///
419    /// All four in the ordinary layout. With `config.focus` on, only the ones
420    /// the pointer has summoned to an edge.
421    #[getter]
422    fn panels_shown(&self) -> (bool, bool, bool, bool) {
423        let p = self.shared.borrow().panels_shown;
424        (p[0], p[1], p[2], p[3])
425    }
426
427    /// The iteration the frame on screen was drawn for.
428    ///
429    /// Not `simulation.state.iteration`, which counts iterations *finished*:
430    /// it moves at the end of a frame, so once iteration 0 has been drawn it
431    /// already reads 1. This is the number the editor's toolbar shows, being
432    /// the one you are actually looking at.
433    #[getter]
434    fn drawn_iteration(&self) -> usize {
435        self.shared.borrow().drawn_iteration
436    }
437
438    /// Whether a run has been asked for and not yet taken.
439    ///
440    /// A peek, unlike `take_script_request`, so a script that is driving its
441    /// own loop can notice the request without consuming it and unwind back
442    /// to whoever owns the loop.
443    #[getter]
444    fn script_requested(&self) -> bool {
445        self.shared.borrow().script_pending.is_some()
446    }
447
448    /// Whether the script in the editor's buffer is the one that is running.
449    ///
450    /// Drives the Play button: `False` and it runs the script, `True` and it
451    /// is a pause toggle. A launcher that has already executed the script
452    /// sets this, so Play does not offer to run it a second time.
453    #[getter]
454    fn script_ran(&self) -> bool {
455        self.shared.borrow().script_ran
456    }
457
458    #[setter]
459    fn set_script_ran(&self, v: bool) {
460        self.shared.borrow_mut().script_ran = v;
461    }
462
463    /// Put stdout and stderr back and flush anything still buffered.
464    ///
465    /// `kalast.editor.capture_output` registers this with `atexit`, so a
466    /// script's last words reach the terminal. Safe to call more than once.
467    fn flush_output(&self) {
468        // The capture is the main thread's, which flushes it as it closes.
469        if let Some(inner) = &self.inner {
470            inner.borrow_mut().flush_output();
471        }
472    }
473
474    /// Append a line to the editor's log panel, or to stdout without one.
475    fn log(&self, line: &str) {
476        self.shared.borrow_mut().log.push(line);
477    }
478
479    /// Draw one frame. Returns `False` once the window has closed.
480    ///
481    /// The alternative to `start()`: the loop stays in the script, so there
482    /// is no callback boundary to hand state across.
483    ///
484    /// **`step()` goes in the middle of the loop body, not in the `while`
485    /// line.**
486    ///
487    /// ```python
488    /// sim = app.simulation
489    /// while app.running:
490    ///     it = sim.state.iteration
491    ///     sim.bodies[0].mat = pose(et0 + it * dt)   # the before_render half
492    ///     sim.request_facet_shadow(0)
493    ///
494    ///     if not app.step():
495    ///         break
496    ///
497    ///     lit = sim.facet_shadow(0)                 # the after_render half
498    /// ```
499    ///
500    /// **Where the code goes, against the callbacks.** Work written *before*
501    /// `step()` is what `before_render` did -- it lands in the frame about to
502    /// be drawn. Work written *after* it is what `after_render` did: the
503    /// frame has rendered, so `facet_shadow()`, `facet_id_map()` and
504    /// `hemicube()` answer for the scene just drawn.
505    ///
506    /// `while app.step():` is wrong, and wrong silently: it puts every line
507    /// after the draw, so the pose you set applies to the next frame while
508    /// the result you read describes the previous one. `while True:` is wrong
509    /// too -- once the window closes `step()` returns at once without
510    /// drawing, `state.iteration` stops advancing, and a loop keyed on it
511    /// spins forever.
512    ///
513    /// Callbacks still run if set, inside the frame, so mixing the two works
514    /// and every existing script is unaffected.
515    ///
516    /// **`step()` does not skip a paused frame.** It draws and returns `True`
517    /// as usual, since the window must stay responsive to the key that
518    /// unpauses it; what it does not do is advance `state.iteration` or run
519    /// the callbacks. A driven loop that should also idle when paused has to
520    /// check `sim.state.is_paused` itself.
521    ///
522    /// One call is one frame. The first is slower than the rest -- it creates
523    /// the window and configures the surface.
524    ///
525    /// Not usable after `start()`: a platform event loop cannot be created
526    /// twice in one process, and `start()` consumes it. Pick one.
527    fn step(&self, py: Python<'_>) -> bool {
528        match &self.inner {
529            Some(inner) => inner.borrow_mut().step(),
530            // On the scripts' thread: the main thread draws it.
531            None => script::step(py, self),
532        }
533    }
534
535    /// Ask the window to close, ending a `while app.step():` loop.
536    ///
537    /// Takes effect on the next `step()`, not immediately: closing runs the
538    /// same shutdown the window button does, which includes flushing every
539    /// queued frame export to disk.
540    fn close(&self) {
541        self.shared.borrow_mut().exit_requested = true;
542    }
543
544    /// Whether the window is still open.
545    #[getter]
546    fn running(&self) -> bool {
547        // `False` once another run is pending as well as once the window has
548        // closed: both end a `while app.running:` loop, and Restart is the
549        // first of them.
550        let shared = self.shared.borrow();
551        shared.running && !shared.superseded()
552    }
553
554    /// Runs before each frame is drawn. Set body transforms, camera and
555    /// sun here.
556    ///
557    /// Called as `f(sim, dt)`: the app's `Simulation`, and `dt` the
558    /// **wall-clock time since the last frame**, in seconds -- not a
559    /// simulation step, so integrating physics with it ties the result to
560    /// the frame rate.
561    ///
562    /// **Annotate the parameter** -- `def before_render(sim: Simulation, dt:
563    /// float)` -- or an editor has no way to know what `sim` is and completes
564    /// nothing inside the body.
565    ///
566    /// ```python
567    /// def before_render(sim: Simulation, dt: float) -> None:
568    ///     sim.huds[0].text = f"it={sim.state.iteration}  {dt * 1e3:.1f} ms"
569    ///     sim.bodies[0].mat = pos_mat("MARS", "IAU_MARS", et0 + sim.state.iteration * step)
570    /// ```
571    ///
572    /// :pytype: Callable[[Simulation, float], None]
573    #[setter]
574    fn set_before_render(&self, callback: Py<PyAny>) {
575        let simulation = self.get_simulation();
576        self.shared.borrow_mut().before_render =
577            Some(crate::app::Tick::Python { callback, simulation });
578    }
579
580    /// Alias for `before_render`, kept because it is what every example and
581    /// existing script uses.
582    ///
583    /// :pytype: Callable[[Simulation, float], None]
584    #[setter]
585    fn set_tick(&self, callback: Py<PyAny>) {
586        self.set_before_render(callback);
587    }
588
589    /// Runs after each frame is drawn, when GPU results for that frame
590    /// exist -- `sim.facet_shadow()` is only filled in once the shadow map
591    /// holds this frame's geometry, so this is where to consume it without
592    /// a one-frame lag.
593    ///
594    /// Scene changes made here apply to the *next* frame, and heavy CPU work
595    /// here blocks the render loop (fine for a simulation run, but frame
596    /// rate stops meaning much).
597    ///
598    /// Called as `f(sim, dt)`, same shape as `before_render`.
599    ///
600    /// :pytype: Callable[[Simulation, float], None]
601    #[setter]
602    fn set_after_render(&self, callback: Py<PyAny>) {
603        let simulation = self.get_simulation();
604        self.shared.borrow_mut().after_render =
605            Some(crate::app::Tick::Python { callback, simulation });
606    }
607}