Compare commits

...

10 Commits

29 changed files with 3669 additions and 2946 deletions

View File

@ -1,50 +0,0 @@
on: [push, pull_request]
name: CI
jobs:
check:
name: Check
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v2
- name: Install toolchain
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: nightly
override: true
- name: Install fonttools
run: sudo apt-get install -y fonttools libzstd-dev
- name: Run cargo check
uses: actions-rs/cargo@v1
with:
command: check
parsing_test:
name: Tests
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v2
- name: Install toolchain
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: nightly
override: true
- name: Install fonttools
run: sudo apt-get install -y fonttools libzstd-dev
- name: Install cargo-all-features
uses: actions-rs/install@v0.1
with:
crate: cargo-all-features
version: latest
- run: cargo test-all-features

View File

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

View File

@ -1,5 +0,0 @@
{
"files.insertFinalNewline": true,
"editor.formatOnSave": true,
"files.trimTrailingWhitespace": true,
}

1878
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,7 @@
[package]
name = "ytbn_graphing_software"
version = "0.1.0"
edition = "2021"
edition = "2024"
license = "AGPL-3.0"
repository = "https://github.com/Titaniumtown/YTBN-Graphing-Software"
description = "Crossplatform (and web-compatible) graphing calculator"
@ -33,17 +33,17 @@ strip = false
[dependencies]
parsing = { path = "./parsing" }
eframe = { git = "https://github.com/titaniumtown/egui.git", default-features = false, features = [
eframe = { git = "https://github.com/titaniumtown/egui.git", rev = "b088efb9fa917845ecb54729a0d2fc592d2399e7", default-features = false, features = [
"glow",
] }
egui = { git = "https://github.com/titaniumtown/egui.git", default-features = false, features = [
egui = { git = "https://github.com/titaniumtown/egui.git", rev = "b088efb9fa917845ecb54729a0d2fc592d2399e7", default-features = false, features = [
"serde",
] }
epaint = { git = "https://github.com/titaniumtown/egui.git", default-features = false , features = [
epaint = { git = "https://github.com/titaniumtown/egui.git", rev = "b088efb9fa917845ecb54729a0d2fc592d2399e7", 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 = { git = "https://github.com/titaniumtown/egui.git", rev = "b088efb9fa917845ecb54729a0d2fc592d2399e7", default-features = false }
egui_plot = { git = "https://github.com/titaniumtown/egui.git", rev = "b088efb9fa917845ecb54729a0d2fc592d2399e7", default-features = false }
@ -56,16 +56,17 @@ itertools = "0.10"
static_assertions = "1.1"
bincode = "1.3"
serde = "1"
base64 = "0.21"
[dev-dependencies]
benchmarks = { path = "./benchmarks" }
[build-dependencies]
shadow-rs = "0.12"
epaint = { git = "https://github.com/titaniumtown/egui.git", default-features = false, features = [
epaint = { git = "https://github.com/titaniumtown/egui.git", rev = "b088efb9fa917845ecb54729a0d2fc592d2399e7", default-features = false, features = [
"bytemuck",
] }
egui = { git = "https://github.com/titaniumtown/egui.git", default-features = false, features = [
egui = { git = "https://github.com/titaniumtown/egui.git", rev = "b088efb9fa917845ecb54729a0d2fc592d2399e7", default-features = false, features = [
"serde",
] }
bincode = "1.3"
@ -88,7 +89,8 @@ 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"
# pinned to 0.4.54 in order to be compatible with nixos's wasm-bindgen-cli version
wasm-bindgen-futures = "=0.4.54"
[package.metadata.cargo-all-features]
skip_optional_dependencies = true #don't test optional dependencies, only features

View File

@ -9,5 +9,4 @@ license = "AGPL-3.0"
[dependencies]
pprof = { version = "0.9", features = ["flamegraph"] }
criterion = "0.3"
criterion-macro = "0.3"
parsing = { path = "../parsing" }

View File

@ -1,17 +1,10 @@
#![feature(custom_test_frameworks)]
#![test_runner(criterion::runner)]
use parsing::{split_function_chars, SplitType};
#[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 criterion::{criterion_group, criterion_main, Criterion};
use pprof::ProfilerGuard;
pub struct FlamegraphProfiler<'a> {
@ -62,7 +55,6 @@ 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)",
@ -86,20 +78,23 @@ fn mutli_split_function(c: &mut Criterion) {
for entry in data_chars {
group.bench_function(entry.iter().collect::<String>(), |b| {
b.iter(|| {
split_function_chars(&entry, parsing::suggestions::SplitType::Multiplication);
split_function_chars(&entry, SplitType::Multiplication);
})
});
}
group.finish();
}
// #[criterion(custom_criterion_flamegraph())]
// Uncomment to enable flamegraph profiling
// fn single_split_function(c: &mut Criterion) {
// let data_chars = "(2x+1)(3x+1)".chars().collect::<Vec<char>>();
//
// c.bench_function("split_function", |b| {
// b.iter(|| {
// split_function_chars(&data_chars);
// split_function_chars(&data_chars, SplitType::Multiplication);
// });
// });
// }
criterion_group!(benches, mutli_split_function);
criterion_main!(benches);

View File

@ -7,8 +7,8 @@ use std::{
};
use epaint::{
text::{FontData, FontDefinitions, FontTweak},
FontFamily,
text::{FontData, FontDefinitions, FontTweak},
};
use run_script::ScriptOptions;

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
}

214
flake.nix Normal file
View File

@ -0,0 +1,214 @@
{
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.stable.latest.default.override {
targets = [ "wasm32-unknown-unknown" ];
};
rustPlatform = pkgs.makeRustPlatform {
cargo = rustToolchain;
rustc = rustToolchain;
};
# 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 = {
"ecolor-0.25.0" = "sha256-9s5LCngwvIIL43txT6sBs4JlRXqmYt1Kw8hlDnwx+DI=";
};
};
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 = with pkgs; [
wasm-bindgen-cli
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

@ -13,13 +13,19 @@ pub enum Movement {
}
impl Movement {
pub const fn is_none(&self) -> bool { matches!(&self, &Self::None) }
pub const fn is_none(&self) -> bool {
matches!(&self, &Self::None)
}
pub const fn is_complete(&self) -> bool { matches!(&self, &Self::Complete) }
pub const fn is_complete(&self) -> bool {
matches!(&self, &Self::Complete)
}
}
impl const Default for Movement {
fn default() -> Self { Self::None }
impl Default for Movement {
fn default() -> Self {
Self::None
}
}
#[derive(Clone, PartialEq)]
@ -29,8 +35,10 @@ pub struct AutoComplete<'a> {
pub string: String,
}
impl<'a> const Default for AutoComplete<'a> {
fn default() -> AutoComplete<'a> { AutoComplete::EMPTY }
impl<'a> Default for AutoComplete<'a> {
fn default() -> AutoComplete<'a> {
AutoComplete::EMPTY
}
}
impl<'a> AutoComplete<'a> {

View File

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

View File

@ -22,7 +22,9 @@ impl FlatExWrapper {
}
#[inline]
const fn is_none(&self) -> bool { self.func.is_none() }
const fn is_none(&self) -> bool {
self.func.is_none()
}
#[inline]
pub fn eval(&self, x: &[f64]) -> f64 {
@ -66,8 +68,10 @@ impl FlatExWrapper {
}
}
impl const Default for FlatExWrapper {
fn default() -> FlatExWrapper { FlatExWrapper::EMPTY }
impl Default for FlatExWrapper {
fn default() -> FlatExWrapper {
FlatExWrapper::EMPTY
}
}
/// Function that includes f(x), f'(x), f'(x)'s string representation, and f''(x)
#[derive(Clone, PartialEq)]
@ -80,11 +84,15 @@ pub struct BackingFunction {
}
impl Default for BackingFunction {
fn default() -> Self { Self::new("").unwrap() }
fn default() -> Self {
Self::new("").unwrap()
}
}
impl BackingFunction {
pub const fn is_none(&self) -> bool { self.function.is_none() }
pub const fn is_none(&self) -> bool {
self.function.is_none()
}
/// Create new [`BackingFunction`] instance
pub fn new(func_str: &str) -> Result<Self, String> {

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

View File

@ -1,12 +1,12 @@
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},
@ -23,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
@ -118,7 +120,7 @@ impl<'de> Deserialize<'de> for FunctionEntry {
}
}
impl const Default for FunctionEntry {
impl Default for FunctionEntry {
/// Creates default FunctionEntry instance (which is empty)
fn default() -> FunctionEntry {
FunctionEntry {
@ -142,7 +144,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;
@ -172,7 +176,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) {
@ -198,7 +204,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);
@ -235,7 +245,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);
@ -244,15 +257,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!(),
};
@ -265,7 +278,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() {
@ -353,7 +369,10 @@ 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() {
return None;
@ -455,25 +474,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

@ -1,8 +1,5 @@
use crate::{
consts::COLORS,
function_entry::FunctionEntry,
misc::{create_id, get_u64_id, random_u64},
widgets::widgets_ontop,
consts::COLORS, function_entry::FunctionEntry, misc::random_u64, widgets::widgets_ontop,
};
use egui::{Button, Id, Key, Modifiers, TextEdit, WidgetText};
use emath::vec2;
@ -22,7 +19,7 @@ impl Default for FunctionManager {
fn default() -> Self {
let mut vec: Functions = Vec::with_capacity(COLORS.len());
vec.push((
create_id(11414819524356497634), // Random number here to avoid call to crate::misc::random_u64()
Id::new(11414819524356497634_u64), // Random number here to avoid call to crate::misc::random_u64()
FunctionEntry::default(),
));
Self { functions: vec }
@ -40,8 +37,8 @@ impl Serialize for FunctionManager {
&self
.functions
.iter()
.map(|(id, func)| (get_u64_id(*id), func.clone()))
.collect::<Vec<(u64, FunctionEntry)>>(),
.map(|(id, func)| (*id, func.clone()))
.collect::<Vec<(Id, FunctionEntry)>>(),
)?;
s.end()
}
@ -53,17 +50,12 @@ impl<'de> Deserialize<'de> for FunctionManager {
D: Deserializer<'de>,
{
#[derive(Deserialize)]
struct Helper(Vec<(u64, FunctionEntry)>);
struct Helper(Vec<(Id, FunctionEntry)>);
let helper = Helper::deserialize(deserializer)?;
Ok(FunctionManager {
functions: helper
.0
.iter()
.cloned()
.map(|(id, func)| (create_id(id), func))
.collect::<Vec<(Id, FunctionEntry)>>(),
functions: helper.0.to_vec(),
})
}
}
@ -151,14 +143,11 @@ 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;
egui::popup_below_widget(ui, POPUP_ID, &re, |ui| {
let autocomplete_popup_id = Id::new("autocomplete popup");
egui::popup_below_widget(ui, autocomplete_popup_id, &re, |ui| {
hints.iter().enumerate().for_each(|(i, candidate)| {
if ui
.selectable_label(i == function.autocomplete.i, *candidate)
@ -175,12 +164,9 @@ impl FunctionManager {
.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));
ui.memory_mut(|x| x.open_popup(autocomplete_popup_id));
}
}
@ -198,7 +184,7 @@ impl FunctionManager {
const BUTTONS_Y_OFFSET: f32 = 1.32;
const Y_OFFSET: f32 = crate::consts::FONT_SIZE * BUTTONS_Y_OFFSET;
widgets_ontop(ui, create_id(i as u64), &re, Y_OFFSET, |ui| {
widgets_ontop(ui, Id::new(i), &re, Y_OFFSET, |ui| {
ui.horizontal(|ui| {
// There's more than 1 function! Functions can now be deleted
if ui
@ -260,7 +246,7 @@ impl FunctionManager {
/// Create and push new empty function entry
pub fn push_empty(&mut self) {
self.functions.push((
create_id(random_u64().expect("unable to generate random id")),
Id::new(random_u64().expect("unable to generate random id")),
FunctionEntry::default(),
));
}
@ -271,11 +257,17 @@ impl FunctionManager {
}
#[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,14 +1,3 @@
#![feature(const_mut_refs)]
#![feature(let_chains)]
#![feature(const_trait_impl)]
#![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;
@ -24,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},
};

View File

@ -1,14 +1,3 @@
#![feature(const_mut_refs)]
#![feature(let_chains)]
#![feature(const_trait_impl)]
#![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;

View File

@ -1,13 +1,13 @@
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,
};
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, SidePanel,
TopBottomPanel, Ui, Vec2, Window, style::Margin,
};
use egui_plot::Plot;
@ -51,7 +51,7 @@ pub struct AppSettings {
pub plot_width: usize,
}
impl const Default for AppSettings {
impl Default for AppSettings {
/// Default implementation of `AppSettings`, this is how the application starts up
fn default() -> Self {
Self {
@ -84,7 +84,7 @@ struct Opened {
pub welcome: bool,
}
impl const Default for Opened {
impl Default for Opened {
fn default() -> Opened {
Self {
help: false,
@ -111,7 +111,9 @@ pub struct MathApp {
}
#[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 {
@ -150,10 +152,9 @@ impl MathApp {
let data = get_localstorage().get_item(DATA_NAME).ok()??;
let (commit, cached_data) = crate::misc::hashed_storage_read(&data)?;
if commit == unsafe { std::mem::transmute::<&str, crate::misc::HashBytes>(build::SHORT_COMMIT) } {
tracing::info!("Reading decompression cache. Bytes: {}", cached_data.len());
return Some(cached_data.to_vec());
return Some(cached_data);
} else {
None
}
@ -161,14 +162,8 @@ impl MathApp {
fn load_functions() -> Option<FunctionManager> {
let data = get_localstorage().get_item(FUNC_NAME).ok()??;
if crate::misc::HASH_LENGTH >= data.len() {
return None;
}
// TODO: stabilize FunctionManager serialize so it can persist across builds
let (commit, func_data) = crate::misc::hashed_storage_read(&data)?;
if commit == unsafe { std::mem::transmute::<&str, &[u8]>(build::SHORT_COMMIT) } {
tracing::info!("Reading previous function data");
let function_manager: FunctionManager = bincode::deserialize(&func_data).ok()?;
@ -183,8 +178,11 @@ 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::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)
@ -364,7 +362,7 @@ impl MathApp {
#[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(

View File

@ -1,4 +1,4 @@
use egui::Id;
use base64::{Engine as _, engine::general_purpose};
use egui_plot::{Line, PlotPoint, PlotPoints, Points};
use emath::Pos2;
use getrandom::getrandom;
@ -27,10 +27,14 @@ impl EguiHelper for Vec<PlotPoint> {
}
#[inline(always)]
fn to_line(self) -> Line { Line::new(self.to_values()) }
fn to_line(self) -> Line {
Line::new(self.to_values())
}
#[inline(always)]
fn to_points(self) -> Points { Points::new(self.to_values()) }
fn to_points(self) -> Points {
Points::new(self.to_values())
}
#[inline(always)]
fn to_tuple(self) -> Vec<(f64, f64)> {
@ -43,7 +47,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,10 +63,6 @@ impl const Offset for Pos2 {
}
}
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) } }
/*
/// Rounds f64 to `n` decimal places
pub fn decimal_round(x: f64, n: usize) -> f64 {
@ -80,7 +80,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 +102,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;
@ -166,24 +172,27 @@ pub type HashBytes = [u8; HASH_LENGTH];
#[allow(dead_code)]
pub fn hashed_storage_create(hashbytes: HashBytes, data: &[u8]) -> String {
unsafe { std::mem::transmute::<Vec<u8>, String>([hashbytes.to_vec(), data.to_vec()].concat()) }
let combined_data = [hashbytes.to_vec(), data.to_vec()].concat();
general_purpose::STANDARD.encode(combined_data)
}
#[allow(dead_code)]
pub fn hashed_storage_read(data: &str) -> Option<(HashBytes, &[u8])> {
pub fn hashed_storage_read(data: &str) -> Option<(HashBytes, Vec<u8>)> {
// Decode base64 data
let decoded_bytes = general_purpose::STANDARD.decode(data).ok()?;
// Make sure data is long enough to decode
if HASH_LENGTH >= data.len() {
if HASH_LENGTH > decoded_bytes.len() {
return None;
}
// Transmute data into slice
let decoded_1: &[u8] = unsafe { std::mem::transmute::<&str, &[u8]>(data) };
// Split hash and data
let (hash_bytes, data_bytes) = decoded_bytes.split_at(HASH_LENGTH);
// Return hash and decoded data
Some((
unsafe { *(decoded_1[..HASH_LENGTH].as_ptr() as *const HashBytes) },
&decoded_1[HASH_LENGTH..],
))
// Convert hash bytes to HashBytes
let hash: HashBytes = hash_bytes.try_into().ok()?;
Some((hash, data_bytes.to_vec()))
}
/// Creates and returns random u64
@ -198,4 +207,6 @@ pub fn random_u64() -> Result<u64, getrandom::Error> {
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)
}

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,
@ -253,10 +258,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);
}