Compare commits
16 Commits
dab002bd15
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
ac6265eae7
|
|||
|
c70c715126
|
|||
|
f2d0d27345
|
|||
|
41b50eb893
|
|||
|
e497987573
|
|||
|
65ab0c6a1f
|
|||
|
f6a09fe449
|
|||
|
b08a727fe3
|
|||
|
5480522ddb
|
|||
|
07858b229f
|
|||
|
3288752dfb
|
|||
|
3305227ffe
|
|||
|
df05601e26
|
|||
|
48fd49e386
|
|||
|
c7760e2123
|
|||
|
2d7c987f11
|
1
Cargo.lock
generated
1
Cargo.lock
generated
@@ -4145,7 +4145,6 @@ dependencies = [
|
||||
"base64",
|
||||
"benchmarks",
|
||||
"bincode",
|
||||
"cfg-if",
|
||||
"eframe",
|
||||
"egui",
|
||||
"egui_plot",
|
||||
|
||||
@@ -48,7 +48,6 @@ epaint = { git = "https://github.com/titaniumtown/egui.git", default-features =
|
||||
emath = { git = "https://github.com/titaniumtown/egui.git", default-features = false }
|
||||
egui_plot = { version = "0.34.0", default-features = false }
|
||||
|
||||
cfg-if = "1"
|
||||
ruzstd = "0.8"
|
||||
tracing = "0.1"
|
||||
itertools = "0.14"
|
||||
|
||||
@@ -8,81 +8,81 @@ use criterion::{criterion_group, criterion_main, Criterion};
|
||||
use pprof::ProfilerGuard;
|
||||
|
||||
pub struct FlamegraphProfiler<'a> {
|
||||
frequency: c_int,
|
||||
active_profiler: Option<ProfilerGuard<'a>>,
|
||||
frequency: c_int,
|
||||
active_profiler: Option<ProfilerGuard<'a>>,
|
||||
}
|
||||
|
||||
impl<'a> FlamegraphProfiler<'a> {
|
||||
#[allow(dead_code)]
|
||||
pub fn new(frequency: c_int) -> Self {
|
||||
FlamegraphProfiler {
|
||||
frequency,
|
||||
active_profiler: None,
|
||||
}
|
||||
}
|
||||
#[allow(dead_code)]
|
||||
pub fn new(frequency: c_int) -> Self {
|
||||
FlamegraphProfiler {
|
||||
frequency,
|
||||
active_profiler: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
fn start_profiling(&mut self, _benchmark_id: &str, _benchmark_dir: &Path) {
|
||||
self.active_profiler = Some(ProfilerGuard::new(self.frequency).unwrap());
|
||||
}
|
||||
|
||||
fn stop_profiling(&mut self, _benchmark_id: &str, benchmark_dir: &Path) {
|
||||
std::fs::create_dir_all(benchmark_dir).unwrap();
|
||||
let flamegraph_path = benchmark_dir.join("flamegraph.svg");
|
||||
let flamegraph_file = File::create(&flamegraph_path)
|
||||
.expect("File system error while creating flamegraph.svg");
|
||||
if let Some(profiler) = self.active_profiler.take() {
|
||||
profiler
|
||||
.report()
|
||||
.build()
|
||||
.unwrap()
|
||||
.flamegraph(flamegraph_file)
|
||||
.expect("Error writing flamegraph");
|
||||
}
|
||||
}
|
||||
fn stop_profiling(&mut self, _benchmark_id: &str, benchmark_dir: &Path) {
|
||||
std::fs::create_dir_all(benchmark_dir).unwrap();
|
||||
let flamegraph_path = benchmark_dir.join("flamegraph.svg");
|
||||
let flamegraph_file = File::create(&flamegraph_path)
|
||||
.expect("File system error while creating flamegraph.svg");
|
||||
if let Some(profiler) = self.active_profiler.take() {
|
||||
profiler
|
||||
.report()
|
||||
.build()
|
||||
.unwrap()
|
||||
.flamegraph(flamegraph_file)
|
||||
.expect("Error writing flamegraph");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[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)
|
||||
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))
|
||||
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 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();
|
||||
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
|
||||
|
||||
2
build.rs
2
build.rs
@@ -6,8 +6,8 @@ use allsorts::{
|
||||
tag,
|
||||
};
|
||||
use epaint::{
|
||||
text::{FontData, FontDefinitions, FontTweak},
|
||||
FontFamily,
|
||||
text::{FontData, FontDefinitions, FontTweak},
|
||||
};
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
|
||||
@@ -4,21 +4,14 @@ use std::collections::HashMap;
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub struct FlatExWrapper {
|
||||
func: Option<FlatEx<f64>>,
|
||||
func_str: Option<String>,
|
||||
}
|
||||
|
||||
impl FlatExWrapper {
|
||||
const EMPTY: FlatExWrapper = FlatExWrapper {
|
||||
func: None,
|
||||
func_str: None,
|
||||
};
|
||||
const EMPTY: FlatExWrapper = FlatExWrapper { func: None };
|
||||
|
||||
#[inline]
|
||||
const fn new(f: FlatEx<f64>) -> Self {
|
||||
Self {
|
||||
func: Some(f),
|
||||
func_str: None,
|
||||
}
|
||||
Self { func: Some(f) }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -34,26 +27,6 @@ impl FlatExWrapper {
|
||||
.unwrap_or(f64::NAN)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn partial(&self, x: usize) -> Self {
|
||||
self.func
|
||||
.as_ref()
|
||||
.map(|f| f.clone().partial(x).map(Self::new).unwrap_or(Self::EMPTY))
|
||||
.unwrap_or(Self::EMPTY)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn get_string(&mut self) -> String {
|
||||
match self.func_str {
|
||||
Some(ref func_str) => func_str.clone(),
|
||||
None => {
|
||||
let calculated = self.func.as_ref().map(|f| f.unparse()).unwrap_or("");
|
||||
self.func_str = Some(calculated.to_owned());
|
||||
calculated.to_owned()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn partial_iter(&self, n: usize) -> Self {
|
||||
self.func
|
||||
@@ -165,18 +138,6 @@ impl BackingFunction {
|
||||
}
|
||||
}
|
||||
|
||||
fn prettyify_function_str(func: &str) -> String {
|
||||
let new_str = func.replace("{x}", "x");
|
||||
|
||||
if &new_str == "0/0" {
|
||||
"Undefined".to_owned()
|
||||
} else {
|
||||
new_str
|
||||
}
|
||||
}
|
||||
|
||||
// pub const VALID_VARIABLES: [char; 3] = ['x', 'e', 'π'];
|
||||
|
||||
/// Case insensitive checks for if `c` is a character used to represent a variable
|
||||
#[inline]
|
||||
pub const fn is_variable(c: &char) -> bool {
|
||||
|
||||
@@ -1,17 +1,61 @@
|
||||
use crate::parsing::is_variable;
|
||||
use crate::SUPPORTED_FUNCTIONS;
|
||||
|
||||
/// Protect function names that start with variable characters (like 'e' in 'exp')
|
||||
/// by replacing them with a placeholder during parsing, then restoring them after.
|
||||
/// This prevents incorrect splitting like "exp" -> "e" * "xp".
|
||||
fn protect_function_names(input: &str) -> (String, Vec<(&'static str, String)>) {
|
||||
let mut result = input.to_string();
|
||||
let mut replacements = Vec::new();
|
||||
|
||||
// Only protect functions that start with a variable character
|
||||
// Sort by length descending to replace longer matches first (e.g., "exp" before "e")
|
||||
let mut funcs: Vec<&'static str> = SUPPORTED_FUNCTIONS
|
||||
.iter()
|
||||
.filter(|&&func| {
|
||||
func.chars()
|
||||
.next()
|
||||
.map(|c| is_variable(&c))
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.copied()
|
||||
.collect();
|
||||
funcs.sort_by(|a, b| b.len().cmp(&a.len()));
|
||||
|
||||
for func in funcs {
|
||||
// Use a placeholder made of letters that will be treated as a function name
|
||||
// The placeholder won't be split because it's all letters
|
||||
let placeholder = format!("zzzfn{}", replacements.len());
|
||||
result = result.replace(func, &placeholder);
|
||||
replacements.push((func, placeholder));
|
||||
}
|
||||
|
||||
(result, replacements)
|
||||
}
|
||||
|
||||
/// Restore protected function names from their placeholders
|
||||
fn restore_function_names(input: &str, replacements: &[(&'static str, String)]) -> String {
|
||||
let mut result = input.to_string();
|
||||
for (func, placeholder) in replacements {
|
||||
result = result.replace(placeholder, func);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub fn split_function(input: &str, split: SplitType) -> Vec<String> {
|
||||
// Protect function names that could be incorrectly split
|
||||
let (protected, replacements) = protect_function_names(input);
|
||||
|
||||
split_function_chars(
|
||||
&input
|
||||
&protected
|
||||
.replace("pi", "π") // replace "pi" text with pi symbol
|
||||
.replace("**", "^") // support alternate manner of expressing exponents
|
||||
.replace("exp", "\u{1fc93}") // stop-gap solution to fix the `exp` function
|
||||
.chars()
|
||||
.collect::<Vec<char>>(),
|
||||
split,
|
||||
)
|
||||
.iter()
|
||||
.map(|x| x.replace('\u{1fc93}', "exp")) // Convert back to `exp` text
|
||||
.map(|x| restore_function_names(x, &replacements))
|
||||
.collect::<Vec<String>>()
|
||||
}
|
||||
|
||||
@@ -62,46 +106,73 @@ impl BoolSlice {
|
||||
self.number && !self.masked_num
|
||||
}
|
||||
|
||||
/// Returns true if this char is a function name letter (not a standalone variable)
|
||||
const fn is_function_letter(&self) -> bool {
|
||||
self.letter && !self.is_unmasked_variable()
|
||||
}
|
||||
|
||||
/// Returns true if this is a "term" - something that can be multiplied
|
||||
const fn is_term(&self) -> bool {
|
||||
self.is_unmasked_number() || self.is_unmasked_variable() || self.letter
|
||||
}
|
||||
|
||||
const fn calculate_mask(&mut self, other: &BoolSlice) {
|
||||
if other.masked_num && self.number {
|
||||
// If previous char was a masked number, and current char is a number, mask current char's variable status
|
||||
// Propagate number masking through consecutive digits
|
||||
self.masked_num = true;
|
||||
} else if other.masked_var && self.variable {
|
||||
// If previous char was a masked variable, and current char is a variable, mask current char's variable status
|
||||
// Propagate variable masking through consecutive variables
|
||||
self.masked_var = true;
|
||||
} else if other.letter && !other.is_unmasked_variable() {
|
||||
} else if other.is_function_letter() {
|
||||
// After a function letter, mask following numbers/variables as part of function name
|
||||
self.masked_num = self.number;
|
||||
self.masked_var = self.variable;
|
||||
}
|
||||
}
|
||||
|
||||
const fn splitable(&self, c: &char, other: &BoolSlice, split: &SplitType) -> bool {
|
||||
if (*c == '*') | (matches!(split, &SplitType::Term) && other.open_parens) {
|
||||
true
|
||||
} else if other.closing_parens {
|
||||
// Cases like `)x`, `)2`, and `)(`
|
||||
return (*c == '(')
|
||||
| (self.letter && !self.is_unmasked_variable())
|
||||
| self.is_unmasked_variable()
|
||||
| self.is_unmasked_number();
|
||||
} else if *c == '(' {
|
||||
// Cases like `x(` and `2(`
|
||||
return (other.is_unmasked_variable() | other.is_unmasked_number()) && !other.letter;
|
||||
} else if other.is_unmasked_number() {
|
||||
// Cases like `2x` and `2sin(x)`
|
||||
return self.is_unmasked_variable() | self.letter;
|
||||
} else if self.is_unmasked_variable() | self.letter {
|
||||
// Cases like `e2` and `xx`
|
||||
return other.is_unmasked_number()
|
||||
| (other.is_unmasked_variable() && self.is_unmasked_variable())
|
||||
| other.is_unmasked_variable();
|
||||
} else if (self.is_unmasked_number() | self.letter | self.is_unmasked_variable())
|
||||
&& (other.is_unmasked_number() | other.letter)
|
||||
{
|
||||
/// Determines if we should split (insert implicit multiplication) before current char
|
||||
const fn splitable(&self, c: &char, prev: &BoolSlice, split: &SplitType) -> bool {
|
||||
// Always split on explicit multiplication
|
||||
if *c == '*' {
|
||||
return true;
|
||||
} else {
|
||||
return self.is_unmasked_number() && other.is_unmasked_variable();
|
||||
}
|
||||
|
||||
// For Term split type, also split after open parens
|
||||
if matches!(split, &SplitType::Term) && prev.open_parens {
|
||||
return true;
|
||||
}
|
||||
|
||||
// After closing paren: split before `(`, letters, variables, or numbers
|
||||
// e.g., `)x`, `)2`, `)(`, `)sin`
|
||||
if prev.closing_parens {
|
||||
return *c == '(' || self.is_term();
|
||||
}
|
||||
|
||||
// Before open paren: split if previous was a standalone number or variable
|
||||
// e.g., `x(`, `2(` but not `sin(`
|
||||
if *c == '(' {
|
||||
return (prev.is_unmasked_variable() || prev.is_unmasked_number()) && !prev.letter;
|
||||
}
|
||||
|
||||
// After a number: split before variables or function letters
|
||||
// e.g., `2x`, `2sin`
|
||||
if prev.is_unmasked_number() {
|
||||
return self.is_unmasked_variable() || self.letter;
|
||||
}
|
||||
|
||||
// Current is a variable or letter: split if previous was a number or variable
|
||||
// e.g., `e2`, `xx`, `xe`
|
||||
if self.is_unmasked_variable() || self.letter {
|
||||
return prev.is_unmasked_number() || prev.is_unmasked_variable();
|
||||
}
|
||||
|
||||
// Current is a number after a variable
|
||||
// e.g., `x2`
|
||||
if self.is_unmasked_number() && prev.is_unmasked_variable() {
|
||||
return true;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,4 +276,13 @@ fn split_function_test() {
|
||||
&["2", "sin(π) + 2", "cos(tau)"],
|
||||
SplitType::Multiplication,
|
||||
);
|
||||
|
||||
// Test that exp() function is properly handled (not split into e*xp)
|
||||
assert_test("exp(x)", &["exp(x)"], SplitType::Multiplication);
|
||||
assert_test("2exp(x)", &["2", "exp(x)"], SplitType::Multiplication);
|
||||
assert_test(
|
||||
"exp(x)sin(x)",
|
||||
&["exp(x)", "sin(x)"],
|
||||
SplitType::Multiplication,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
use crate::math_app::AppSettings;
|
||||
use crate::misc::{EguiHelper, newtons_method_helper, step_helper};
|
||||
use crate::symbolic::try_symbolic;
|
||||
use egui::{Checkbox, Context};
|
||||
use egui_plot::{Bar, BarChart, PlotPoint, PlotUi};
|
||||
use egui_plot::{Bar, BarChart, PlotPoint, PlotUi, Points};
|
||||
|
||||
use epaint::Color32;
|
||||
use parsing::{AutoComplete, generate_hint};
|
||||
use parsing::{BackingFunction, process_func_str};
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer, ser::SerializeStruct};
|
||||
use std::{
|
||||
fmt::{self, Debug},
|
||||
hash::{Hash, Hasher},
|
||||
};
|
||||
use std::fmt::{self, Debug};
|
||||
|
||||
/// Represents the possible variations of Riemann Sums
|
||||
#[derive(PartialEq, Eq, Debug, Copy, Clone, Default)]
|
||||
@@ -34,16 +32,13 @@ pub struct FunctionEntry {
|
||||
/// The `BackingFunction` instance that is used to generate `f(x)`, `f'(x)`, and `f''(x)`
|
||||
function: BackingFunction,
|
||||
|
||||
/// Stores a function string (that hasn't been processed via `process_func_str`) to display to the user
|
||||
pub raw_func_str: String,
|
||||
|
||||
/// If calculating/displayingintegrals are enabled
|
||||
pub integral: bool,
|
||||
|
||||
/// If displaying derivatives are enabled (note, they are still calculated for other purposes)
|
||||
pub derivative: bool,
|
||||
|
||||
pub nth_derviative: bool,
|
||||
pub nth_derivative: bool,
|
||||
|
||||
pub back_data: Vec<PlotPoint>,
|
||||
pub integral_data: Option<(Vec<Bar>, f64)>,
|
||||
@@ -60,23 +55,13 @@ pub struct FunctionEntry {
|
||||
pub settings_opened: bool,
|
||||
}
|
||||
|
||||
impl Hash for FunctionEntry {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.raw_func_str.hash(state);
|
||||
self.integral.hash(state);
|
||||
self.nth_derviative.hash(state);
|
||||
self.curr_nth.hash(state);
|
||||
self.settings_opened.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for FunctionEntry {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
let mut s = serializer.serialize_struct("FunctionEntry", 4)?;
|
||||
s.serialize_field("raw_func_str", &self.raw_func_str)?;
|
||||
s.serialize_field("raw_func_str", &self.autocomplete.string)?;
|
||||
s.serialize_field("integral", &self.integral)?;
|
||||
s.serialize_field("derivative", &self.derivative)?;
|
||||
s.serialize_field("curr_nth", &self.curr_nth)?;
|
||||
@@ -125,10 +110,9 @@ impl Default for FunctionEntry {
|
||||
fn default() -> FunctionEntry {
|
||||
FunctionEntry {
|
||||
function: BackingFunction::default(),
|
||||
raw_func_str: String::new(),
|
||||
integral: false,
|
||||
derivative: false,
|
||||
nth_derviative: false,
|
||||
nth_derivative: false,
|
||||
back_data: Vec::new(),
|
||||
integral_data: None,
|
||||
derivative_data: Vec::new(),
|
||||
@@ -150,14 +134,14 @@ impl FunctionEntry {
|
||||
|
||||
pub fn settings_window(&mut self, ctx: &Context) {
|
||||
let mut invalidate_nth = false;
|
||||
egui::Window::new(format!("Settings: {}", self.raw_func_str))
|
||||
egui::Window::new(format!("Settings: {}", self.func_str()))
|
||||
.open(&mut self.settings_opened)
|
||||
.default_pos([200.0, 200.0])
|
||||
.resizable(false)
|
||||
.collapsible(false)
|
||||
.show(ctx, |ui| {
|
||||
ui.add(Checkbox::new(
|
||||
&mut self.nth_derviative,
|
||||
&mut self.nth_derivative,
|
||||
"Display Nth Derivative",
|
||||
));
|
||||
|
||||
@@ -180,13 +164,32 @@ impl FunctionEntry {
|
||||
&self.test_result
|
||||
}
|
||||
|
||||
/// Get the raw function string
|
||||
#[inline]
|
||||
pub fn func_str(&self) -> &str {
|
||||
&self.autocomplete.string
|
||||
}
|
||||
|
||||
/// Update function string and test it
|
||||
pub fn update_string(&mut self, raw_func_str: &str) {
|
||||
if raw_func_str == self.raw_func_str {
|
||||
if raw_func_str == self.func_str() {
|
||||
return;
|
||||
}
|
||||
|
||||
self.raw_func_str = raw_func_str.to_owned();
|
||||
// Update the autocomplete string (which is now the source of truth for the raw string)
|
||||
self.autocomplete.update_string(raw_func_str);
|
||||
|
||||
self.reparse_function(raw_func_str);
|
||||
}
|
||||
|
||||
/// Re-parse the function from the current autocomplete string.
|
||||
/// Call this when the autocomplete string was updated externally (e.g., via hint application).
|
||||
pub fn sync_from_autocomplete(&mut self) {
|
||||
self.reparse_function(&self.autocomplete.string.clone());
|
||||
}
|
||||
|
||||
/// Internal helper to parse a function string and update internal state
|
||||
fn reparse_function(&mut self, raw_func_str: &str) {
|
||||
let processed_func = process_func_str(raw_func_str);
|
||||
let new_func_result = BackingFunction::new(&processed_func);
|
||||
|
||||
@@ -212,17 +215,16 @@ impl FunctionEntry {
|
||||
) -> (Vec<(f64, f64)>, f64) {
|
||||
let step = (integral_max_x - integral_min_x) / (integral_num as f64);
|
||||
|
||||
// let sum_func = self.get_sum_func(sum);
|
||||
|
||||
let data2: Vec<(f64, f64)> = step_helper(integral_num, integral_min_x, step)
|
||||
let data: Vec<(f64, f64)> = step_helper(integral_num, integral_min_x, step)
|
||||
.into_iter()
|
||||
.map(|x| {
|
||||
let step_offset = step.copysign(x); // store the offset here so it doesn't have to be calculated multiple times
|
||||
let x2: f64 = x + step_offset;
|
||||
let step_offset = step.copysign(x);
|
||||
let x2 = x + step_offset;
|
||||
|
||||
let (left_x, right_x) = match x.is_sign_positive() {
|
||||
true => (x, x2),
|
||||
false => (x2, x),
|
||||
let (left_x, right_x) = if x.is_sign_positive() {
|
||||
(x, x2)
|
||||
} else {
|
||||
(x2, x)
|
||||
};
|
||||
|
||||
let y = match sum {
|
||||
@@ -238,9 +240,9 @@ impl FunctionEntry {
|
||||
.filter(|(_, y)| y.is_finite())
|
||||
.collect();
|
||||
|
||||
let area = data2.iter().map(move |(_, y)| y * step).sum();
|
||||
let area = data.iter().map(|(_, y)| y * step).sum();
|
||||
|
||||
(data2, area)
|
||||
(data, area)
|
||||
}
|
||||
|
||||
/// Helps with processing newton's method depending on level of derivative
|
||||
@@ -252,27 +254,33 @@ impl FunctionEntry {
|
||||
) -> Vec<PlotPoint> {
|
||||
self.function.generate_derivative(derivative_level);
|
||||
self.function.generate_derivative(derivative_level + 1);
|
||||
let newtons_method_output: Vec<f64> = match derivative_level {
|
||||
0 => newtons_method_helper(
|
||||
threshold,
|
||||
range,
|
||||
self.back_data.as_slice(),
|
||||
self.function.get_function_derivative(0),
|
||||
self.function.get_function_derivative(1),
|
||||
),
|
||||
1 => newtons_method_helper(
|
||||
threshold,
|
||||
range,
|
||||
self.derivative_data.as_slice(),
|
||||
self.function.get_function_derivative(1),
|
||||
self.function.get_function_derivative(2),
|
||||
),
|
||||
|
||||
let data_source = match derivative_level {
|
||||
0 => self.back_data.as_slice(),
|
||||
1 => self.derivative_data.as_slice(),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
newtons_method_output
|
||||
.into_iter()
|
||||
.map(|x| PlotPoint::new(x, self.function.get(0, x)))
|
||||
newtons_method_helper(
|
||||
threshold,
|
||||
range,
|
||||
data_source,
|
||||
self.function.get_function_derivative(derivative_level),
|
||||
self.function.get_function_derivative(derivative_level + 1),
|
||||
)
|
||||
.into_iter()
|
||||
.map(|x| PlotPoint::new(x, self.function.get(0, x)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Generates plot data for a given derivative level over the resolution iterator
|
||||
fn generate_plot_data(&mut self, derivative: usize, resolution_iter: &[f64]) -> Vec<PlotPoint> {
|
||||
if derivative > 0 {
|
||||
self.function.generate_derivative(derivative);
|
||||
}
|
||||
resolution_iter
|
||||
.iter()
|
||||
.map(|&x| PlotPoint::new(x, self.function.get(derivative, x)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -304,32 +312,17 @@ impl FunctionEntry {
|
||||
}
|
||||
|
||||
if self.back_data.is_empty() {
|
||||
let data: Vec<PlotPoint> = resolution_iter
|
||||
.clone()
|
||||
.into_iter()
|
||||
.map(|x| PlotPoint::new(x, self.function.get(0, x)))
|
||||
.collect();
|
||||
debug_assert_eq!(data.len(), settings.plot_width + 1);
|
||||
|
||||
self.back_data = data;
|
||||
self.back_data = self.generate_plot_data(0, &resolution_iter);
|
||||
debug_assert_eq!(self.back_data.len(), settings.plot_width + 1);
|
||||
}
|
||||
|
||||
if self.derivative_data.is_empty() {
|
||||
self.function.generate_derivative(1);
|
||||
let data: Vec<PlotPoint> = resolution_iter
|
||||
.clone()
|
||||
.into_iter()
|
||||
.map(|x| PlotPoint::new(x, self.function.get(1, x)))
|
||||
.collect();
|
||||
debug_assert_eq!(data.len(), settings.plot_width + 1);
|
||||
self.derivative_data = data;
|
||||
self.derivative_data = self.generate_plot_data(1, &resolution_iter);
|
||||
debug_assert_eq!(self.derivative_data.len(), settings.plot_width + 1);
|
||||
}
|
||||
|
||||
if self.nth_derviative && self.nth_derivative_data.is_none() {
|
||||
let data: Vec<PlotPoint> = resolution_iter
|
||||
.into_iter()
|
||||
.map(|x| PlotPoint::new(x, self.function.get(self.curr_nth, x)))
|
||||
.collect();
|
||||
if self.nth_derivative && self.nth_derivative_data.is_none() {
|
||||
let data = self.generate_plot_data(self.curr_nth, &resolution_iter);
|
||||
debug_assert_eq!(data.len(), settings.plot_width + 1);
|
||||
self.nth_derivative_data = Some(data);
|
||||
}
|
||||
@@ -352,7 +345,7 @@ impl FunctionEntry {
|
||||
self.clear_integral();
|
||||
}
|
||||
|
||||
let threshold: f64 = resolution / 2.0;
|
||||
let threshold: f64 = f64::EPSILON;
|
||||
let x_range = settings.min_x..settings.max_x;
|
||||
|
||||
// Calculates extrema
|
||||
@@ -385,7 +378,11 @@ impl FunctionEntry {
|
||||
let step = (settings.max_x - settings.min_x) / (settings.plot_width as f64);
|
||||
debug_assert!(step > 0.0);
|
||||
|
||||
// Plot back data
|
||||
// Check if we have any special points that need exclusion zones
|
||||
let has_special_points = (settings.do_extrema && !self.extrema_data.is_empty())
|
||||
|| (settings.do_roots && !self.root_data.is_empty());
|
||||
|
||||
// Plot back data, filtering out points near special points for better hover detection
|
||||
if !self.back_data.is_empty() {
|
||||
if self.integral && (step >= integral_step) {
|
||||
plot_ui.line(
|
||||
@@ -403,45 +400,109 @@ impl FunctionEntry {
|
||||
.fill(0.0),
|
||||
);
|
||||
}
|
||||
plot_ui.line(
|
||||
|
||||
// Only filter when there are special points to avoid
|
||||
let main_line = if has_special_points {
|
||||
let exclusion_radius = step * 3.0;
|
||||
let is_near_special = |p: &PlotPoint| {
|
||||
(settings.do_extrema
|
||||
&& self
|
||||
.extrema_data
|
||||
.iter()
|
||||
.any(|sp| (p.x - sp.x).abs() < exclusion_radius))
|
||||
|| (settings.do_roots
|
||||
&& self
|
||||
.root_data
|
||||
.iter()
|
||||
.any(|sp| (p.x - sp.x).abs() < exclusion_radius))
|
||||
};
|
||||
self.back_data
|
||||
.clone()
|
||||
.iter()
|
||||
.filter(|p| !is_near_special(p))
|
||||
.cloned()
|
||||
.collect::<Vec<PlotPoint>>()
|
||||
.to_line()
|
||||
.stroke(egui::Stroke::new(4.0, main_plot_color)),
|
||||
);
|
||||
} else {
|
||||
// No filtering needed - use data directly
|
||||
self.back_data.clone().to_line()
|
||||
};
|
||||
|
||||
plot_ui.line(main_line.stroke(egui::Stroke::new(4.0, main_plot_color)));
|
||||
}
|
||||
|
||||
// Plot derivative data
|
||||
if self.derivative && !self.derivative_data.is_empty() {
|
||||
plot_ui.line(self.derivative_data.clone().to_line().color(Color32::GREEN));
|
||||
let derivative_line = if has_special_points {
|
||||
let exclusion_radius = step * 3.0;
|
||||
let is_near_special = |p: &PlotPoint| {
|
||||
(settings.do_extrema
|
||||
&& self
|
||||
.extrema_data
|
||||
.iter()
|
||||
.any(|sp| (p.x - sp.x).abs() < exclusion_radius))
|
||||
|| (settings.do_roots
|
||||
&& self
|
||||
.root_data
|
||||
.iter()
|
||||
.any(|sp| (p.x - sp.x).abs() < exclusion_radius))
|
||||
};
|
||||
self.derivative_data
|
||||
.iter()
|
||||
.filter(|p| !is_near_special(p))
|
||||
.cloned()
|
||||
.collect::<Vec<PlotPoint>>()
|
||||
.to_line()
|
||||
} else {
|
||||
self.derivative_data.clone().to_line()
|
||||
};
|
||||
|
||||
plot_ui.line(derivative_line.color(Color32::GREEN));
|
||||
}
|
||||
|
||||
// Plot extrema points
|
||||
if settings.do_extrema && !self.extrema_data.is_empty() {
|
||||
plot_ui.points(
|
||||
self.extrema_data
|
||||
.clone()
|
||||
.to_points()
|
||||
.color(Color32::YELLOW)
|
||||
.radius(5.0), // Radius of points of Extrema
|
||||
);
|
||||
for point in &self.extrema_data {
|
||||
let name = format!(
|
||||
"({}, {})",
|
||||
try_symbolic(point.x)
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_else(|| format!("{:.4}", point.x)),
|
||||
try_symbolic(point.y)
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_else(|| format!("{:.4}", point.y))
|
||||
);
|
||||
plot_ui.points(
|
||||
Points::new(name, vec![[point.x, point.y]])
|
||||
.color(Color32::YELLOW)
|
||||
.radius(5.0),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Plot roots points
|
||||
if settings.do_roots && !self.root_data.is_empty() {
|
||||
plot_ui.points(
|
||||
self.root_data
|
||||
.clone()
|
||||
.to_points()
|
||||
.color(Color32::LIGHT_BLUE)
|
||||
.radius(5.0), // Radius of points of Roots
|
||||
);
|
||||
for point in &self.root_data {
|
||||
let name = format!(
|
||||
"({}, {})",
|
||||
try_symbolic(point.x)
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_else(|| format!("{:.4}", point.x)),
|
||||
try_symbolic(point.y)
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_else(|| format!("{:.4}", point.y))
|
||||
);
|
||||
plot_ui.points(
|
||||
Points::new(name, vec![[point.x, point.y]])
|
||||
.color(Color32::LIGHT_BLUE)
|
||||
.radius(5.0),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if self.nth_derviative
|
||||
&& let Some(ref nth_derviative) = self.nth_derivative_data
|
||||
if self.nth_derivative
|
||||
&& let Some(ref nth_derivative) = self.nth_derivative_data
|
||||
{
|
||||
plot_ui.line(nth_derviative.clone().to_line().color(Color32::DARK_RED));
|
||||
plot_ui.line(nth_derivative.clone().to_line().color(Color32::DARK_RED));
|
||||
}
|
||||
|
||||
// Plot integral data
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
use crate::{consts::COLORS, function_entry::FunctionEntry, widgets::widgets_ontop};
|
||||
use egui::{Button, Id, Key, Modifiers, PopupCloseBehavior, TextEdit, WidgetText};
|
||||
use crate::{function_entry::FunctionEntry, widgets::widgets_ontop};
|
||||
use egui::{Button, Id, Key, Modifiers, Popup, PopupCloseBehavior, TextEdit, WidgetText};
|
||||
use emath::vec2;
|
||||
use parsing::Movement;
|
||||
use serde::ser::SerializeStruct;
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::ops::BitXorAssign;
|
||||
|
||||
type Functions = Vec<(Id, FunctionEntry)>;
|
||||
@@ -33,8 +30,8 @@ fn func_manager_roundtrip_serdes() {
|
||||
let ser = bincode::serialize(&func_manager).expect("unable to serialize");
|
||||
let des: FunctionManager = bincode::deserialize(&ser).expect("unable to deserialize");
|
||||
assert_eq!(
|
||||
func_manager.functions[0].1.raw_func_str,
|
||||
des.functions[0].1.raw_func_str
|
||||
func_manager.functions[0].1.func_str(),
|
||||
des.functions[0].1.func_str()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -50,17 +47,9 @@ impl FunctionManager {
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn get_hash(&self) -> u64 {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
self.functions.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
/// Displays function entries alongside returning whether or not functions have been modified
|
||||
pub fn display_entries(&mut self, ui: &mut egui::Ui) -> bool {
|
||||
let initial_hash = self.get_hash();
|
||||
|
||||
let mut changed = false;
|
||||
let can_remove = self.functions.len() > 1;
|
||||
|
||||
let available_width = ui.available_width();
|
||||
@@ -68,7 +57,6 @@ impl FunctionManager {
|
||||
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();
|
||||
function.update_string(&new_string);
|
||||
|
||||
let mut movement: Movement = Movement::default();
|
||||
|
||||
@@ -92,11 +80,15 @@ impl FunctionManager {
|
||||
// Only keep valid chars
|
||||
new_string.retain(crate::misc::is_valid_char);
|
||||
|
||||
// Track if function string changed and update the function
|
||||
if new_string != function.autocomplete.string {
|
||||
changed = true;
|
||||
function.update_string(&new_string);
|
||||
}
|
||||
|
||||
// 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 {
|
||||
function.autocomplete.update_string(&new_string);
|
||||
|
||||
if function.autocomplete.hint.is_some() {
|
||||
// only register up and down arrow movements if hint is type `Hint::Many`
|
||||
if !function.autocomplete.hint.is_single() {
|
||||
@@ -121,9 +113,18 @@ impl FunctionManager {
|
||||
movement = Movement::Complete;
|
||||
}
|
||||
|
||||
// Remember string before movement to detect changes
|
||||
let string_before = function.autocomplete.string.clone();
|
||||
|
||||
// Register movement and apply proper changes
|
||||
function.autocomplete.register_movement(&movement);
|
||||
|
||||
// If the string changed (hint was applied), update the backing function
|
||||
if function.autocomplete.string != string_before {
|
||||
function.sync_from_autocomplete();
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if movement != Movement::Complete
|
||||
&& let Some(hints) = function.autocomplete.hint.many()
|
||||
{
|
||||
@@ -131,12 +132,10 @@ impl FunctionManager {
|
||||
|
||||
let autocomplete_popup_id = Id::new("autocomplete popup");
|
||||
|
||||
egui::popup_below_widget(
|
||||
ui,
|
||||
autocomplete_popup_id,
|
||||
&re,
|
||||
PopupCloseBehavior::CloseOnClickOutside,
|
||||
|ui| {
|
||||
Popup::from_response(&re)
|
||||
.id(autocomplete_popup_id)
|
||||
.close_behavior(PopupCloseBehavior::CloseOnClickOutside)
|
||||
.show(|ui| {
|
||||
hints.iter().enumerate().for_each(|(i, candidate)| {
|
||||
if ui
|
||||
.selectable_label(i == function.autocomplete.i, *candidate)
|
||||
@@ -146,17 +145,19 @@ impl FunctionManager {
|
||||
function.autocomplete.i = i;
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
if clicked {
|
||||
function
|
||||
.autocomplete
|
||||
.apply_hint(hints[function.autocomplete.i]);
|
||||
// Update the backing function with the new string after hint was applied
|
||||
function.sync_from_autocomplete();
|
||||
changed = true;
|
||||
|
||||
movement = Movement::Complete;
|
||||
} else {
|
||||
ui.memory_mut(|x| x.open_popup(autocomplete_popup_id));
|
||||
Popup::open_id(ui.ctx(), autocomplete_popup_id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -230,11 +231,10 @@ impl FunctionManager {
|
||||
// Remove function if the user requests it
|
||||
if let Some(remove_i_unwrap) = remove_i {
|
||||
self.functions.remove(remove_i_unwrap);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
let final_hash = self.get_hash();
|
||||
|
||||
initial_hash != final_hash
|
||||
changed
|
||||
}
|
||||
|
||||
/// Create and push new empty function entry
|
||||
|
||||
110
src/lib.rs
110
src/lib.rs
@@ -12,64 +12,76 @@ mod widgets;
|
||||
|
||||
pub use crate::{
|
||||
function_entry::{FunctionEntry, Riemann},
|
||||
math_app::AppSettings,
|
||||
math_app::{AppSettings, MathApp},
|
||||
misc::{EguiHelper, newtons_method, option_vec_printer, step_helper},
|
||||
unicode_helper::{to_chars_array, to_unicode_hash},
|
||||
};
|
||||
|
||||
cfg_if::cfg_if! {
|
||||
if #[cfg(target_arch = "wasm32")] {
|
||||
use wasm_bindgen::prelude::*;
|
||||
use web_sys::HtmlCanvasElement;
|
||||
// WASM-specific setup
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod wasm {
|
||||
use super::math_app;
|
||||
use eframe::WebRunner;
|
||||
use lol_alloc::{FreeListAllocator, LockedAllocator};
|
||||
use wasm_bindgen::prelude::*;
|
||||
use web_sys::HtmlCanvasElement;
|
||||
|
||||
use lol_alloc::{FreeListAllocator, LockedAllocator};
|
||||
#[global_allocator]
|
||||
static ALLOCATOR: LockedAllocator<FreeListAllocator> = LockedAllocator::new(FreeListAllocator::new());
|
||||
#[global_allocator]
|
||||
static ALLOCATOR: LockedAllocator<FreeListAllocator> =
|
||||
LockedAllocator::new(FreeListAllocator::new());
|
||||
|
||||
use eframe::WebRunner;
|
||||
// use tracing::metadata::LevelFilter;
|
||||
#[derive(Clone)]
|
||||
#[wasm_bindgen]
|
||||
pub struct WebHandle {
|
||||
runner: WebRunner,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
#[wasm_bindgen]
|
||||
pub struct WebHandle {
|
||||
runner: WebRunner,
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl WebHandle {
|
||||
/// Installs a panic hook, then returns.
|
||||
#[allow(clippy::new_without_default)]
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new() -> Self {
|
||||
// eframe::WebLogger::init(LevelFilter::Debug).ok();
|
||||
tracing_wasm::set_as_global_default();
|
||||
|
||||
Self {
|
||||
runner: WebRunner::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Call this once from JavaScript to start your app.
|
||||
#[wasm_bindgen]
|
||||
pub async fn start(&self, canvas_id: HtmlCanvasElement) -> Result<(), wasm_bindgen::JsValue> {
|
||||
self.runner
|
||||
.start(
|
||||
canvas_id,
|
||||
eframe::WebOptions::default(),
|
||||
Box::new(|cc| Ok(Box::new(math_app::MathApp::new(cc)))),
|
||||
)
|
||||
.await
|
||||
}
|
||||
#[wasm_bindgen]
|
||||
impl WebHandle {
|
||||
/// Installs a panic hook, then returns.
|
||||
#[allow(clippy::new_without_default)]
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new() -> Self {
|
||||
tracing_wasm::set_as_global_default();
|
||||
Self {
|
||||
runner: WebRunner::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen(start)]
|
||||
pub async fn start() {
|
||||
tracing::info!("Starting...");
|
||||
|
||||
let document = web_sys::window().unwrap().document().unwrap();
|
||||
let canvas = document.get_element_by_id("canvas").unwrap().dyn_into::<HtmlCanvasElement>().unwrap();
|
||||
|
||||
let web_handle = WebHandle::new();
|
||||
web_handle.start(canvas).await.unwrap()
|
||||
/// Call this once from JavaScript to start your app.
|
||||
#[wasm_bindgen]
|
||||
pub async fn start(
|
||||
&self,
|
||||
canvas_id: HtmlCanvasElement,
|
||||
) -> Result<(), wasm_bindgen::JsValue> {
|
||||
self.runner
|
||||
.start(
|
||||
canvas_id,
|
||||
eframe::WebOptions::default(),
|
||||
Box::new(|cc| Ok(Box::new(math_app::MathApp::new(cc)))),
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen(start)]
|
||||
pub async fn start() {
|
||||
tracing::info!("Starting...");
|
||||
|
||||
let document = web_sys::window()
|
||||
.expect("no window")
|
||||
.document()
|
||||
.expect("no document");
|
||||
let canvas = document
|
||||
.get_element_by_id("canvas")
|
||||
.expect("no canvas element")
|
||||
.dyn_into::<HtmlCanvasElement>()
|
||||
.expect("canvas is not an HtmlCanvasElement");
|
||||
|
||||
let web_handle = WebHandle::new();
|
||||
web_handle
|
||||
.start(canvas)
|
||||
.await
|
||||
.expect("failed to start web app");
|
||||
}
|
||||
}
|
||||
|
||||
13
src/main.rs
13
src/main.rs
@@ -1,14 +1,3 @@
|
||||
#[macro_use]
|
||||
extern crate static_assertions;
|
||||
|
||||
mod consts;
|
||||
mod function_entry;
|
||||
mod function_manager;
|
||||
mod math_app;
|
||||
mod misc;
|
||||
mod unicode_helper;
|
||||
mod widgets;
|
||||
|
||||
// For running the program natively! (Because why not?)
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn main() -> eframe::Result<()> {
|
||||
@@ -21,6 +10,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| Ok(Box::new(ytbn_graphing_software::MathApp::new(cc)))),
|
||||
)
|
||||
}
|
||||
|
||||
176
src/math_app.rs
176
src/math_app.rs
@@ -3,6 +3,7 @@ use crate::{
|
||||
function_entry::Riemann,
|
||||
function_manager::FunctionManager,
|
||||
misc::option_vec_printer,
|
||||
widgets::toggle_button,
|
||||
};
|
||||
use eframe::App;
|
||||
use egui::{
|
||||
@@ -14,7 +15,7 @@ use egui_plot::Plot;
|
||||
use emath::{Align, Align2};
|
||||
use epaint::Margin;
|
||||
use itertools::Itertools;
|
||||
use std::{io::Read, ops::BitXorAssign};
|
||||
use std::io::Read;
|
||||
|
||||
/// Stores current settings/state of [`MathApp`]
|
||||
#[derive(Copy, Clone)]
|
||||
@@ -123,92 +124,48 @@ const DATA_NAME: &str = "YTBN-DECOMPRESSED";
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
const FUNC_NAME: &str = "YTBN-FUNCTIONS";
|
||||
|
||||
/// Load functions from localStorage (WASM only)
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn load_functions() -> Option<FunctionManager> {
|
||||
let data = get_localstorage().get_item(FUNC_NAME).ok()??;
|
||||
let func_data = crate::misc::hashed_storage_read(&data)?;
|
||||
|
||||
tracing::info!("Reading previous function data");
|
||||
match bincode::deserialize(&func_data) {
|
||||
Ok(Some(function_manager)) => Some(function_manager),
|
||||
_ => {
|
||||
tracing::info!("Unable to load functionManager instance");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn decompress_fonts() -> epaint::text::FontDefinitions {
|
||||
let mut data = Vec::new();
|
||||
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");
|
||||
|
||||
bincode::deserialize(data.as_slice()).expect("unable to deserialize bincode")
|
||||
}
|
||||
|
||||
impl MathApp {
|
||||
#[allow(dead_code)] // This is used lol
|
||||
/// Create new instance of [`MathApp`] and return it
|
||||
pub fn new(cc: &eframe::CreationContext<'_>) -> Self {
|
||||
tracing::info!("Initializing...");
|
||||
|
||||
cfg_if::cfg_if! {
|
||||
if #[cfg(target_arch = "wasm32")] {
|
||||
|
||||
tracing::info!("Web Info: {:?}", &cc.integration_info.web_info);
|
||||
|
||||
fn get_storage_decompressed() -> Option<Vec<u8>> {
|
||||
let data = get_localstorage().get_item(DATA_NAME).ok()??;
|
||||
let cached_data = crate::misc::hashed_storage_read(&data)?;
|
||||
|
||||
tracing::info!("Reading decompression cache. Bytes: {}", cached_data.len());
|
||||
return Some(cached_data);
|
||||
|
||||
}
|
||||
|
||||
fn load_functions() -> Option<FunctionManager> {
|
||||
let data = get_localstorage().get_item(FUNC_NAME).ok()??;
|
||||
let func_data = crate::misc::hashed_storage_read(&data)?;
|
||||
|
||||
|
||||
tracing::info!("Reading previous function data");
|
||||
if let Ok(Some(function_manager)) = bincode::deserialize(&func_data) {
|
||||
return Some(function_manager);
|
||||
} else {
|
||||
tracing::info!("Unable to load functionManager instance");
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
fn decompress_fonts() -> epaint::text::FontDefinitions {
|
||||
let mut data = Vec::new();
|
||||
let _ =
|
||||
ruzstd::decoding::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 = "wasm32")]
|
||||
{
|
||||
tracing::info!("Setting decompression cache");
|
||||
|
||||
let saved_data = hashed_storage_create(data);
|
||||
tracing::info!("Bytes: {}", saved_data.len());
|
||||
get_localstorage()
|
||||
.set_item(DATA_NAME, saved_data)
|
||||
.expect("failed to set local storage cache");
|
||||
}
|
||||
|
||||
bincode::deserialize(data.as_slice()).expect("unable to deserialize bincode")
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
tracing::info!("Web Info: {:?}", &cc.integration_info.web_info);
|
||||
|
||||
tracing::info!("Reading fonts...");
|
||||
|
||||
// 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 = "wasm32")]
|
||||
if let Some(Ok(data)) =
|
||||
get_storage_decompressed().map(|data| bincode::deserialize(data.as_slice()))
|
||||
{
|
||||
data
|
||||
} else {
|
||||
decompress_fonts()
|
||||
}
|
||||
|
||||
#[cfg(not(target = "wasm32"))]
|
||||
decompress_fonts()
|
||||
});
|
||||
|
||||
// Set dark mode by default
|
||||
// cc.egui_ctx.set_visuals(crate::style::style());
|
||||
|
||||
// Set spacing
|
||||
// cc.egui_ctx.set_spacing(crate::style::SPACING);
|
||||
cc.egui_ctx.set_fonts(decompress_fonts());
|
||||
|
||||
tracing::info!("Initialized!");
|
||||
|
||||
@@ -319,22 +276,20 @@ impl MathApp {
|
||||
});
|
||||
|
||||
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(),
|
||||
toggle_button(
|
||||
ui,
|
||||
&mut self.settings.do_extrema,
|
||||
"Extrema",
|
||||
"Disable Displaying Extrema",
|
||||
"Display Extrema",
|
||||
);
|
||||
|
||||
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(),
|
||||
toggle_button(
|
||||
ui,
|
||||
&mut self.settings.do_roots,
|
||||
"Roots",
|
||||
"Disable Displaying Roots",
|
||||
"Display Roots",
|
||||
);
|
||||
});
|
||||
|
||||
@@ -376,22 +331,21 @@ impl App for MathApp {
|
||||
// If keyboard input isn't being grabbed, check for key combos
|
||||
if !ctx.wants_keyboard_input() {
|
||||
// If `H` key is pressed, toggle Side Panel
|
||||
self.opened
|
||||
.side_panel
|
||||
.bitxor_assign(ctx.input_mut(|x| x.consume_key(egui::Modifiers::NONE, Key::H)));
|
||||
if ctx.input_mut(|x| x.consume_key(egui::Modifiers::NONE, Key::H)) {
|
||||
self.opened.side_panel = !self.opened.side_panel;
|
||||
}
|
||||
}
|
||||
|
||||
// Creates Top bar that contains some general options
|
||||
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(
|
||||
ui.add(Button::new("Panel"))
|
||||
.on_hover_text(match self.opened.side_panel {
|
||||
true => "Hide Side Panel",
|
||||
false => "Show Side Panel",
|
||||
})
|
||||
.clicked(),
|
||||
toggle_button(
|
||||
ui,
|
||||
&mut self.opened.side_panel,
|
||||
"Panel",
|
||||
"Hide Side Panel",
|
||||
"Show Side Panel",
|
||||
);
|
||||
|
||||
// Button to add a new function
|
||||
@@ -407,13 +361,12 @@ impl App for MathApp {
|
||||
}
|
||||
|
||||
// Toggles opening the Help window
|
||||
self.opened.help.bitxor_assign(
|
||||
ui.add(Button::new("Help"))
|
||||
.on_hover_text(match self.opened.help {
|
||||
true => "Close Help Window",
|
||||
false => "Open Help Window",
|
||||
})
|
||||
.clicked(),
|
||||
toggle_button(
|
||||
ui,
|
||||
&mut self.opened.help,
|
||||
"Help",
|
||||
"Close Help Window",
|
||||
"Open Help Window",
|
||||
);
|
||||
|
||||
// Display Area and time of last frame
|
||||
@@ -492,13 +445,8 @@ impl App for MathApp {
|
||||
.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())
|
||||
}
|
||||
})
|
||||
.filter_map(|(i, error)| error.as_ref().map(|x| (i, x)))
|
||||
.map(|(i, error)| format!("(Function #{}) {}\n", i, error))
|
||||
.join("");
|
||||
|
||||
if !errors_formatted.is_empty() {
|
||||
|
||||
@@ -91,9 +91,7 @@ pub fn newtons_method_helper(
|
||||
.filter(|(prev, curr)| prev.y.is_finite() && curr.y.is_finite())
|
||||
.filter(|(prev, curr)| prev.y.signum() != curr.y.signum())
|
||||
.map(|(start, _)| start.x)
|
||||
.map(|x| newtons_method(f, f_1, x, range, threshold))
|
||||
.filter(|x| x.is_some())
|
||||
.map(|x| unsafe { x.unwrap_unchecked() })
|
||||
.filter_map(|x| newtons_method(f, f_1, x, range, threshold))
|
||||
.collect()
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::misc::Offset;
|
||||
use egui::{Id, InnerResponse};
|
||||
use egui::{Button, Id, InnerResponse, Ui};
|
||||
use std::ops::BitXorAssign;
|
||||
|
||||
/// Creates an area ontop of a widget with an y offset
|
||||
pub fn widgets_ontop<R>(
|
||||
@@ -15,3 +16,19 @@ pub fn widgets_ontop<R>(
|
||||
|
||||
area.show(ui.ctx(), |ui| add_contents(ui))
|
||||
}
|
||||
|
||||
/// A toggle button that XORs its state when clicked.
|
||||
/// Shows different hover text based on current state.
|
||||
pub fn toggle_button(
|
||||
ui: &mut Ui,
|
||||
state: &mut bool,
|
||||
label: &str,
|
||||
enabled_tip: &str,
|
||||
disabled_tip: &str,
|
||||
) {
|
||||
state.bitxor_assign(
|
||||
ui.add(Button::new(label))
|
||||
.on_hover_text(if *state { enabled_tip } else { disabled_tip })
|
||||
.clicked(),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -230,7 +230,7 @@ fn do_test(sum: Riemann, area_target: f64) {
|
||||
{
|
||||
function.update_string("sin(x)");
|
||||
assert!(function.get_test_result().is_none());
|
||||
assert_eq!(&function.raw_func_str, "sin(x)");
|
||||
assert_eq!(function.func_str(), "sin(x)");
|
||||
|
||||
function.integral = false;
|
||||
function.derivative = false;
|
||||
|
||||
Reference in New Issue
Block a user