Compare commits
10 Commits
d592c74654
...
aa07631296
| Author | SHA1 | Date | |
|---|---|---|---|
| aa07631296 | |||
| 5a92020dae | |||
| 0889f81664 | |||
| 87de396fc2 | |||
| 724d705d21 | |||
| 53cb50316e | |||
| 75092e7d9f | |||
| 5e01e1762f | |||
| 4c9def194e | |||
| 0edd1b51a1 |
1658
Cargo.lock
generated
1658
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
61
Cargo.toml
61
Cargo.toml
@ -2,7 +2,6 @@
|
||||
name = "ytbn_graphing_software"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.88"
|
||||
license = "AGPL-3.0"
|
||||
repository = "https://github.com/Titaniumtown/YTBN-Graphing-Software"
|
||||
description = "Crossplatform (and web-compatible) graphing calculator"
|
||||
@ -34,74 +33,64 @@ strip = false
|
||||
|
||||
[dependencies]
|
||||
parsing = { path = "./parsing" }
|
||||
eframe = { path = "../simon-egui/crates/eframe", default-features = false, features = [
|
||||
eframe = { git = "https://github.com/titaniumtown/egui.git", rev = "b088efb9fa917845ecb54729a0d2fc592d2399e7", default-features = false, features = [
|
||||
"glow",
|
||||
"x11",
|
||||
] }
|
||||
egui = { path = "../simon-egui/crates/egui", default-features = false, features = [
|
||||
egui = { git = "https://github.com/titaniumtown/egui.git", rev = "b088efb9fa917845ecb54729a0d2fc592d2399e7", default-features = false, features = [
|
||||
"serde",
|
||||
] }
|
||||
epaint = { path = "../simon-egui/crates/epaint", default-features = false, features = [
|
||||
epaint = { git = "https://github.com/titaniumtown/egui.git", rev = "b088efb9fa917845ecb54729a0d2fc592d2399e7", default-features = false , features = [
|
||||
"bytemuck",
|
||||
] }
|
||||
emath = { path = "../simon-egui/crates/emath", default-features = false }
|
||||
egui_plot = { git = "https://github.com/emilk/egui_plot.git", default-features = false }
|
||||
emath = { git = "https://github.com/titaniumtown/egui.git", rev = "b088efb9fa917845ecb54729a0d2fc592d2399e7", default-features = false }
|
||||
egui_plot = { git = "https://github.com/titaniumtown/egui.git", rev = "b088efb9fa917845ecb54729a0d2fc592d2399e7", default-features = false }
|
||||
|
||||
shadow-rs = { version = "0.38", default-features = false }
|
||||
|
||||
|
||||
shadow-rs = { version = "0.12", default-features = false }
|
||||
const_format = { version = "0.2", default-features = false, features = ["fmt"] }
|
||||
cfg-if = "1"
|
||||
ruzstd = "0.8"
|
||||
ruzstd = "0.5"
|
||||
tracing = "0.1"
|
||||
itertools = "0.14"
|
||||
itertools = "0.10"
|
||||
static_assertions = "1.1"
|
||||
bincode = "1.3"
|
||||
serde = "1"
|
||||
log = "0.4"
|
||||
base64 = "0.22"
|
||||
base64 = "0.21"
|
||||
|
||||
# Note: benchmarks are in a separate crate - run with:
|
||||
# cd benchmarks && cargo bench
|
||||
[dev-dependencies]
|
||||
benchmarks = { path = "./benchmarks" }
|
||||
|
||||
[build-dependencies]
|
||||
shadow-rs = "0.38"
|
||||
epaint = { path = "../simon-egui/crates/epaint", default-features = false, features = [
|
||||
shadow-rs = "0.12"
|
||||
epaint = { git = "https://github.com/titaniumtown/egui.git", rev = "b088efb9fa917845ecb54729a0d2fc592d2399e7", default-features = false, features = [
|
||||
"bytemuck",
|
||||
] }
|
||||
egui = { path = "../simon-egui/crates/egui", default-features = false, features = [
|
||||
egui = { git = "https://github.com/titaniumtown/egui.git", rev = "b088efb9fa917845ecb54729a0d2fc592d2399e7", default-features = false, features = [
|
||||
"serde",
|
||||
] }
|
||||
bincode = "1.3"
|
||||
serde = "1"
|
||||
serde_json = "1"
|
||||
zstd = { version = "0.13", default-features = false }
|
||||
run_script = "0.10"
|
||||
zstd = { version = "0.11", default-features = false, features = ["pkg-config"] }
|
||||
run_script = "0.9"
|
||||
json5 = "0.4"
|
||||
itertools = "0.14"
|
||||
itertools = "0.10"
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
web-time = "1.1"
|
||||
instant = "0.1"
|
||||
tracing-subscriber = "0.3"
|
||||
getrandom = { version = "0.3" }
|
||||
getrandom = { version = "0.2" }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
web-time = "1.1"
|
||||
lol_alloc = "0.4"
|
||||
instant = { version = "0.1", features = ["wasm-bindgen"] }
|
||||
lol_alloc = "0.4.0"
|
||||
wasm-bindgen = { version = "0.2", default-features = false, features = ["std"] }
|
||||
web-sys = "0.3"
|
||||
tracing-wasm = "0.2"
|
||||
getrandom = { version = "0.3", features = ["wasm_js"] }
|
||||
# pinned to 0.4.54 because nix provides up to 0.2.104 wasm-bindgen-cli
|
||||
getrandom = { version = "0.2", features = ["js"] }
|
||||
# pinned to 0.4.54 in order to be compatible with nixos's wasm-bindgen-cli version
|
||||
wasm-bindgen-futures = "=0.4.54"
|
||||
|
||||
[package.metadata.cargo-all-features]
|
||||
skip_optional_dependencies = true #don't test optional dependencies, only features
|
||||
|
||||
[patch.crates-io]
|
||||
egui = { path = "../simon-egui/crates/egui" }
|
||||
epaint = { path = "../simon-egui/crates/epaint" }
|
||||
emath = { path = "../simon-egui/crates/emath" }
|
||||
ecolor = { path = "../simon-egui/crates/ecolor" }
|
||||
eframe = { path = "../simon-egui/crates/eframe" }
|
||||
egui-winit = { path = "../simon-egui/crates/egui-winit" }
|
||||
egui_glow = { path = "../simon-egui/crates/egui_glow" }
|
||||
egui-wgpu = { path = "../simon-egui/crates/egui-wgpu" }
|
||||
|
||||
6
TODO.md
6
TODO.md
@ -1,8 +1,14 @@
|
||||
## TODO:
|
||||
1. Function management
|
||||
- Integrals between functions (too hard to implement, maybe will shelve)
|
||||
- Display intersection between functions (would have to rewrite a lot of the function plotting handling)
|
||||
- [Drag and drop support](https://github.com/emilk/egui/discussions/1530) in the UI to re-order functions
|
||||
- Hide/disable functions
|
||||
- Prevent user from making too many function entries
|
||||
- Display function errors as tooltips or a warning box (not preventing the display of the graph)
|
||||
- Clone functions
|
||||
2. Smart display of graph
|
||||
- Display of intersections between functions
|
||||
3. Allow constants in min/max integral input (like pi or euler's number)
|
||||
4. Sliding values for functions (like a user-interactable slider that adjusts a variable in the function, like desmos)
|
||||
5. Fix integral display
|
||||
|
||||
@ -1,18 +1,12 @@
|
||||
[package]
|
||||
name = "benchmarks"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.88"
|
||||
edition = "2021"
|
||||
license = "AGPL-3.0"
|
||||
|
||||
[lib]
|
||||
bench = false
|
||||
|
||||
[[bench]]
|
||||
name = "split_function"
|
||||
harness = false
|
||||
|
||||
[dependencies]
|
||||
pprof = { version = "0.14", features = ["flamegraph"] }
|
||||
criterion = { version = "0.5", features = ["html_reports"] }
|
||||
pprof = { version = "0.9", features = ["flamegraph"] }
|
||||
criterion = "0.3"
|
||||
parsing = { path = "../parsing" }
|
||||
|
||||
@ -1,46 +0,0 @@
|
||||
use criterion::{criterion_group, criterion_main, Criterion};
|
||||
use parsing::split_function_chars;
|
||||
use std::time::Duration;
|
||||
|
||||
fn custom_criterion() -> Criterion {
|
||||
Criterion::default()
|
||||
.warm_up_time(Duration::from_millis(250))
|
||||
.sample_size(1000)
|
||||
}
|
||||
|
||||
fn mutli_split_function(c: &mut Criterion) {
|
||||
let data_chars = vec![
|
||||
"sin(x)cos(x)",
|
||||
"x^2",
|
||||
"2x",
|
||||
"log10(x)",
|
||||
"E^x",
|
||||
"xxxxx",
|
||||
"xsin(x)",
|
||||
"(2x+1)(3x+1)",
|
||||
"x**2",
|
||||
"pipipipipipix",
|
||||
"pi(2x+1)",
|
||||
"(2x+1)pi",
|
||||
]
|
||||
.iter()
|
||||
.map(|a| a.chars().collect::<Vec<char>>())
|
||||
.collect::<Vec<Vec<char>>>();
|
||||
|
||||
let mut group = c.benchmark_group("split_function");
|
||||
for entry in data_chars {
|
||||
group.bench_function(entry.iter().collect::<String>(), |b| {
|
||||
b.iter(|| {
|
||||
split_function_chars(&entry, parsing::SplitType::Multiplication);
|
||||
})
|
||||
});
|
||||
}
|
||||
group.finish();
|
||||
}
|
||||
|
||||
criterion_group! {
|
||||
name = benches;
|
||||
config = custom_criterion();
|
||||
targets = mutli_split_function
|
||||
}
|
||||
criterion_main!(benches);
|
||||
@ -1,18 +1,19 @@
|
||||
//! Benchmarks library - profiler utilities for flamegraphs
|
||||
use parsing::{split_function_chars, SplitType};
|
||||
|
||||
use std::time::Duration;
|
||||
use std::{fs::File, os::raw::c_int, path::Path};
|
||||
|
||||
use criterion::profiler::Profiler;
|
||||
use criterion::{criterion_group, criterion_main, Criterion};
|
||||
use pprof::ProfilerGuard;
|
||||
|
||||
/// Flamegraph profiler for criterion benchmarks
|
||||
pub struct FlamegraphProfiler<'a> {
|
||||
frequency: c_int,
|
||||
active_profiler: Option<ProfilerGuard<'a>>,
|
||||
}
|
||||
|
||||
impl<'a> FlamegraphProfiler<'a> {
|
||||
/// Create a new flamegraph profiler with the given sampling frequency
|
||||
#[allow(dead_code)]
|
||||
pub fn new(frequency: c_int) -> Self {
|
||||
FlamegraphProfiler {
|
||||
frequency,
|
||||
@ -21,7 +22,7 @@ impl<'a> FlamegraphProfiler<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
impl Profiler for FlamegraphProfiler<'_> {
|
||||
impl<'a> Profiler for FlamegraphProfiler<'a> {
|
||||
fn start_profiling(&mut self, _benchmark_id: &str, _benchmark_dir: &Path) {
|
||||
self.active_profiler = Some(ProfilerGuard::new(self.frequency).unwrap());
|
||||
}
|
||||
@ -41,3 +42,59 @@ impl Profiler for FlamegraphProfiler<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)] // this infact IS used by benchmarks
|
||||
fn custom_criterion() -> Criterion {
|
||||
Criterion::default()
|
||||
.warm_up_time(Duration::from_millis(250))
|
||||
.sample_size(1000)
|
||||
}
|
||||
|
||||
#[allow(dead_code)] // this infact IS used by benchmarks
|
||||
fn custom_criterion_flamegraph() -> Criterion {
|
||||
custom_criterion().with_profiler(FlamegraphProfiler::new(100))
|
||||
}
|
||||
|
||||
fn mutli_split_function(c: &mut Criterion) {
|
||||
let data_chars = vec![
|
||||
"sin(x)cos(x)",
|
||||
"x^2",
|
||||
"2x",
|
||||
"log10(x)",
|
||||
"E^x",
|
||||
"xxxxx",
|
||||
"xsin(x)",
|
||||
"(2x+1)(3x+1)",
|
||||
"x**2",
|
||||
"pipipipipipix",
|
||||
"pi(2x+1)",
|
||||
"(2x+1)pi",
|
||||
]
|
||||
.iter()
|
||||
.map(|a| a.chars().collect::<Vec<char>>())
|
||||
.collect::<Vec<Vec<char>>>();
|
||||
|
||||
let mut group = c.benchmark_group("split_function");
|
||||
for entry in data_chars {
|
||||
group.bench_function(entry.iter().collect::<String>(), |b| {
|
||||
b.iter(|| {
|
||||
split_function_chars(&entry, SplitType::Multiplication);
|
||||
})
|
||||
});
|
||||
}
|
||||
group.finish();
|
||||
}
|
||||
|
||||
// Uncomment to enable flamegraph profiling
|
||||
// fn single_split_function(c: &mut Criterion) {
|
||||
// let data_chars = "(2x+1)(3x+1)".chars().collect::<Vec<char>>();
|
||||
//
|
||||
// c.bench_function("split_function", |b| {
|
||||
// b.iter(|| {
|
||||
// split_function_chars(&data_chars, SplitType::Multiplication);
|
||||
// });
|
||||
// });
|
||||
// }
|
||||
|
||||
criterion_group!(benches, mutli_split_function);
|
||||
criterion_main!(benches);
|
||||
|
||||
37
build.rs
37
build.rs
@ -4,7 +4,6 @@ use std::{
|
||||
fs::File,
|
||||
io::{BufWriter, Write},
|
||||
path::Path,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use epaint::{
|
||||
@ -73,9 +72,7 @@ fn main() {
|
||||
println!("cargo:rerun-if-changed=.git/logs/HEAD");
|
||||
println!("cargo:rerun-if-changed=assets/*");
|
||||
|
||||
shadow_rs::ShadowBuilder::builder()
|
||||
.build()
|
||||
.expect("Could not initialize shadow_rs");
|
||||
shadow_rs::new().expect("Could not initialize shadow_rs");
|
||||
|
||||
let mut main_chars: Vec<char> =
|
||||
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzsu0123456789?.,!(){}[]-_=+-/<>'\\ :^*`@#$%&|~;"
|
||||
@ -107,43 +104,37 @@ fn main() {
|
||||
font_data: BTreeMap::from([
|
||||
(
|
||||
"Ubuntu-Light".to_owned(),
|
||||
Arc::new(FontData::from_owned(
|
||||
FontData::from_owned(
|
||||
font_stripper(
|
||||
"Ubuntu-Light.ttf",
|
||||
"ubuntu-light.ttf",
|
||||
[main_chars, vec!['∫']].concat(),
|
||||
)
|
||||
.unwrap(),
|
||||
)),
|
||||
),
|
||||
),
|
||||
(
|
||||
"NotoEmoji-Regular".to_owned(),
|
||||
Arc::new(FontData::from_owned(
|
||||
FontData::from_owned(
|
||||
font_stripper(
|
||||
"NotoEmoji-Regular.ttf",
|
||||
"noto-emoji.ttf",
|
||||
vec!['🌞', '🌙', '✖'],
|
||||
)
|
||||
.unwrap(),
|
||||
)),
|
||||
),
|
||||
),
|
||||
(
|
||||
"emoji-icon-font".to_owned(),
|
||||
Arc::new(
|
||||
FontData::from_owned(
|
||||
font_stripper(
|
||||
"emoji-icon-font.ttf",
|
||||
"emoji-icon.ttf",
|
||||
vec!['⚙', '⎘', '👁', '○', '⬆', '⬇', '⚠'],
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.tweak(FontTweak {
|
||||
scale: 0.8,
|
||||
y_offset_factor: 0.07,
|
||||
y_offset: 0.0,
|
||||
}),
|
||||
),
|
||||
FontData::from_owned(
|
||||
font_stripper("emoji-icon-font.ttf", "emoji-icon.ttf", vec!['⚙']).unwrap(),
|
||||
)
|
||||
.tweak(FontTweak {
|
||||
scale: 0.8,
|
||||
y_offset_factor: 0.07,
|
||||
y_offset: 0.0,
|
||||
baseline_offset_factor: -0.0333,
|
||||
}),
|
||||
),
|
||||
]),
|
||||
families: BTreeMap::from([
|
||||
|
||||
8
flake.lock
generated
8
flake.lock
generated
@ -65,17 +65,17 @@
|
||||
"simon-egui": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1764740756,
|
||||
"narHash": "sha256-CX0v82hDmLSEx5uFViWvfJaeADFJKR0G+MJYFFQcxng=",
|
||||
"lastModified": 1764730109,
|
||||
"narHash": "sha256-vNETC0oq6tKJKF8KOGQKKIWRom38m0RwGgi3MPBrRx8=",
|
||||
"owner": "Titaniumtown",
|
||||
"repo": "egui",
|
||||
"rev": "217d3f250c499ae88c02930b26cacb945c4a2369",
|
||||
"rev": "b63c21d70150f1b414370f0f9a8af56e886662f4",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "Titaniumtown",
|
||||
"repo": "egui",
|
||||
"rev": "217d3f250c499ae88c02930b26cacb945c4a2369",
|
||||
"rev": "b63c21d70150f1b414370f0f9a8af56e886662f4",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
|
||||
@ -9,7 +9,7 @@
|
||||
inputs.nixpkgs.follows = "nixpkgs";
|
||||
};
|
||||
simon-egui = {
|
||||
url = "github:Titaniumtown/egui/217d3f250c499ae88c02930b26cacb945c4a2369";
|
||||
url = "github:Titaniumtown/egui/b63c21d70150f1b414370f0f9a8af56e886662f4";
|
||||
flake = false;
|
||||
};
|
||||
};
|
||||
@ -66,7 +66,7 @@
|
||||
cargoLock = {
|
||||
lockFile = ./Cargo.lock;
|
||||
outputHashes = {
|
||||
"egui_plot-0.34.0" = "sha256-lk0yeljsvkHzF0eLD5llQ+05DycPqG2jGzhBvQ0X6Qw=";
|
||||
"ecolor-0.25.0" = "sha256-9s5LCngwvIIL43txT6sBs4JlRXqmYt1Kw8hlDnwx+DI=";
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@ -13,13 +13,19 @@ pub enum Movement {
|
||||
}
|
||||
|
||||
impl Movement {
|
||||
pub const fn is_none(&self) -> bool { matches!(&self, &Self::None) }
|
||||
pub const fn is_none(&self) -> bool {
|
||||
matches!(&self, &Self::None)
|
||||
}
|
||||
|
||||
pub const fn is_complete(&self) -> bool { matches!(&self, &Self::Complete) }
|
||||
pub const fn is_complete(&self) -> bool {
|
||||
matches!(&self, &Self::Complete)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Movement {
|
||||
fn default() -> Self { Self::None }
|
||||
fn default() -> Self {
|
||||
Self::None
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq)]
|
||||
@ -30,7 +36,9 @@ pub struct AutoComplete<'a> {
|
||||
}
|
||||
|
||||
impl<'a> Default for AutoComplete<'a> {
|
||||
fn default() -> AutoComplete<'a> { AutoComplete::EMPTY }
|
||||
fn default() -> AutoComplete<'a> {
|
||||
AutoComplete::EMPTY
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> AutoComplete<'a> {
|
||||
|
||||
@ -22,7 +22,9 @@ impl FlatExWrapper {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
const fn is_none(&self) -> bool { self.func.is_none() }
|
||||
const fn is_none(&self) -> bool {
|
||||
self.func.is_none()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn eval(&self, x: &[f64]) -> f64 {
|
||||
@ -58,7 +60,7 @@ impl FlatExWrapper {
|
||||
.as_ref()
|
||||
.map(|f| {
|
||||
f.clone()
|
||||
.partial_iter((0..n).map(|_| 0))
|
||||
.partial_iter((0..=n).map(|_| 0))
|
||||
.map(Self::new)
|
||||
.unwrap_or(Self::EMPTY)
|
||||
})
|
||||
@ -67,7 +69,9 @@ impl FlatExWrapper {
|
||||
}
|
||||
|
||||
impl Default for FlatExWrapper {
|
||||
fn default() -> FlatExWrapper { FlatExWrapper::EMPTY }
|
||||
fn default() -> FlatExWrapper {
|
||||
FlatExWrapper::EMPTY
|
||||
}
|
||||
}
|
||||
/// Function that includes f(x), f'(x), f'(x)'s string representation, and f''(x)
|
||||
#[derive(Clone, PartialEq)]
|
||||
@ -80,11 +84,15 @@ pub struct BackingFunction {
|
||||
}
|
||||
|
||||
impl Default for BackingFunction {
|
||||
fn default() -> Self { Self::new("").unwrap() }
|
||||
fn default() -> Self {
|
||||
Self::new("").unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl BackingFunction {
|
||||
pub const fn is_none(&self) -> bool { self.function.is_none() }
|
||||
pub const fn is_none(&self) -> bool {
|
||||
self.function.is_none()
|
||||
}
|
||||
|
||||
/// Create new [`BackingFunction`] instance
|
||||
pub fn new(func_str: &str) -> Result<Self, String> {
|
||||
|
||||
@ -45,9 +45,6 @@ pub struct FunctionEntry {
|
||||
|
||||
pub nth_derviative: bool,
|
||||
|
||||
/// If the function is visible on the graph
|
||||
pub visible: bool,
|
||||
|
||||
pub back_data: Vec<PlotPoint>,
|
||||
pub integral_data: Option<(Vec<Bar>, f64)>,
|
||||
pub derivative_data: Vec<PlotPoint>,
|
||||
@ -70,7 +67,6 @@ impl Hash for FunctionEntry {
|
||||
self.nth_derviative.hash(state);
|
||||
self.curr_nth.hash(state);
|
||||
self.settings_opened.hash(state);
|
||||
self.visible.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
@ -79,12 +75,11 @@ impl Serialize for FunctionEntry {
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
let mut s = serializer.serialize_struct("FunctionEntry", 5)?;
|
||||
let mut s = serializer.serialize_struct("FunctionEntry", 4)?;
|
||||
s.serialize_field("raw_func_str", &self.raw_func_str)?;
|
||||
s.serialize_field("integral", &self.integral)?;
|
||||
s.serialize_field("derivative", &self.derivative)?;
|
||||
s.serialize_field("curr_nth", &self.curr_nth)?;
|
||||
s.serialize_field("visible", &self.visible)?;
|
||||
|
||||
s.end()
|
||||
}
|
||||
@ -101,12 +96,6 @@ impl<'de> Deserialize<'de> for FunctionEntry {
|
||||
integral: bool,
|
||||
derivative: bool,
|
||||
curr_nth: usize,
|
||||
#[serde(default = "default_visible")]
|
||||
visible: bool,
|
||||
}
|
||||
|
||||
fn default_visible() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
let helper = Helper::deserialize(deserializer)?;
|
||||
@ -126,7 +115,6 @@ impl<'de> Deserialize<'de> for FunctionEntry {
|
||||
new_func_entry.integral = helper.integral;
|
||||
new_func_entry.derivative = helper.derivative;
|
||||
new_func_entry.curr_nth = helper.curr_nth;
|
||||
new_func_entry.visible = helper.visible;
|
||||
|
||||
Ok(new_func_entry)
|
||||
}
|
||||
@ -141,7 +129,6 @@ impl Default for FunctionEntry {
|
||||
integral: false,
|
||||
derivative: false,
|
||||
nth_derviative: false,
|
||||
visible: true,
|
||||
back_data: Vec::new(),
|
||||
integral_data: None,
|
||||
derivative_data: Vec::new(),
|
||||
@ -387,7 +374,7 @@ impl FunctionEntry {
|
||||
settings: &AppSettings,
|
||||
main_plot_color: Color32,
|
||||
) -> Option<f64> {
|
||||
if self.test_result.is_some() | self.function.is_none() | !self.visible {
|
||||
if self.test_result.is_some() | self.function.is_none() {
|
||||
return None;
|
||||
}
|
||||
|
||||
@ -411,7 +398,7 @@ impl FunctionEntry {
|
||||
.cloned()
|
||||
.collect::<Vec<PlotPoint>>()
|
||||
.to_line()
|
||||
.stroke((0.0, Color32::TRANSPARENT))
|
||||
.stroke(epaint::Stroke::NONE)
|
||||
.color(Color32::from_rgb(4, 4, 255))
|
||||
.fill(0.0),
|
||||
);
|
||||
@ -420,7 +407,7 @@ impl FunctionEntry {
|
||||
self.back_data
|
||||
.clone()
|
||||
.to_line()
|
||||
.stroke((4.0, main_plot_color)),
|
||||
.stroke(egui::Stroke::new(4.0, main_plot_color)),
|
||||
);
|
||||
}
|
||||
|
||||
@ -462,7 +449,7 @@ impl FunctionEntry {
|
||||
Some(integral_data) => {
|
||||
if integral_step > step {
|
||||
plot_ui.bar_chart(
|
||||
BarChart::new("integral", integral_data.0.clone())
|
||||
BarChart::new(integral_data.0.clone())
|
||||
.color(Color32::BLUE)
|
||||
.width(integral_step),
|
||||
);
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
use crate::{
|
||||
consts::COLORS, function_entry::FunctionEntry, misc::random_u64, widgets::widgets_ontop,
|
||||
};
|
||||
use egui::{Button, Id, Key, Modifiers, Popup, TextEdit, WidgetText};
|
||||
use egui::{Button, Id, Key, Modifiers, TextEdit, WidgetText};
|
||||
use emath::vec2;
|
||||
use parsing::Movement;
|
||||
use serde::ser::SerializeStruct;
|
||||
@ -19,7 +19,7 @@ impl Default for FunctionManager {
|
||||
fn default() -> Self {
|
||||
let mut vec: Functions = Vec::with_capacity(COLORS.len());
|
||||
vec.push((
|
||||
Id::NULL.with(11414819524356497634_u64), // Random number here to avoid call to crate::misc::random_u64()
|
||||
Id::new(11414819524356497634_u64), // Random number here to avoid call to crate::misc::random_u64()
|
||||
FunctionEntry::default(),
|
||||
));
|
||||
Self { functions: vec }
|
||||
@ -78,14 +78,9 @@ impl FunctionManager {
|
||||
let initial_hash = self.get_hash();
|
||||
|
||||
let can_remove = self.functions.len() > 1;
|
||||
let can_add = self.functions.len() < COLORS.len();
|
||||
let num_functions = self.functions.len();
|
||||
|
||||
let available_width = ui.available_width();
|
||||
let mut remove_i: Option<usize> = None;
|
||||
let mut clone_i: Option<usize> = None;
|
||||
let mut move_up_i: Option<usize> = None;
|
||||
let mut move_down_i: Option<usize> = None;
|
||||
let target_size = vec2(available_width, crate::consts::FONT_SIZE);
|
||||
for (i, (te_id, function)) in self.functions.iter_mut().map(|(a, b)| (*a, b)).enumerate() {
|
||||
let mut new_string = function.autocomplete.string.clone();
|
||||
@ -113,19 +108,6 @@ impl FunctionManager {
|
||||
// Only keep valid chars
|
||||
new_string.retain(crate::misc::is_valid_char);
|
||||
|
||||
// Display error indicator with tooltip if there's a parsing error
|
||||
if let Some(error) = function.get_test_result() {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(egui::RichText::new("⚠").color(egui::Color32::YELLOW))
|
||||
.on_hover_text(error);
|
||||
ui.label(
|
||||
egui::RichText::new(error)
|
||||
.color(egui::Color32::LIGHT_RED)
|
||||
.small(),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// If not fully open, return here as buttons cannot yet be displayed, therefore the user is inable to mark it for deletion
|
||||
let animate_bool = ui.ctx().animate_bool(te_id, re.has_focus());
|
||||
if animate_bool == 1.0 {
|
||||
@ -162,32 +144,38 @@ impl FunctionManager {
|
||||
&& let Some(hints) = function.autocomplete.hint.many()
|
||||
{
|
||||
let mut clicked = false;
|
||||
let selected_i = function.autocomplete.i;
|
||||
|
||||
if let Some(popup_response) = Popup::menu(&re).show(|ui| {
|
||||
let autocomplete_popup_id = Id::new("autocomplete popup");
|
||||
|
||||
egui::popup_below_widget(ui, autocomplete_popup_id, &re, |ui| {
|
||||
hints.iter().enumerate().for_each(|(i, candidate)| {
|
||||
if ui.selectable_label(i == selected_i, *candidate).clicked() {
|
||||
if ui
|
||||
.selectable_label(i == function.autocomplete.i, *candidate)
|
||||
.clicked()
|
||||
{
|
||||
clicked = true;
|
||||
function.autocomplete.i = i;
|
||||
}
|
||||
});
|
||||
}) && clicked
|
||||
{
|
||||
});
|
||||
|
||||
if clicked {
|
||||
function
|
||||
.autocomplete
|
||||
.apply_hint(hints[function.autocomplete.i]);
|
||||
|
||||
movement = Movement::Complete;
|
||||
} else {
|
||||
ui.memory_mut(|x| x.open_popup(autocomplete_popup_id));
|
||||
}
|
||||
}
|
||||
|
||||
// Push cursor to end if needed
|
||||
if movement == Movement::Complete
|
||||
&& let Some(mut state) = TextEdit::load_state(ui.ctx(), te_id)
|
||||
{
|
||||
if movement == Movement::Complete {
|
||||
let mut state =
|
||||
unsafe { TextEdit::load_state(ui.ctx(), te_id).unwrap_unchecked() };
|
||||
let ccursor = egui::text::CCursor::new(function.autocomplete.string.len());
|
||||
state
|
||||
.cursor
|
||||
.set_char_range(Some(egui::text::CCursorRange::one(ccursor)));
|
||||
state.set_ccursor_range(Some(egui::text::CCursorRange::one(ccursor)));
|
||||
TextEdit::store_state(ui.ctx(), te_id, state);
|
||||
}
|
||||
}
|
||||
@ -196,7 +184,7 @@ impl FunctionManager {
|
||||
const BUTTONS_Y_OFFSET: f32 = 1.32;
|
||||
const Y_OFFSET: f32 = crate::consts::FONT_SIZE * BUTTONS_Y_OFFSET;
|
||||
|
||||
widgets_ontop(ui, Id::NULL.with(i), &re, Y_OFFSET, |ui| {
|
||||
widgets_ontop(ui, Id::new(i), &re, Y_OFFSET, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
// There's more than 1 function! Functions can now be deleted
|
||||
if ui
|
||||
@ -207,47 +195,6 @@ impl FunctionManager {
|
||||
remove_i = Some(i);
|
||||
}
|
||||
|
||||
// Toggle visibility
|
||||
function.visible.bitxor_assign(
|
||||
ui.add(button_area_button(if function.visible {
|
||||
"👁"
|
||||
} else {
|
||||
"○"
|
||||
}))
|
||||
.on_hover_text(match function.visible {
|
||||
true => "Hide Function",
|
||||
false => "Show Function",
|
||||
})
|
||||
.clicked(),
|
||||
);
|
||||
|
||||
// Clone function
|
||||
if ui
|
||||
.add_enabled(can_add, button_area_button("⎘"))
|
||||
.on_hover_text("Clone Function")
|
||||
.clicked()
|
||||
{
|
||||
clone_i = Some(i);
|
||||
}
|
||||
|
||||
// Move up (only if not first)
|
||||
if ui
|
||||
.add_enabled(i > 0, button_area_button("⬆"))
|
||||
.on_hover_text("Move Up")
|
||||
.clicked()
|
||||
{
|
||||
move_up_i = Some(i);
|
||||
}
|
||||
|
||||
// Move down (only if not last)
|
||||
if ui
|
||||
.add_enabled(i < num_functions - 1, button_area_button("⬇"))
|
||||
.on_hover_text("Move Down")
|
||||
.clicked()
|
||||
{
|
||||
move_down_i = Some(i);
|
||||
}
|
||||
|
||||
ui.add_enabled_ui(function.is_some(), |ui| {
|
||||
// Toggle integral being enabled or not
|
||||
function.integral.bitxor_assign(
|
||||
@ -291,26 +238,6 @@ impl FunctionManager {
|
||||
self.functions.remove(remove_i_unwrap);
|
||||
}
|
||||
|
||||
// Clone function if the user requests it
|
||||
if let Some(clone_i_unwrap) = clone_i {
|
||||
let cloned = self.functions[clone_i_unwrap].1.clone();
|
||||
self.push_cloned(cloned);
|
||||
}
|
||||
|
||||
// Move function up if the user requests it
|
||||
if let Some(i) = move_up_i
|
||||
&& i > 0
|
||||
{
|
||||
self.functions.swap(i, i - 1);
|
||||
}
|
||||
|
||||
// Move function down if the user requests it
|
||||
if let Some(i) = move_down_i
|
||||
&& i < self.functions.len() - 1
|
||||
{
|
||||
self.functions.swap(i, i + 1);
|
||||
}
|
||||
|
||||
let final_hash = self.get_hash();
|
||||
|
||||
initial_hash != final_hash
|
||||
@ -319,21 +246,11 @@ impl FunctionManager {
|
||||
/// Create and push new empty function entry
|
||||
pub fn push_empty(&mut self) {
|
||||
self.functions.push((
|
||||
Id::NULL.with(random_u64().expect("unable to generate random id")),
|
||||
Id::new(random_u64().expect("unable to generate random id")),
|
||||
FunctionEntry::default(),
|
||||
));
|
||||
}
|
||||
|
||||
/// Push a cloned function entry
|
||||
pub fn push_cloned(&mut self, mut entry: FunctionEntry) {
|
||||
// Reset settings_opened so the cloned function doesn't have settings open
|
||||
entry.settings_opened = false;
|
||||
self.functions.push((
|
||||
Id::NULL.with(random_u64().expect("unable to generate random id")),
|
||||
entry,
|
||||
));
|
||||
}
|
||||
|
||||
/// Detect if any functions are using integrals
|
||||
pub fn any_using_integral(&self) -> bool {
|
||||
self.functions.iter().any(|(_, func)| func.integral)
|
||||
|
||||
15
src/lib.rs
15
src/lib.rs
@ -51,12 +51,12 @@ cfg_if::cfg_if! {
|
||||
|
||||
/// Call this once from JavaScript to start your app.
|
||||
#[wasm_bindgen]
|
||||
pub async fn start(&self, canvas: web_sys::HtmlCanvasElement) -> Result<(), wasm_bindgen::JsValue> {
|
||||
pub async fn start(&self, canvas_id: &str) -> Result<(), wasm_bindgen::JsValue> {
|
||||
self.runner
|
||||
.start(
|
||||
canvas,
|
||||
canvas_id,
|
||||
eframe::WebOptions::default(),
|
||||
Box::new(|cc| Ok(Box::new(math_app::MathApp::new(cc)))),
|
||||
Box::new(|cc| Box::new(math_app::MathApp::new(cc))),
|
||||
)
|
||||
.await
|
||||
}
|
||||
@ -66,16 +66,9 @@ cfg_if::cfg_if! {
|
||||
pub async fn start() {
|
||||
tracing::info!("Starting...");
|
||||
|
||||
let window = web_sys::window().expect("no global window exists");
|
||||
let document = window.document().expect("should have a document on window");
|
||||
let canvas = document
|
||||
.get_element_by_id("canvas")
|
||||
.expect("should have a canvas element with id 'canvas'")
|
||||
.dyn_into::<web_sys::HtmlCanvasElement>()
|
||||
.expect("canvas element should be an HtmlCanvasElement");
|
||||
|
||||
let web_handle = WebHandle::new();
|
||||
web_handle.start(canvas).await.unwrap()
|
||||
web_handle.start("canvas").await.unwrap()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -11,7 +11,7 @@ mod widgets;
|
||||
|
||||
// For running the program natively! (Because why not?)
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn main() -> eframe::Result {
|
||||
fn main() -> eframe::Result<()> {
|
||||
let subscriber = tracing_subscriber::FmtSubscriber::builder()
|
||||
.with_max_level(tracing::Level::INFO)
|
||||
.finish();
|
||||
@ -21,6 +21,6 @@ fn main() -> eframe::Result {
|
||||
eframe::run_native(
|
||||
"(Yet-to-be-named) Graphing Software",
|
||||
eframe::NativeOptions::default(),
|
||||
Box::new(|cc| Ok(Box::new(math_app::MathApp::new(cc)))),
|
||||
Box::new(|cc| Box::new(math_app::MathApp::new(cc))),
|
||||
)
|
||||
}
|
||||
|
||||
409
src/math_app.rs
409
src/math_app.rs
@ -2,20 +2,20 @@ use crate::{
|
||||
consts::{BUILD_INFO, COLORS, DEFAULT_INTEGRAL_NUM, DEFAULT_MAX_X, DEFAULT_MIN_X, build},
|
||||
function_entry::Riemann,
|
||||
function_manager::FunctionManager,
|
||||
misc::{EguiHelper, find_intersections, option_vec_printer},
|
||||
misc::option_vec_printer,
|
||||
};
|
||||
use eframe::App;
|
||||
use egui::{
|
||||
Button, CentralPanel, Color32, ComboBox, Context, DragValue, Frame, Key, Layout, Panel, Ui,
|
||||
Vec2, Window,
|
||||
Button, CentralPanel, Color32, ComboBox, Context, DragValue, Frame, Key, Layout, SidePanel,
|
||||
TopBottomPanel, Ui, Vec2, Window, style::Margin,
|
||||
};
|
||||
use egui_plot::Plot;
|
||||
|
||||
use emath::{Align, Align2};
|
||||
use epaint::{CornerRadius, Margin};
|
||||
|
||||
use epaint::Rounding;
|
||||
use instant::Instant;
|
||||
use itertools::Itertools;
|
||||
use std::{io::Read, ops::BitXorAssign};
|
||||
use web_time::Instant;
|
||||
|
||||
/// Stores current settings/state of [`MathApp`]
|
||||
#[derive(Copy, Clone)]
|
||||
@ -47,9 +47,6 @@ pub struct AppSettings {
|
||||
/// Stores whether or not displaying roots is enabled
|
||||
pub do_roots: bool,
|
||||
|
||||
/// Stores whether or not displaying intersections between functions is enabled
|
||||
pub do_intersections: bool,
|
||||
|
||||
/// Stores current plot pixel width
|
||||
pub plot_width: usize,
|
||||
}
|
||||
@ -67,7 +64,6 @@ impl Default for AppSettings {
|
||||
integral_num: DEFAULT_INTEGRAL_NUM,
|
||||
do_extrema: true,
|
||||
do_roots: true,
|
||||
do_intersections: true,
|
||||
plot_width: 0,
|
||||
}
|
||||
}
|
||||
@ -112,9 +108,6 @@ pub struct MathApp {
|
||||
|
||||
/// Stores settings (pretty self-explanatory)
|
||||
settings: AppSettings,
|
||||
|
||||
/// Stores intersection points between functions
|
||||
intersections: Vec<egui_plot::PlotPoint>,
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
@ -159,10 +152,9 @@ impl MathApp {
|
||||
let data = get_localstorage().get_item(DATA_NAME).ok()??;
|
||||
let (commit, cached_data) = crate::misc::hashed_storage_read(&data)?;
|
||||
|
||||
|
||||
if commit == unsafe { std::mem::transmute::<&str, crate::misc::HashBytes>(build::SHORT_COMMIT) } {
|
||||
tracing::info!("Reading decompression cache. Bytes: {}", cached_data.len());
|
||||
return Some(cached_data.to_vec());
|
||||
return Some(cached_data);
|
||||
} else {
|
||||
None
|
||||
}
|
||||
@ -170,14 +162,7 @@ impl MathApp {
|
||||
|
||||
fn load_functions() -> Option<FunctionManager> {
|
||||
let data = get_localstorage().get_item(FUNC_NAME).ok()??;
|
||||
if crate::misc::HASH_LENGTH >= data.len() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// TODO: stabilize FunctionManager serialize so it can persist across builds
|
||||
let (commit, func_data) = crate::misc::hashed_storage_read(&data)?;
|
||||
let func_data: &[u8] = &func_data;
|
||||
|
||||
|
||||
if commit == unsafe { std::mem::transmute::<&str, &[u8]>(build::SHORT_COMMIT) } {
|
||||
tracing::info!("Reading previous function data");
|
||||
@ -193,26 +178,28 @@ impl MathApp {
|
||||
|
||||
fn decompress_fonts() -> epaint::text::FontDefinitions {
|
||||
let mut data = Vec::new();
|
||||
let _ = ruzstd::decoding::StreamingDecoder::new(
|
||||
const { include_bytes!(concat!(env!("OUT_DIR"), "/compressed_data")).as_slice() },
|
||||
)
|
||||
.expect("unable to decode compressed data")
|
||||
.read_to_end(&mut data)
|
||||
.expect("unable to read compressed data");
|
||||
let _ =
|
||||
ruzstd::StreamingDecoder::new(
|
||||
&mut const {
|
||||
include_bytes!(concat!(env!("OUT_DIR"), "/compressed_data")).as_slice()
|
||||
},
|
||||
)
|
||||
.expect("unable to decode compressed data")
|
||||
.read_to_end(&mut data)
|
||||
.expect("unable to read compressed data");
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
#[cfg(target = "wasm32")]
|
||||
{
|
||||
tracing::info!("Setting decompression cache");
|
||||
// Convert SHORT_COMMIT string to fixed-size byte array
|
||||
let commit_bytes = build::SHORT_COMMIT.as_bytes();
|
||||
let mut commit: crate::misc::HashBytes = [0u8; crate::misc::HASH_LENGTH];
|
||||
let len = commit_bytes.len().min(crate::misc::HASH_LENGTH);
|
||||
commit[..len].copy_from_slice(&commit_bytes[..len]);
|
||||
|
||||
let saved_data = crate::misc::hashed_storage_create(commit, &data);
|
||||
let commit: crate::misc::HashBytes = const {
|
||||
unsafe {
|
||||
std::mem::transmute::<&str, crate::misc::HashBytes>(build::SHORT_COMMIT)
|
||||
}
|
||||
};
|
||||
let saved_data = commit.hashed_storage_create(data);
|
||||
tracing::info!("Bytes: {}", saved_data.len());
|
||||
get_localstorage()
|
||||
.set_item(DATA_NAME, &saved_data)
|
||||
.set_item(DATA_NAME, saved_data)
|
||||
.expect("failed to set local storage cache");
|
||||
}
|
||||
|
||||
@ -224,7 +211,7 @@ impl MathApp {
|
||||
// Initialize fonts
|
||||
// This used to be in the `update` method, but (after a ton of digging) this actually caused OOMs. that was a pain to debug
|
||||
cc.egui_ctx.set_fonts({
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
#[cfg(target = "wasm32")]
|
||||
if let Some(Ok(data)) =
|
||||
get_storage_decompressed().map(|data| bincode::deserialize(data.as_slice()))
|
||||
{
|
||||
@ -233,7 +220,7 @@ impl MathApp {
|
||||
decompress_fonts()
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[cfg(not(target = "wasm32"))]
|
||||
decompress_fonts()
|
||||
});
|
||||
|
||||
@ -255,7 +242,6 @@ impl MathApp {
|
||||
last_info: (None, None),
|
||||
opened: Opened::default(),
|
||||
settings: AppSettings::default(),
|
||||
intersections: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@ -263,150 +249,147 @@ impl MathApp {
|
||||
fn side_panel(&mut self, ctx: &Context) {
|
||||
// Side Panel which contains vital options to the operation of the application
|
||||
// (such as adding functions and other options)
|
||||
Panel::left("side_panel").resizable(false).show(ctx, |ui| {
|
||||
let any_using_integral = self.functions.any_using_integral();
|
||||
let prev_sum = self.settings.riemann_sum;
|
||||
// ComboBox for selecting what Riemann sum type to use
|
||||
ui.add_enabled_ui(any_using_integral, |ui| {
|
||||
let spacing_mut = ui.spacing_mut();
|
||||
SidePanel::left("side_panel")
|
||||
.resizable(false)
|
||||
.show(ctx, |ui| {
|
||||
let any_using_integral = self.functions.any_using_integral();
|
||||
let prev_sum = self.settings.riemann_sum;
|
||||
// ComboBox for selecting what Riemann sum type to use
|
||||
ui.add_enabled_ui(any_using_integral, |ui| {
|
||||
let spacing_mut = ui.spacing_mut();
|
||||
|
||||
spacing_mut.item_spacing.x = 1.0;
|
||||
spacing_mut.interact_size *= 0.5;
|
||||
ComboBox::from_label("Riemann Sum")
|
||||
.selected_text(self.settings.riemann_sum.to_string())
|
||||
.show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut self.settings.riemann_sum, Riemann::Left, "Left");
|
||||
ui.selectable_value(
|
||||
&mut self.settings.riemann_sum,
|
||||
Riemann::Middle,
|
||||
"Middle",
|
||||
spacing_mut.item_spacing.x = 1.0;
|
||||
spacing_mut.interact_size *= 0.5;
|
||||
ComboBox::from_label("Riemann Sum")
|
||||
.selected_text(self.settings.riemann_sum.to_string())
|
||||
.show_ui(ui, |ui| {
|
||||
ui.selectable_value(
|
||||
&mut self.settings.riemann_sum,
|
||||
Riemann::Left,
|
||||
"Left",
|
||||
);
|
||||
ui.selectable_value(
|
||||
&mut self.settings.riemann_sum,
|
||||
Riemann::Middle,
|
||||
"Middle",
|
||||
);
|
||||
ui.selectable_value(
|
||||
&mut self.settings.riemann_sum,
|
||||
Riemann::Right,
|
||||
"Right",
|
||||
);
|
||||
});
|
||||
|
||||
let riemann_changed = prev_sum != self.settings.riemann_sum;
|
||||
|
||||
let min_x_old = self.settings.integral_min_x;
|
||||
let max_x_old = self.settings.integral_max_x;
|
||||
|
||||
let (min_x_changed, max_x_changed) = ui
|
||||
.horizontal(|ui: &mut Ui| {
|
||||
// let spacing_mut = ui.spacing_mut();
|
||||
|
||||
// spacing_mut.item_spacing = Vec2::new(1.0, 0.0);
|
||||
// spacing_mut.interact_size *= 0.5;
|
||||
|
||||
ui.label("Integral: [");
|
||||
let min_x_changed = ui
|
||||
.add(DragValue::new(&mut self.settings.integral_min_x))
|
||||
.changed();
|
||||
ui.label(",");
|
||||
let max_x_changed = ui
|
||||
.add(DragValue::new(&mut self.settings.integral_max_x))
|
||||
.changed();
|
||||
ui.label("]");
|
||||
(min_x_changed, max_x_changed)
|
||||
})
|
||||
.inner;
|
||||
|
||||
// Checks integral bounds, and if they are invalid, fix them
|
||||
if self.settings.integral_min_x >= self.settings.integral_max_x {
|
||||
if max_x_changed {
|
||||
self.settings.integral_max_x = max_x_old;
|
||||
} else if min_x_changed {
|
||||
self.settings.integral_min_x = min_x_old;
|
||||
} else {
|
||||
// No clue how this would happen, but just in case
|
||||
self.settings.integral_min_x = DEFAULT_MIN_X;
|
||||
self.settings.integral_max_x = DEFAULT_MAX_X;
|
||||
}
|
||||
}
|
||||
|
||||
// Number of Rectangles for Riemann sum
|
||||
let integral_num_changed = ui
|
||||
.horizontal(|ui| {
|
||||
let spacing_mut = ui.spacing_mut();
|
||||
|
||||
spacing_mut.item_spacing.x = 1.5;
|
||||
ui.label("Interval:");
|
||||
ui.add(DragValue::new(&mut self.settings.integral_num))
|
||||
.changed()
|
||||
})
|
||||
.inner;
|
||||
|
||||
if integral_num_changed {
|
||||
self.settings.integral_num = self.settings.integral_num.clamp(0, 500000);
|
||||
}
|
||||
|
||||
self.settings.integral_changed = any_using_integral
|
||||
&& (max_x_changed | min_x_changed | integral_num_changed | riemann_changed);
|
||||
});
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
self.settings.do_extrema.bitxor_assign(
|
||||
ui.add(Button::new("Extrema"))
|
||||
.on_hover_text(match self.settings.do_extrema {
|
||||
true => "Disable Displaying Extrema",
|
||||
false => "Display Extrema",
|
||||
})
|
||||
.clicked(),
|
||||
);
|
||||
|
||||
self.settings.do_roots.bitxor_assign(
|
||||
ui.add(Button::new("Roots"))
|
||||
.on_hover_text(match self.settings.do_roots {
|
||||
true => "Disable Displaying Roots",
|
||||
false => "Display Roots",
|
||||
})
|
||||
.clicked(),
|
||||
);
|
||||
});
|
||||
|
||||
if self.functions.display_entries(ui) {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
tracing::info!("Saving function data");
|
||||
use crate::misc::{HashBytes, hashed_storage_create};
|
||||
let hash: HashBytes =
|
||||
unsafe { std::mem::transmute::<&str, HashBytes>(build::SHORT_COMMIT) };
|
||||
let saved_data = hashed_storage_create(
|
||||
hash,
|
||||
&bincode::serialize(&self.functions)
|
||||
.expect("unable to deserialize functions"),
|
||||
);
|
||||
ui.selectable_value(
|
||||
&mut self.settings.riemann_sum,
|
||||
Riemann::Right,
|
||||
"Right",
|
||||
);
|
||||
});
|
||||
|
||||
let riemann_changed = prev_sum != self.settings.riemann_sum;
|
||||
|
||||
let min_x_old = self.settings.integral_min_x;
|
||||
let max_x_old = self.settings.integral_max_x;
|
||||
|
||||
let (min_x_changed, max_x_changed) = ui
|
||||
.horizontal(|ui: &mut Ui| {
|
||||
// let spacing_mut = ui.spacing_mut();
|
||||
|
||||
// spacing_mut.item_spacing = Vec2::new(1.0, 0.0);
|
||||
// spacing_mut.interact_size *= 0.5;
|
||||
|
||||
ui.label("Integral: [");
|
||||
let min_x_changed = ui
|
||||
.add(DragValue::new(&mut self.settings.integral_min_x))
|
||||
.changed();
|
||||
ui.label(",");
|
||||
let max_x_changed = ui
|
||||
.add(DragValue::new(&mut self.settings.integral_max_x))
|
||||
.changed();
|
||||
ui.label("]");
|
||||
(min_x_changed, max_x_changed)
|
||||
})
|
||||
.inner;
|
||||
|
||||
// Checks integral bounds, and if they are invalid, fix them
|
||||
if self.settings.integral_min_x >= self.settings.integral_max_x {
|
||||
if max_x_changed {
|
||||
self.settings.integral_max_x = max_x_old;
|
||||
} else if min_x_changed {
|
||||
self.settings.integral_min_x = min_x_old;
|
||||
} else {
|
||||
// No clue how this would happen, but just in case
|
||||
self.settings.integral_min_x = DEFAULT_MIN_X;
|
||||
self.settings.integral_max_x = DEFAULT_MAX_X;
|
||||
// tracing::info!("Bytes: {}", saved_data.len());
|
||||
get_localstorage()
|
||||
.set_item(FUNC_NAME, &saved_data)
|
||||
.expect("failed to set local function storage");
|
||||
}
|
||||
}
|
||||
|
||||
// Number of Rectangles for Riemann sum
|
||||
let integral_num_changed = ui
|
||||
.horizontal(|ui| {
|
||||
let spacing_mut = ui.spacing_mut();
|
||||
// Only render if there's enough space
|
||||
if ui.available_height() > crate::consts::FONT_SIZE {
|
||||
ui.with_layout(Layout::bottom_up(Align::Min), |ui| {
|
||||
// Contents put in reverse order from bottom to top due to the 'buttom_up' layout
|
||||
|
||||
spacing_mut.item_spacing.x = 1.5;
|
||||
ui.label("Interval:");
|
||||
ui.add(DragValue::new(&mut self.settings.integral_num))
|
||||
.changed()
|
||||
})
|
||||
.inner;
|
||||
|
||||
if integral_num_changed {
|
||||
self.settings.integral_num = self.settings.integral_num.clamp(0, 500000);
|
||||
// Hyperlink to project's github
|
||||
ui.hyperlink_to(
|
||||
"I'm Open Source!",
|
||||
"https://github.com/Titaniumtown/YTBN-Graphing-Software",
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
self.settings.integral_changed = any_using_integral
|
||||
&& (max_x_changed | min_x_changed | integral_num_changed | riemann_changed);
|
||||
});
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
self.settings.do_extrema.bitxor_assign(
|
||||
ui.add(Button::new("Extrema"))
|
||||
.on_hover_text(match self.settings.do_extrema {
|
||||
true => "Disable Displaying Extrema",
|
||||
false => "Display Extrema",
|
||||
})
|
||||
.clicked(),
|
||||
);
|
||||
|
||||
self.settings.do_roots.bitxor_assign(
|
||||
ui.add(Button::new("Roots"))
|
||||
.on_hover_text(match self.settings.do_roots {
|
||||
true => "Disable Displaying Roots",
|
||||
false => "Display Roots",
|
||||
})
|
||||
.clicked(),
|
||||
);
|
||||
|
||||
self.settings.do_intersections.bitxor_assign(
|
||||
ui.add(Button::new("Intersections"))
|
||||
.on_hover_text(match self.settings.do_intersections {
|
||||
true => "Disable Displaying Intersections",
|
||||
false => "Display Intersections between functions",
|
||||
})
|
||||
.clicked(),
|
||||
);
|
||||
});
|
||||
|
||||
if self.functions.display_entries(ui) {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
tracing::info!("Saving function data");
|
||||
use crate::misc::{HashBytes, hashed_storage_create};
|
||||
let hash: HashBytes =
|
||||
unsafe { std::mem::transmute::<&str, HashBytes>(build::SHORT_COMMIT) };
|
||||
let saved_data = hashed_storage_create(
|
||||
hash,
|
||||
&bincode::serialize(&self.functions)
|
||||
.expect("unable to deserialize functions"),
|
||||
);
|
||||
// tracing::info!("Bytes: {}", saved_data.len());
|
||||
get_localstorage()
|
||||
.set_item(FUNC_NAME, &saved_data)
|
||||
.expect("failed to set local function storage");
|
||||
}
|
||||
}
|
||||
|
||||
// Only render if there's enough space
|
||||
if ui.available_height() > crate::consts::FONT_SIZE {
|
||||
ui.with_layout(Layout::bottom_up(Align::Min), |ui| {
|
||||
// Contents put in reverse order from bottom to top due to the 'buttom_up' layout
|
||||
|
||||
// Hyperlink to project's github
|
||||
ui.hyperlink_to(
|
||||
"I'm Open Source!",
|
||||
"https://github.com/Titaniumtown/YTBN-Graphing-Software",
|
||||
);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@ -415,7 +398,7 @@ impl App for MathApp {
|
||||
fn update(&mut self, ctx: &Context, _frame: &mut eframe::Frame) {
|
||||
// start timer
|
||||
let start = if self.opened.info {
|
||||
Some(Instant::now())
|
||||
Some(instant::Instant::now())
|
||||
} else {
|
||||
// if disabled, clear the stored formatted time
|
||||
self.last_info.1 = None;
|
||||
@ -432,7 +415,7 @@ impl App for MathApp {
|
||||
}
|
||||
|
||||
// Creates Top bar that contains some general options
|
||||
Panel::top("top_bar").show(ctx, |ui| {
|
||||
TopBottomPanel::top("top_bar").show(ctx, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
// Button in top bar to toggle showing the side panel
|
||||
self.opened.side_panel.bitxor_assign(
|
||||
@ -549,23 +532,46 @@ impl App for MathApp {
|
||||
self.side_panel(ctx);
|
||||
}
|
||||
|
||||
// Central panel which contains the central plot
|
||||
// Central panel which contains the central plot (or an error created when parsing)
|
||||
CentralPanel::default()
|
||||
.frame(Frame {
|
||||
inner_margin: Margin::ZERO,
|
||||
corner_radius: CornerRadius::ZERO,
|
||||
inner_margin: Margin::symmetric(0.0, 0.0),
|
||||
rounding: Rounding::ZERO,
|
||||
// fill: crate::style::STYLE.window_fill(),
|
||||
fill: Color32::from_gray(27),
|
||||
..Frame::NONE
|
||||
..Frame::none()
|
||||
})
|
||||
.show(ctx, |ui| {
|
||||
// Display an error if it exists
|
||||
let errors_formatted: String = self
|
||||
.functions
|
||||
.get_entries()
|
||||
.iter()
|
||||
.map(|(_, func)| func.get_test_result())
|
||||
.enumerate()
|
||||
.filter(|(_, error)| error.is_some())
|
||||
.map(|(i, error)| {
|
||||
// use unwrap_unchecked as None Errors are already filtered out
|
||||
unsafe {
|
||||
format!("(Function #{}) {}\n", i, error.as_ref().unwrap_unchecked())
|
||||
}
|
||||
})
|
||||
.join("");
|
||||
|
||||
if !errors_formatted.is_empty() {
|
||||
ui.centered_and_justified(|ui| {
|
||||
ui.heading(errors_formatted);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
let available_width: usize = (ui.available_width() as usize) + 1; // Used in later logic
|
||||
let width_changed = available_width != self.settings.plot_width;
|
||||
self.settings.plot_width = available_width;
|
||||
|
||||
// Create and setup plot
|
||||
Plot::new("plot")
|
||||
.set_margin_fraction(emath::Vec2::ZERO)
|
||||
.set_margin_fraction(Vec2::ZERO)
|
||||
.data_aspect(1.0)
|
||||
.include_y(0)
|
||||
.show(ui, |plot_ui| {
|
||||
@ -603,41 +609,6 @@ impl App for MathApp {
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Calculate and display intersections between functions
|
||||
if self.settings.do_intersections {
|
||||
let entries = self.functions.get_entries();
|
||||
let visible_entries: Vec<_> = entries
|
||||
.iter()
|
||||
.filter(|(_, f)| f.visible && f.is_some())
|
||||
.collect();
|
||||
|
||||
// Clear previous intersections
|
||||
self.intersections.clear();
|
||||
|
||||
// Find intersections between all pairs of visible functions
|
||||
for i in 0..visible_entries.len() {
|
||||
for j in (i + 1)..visible_entries.len() {
|
||||
let (_, func1) = visible_entries[i];
|
||||
let (_, func2) = visible_entries[j];
|
||||
|
||||
let mut intersections =
|
||||
find_intersections(&func1.back_data, &func2.back_data);
|
||||
self.intersections.append(&mut intersections);
|
||||
}
|
||||
}
|
||||
|
||||
// Display intersection points
|
||||
if !self.intersections.is_empty() {
|
||||
plot_ui.points(
|
||||
self.intersections
|
||||
.clone()
|
||||
.to_points()
|
||||
.color(Color32::from_rgb(255, 105, 180)) // Hot pink for visibility
|
||||
.radius(6.0),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
self.last_info.0 = if area.iter().any(|e| e.is_some()) {
|
||||
Some(format!("Area: {}", option_vec_printer(area.as_slice())))
|
||||
} else {
|
||||
@ -647,6 +618,6 @@ impl App for MathApp {
|
||||
});
|
||||
|
||||
// Calculate and store the last time it took to draw the frame
|
||||
self.last_info.1 = start.map(|a| format!("Took: {}us", a.elapsed().as_micros()));
|
||||
self.last_info.1 = start.map(|a| format!("Took: {}ms", a.elapsed().as_micros()));
|
||||
}
|
||||
}
|
||||
|
||||
84
src/misc.rs
84
src/misc.rs
@ -1,18 +1,20 @@
|
||||
use base64::{Engine as _, engine::general_purpose};
|
||||
use egui_plot::{Line, PlotPoint, PlotPoints, Points};
|
||||
use emath::Pos2;
|
||||
use getrandom::getrandom;
|
||||
use itertools::Itertools;
|
||||
use parsing::FlatExWrapper;
|
||||
|
||||
/// Implements traits that are useful when dealing with Vectors of egui's `Value`
|
||||
pub trait EguiHelper {
|
||||
/// Converts to `egui::plot::Values`
|
||||
fn to_values(self) -> PlotPoints<'static>;
|
||||
fn to_values(self) -> PlotPoints;
|
||||
|
||||
/// Converts to `egui::plot::Line`
|
||||
fn to_line(self) -> Line<'static>;
|
||||
fn to_line(self) -> Line;
|
||||
|
||||
/// Converts to `egui::plot::Points`
|
||||
fn to_points(self) -> Points<'static>;
|
||||
fn to_points(self) -> Points;
|
||||
|
||||
/// Converts Vector of Values into vector of tuples
|
||||
fn to_tuple(self) -> Vec<(f64, f64)>;
|
||||
@ -20,18 +22,18 @@ pub trait EguiHelper {
|
||||
|
||||
impl EguiHelper for Vec<PlotPoint> {
|
||||
#[inline(always)]
|
||||
fn to_values(self) -> PlotPoints<'static> {
|
||||
fn to_values(self) -> PlotPoints {
|
||||
PlotPoints::from(unsafe { std::mem::transmute::<Vec<PlotPoint>, Vec<[f64; 2]>>(self) })
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn to_line(self) -> Line<'static> {
|
||||
Line::new("", self.to_values())
|
||||
fn to_line(self) -> Line {
|
||||
Line::new(self.to_values())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn to_points(self) -> Points<'static> {
|
||||
Points::new("", self.to_values())
|
||||
fn to_points(self) -> Points {
|
||||
Points::new(self.to_values())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
@ -170,27 +172,27 @@ pub type HashBytes = [u8; HASH_LENGTH];
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn hashed_storage_create(hashbytes: HashBytes, data: &[u8]) -> String {
|
||||
// Use base64 encoding to safely store binary data in localStorage
|
||||
let combined: Vec<u8> = [hashbytes.to_vec(), data.to_vec()].concat();
|
||||
base64::encode(combined)
|
||||
let combined_data = [hashbytes.to_vec(), data.to_vec()].concat();
|
||||
general_purpose::STANDARD.encode(combined_data)
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn hashed_storage_read(data: &str) -> Option<(HashBytes, Vec<u8>)> {
|
||||
// Decode base64 data
|
||||
let decoded = base64::decode(data).ok()?;
|
||||
let decoded_bytes = general_purpose::STANDARD.decode(data).ok()?;
|
||||
|
||||
// Make sure data is long enough to decode
|
||||
if HASH_LENGTH >= decoded.len() {
|
||||
if HASH_LENGTH > decoded_bytes.len() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Extract hash and data
|
||||
let mut hash: HashBytes = [0u8; HASH_LENGTH];
|
||||
hash.copy_from_slice(&decoded[..HASH_LENGTH]);
|
||||
let data_part = decoded[HASH_LENGTH..].to_vec();
|
||||
// Split hash and data
|
||||
let (hash_bytes, data_bytes) = decoded_bytes.split_at(HASH_LENGTH);
|
||||
|
||||
Some((hash, data_part))
|
||||
// Convert hash bytes to HashBytes
|
||||
let hash: HashBytes = hash_bytes.try_into().ok()?;
|
||||
|
||||
Some((hash, data_bytes.to_vec()))
|
||||
}
|
||||
|
||||
/// Creates and returns random u64
|
||||
@ -198,7 +200,7 @@ pub fn random_u64() -> Result<u64, getrandom::Error> {
|
||||
// Buffer of 8 `u8`s that are later merged into one u64
|
||||
let mut buf = [0u8; 8];
|
||||
// Populate buffer with random values
|
||||
getrandom::fill(&mut buf)?;
|
||||
getrandom(&mut buf)?;
|
||||
// Merge buffer into u64
|
||||
Ok(u64::from_be_bytes(buf))
|
||||
}
|
||||
@ -208,47 +210,3 @@ include!(concat!(env!("OUT_DIR"), "/valid_chars.rs"));
|
||||
pub fn is_valid_char(c: char) -> bool {
|
||||
c.is_alphanumeric() | VALID_EXTRA_CHARS.contains(&c)
|
||||
}
|
||||
|
||||
/// Find intersection points between two functions given their plotted data
|
||||
/// Returns a vector of PlotPoints where the functions intersect
|
||||
pub fn find_intersections(data1: &[PlotPoint], data2: &[PlotPoint]) -> Vec<PlotPoint> {
|
||||
if data1.is_empty() || data2.is_empty() || data1.len() != data2.len() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
// Calculate difference between functions at each x point
|
||||
let differences: Vec<(f64, f64)> = data1
|
||||
.iter()
|
||||
.zip(data2.iter())
|
||||
.filter(|(p1, p2)| p1.y.is_finite() && p2.y.is_finite())
|
||||
.map(|(p1, p2)| (p1.x, p1.y - p2.y))
|
||||
.collect();
|
||||
|
||||
// Find where sign changes (intersection points)
|
||||
differences
|
||||
.iter()
|
||||
.tuple_windows()
|
||||
.filter(|((_, diff1), (_, diff2))| diff1.signum() != diff2.signum())
|
||||
.map(|((x1, diff1), (x2, diff2))| {
|
||||
// Linear interpolation to find approximate x of intersection
|
||||
let t = diff1.abs() / (diff1.abs() + diff2.abs());
|
||||
let x = x1 + t * (x2 - x1);
|
||||
|
||||
// Find corresponding y values and average them for the intersection point
|
||||
// We need to interpolate y values from both functions
|
||||
let y1_at_x1 = data1
|
||||
.iter()
|
||||
.find(|p| (p.x - x1).abs() < f64::EPSILON)
|
||||
.map(|p| p.y)
|
||||
.unwrap_or(0.0);
|
||||
let y1_at_x2 = data1
|
||||
.iter()
|
||||
.find(|p| (p.x - x2).abs() < f64::EPSILON)
|
||||
.map(|p| p.y)
|
||||
.unwrap_or(0.0);
|
||||
let y = y1_at_x1 + t * (y1_at_x2 - y1_at_x1);
|
||||
|
||||
PlotPoint::new(x, y)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@ -19,7 +19,6 @@ fn app_settings_constructor(
|
||||
integral_num,
|
||||
do_extrema: false,
|
||||
do_roots: false,
|
||||
do_intersections: false,
|
||||
plot_width: pixel_width,
|
||||
}
|
||||
}
|
||||
|
||||
@ -143,9 +143,8 @@ fn invalid_hashed_storage() {
|
||||
fn newtons_method() {
|
||||
use parsing::BackingFunction;
|
||||
use parsing::FlatExWrapper;
|
||||
use parsing::process_func_str;
|
||||
fn get_flatexwrapper(func: &str) -> FlatExWrapper {
|
||||
let backing_func = BackingFunction::new(&process_func_str(func)).unwrap();
|
||||
let mut backing_func = BackingFunction::new(func).unwrap();
|
||||
backing_func.get_function_derivative(0).clone()
|
||||
}
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user