Compare commits

...

10 Commits

Author SHA1 Message Date
e005675bb8
nix + web stuff
Some checks failed
CI / Check (push) Has been cancelled
CI / Tests (push) Has been cancelled
2025-12-02 23:44:36 -05:00
e62be3080f
remove shell scripts 2025-12-02 23:13:57 -05:00
d95b29fb7f
implement intesections + misc function options 2025-12-02 23:10:43 -05:00
bccb19cecc
cargo clippy + fmt 2025-12-02 22:41:44 -05:00
dd377c1659
update EVERYTHING and rebase egui and depdencies 2025-12-02 22:40:08 -05:00
33847acd53
nix: add shell.nix 2025-12-02 22:39:53 -05:00
Simon Gardling
9ad115729f update dependencies 2024-01-26 00:15:31 -05:00
Simon Gardling
9b53c63070 update dependencies 2023-12-20 07:00:24 +01:00
Simon Gardling
57c31977e0 cleanup 2023-12-11 20:01:14 -05:00
Simon Gardling
625bfae3be stuff 2023-12-08 10:12:27 -05:00
32 changed files with 4621 additions and 3635 deletions

View File

@ -1,4 +0,0 @@
edition = "2021"
fn_params_layout = "Compressed"
fn_single_line = true
hard_tabs = true

3184
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,8 @@
[package]
name = "ytbn_graphing_software"
version = "0.1.0"
edition = "2021"
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"
@ -33,62 +34,72 @@ strip = false
[dependencies]
parsing = { path = "./parsing" }
eframe = { git = "https://github.com/titaniumtown/egui.git", default-features = false, features = [
eframe = { path = "../simon-egui/crates/eframe", default-features = false, features = [
"glow",
"x11",
] }
egui = { git = "https://github.com/titaniumtown/egui.git", default-features = false, features = [
egui = { path = "../simon-egui/crates/egui", default-features = false, features = [
"serde",
] }
epaint = { git = "https://github.com/titaniumtown/egui.git", default-features = false , features = [
epaint = { path = "../simon-egui/crates/epaint", default-features = false, features = [
"bytemuck",
] }
emath = { git = "https://github.com/titaniumtown/egui.git", default-features = false }
egui_plot = { git = "https://github.com/titaniumtown/egui.git", default-features = false }
emath = { path = "../simon-egui/crates/emath", default-features = false }
egui_plot = { git = "https://github.com/emilk/egui_plot.git", default-features = false }
shadow-rs = { version = "0.12", default-features = false }
shadow-rs = { version = "0.38", default-features = false }
const_format = { version = "0.2", default-features = false, features = ["fmt"] }
cfg-if = "1"
ruzstd = "0.5"
ruzstd = "0.8"
tracing = "0.1"
itertools = "0.10"
itertools = "0.14"
static_assertions = "1.1"
bincode = "1.3"
serde = "1"
log = "0.4"
[dev-dependencies]
benchmarks = { path = "./benchmarks" }
# Note: benchmarks are in a separate crate - run with:
# cd benchmarks && cargo bench
[build-dependencies]
shadow-rs = "0.12"
epaint = { git = "https://github.com/titaniumtown/egui.git", default-features = false, features = [
shadow-rs = "0.38"
epaint = { path = "../simon-egui/crates/epaint", default-features = false, features = [
"bytemuck",
] }
egui = { git = "https://github.com/titaniumtown/egui.git", default-features = false, features = [
egui = { path = "../simon-egui/crates/egui", default-features = false, features = [
"serde",
] }
bincode = "1.3"
serde = "1"
serde_json = "1"
zstd = { version = "0.11", default-features = false, features = ["pkg-config"] }
run_script = "0.9"
zstd = { version = "0.13", default-features = false }
run_script = "0.10"
json5 = "0.4"
itertools = "0.10"
itertools = "0.14"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
instant = "0.1"
web-time = "1.1"
tracing-subscriber = "0.3"
getrandom = { version = "0.2" }
getrandom = { version = "0.3" }
[target.'cfg(target_arch = "wasm32")'.dependencies]
instant = { version = "0.1", features = ["wasm-bindgen"] }
lol_alloc = "0.4.0"
web-time = "1.1"
lol_alloc = "0.4"
wasm-bindgen = { version = "0.2", default-features = false, features = ["std"] }
web-sys = "0.3"
tracing-wasm = "0.2"
getrandom = { version = "0.2", features = ["js"] }
wasm-bindgen-futures = "0.4.34"
getrandom = { version = "0.3", features = ["wasm_js"] }
wasm-bindgen-futures = "0.4"
[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" }

View File

@ -1,14 +1,8 @@
## 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

View File

@ -1,13 +1,18 @@
[package]
name = "benchmarks"
version = "0.1.0"
edition = "2021"
edition = "2024"
rust-version = "1.88"
license = "AGPL-3.0"
[lib]
bench = false
[[bench]]
name = "split_function"
harness = false
[dependencies]
pprof = { version = "0.9", features = ["flamegraph"] }
criterion = "0.3"
criterion-macro = "0.3"
pprof = { version = "0.14", features = ["flamegraph"] }
criterion = { version = "0.5", features = ["html_reports"] }
parsing = { path = "../parsing" }

View File

@ -0,0 +1,46 @@
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);

View File

@ -1,26 +1,18 @@
#![feature(custom_test_frameworks)]
#![test_runner(criterion::runner)]
//! Benchmarks library - profiler utilities for flamegraphs
#[allow(unused_imports)]
use parsing::split_function_chars;
#[allow(unused_imports)]
use std::time::Duration;
use std::{fs::File, os::raw::c_int, path::Path};
use criterion::profiler::Profiler;
#[allow(unused_imports)]
use criterion::{BenchmarkId, Criterion};
use criterion_macro::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> {
#[allow(dead_code)]
/// Create a new flamegraph profiler with the given sampling frequency
pub fn new(frequency: c_int) -> Self {
FlamegraphProfiler {
frequency,
@ -29,7 +21,7 @@ impl<'a> FlamegraphProfiler<'a> {
}
}
impl<'a> Profiler for FlamegraphProfiler<'a> {
impl Profiler for FlamegraphProfiler<'_> {
fn start_profiling(&mut self, _benchmark_id: &str, _benchmark_dir: &Path) {
self.active_profiler = Some(ProfilerGuard::new(self.frequency).unwrap());
}
@ -49,57 +41,3 @@ impl<'a> Profiler for FlamegraphProfiler<'a> {
}
}
}
#[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))
}
#[criterion(custom_criterion())]
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::suggestions::SplitType::Multiplication);
})
});
}
group.finish();
}
// #[criterion(custom_criterion_flamegraph())]
// 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);
// });
// });
// }

View File

@ -4,11 +4,12 @@ use std::{
fs::File,
io::{BufWriter, Write},
path::Path,
sync::Arc,
};
use epaint::{
text::{FontData, FontDefinitions, FontTweak},
FontFamily,
text::{FontData, FontDefinitions, FontTweak},
};
use run_script::ScriptOptions;
@ -72,7 +73,9 @@ fn main() {
println!("cargo:rerun-if-changed=.git/logs/HEAD");
println!("cargo:rerun-if-changed=assets/*");
shadow_rs::new().expect("Could not initialize shadow_rs");
shadow_rs::ShadowBuilder::builder()
.build()
.expect("Could not initialize shadow_rs");
let mut main_chars: Vec<char> =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzsu0123456789?.,!(){}[]-_=+-/<>'\\ :^*`@#$%&|~;"
@ -104,38 +107,44 @@ fn main() {
font_data: BTreeMap::from([
(
"Ubuntu-Light".to_owned(),
FontData::from_owned(
Arc::new(FontData::from_owned(
font_stripper(
"Ubuntu-Light.ttf",
"ubuntu-light.ttf",
[main_chars, vec!['∫']].concat(),
)
.unwrap(),
),
)),
),
(
"NotoEmoji-Regular".to_owned(),
FontData::from_owned(
Arc::new(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(),
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([
(

View File

@ -1,76 +0,0 @@
#!/bin/bash
set -e
rm -fr tmp | true
rm -fr pkg | true
# cargo test
export RUSTFLAGS="--cfg=web_sys_unstable_apis"
if test "$1" == "" || test "$1" == "release"; then
time cargo build --release --target wasm32-unknown-unknown -Z build-std=core,compiler_builtins,alloc,std,panic_abort,panic_unwind,proc_macro,unwind -Z build-std-features=panic_immediate_abort --lib --timings
llvm-strip -s target/wasm32-unknown-unknown/release/ytbn_graphing_software.wasm
export TYPE="release"
elif test "$1" == "debug"; then
time cargo build --target wasm32-unknown-unknown -Z build-std=core,compiler_builtins,alloc,std,panic_abort,panic_unwind,proc_macro,unwind -Z build-std-features=panic-unwind --lib
export TYPE="debug"
else
echo "ERROR: build.sh, argument invalid"
exit 1
fi
pre_size=$(du -sb target/wasm32-unknown-unknown/${TYPE}/ytbn_graphing_software.wasm | awk '{ print $1 }')
echo "compiled size: $pre_size"
wasm-bindgen target/wasm32-unknown-unknown/${TYPE}/ytbn_graphing_software.wasm --out-dir pkg --target web --no-typescript
if test "$TYPE" == "release"; then
echo "running wasm-opt..."
time wasm-opt --converge -Oz --code-folding --const-hoisting --coalesce-locals-learning --vacuum --merge-locals --merge-blocks --fast-math --precompute --rse --low-memory-unused --once-reduction --optimize-instructions --licm --intrinsic-lowering \
--dce --dae-optimizing --inlining-optimizing --strip-debug \
-o pkg/ytbn_graphing_software_bg_2.wasm pkg/ytbn_graphing_software_bg.wasm
mv pkg/ytbn_graphing_software_bg_2.wasm pkg/ytbn_graphing_software_bg.wasm
fi
mkdir tmp
cp -r pkg/ytbn_graphing_software_bg.wasm tmp/
sed -i 's/fatal: true/fatal: false/g' pkg/ytbn_graphing_software.js
sed -i "s/TextEncoder('utf-8')/TextEncoder('utf-8', { ignoreBOM: true, fatal: false })/g" pkg/ytbn_graphing_software.js
#minify pkg/ytbn_graphing_software.js > tmp/ytbn_graphing_software.js
cp www/* tmp/
cp assets/logo.svg tmp/
#minify www/index.html > tmp/index.html
#minify www/sw.js > tmp/sw.js
cp www/index.html www/sw.js pkg/ytbn_graphing_software.js tmp/
wasm_sum=($(md5sum tmp/ytbn_graphing_software_bg.wasm))
js_sum=($(md5sum tmp/ytbn_graphing_software.js))
sum=($(echo "$wasm_sum $js_sum" | md5sum))
echo "sum: $sum"
new_wasm_name="${sum}.wasm"
new_js_name="${sum}.js"
mv tmp/ytbn_graphing_software_bg.wasm "tmp/${new_wasm_name}"
mv tmp/ytbn_graphing_software.js "tmp/${new_js_name}"
sed -i "s/ytbn_graphing_software_bg.wasm/${new_wasm_name}/g" tmp/*.*
sed -i "s/ytbn_graphing_software.js/${new_js_name}/g" tmp/*.*
new_size=$(du -b tmp/${new_wasm_name} | awk '{ print $1 }')
diff=$(echo "scale=5 ; $new_size / $pre_size" | bc)
percent=$(echo "scale=5 ; (1-$diff)*100" | bc)
echo "Total size: $(du -sb tmp)"
echo "Binary size: $new_size reduced: $percent%"

100
flake.lock generated Normal file
View File

@ -0,0 +1,100 @@
{
"nodes": {
"flake-utils": {
"inputs": {
"systems": "systems"
},
"locked": {
"lastModified": 1731533236,
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1764517877,
"narHash": "sha256-pp3uT4hHijIC8JUK5MEqeAWmParJrgBVzHLNfJDZxg4=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "2d293cbfa5a793b4c50d17c05ef9e385b90edf6c",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"flake-utils": "flake-utils",
"nixpkgs": "nixpkgs",
"rust-overlay": "rust-overlay",
"simon-egui": "simon-egui"
}
},
"rust-overlay": {
"inputs": {
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1764729618,
"narHash": "sha256-z4RA80HCWv2los1KD346c+PwNPzMl79qgl7bCVgz8X0=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "52764074a85145d5001bf0aa30cb71936e9ad5b8",
"type": "github"
},
"original": {
"owner": "oxalica",
"repo": "rust-overlay",
"type": "github"
}
},
"simon-egui": {
"flake": false,
"locked": {
"lastModified": 1764730109,
"narHash": "sha256-vNETC0oq6tKJKF8KOGQKKIWRom38m0RwGgi3MPBrRx8=",
"owner": "Titaniumtown",
"repo": "egui",
"rev": "b63c21d70150f1b414370f0f9a8af56e886662f4",
"type": "github"
},
"original": {
"owner": "Titaniumtown",
"repo": "egui",
"rev": "b63c21d70150f1b414370f0f9a8af56e886662f4",
"type": "github"
}
},
"systems": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
}
},
"root": "root",
"version": 7
}

225
flake.nix Normal file
View File

@ -0,0 +1,225 @@
{
description = "YTBN Graphing Software - Web-compatible graphing calculator";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
flake-utils.url = "github:numtide/flake-utils";
rust-overlay = {
url = "github:oxalica/rust-overlay";
inputs.nixpkgs.follows = "nixpkgs";
};
simon-egui = {
url = "github:Titaniumtown/egui/b63c21d70150f1b414370f0f9a8af56e886662f4";
flake = false;
};
};
outputs = { self, nixpkgs, flake-utils, rust-overlay, simon-egui }:
flake-utils.lib.eachDefaultSystem (system:
let
overlays = [ (import rust-overlay) ];
pkgs = import nixpkgs {
inherit system overlays;
};
# Use nightly rust with wasm32 target
rustToolchain = pkgs.rust-bin.nightly."2025-05-01".default.override {
targets = [ "wasm32-unknown-unknown" ];
};
rustPlatform = pkgs.makeRustPlatform {
cargo = rustToolchain;
rustc = rustToolchain;
};
# Build wasm-bindgen-cli matching the version in Cargo.lock (0.2.106)
wasm-bindgen-cli = rustPlatform.buildRustPackage rec {
pname = "wasm-bindgen-cli";
version = "0.2.106";
src = pkgs.fetchCrate {
inherit pname version;
hash = "sha256-M6WuGl7EruNopHZbqBpucu4RWz44/MSdv6f0zkYw+44=";
};
cargoHash = "sha256-ElDatyOwdKwHg3bNH/1pcxKI7LXkhsotlDPQjiLHBwA=";
nativeBuildInputs = [ pkgs.pkg-config ];
buildInputs = [ pkgs.openssl ] ++ pkgs.lib.optionals pkgs.stdenv.isDarwin [
pkgs.curl
pkgs.darwin.apple_sdk.frameworks.Security
];
# Tests require network access
doCheck = false;
};
# Create a combined source with the main project and dependencies
combinedSrc = pkgs.stdenv.mkDerivation {
name = "ytbn-combined-src";
phases = [ "installPhase" ];
installPhase = ''
mkdir -p $out/integral_site_rust
mkdir -p $out/simon-egui
cp -r ${./.}/* $out/integral_site_rust/
cp -r ${simon-egui}/* $out/simon-egui/
chmod -R u+w $out
'';
};
# Build the wasm library using rustPlatform
wasmLib = rustPlatform.buildRustPackage {
pname = "ytbn-graphing-software-wasm";
version = "0.1.0";
src = combinedSrc;
sourceRoot = "${combinedSrc.name}/integral_site_rust";
cargoLock = {
lockFile = ./Cargo.lock;
outputHashes = {
"egui_plot-0.34.0" = "sha256-lk0yeljsvkHzF0eLD5llQ+05DycPqG2jGzhBvQ0X6Qw=";
};
};
nativeBuildInputs = with pkgs; [
python3Packages.fonttools
pkg-config
clang
];
buildInputs = with pkgs; [
openssl
zstd
];
buildPhase = ''
runHook preBuild
export HOME=$TMPDIR
cargo build \
--release \
--lib \
--target wasm32-unknown-unknown
runHook postBuild
'';
installPhase = ''
runHook preInstall
mkdir -p $out/lib
cp target/wasm32-unknown-unknown/release/*.wasm $out/lib/
runHook postInstall
'';
doCheck = false;
};
# Final web package with wasm-bindgen processing
ytbn-graphing-software-web = pkgs.stdenv.mkDerivation {
pname = "ytbn-graphing-software-web";
version = "0.1.0";
src = ./.;
nativeBuildInputs = [
wasm-bindgen-cli
pkgs.binaryen
];
buildPhase = ''
runHook preBuild
# Generate JS bindings
wasm-bindgen ${wasmLib}/lib/ytbn_graphing_software.wasm \
--out-dir out \
--out-name ytbn_graphing_software \
--target web \
--no-typescript
# Optimize wasm (enable features used by modern rust wasm targets)
wasm-opt out/ytbn_graphing_software_bg.wasm \
-O2 --fast-math \
--enable-bulk-memory \
--enable-nontrapping-float-to-int \
--enable-sign-ext \
--enable-mutable-globals \
-o out/ytbn_graphing_software_bg.wasm
runHook postBuild
'';
installPhase = ''
runHook preInstall
mkdir -p $out
# Copy wasm and js files
cp out/ytbn_graphing_software_bg.wasm $out/
cp out/ytbn_graphing_software.js $out/
# Copy static web assets
cp www/index.html $out/
cp www/manifest.json $out/
cp www/sw.js $out/
# Copy logo
cp assets/logo.svg $out/
runHook postInstall
'';
meta = with pkgs.lib; {
description = "Web-compatible graphing calculator similar to Desmos";
homepage = "https://github.com/Titaniumtown/YTBN-Graphing-Software";
license = licenses.agpl3Only;
platforms = platforms.all;
};
};
in
{
packages = {
default = ytbn-graphing-software-web;
web = ytbn-graphing-software-web;
wasm = wasmLib;
};
devShells.default = pkgs.mkShell {
nativeBuildInputs = with pkgs; [
rustToolchain
wasm-bindgen-cli
binaryen
python3Packages.fonttools
rust-analyzer
pkg-config
clang
# Runtime deps for native builds
libxkbcommon
libGL
wayland
xorg.libX11
xorg.libXcursor
xorg.libXi
];
buildInputs = with pkgs; [
openssl
zstd
];
LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath (with pkgs; [
libxkbcommon
libGL
wayland
xorg.libX11
xorg.libXcursor
xorg.libXi
]);
};
}
);
}

View File

@ -1,4 +1,4 @@
use std::{hint::unreachable_unchecked, intrinsics::assume};
use std::hint::unreachable_unchecked;
use crate::{generate_hint, Hint, HINT_EMPTY};
@ -18,7 +18,7 @@ impl Movement {
pub const fn is_complete(&self) -> bool { matches!(&self, &Self::Complete) }
}
impl const Default for Movement {
impl Default for Movement {
fn default() -> Self { Self::None }
}
@ -29,7 +29,7 @@ pub struct AutoComplete<'a> {
pub string: String,
}
impl<'a> const Default for AutoComplete<'a> {
impl<'a> Default for AutoComplete<'a> {
fn default() -> AutoComplete<'a> { AutoComplete::EMPTY }
}
@ -70,12 +70,6 @@ impl<'a> AutoComplete<'a> {
// Impossible for plural hints to be singular or non-existant
debug_assert!(hints.len() > 1); // check on debug
// Hint to the compiler
unsafe {
assume(hints.len() > 1);
assume(!hints.is_empty());
}
match movement {
Movement::Up => {
// Wrap self.i to maximum `i` value if needed

View File

@ -1,7 +1,3 @@
#![feature(const_trait_impl)]
#![feature(core_intrinsics)]
#![feature(const_mut_refs)]
#![feature(const_for)]
mod autocomplete;
mod autocomplete_hashmap;
mod parsing;

View File

@ -58,7 +58,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)
})
@ -66,7 +66,7 @@ impl FlatExWrapper {
}
}
impl const Default for FlatExWrapper {
impl Default for FlatExWrapper {
fn default() -> FlatExWrapper { FlatExWrapper::EMPTY }
}
/// Function that includes f(x), f'(x), f'(x)'s string representation, and f''(x)

View File

@ -127,6 +127,7 @@ pub fn split_function_chars(chars: &[char], split: SplitType) -> Vec<String> {
// Append split
if curr_c.splitable(c, &prev_char, &split) {
// create new buffer
data.push(String::new());
last = unsafe { data.last_mut().unwrap_unchecked() };
}

View File

@ -1,5 +1,4 @@
use crate::{split_function_chars, SplitType};
use std::intrinsics::assume;
pub const HINT_EMPTY: Hint = Hint::Single("x^2");
const HINT_CLOSED_PARENS: Hint = Hint::Single(")");
@ -20,10 +19,6 @@ pub fn generate_hint<'a>(input: &str) -> &'a Hint<'a> {
} else {
let chars: Vec<char> = input.chars().collect::<Vec<char>>();
unsafe {
assume(!chars.is_empty());
}
let key = get_last_term(&chars);
match key {
Some(key) => {

15
push.sh
View File

@ -1,15 +0,0 @@
#!/bin/bash
set -e #kill script if error occurs
cargo test
bash build.sh release
echo "rsyncing"
# rsync -av --delete --info=progress2 tmp/ rpi-public:/mnt/hdd/http_share/ytbn/
rsync -av --delete --info=progress2 --exclude=".git" tmp/ ../titaniumtown.github.io/
rm -fr tmp
cd ../titaniumtown.github.io
git add .
git commit -m "update" | true
git push

30
shell.nix Normal file
View File

@ -0,0 +1,30 @@
{
pkgs ? import <nixpkgs> { },
}:
pkgs.mkShell rec {
libs = with pkgs; [
# wayland
libxkbcommon
libGL
wayland
libx11
libxcursor
libxi
clang
];
nativeBuildInputs =
with pkgs;
[
rustc
cargo
rust-analyzer
python3Packages.fonttools
]
++ libs;
# add libs to path
LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath libs}";
}

View File

@ -1,16 +1,15 @@
use crate::math_app::AppSettings;
use crate::misc::{newtons_method_helper, step_helper, EguiHelper};
use crate::misc::{EguiHelper, newtons_method_helper, step_helper};
use egui::{Checkbox, Context};
use egui_plot::{Bar, BarChart, PlotPoint, PlotUi};
use epaint::Color32;
use parsing::{generate_hint, AutoComplete};
use parsing::{process_func_str, BackingFunction};
use serde::{ser::SerializeStruct, Deserialize, Deserializer, Serialize, Serializer};
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},
intrinsics::assume,
};
/// Represents the possible variations of Riemann Sums
@ -24,7 +23,9 @@ pub enum Riemann {
}
impl fmt::Display for Riemann {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self) }
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
}
}
/// `FunctionEntry` is a function that can calculate values, integrals, derivatives, etc etc
@ -44,6 +45,9 @@ 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>,
@ -66,6 +70,7 @@ impl Hash for FunctionEntry {
self.nth_derviative.hash(state);
self.curr_nth.hash(state);
self.settings_opened.hash(state);
self.visible.hash(state);
}
}
@ -74,11 +79,12 @@ impl Serialize for FunctionEntry {
where
S: Serializer,
{
let mut s = serializer.serialize_struct("FunctionEntry", 4)?;
let mut s = serializer.serialize_struct("FunctionEntry", 5)?;
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()
}
@ -95,6 +101,12 @@ 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)?;
@ -114,12 +126,13 @@ 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)
}
}
impl const Default for FunctionEntry {
impl Default for FunctionEntry {
/// Creates default FunctionEntry instance (which is empty)
fn default() -> FunctionEntry {
FunctionEntry {
@ -128,6 +141,7 @@ impl const Default for FunctionEntry {
integral: false,
derivative: false,
nth_derviative: false,
visible: true,
back_data: Vec::new(),
integral_data: None,
derivative_data: Vec::new(),
@ -143,7 +157,9 @@ impl const Default for FunctionEntry {
}
impl FunctionEntry {
pub const fn is_some(&self) -> bool { !self.function.is_none() }
pub const fn is_some(&self) -> bool {
!self.function.is_none()
}
pub fn settings_window(&mut self, ctx: &Context) {
let mut invalidate_nth = false;
@ -173,7 +189,9 @@ impl FunctionEntry {
}
/// Get function's cached test result
pub fn get_test_result(&self) -> &Option<String> { &self.test_result }
pub fn get_test_result(&self) -> &Option<String> {
&self.test_result
}
/// Update function string and test it
pub fn update_string(&mut self, raw_func_str: &str) {
@ -199,7 +217,11 @@ impl FunctionEntry {
/// Creates and does the math for creating all the rectangles under the graph
fn integral_rectangles(
&mut self, integral_min_x: f64, integral_max_x: f64, sum: Riemann, integral_num: usize,
&mut self,
integral_min_x: f64,
integral_max_x: f64,
sum: Riemann,
integral_num: usize,
) -> (Vec<(f64, f64)>, f64) {
let step = (integral_max_x - integral_min_x) / (integral_num as f64);
@ -236,7 +258,10 @@ impl FunctionEntry {
/// Helps with processing newton's method depending on level of derivative
fn newtons_method_helper(
&mut self, threshold: f64, derivative_level: usize, range: &std::ops::Range<f64>,
&mut self,
threshold: f64,
derivative_level: usize,
range: &std::ops::Range<f64>,
) -> Vec<PlotPoint> {
self.function.generate_derivative(derivative_level);
self.function.generate_derivative(derivative_level + 1);
@ -245,15 +270,15 @@ impl FunctionEntry {
threshold,
range,
self.back_data.as_slice(),
&self.function.get_function_derivative(0),
&self.function.get_function_derivative(1),
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),
self.function.get_function_derivative(1),
self.function.get_function_derivative(2),
),
_ => unreachable!(),
};
@ -266,7 +291,10 @@ impl FunctionEntry {
/// Does the calculations and stores results in `self`
pub fn calculate(
&mut self, width_changed: bool, min_max_changed: bool, did_zoom: bool,
&mut self,
width_changed: bool,
min_max_changed: bool,
did_zoom: bool,
settings: AppSettings,
) {
if self.test_result.is_some() | self.function.is_none() {
@ -277,8 +305,6 @@ impl FunctionEntry {
debug_assert!(resolution > 0.0);
let resolution_iter = step_helper(settings.plot_width + 1, settings.min_x, resolution);
unsafe { assume(!resolution_iter.is_empty()) }
// Makes sure proper arguments are passed when integral is enabled
if self.integral && settings.integral_changed {
self.clear_integral();
@ -356,9 +382,12 @@ impl FunctionEntry {
/// Displays the function's output on PlotUI `plot_ui` with settings `settings`.
/// Returns an `Option<f64>` of the calculated integral.
pub fn display(
&self, plot_ui: &mut PlotUi, settings: &AppSettings, main_plot_color: Color32,
&self,
plot_ui: &mut PlotUi,
settings: &AppSettings,
main_plot_color: Color32,
) -> Option<f64> {
if self.test_result.is_some() | self.function.is_none() {
if self.test_result.is_some() | self.function.is_none() | !self.visible {
return None;
}
@ -382,7 +411,7 @@ impl FunctionEntry {
.cloned()
.collect::<Vec<PlotPoint>>()
.to_line()
.stroke(epaint::Stroke::NONE)
.stroke((0.0, Color32::TRANSPARENT))
.color(Color32::from_rgb(4, 4, 255))
.fill(0.0),
);
@ -391,7 +420,7 @@ impl FunctionEntry {
self.back_data
.clone()
.to_line()
.stroke(egui::Stroke::new(4.0, main_plot_color)),
.stroke((4.0, main_plot_color)),
);
}
@ -433,7 +462,7 @@ impl FunctionEntry {
Some(integral_data) => {
if integral_step > step {
plot_ui.bar_chart(
BarChart::new(integral_data.0.clone())
BarChart::new("integral", integral_data.0.clone())
.color(Color32::BLUE)
.width(integral_step),
);
@ -458,25 +487,37 @@ impl FunctionEntry {
/// Invalidate `back` data
#[inline]
fn clear_back(&mut self) { self.back_data.clear(); }
fn clear_back(&mut self) {
self.back_data.clear();
}
/// Invalidate Integral data
#[inline]
fn clear_integral(&mut self) { self.integral_data = None; }
fn clear_integral(&mut self) {
self.integral_data = None;
}
/// Invalidate Derivative data
#[inline]
fn clear_derivative(&mut self) { self.derivative_data.clear(); }
fn clear_derivative(&mut self) {
self.derivative_data.clear();
}
/// Invalidates `n`th derivative data
#[inline]
fn clear_nth(&mut self) { self.nth_derivative_data = None }
fn clear_nth(&mut self) {
self.nth_derivative_data = None
}
/// Invalidate extrema data
#[inline]
fn clear_extrema(&mut self) { self.extrema_data.clear() }
fn clear_extrema(&mut self) {
self.extrema_data.clear()
}
/// Invalidate root data
#[inline]
fn clear_roots(&mut self) { self.root_data.clear() }
fn clear_roots(&mut self) {
self.root_data.clear()
}
}

View File

@ -4,7 +4,7 @@ use crate::{
misc::{create_id, get_u64_id, random_u64},
widgets::widgets_ontop,
};
use egui::{Button, Id, Key, Modifiers, TextEdit, WidgetText};
use egui::{Button, Id, Key, Modifiers, Popup, TextEdit, WidgetText};
use emath::vec2;
use parsing::Movement;
use serde::ser::SerializeStruct;
@ -86,9 +86,14 @@ 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();
@ -116,6 +121,19 @@ 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 {
@ -151,45 +169,33 @@ impl FunctionManager {
if movement != Movement::Complete
&& let Some(hints) = function.autocomplete.hint.many()
{
// Doesn't need to have a number in id as there should only be 1 autocomplete popup in the entire gui
// hashed "autocomplete_popup"
const POPUP_ID: Id = create_id(7574801616484505465);
let mut clicked = false;
let selected_i = function.autocomplete.i;
egui::popup_below_widget(ui, POPUP_ID, &re, |ui| {
if let Some(popup_response) = Popup::menu(&re).show(|ui| {
hints.iter().enumerate().for_each(|(i, candidate)| {
if ui
.selectable_label(i == function.autocomplete.i, *candidate)
.clicked()
{
if ui.selectable_label(i == selected_i, *candidate).clicked() {
clicked = true;
function.autocomplete.i = i;
}
});
});
if clicked {
}) && clicked
{
function
.autocomplete
.apply_hint(hints[function.autocomplete.i]);
// Don't need this here as it simply won't be display next frame
// ui.memory_mut().close_popup();
movement = Movement::Complete;
} else {
ui.memory_mut(|x| x.open_popup(POPUP_ID));
}
}
// Push cursor to end if needed
if movement == Movement::Complete {
let mut state =
unsafe { TextEdit::load_state(ui.ctx(), te_id).unwrap_unchecked() };
if movement == Movement::Complete
&& let Some(mut state) = TextEdit::load_state(ui.ctx(), te_id)
{
let ccursor = egui::text::CCursor::new(function.autocomplete.string.len());
state.set_ccursor_range(Some(egui::text::CCursorRange::one(ccursor)));
state
.cursor
.set_char_range(Some(egui::text::CCursorRange::one(ccursor)));
TextEdit::store_state(ui.ctx(), te_id, state);
}
}
@ -209,6 +215,47 @@ 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(
@ -252,6 +299,26 @@ 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
@ -265,17 +332,33 @@ impl FunctionManager {
));
}
/// 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((
create_id(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)
}
#[inline]
pub fn len(&self) -> usize { self.functions.len() }
pub fn len(&self) -> usize {
self.functions.len()
}
#[inline]
pub fn get_entries_mut(&mut self) -> &mut Functions { &mut self.functions }
pub fn get_entries_mut(&mut self) -> &mut Functions {
&mut self.functions
}
#[inline]
pub fn get_entries(&self) -> &Functions { &self.functions }
pub fn get_entries(&self) -> &Functions {
&self.functions
}
}

View File

@ -1,15 +1,3 @@
#![feature(const_mut_refs)]
#![feature(let_chains)]
#![feature(const_trait_impl)]
#![feature(core_intrinsics)]
#![feature(const_fn_floating_point_arithmetic)]
#![feature(const_assume)]
#![feature(const_option_ext)]
#![feature(const_slice_index)]
#![feature(slice_split_at_unchecked)]
#![feature(inline_const)]
#![feature(const_for)]
#[macro_use]
extern crate static_assertions;
@ -25,8 +13,8 @@ pub use crate::{
function_entry::{FunctionEntry, Riemann},
math_app::AppSettings,
misc::{
hashed_storage_create, hashed_storage_read, newtons_method, option_vec_printer,
step_helper, EguiHelper, HashBytes,
EguiHelper, HashBytes, hashed_storage_create, hashed_storage_read, newtons_method,
option_vec_printer, step_helper,
},
unicode_helper::{to_chars_array, to_unicode_hash},
};
@ -63,12 +51,12 @@ cfg_if::cfg_if! {
/// Call this once from JavaScript to start your app.
#[wasm_bindgen]
pub async fn start(&self, canvas_id: &str) -> Result<(), wasm_bindgen::JsValue> {
pub async fn start(&self, canvas: web_sys::HtmlCanvasElement) -> Result<(), wasm_bindgen::JsValue> {
self.runner
.start(
canvas_id,
canvas,
eframe::WebOptions::default(),
Box::new(|cc| Box::new(math_app::MathApp::new(cc))),
Box::new(|cc| Ok(Box::new(math_app::MathApp::new(cc)))),
)
.await
}
@ -78,9 +66,16 @@ 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()
}
}
}

View File

@ -1,15 +1,3 @@
#![feature(const_mut_refs)]
#![feature(let_chains)]
#![feature(const_trait_impl)]
#![feature(core_intrinsics)]
#![feature(const_fn_floating_point_arithmetic)]
#![feature(const_assume)]
#![feature(const_option_ext)]
#![feature(const_slice_index)]
#![feature(slice_split_at_unchecked)]
#![feature(inline_const)]
#![feature(const_for)]
#[macro_use]
extern crate static_assertions;
@ -23,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();
@ -33,6 +21,6 @@ fn main() -> eframe::Result<()> {
eframe::run_native(
"(Yet-to-be-named) Graphing Software",
eframe::NativeOptions::default(),
Box::new(|cc| Box::new(math_app::MathApp::new(cc))),
Box::new(|cc| Ok(Box::new(math_app::MathApp::new(cc)))),
)
}

View File

@ -1,21 +1,21 @@
use crate::{
consts::{build, BUILD_INFO, COLORS, DEFAULT_INTEGRAL_NUM, DEFAULT_MAX_X, DEFAULT_MIN_X},
consts::{BUILD_INFO, COLORS, DEFAULT_INTEGRAL_NUM, DEFAULT_MAX_X, DEFAULT_MIN_X, build},
function_entry::Riemann,
function_manager::FunctionManager,
misc::option_vec_printer,
misc::{EguiHelper, find_intersections, option_vec_printer},
};
use eframe::App;
use egui::{
style::Margin, Button, CentralPanel, Color32, ComboBox, Context, DragValue, Frame, Key, Layout,
SidePanel, TopBottomPanel, Ui, Vec2, Window,
Button, CentralPanel, Color32, ComboBox, Context, DragValue, Frame, Key, Layout, Panel, Ui,
Vec2, Window,
};
use egui_plot::Plot;
use emath::{Align, Align2};
use epaint::Rounding;
use instant::Instant;
use itertools::Itertools;
use epaint::{CornerRadius, Margin};
use std::{io::Read, ops::BitXorAssign};
use web_time::Instant;
/// Stores current settings/state of [`MathApp`]
#[derive(Copy, Clone)]
@ -47,6 +47,9 @@ 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,
}
@ -64,6 +67,7 @@ impl Default for AppSettings {
integral_num: DEFAULT_INTEGRAL_NUM,
do_extrema: true,
do_roots: true,
do_intersections: true,
plot_width: 0,
}
}
@ -84,7 +88,7 @@ struct Opened {
pub welcome: bool,
}
impl const Default for Opened {
impl Default for Opened {
fn default() -> Opened {
Self {
help: false,
@ -108,10 +112,15 @@ pub struct MathApp {
/// Stores settings (pretty self-explanatory)
settings: AppSettings,
/// Stores intersection points between functions
intersections: Vec<egui_plot::PlotPoint>,
}
#[cfg(target_arch = "wasm32")]
fn get_window() -> web_sys::Window { web_sys::window().expect("Could not get web_sys window") }
fn get_window() -> web_sys::Window {
web_sys::window().expect("Could not get web_sys window")
}
#[cfg(target_arch = "wasm32")]
fn get_localstorage() -> web_sys::Storage {
@ -143,7 +152,6 @@ impl MathApp {
cfg_if::cfg_if! {
if #[cfg(target_arch = "wasm32")] {
use core::intrinsics::assume;
tracing::info!("Web Info: {:?}", &cc.integration_info.web_info);
@ -151,13 +159,6 @@ impl MathApp {
let data = get_localstorage().get_item(DATA_NAME).ok()??;
let (commit, cached_data) = crate::misc::hashed_storage_read(&data)?;
debug_assert!(!commit.is_empty());
debug_assert!(!cached_data.is_empty());
unsafe {
assume(!commit.is_empty());
assume(!cached_data.is_empty());
}
if commit == unsafe { std::mem::transmute::<&str, crate::misc::HashBytes>(build::SHORT_COMMIT) } {
tracing::info!("Reading decompression cache. Bytes: {}", cached_data.len());
@ -176,13 +177,6 @@ impl MathApp {
// TODO: stabilize FunctionManager serialize so it can persist across builds
let (commit, func_data) = crate::misc::hashed_storage_read(&data)?;
debug_assert!(!commit.is_empty());
debug_assert!(!func_data.is_empty());
unsafe {
assume(!commit.is_empty());
assume(!func_data.is_empty());
}
if commit == unsafe { std::mem::transmute::<&str, &[u8]>(build::SHORT_COMMIT) } {
tracing::info!("Reading previous function data");
@ -198,31 +192,26 @@ impl MathApp {
fn decompress_fonts() -> epaint::text::FontDefinitions {
let mut data = Vec::new();
let _ = ruzstd::StreamingDecoder::new(
&mut const { include_bytes!(concat!(env!("OUT_DIR"), "/compressed_data")).as_slice() },
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");
#[cfg(target = "wasm32")]
#[cfg(target_arch = "wasm32")]
{
debug_assert!(!data.is_empty());
unsafe {
assume(!data.is_empty());
}
tracing::info!("Setting decompression cache");
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);
// 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);
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");
}
@ -234,7 +223,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 = "wasm32")]
#[cfg(target_arch = "wasm32")]
if let Some(Ok(data)) =
get_storage_decompressed().map(|data| bincode::deserialize(data.as_slice()))
{
@ -243,7 +232,7 @@ impl MathApp {
decompress_fonts()
}
#[cfg(not(target = "wasm32"))]
#[cfg(not(target_arch = "wasm32"))]
decompress_fonts()
});
@ -265,6 +254,7 @@ impl MathApp {
last_info: (None, None),
opened: Opened::default(),
settings: AppSettings::default(),
intersections: Vec::new(),
}
}
@ -272,9 +262,7 @@ 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)
SidePanel::left("side_panel")
.resizable(false)
.show(ctx, |ui| {
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
@ -286,11 +274,7 @@ impl MathApp {
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::Left, "Left");
ui.selectable_value(
&mut self.settings.riemann_sum,
Riemann::Middle,
@ -379,13 +363,22 @@ impl MathApp {
})
.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::{hashed_storage_create, HashBytes};
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(
@ -421,7 +414,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::Instant::now())
Some(Instant::now())
} else {
// if disabled, clear the stored formatted time
self.last_info.1 = None;
@ -438,7 +431,7 @@ impl App for MathApp {
}
// Creates Top bar that contains some general options
TopBottomPanel::top("top_bar").show(ctx, |ui| {
Panel::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(
@ -555,46 +548,23 @@ impl App for MathApp {
self.side_panel(ctx);
}
// Central panel which contains the central plot (or an error created when parsing)
// Central panel which contains the central plot
CentralPanel::default()
.frame(Frame {
inner_margin: Margin::symmetric(0.0, 0.0),
rounding: Rounding::ZERO,
inner_margin: Margin::ZERO,
corner_radius: CornerRadius::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(Vec2::ZERO)
.set_margin_fraction(emath::Vec2::ZERO)
.data_aspect(1.0)
.include_y(0)
.show(ui, |plot_ui| {
@ -632,6 +602,41 @@ 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 {
@ -641,6 +646,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: {}ms", a.elapsed().as_micros()));
self.last_info.1 = start.map(|a| format!("Took: {}us", a.elapsed().as_micros()));
}
}

View File

@ -1,20 +1,19 @@
use egui::Id;
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;
fn to_values(self) -> PlotPoints<'static>;
/// Converts to `egui::plot::Line`
fn to_line(self) -> Line;
fn to_line(self) -> Line<'static>;
/// Converts to `egui::plot::Points`
fn to_points(self) -> Points;
fn to_points(self) -> Points<'static>;
/// Converts Vector of Values into vector of tuples
fn to_tuple(self) -> Vec<(f64, f64)>;
@ -22,15 +21,19 @@ pub trait EguiHelper {
impl EguiHelper for Vec<PlotPoint> {
#[inline(always)]
fn to_values(self) -> PlotPoints {
fn to_values(self) -> PlotPoints<'static> {
PlotPoints::from(unsafe { std::mem::transmute::<Vec<PlotPoint>, Vec<[f64; 2]>>(self) })
}
#[inline(always)]
fn to_line(self) -> Line { Line::new(self.to_values()) }
fn to_line(self) -> Line<'static> {
Line::new("", self.to_values())
}
#[inline(always)]
fn to_points(self) -> Points { Points::new(self.to_values()) }
fn to_points(self) -> Points<'static> {
Points::new("", self.to_values())
}
#[inline(always)]
fn to_tuple(self) -> Vec<(f64, f64)> {
@ -43,7 +46,7 @@ pub trait Offset {
fn offset_x(self, x_offset: f32) -> Pos2;
}
impl const Offset for Pos2 {
impl Offset for Pos2 {
fn offset_y(self, y_offset: f32) -> Pos2 {
Pos2 {
x: self.x,
@ -59,9 +62,13 @@ impl const Offset for Pos2 {
}
}
pub const fn create_id(x: u64) -> Id { unsafe { std::mem::transmute::<u64, Id>(x) } }
pub const fn create_id(x: u64) -> Id {
unsafe { std::mem::transmute::<u64, Id>(x) }
}
pub const fn get_u64_id(id: Id) -> u64 { unsafe { std::mem::transmute::<Id, u64>(id) } }
pub const fn get_u64_id(id: Id) -> u64 {
unsafe { std::mem::transmute::<Id, u64>(id) }
}
/*
/// Rounds f64 to `n` decimal places
@ -80,7 +87,10 @@ pub fn decimal_round(x: f64, n: usize) -> f64 {
/// `f_1` is f'(x) aka the derivative of f(x)
/// The function returns a Vector of `x` values where roots occur
pub fn newtons_method_helper(
threshold: f64, range: &std::ops::Range<f64>, data: &[PlotPoint], f: &FlatExWrapper,
threshold: f64,
range: &std::ops::Range<f64>,
data: &[PlotPoint],
f: &FlatExWrapper,
f_1: &FlatExWrapper,
) -> Vec<f64> {
data.iter()
@ -99,7 +109,10 @@ pub fn newtons_method_helper(
/// `f_1` is f'(x) aka the derivative of f(x)
/// The function returns an `Option<f64>` of the x value at which a root occurs
pub fn newtons_method(
f: &FlatExWrapper, f_1: &FlatExWrapper, start_x: f64, range: &std::ops::Range<f64>,
f: &FlatExWrapper,
f_1: &FlatExWrapper,
start_x: f64,
range: &std::ops::Range<f64>,
threshold: f64,
) -> Option<f64> {
let mut x1: f64 = start_x;
@ -191,11 +204,57 @@ 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(&mut buf)?;
getrandom::fill(&mut buf)?;
// Merge buffer into u64
Ok(u64::from_be_bytes(buf))
}
include!(concat!(env!("OUT_DIR"), "/valid_chars.rs"));
pub fn is_valid_char(c: char) -> bool { c.is_alphanumeric() | VALID_EXTRA_CHARS.contains(&c) }
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()
}

View File

@ -3,7 +3,10 @@ use egui::{Id, InnerResponse};
/// Creates an area ontop of a widget with an y offset
pub fn widgets_ontop<R>(
ui: &egui::Ui, id: Id, re: &egui::Response, y_offset: f32,
ui: &egui::Ui,
id: Id,
re: &egui::Response,
y_offset: f32,
add_contents: impl FnOnce(&mut egui::Ui) -> R,
) -> InnerResponse<R> {
let area = egui::Area::new(id)

View File

@ -1,6 +0,0 @@
#!/bin/bash
set -e
bash build.sh "$1"
basic-http-server tmp/

View File

@ -1,8 +1,13 @@
use ytbn_graphing_software::{AppSettings, EguiHelper, FunctionEntry, Riemann};
fn app_settings_constructor(
sum: Riemann, integral_min_x: f64, integral_max_x: f64, pixel_width: usize,
integral_num: usize, min_x: f64, max_x: f64,
sum: Riemann,
integral_min_x: f64,
integral_max_x: f64,
pixel_width: usize,
integral_num: usize,
min_x: f64,
max_x: f64,
) -> AppSettings {
AppSettings {
riemann_sum: sum,
@ -14,6 +19,7 @@ fn app_settings_constructor(
integral_num,
do_extrema: false,
do_roots: false,
do_intersections: false,
plot_width: pixel_width,
}
}
@ -253,10 +259,16 @@ fn do_test(sum: Riemann, area_target: f64) {
}
#[test]
fn left_function() { do_test(Riemann::Left, 0.9600000000000001); }
fn left_function() {
do_test(Riemann::Left, 0.9600000000000001);
}
#[test]
fn middle_function() { do_test(Riemann::Middle, 0.92); }
fn middle_function() {
do_test(Riemann::Middle, 0.92);
}
#[test]
fn right_function() { do_test(Riemann::Right, 0.8800000000000001); }
fn right_function() {
do_test(Riemann::Right, 0.8800000000000001);
}

View File

@ -143,8 +143,9 @@ 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 mut backing_func = BackingFunction::new(func).unwrap();
let backing_func = BackingFunction::new(&process_func_str(func)).unwrap();
backing_func.get_function_derivative(0).clone()
}