use crate::COORDINATE_LIMIT;
use f_office_units::fixed::{self, ONE, product, root, rounded};
use f_office_units::scale::QUARTER_TURN;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Operand {
Number(i64),
Guide(usize),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Operation {
MultiplyDivide,
AddSubtract,
AddDivide,
IfElse,
Absolute,
ArcTangent,
CosineArcTangent,
Cosine,
Maximum,
Minimum,
Modulus,
Pin,
SineArcTangent,
Sine,
SquareRoot,
Tangent,
Value,
}
const OPERATIONS: [(&str, Operation, usize); 17] = [
("*/", Operation::MultiplyDivide, 3),
("+-", Operation::AddSubtract, 3),
("+/", Operation::AddDivide, 3),
("?:", Operation::IfElse, 3),
("abs", Operation::Absolute, 1),
("at2", Operation::ArcTangent, 2),
("cat2", Operation::CosineArcTangent, 3),
("cos", Operation::Cosine, 2),
("max", Operation::Maximum, 2),
("min", Operation::Minimum, 2),
("mod", Operation::Modulus, 3),
("pin", Operation::Pin, 3),
("sat2", Operation::SineArcTangent, 3),
("sin", Operation::Sine, 2),
("sqrt", Operation::SquareRoot, 1),
("tan", Operation::Tangent, 2),
("val", Operation::Value, 1),
];
#[derive(Clone, Copy, Debug)]
enum Measure {
Width,
Height,
Shortest,
Longest,
Origin,
Angle(i64),
}
const BUILT_IN: [(&str, Measure, i64); 37] = [
("3cd4", Measure::Angle(16_200_000), 1),
("3cd8", Measure::Angle(8_100_000), 1),
("5cd8", Measure::Angle(13_500_000), 1),
("7cd8", Measure::Angle(18_900_000), 1),
("b", Measure::Height, 1),
("cd2", Measure::Angle(10_800_000), 1),
("cd4", Measure::Angle(QUARTER_TURN), 1),
("cd8", Measure::Angle(2_700_000), 1),
("h", Measure::Height, 1),
("hc", Measure::Width, 2),
("hd2", Measure::Height, 2),
("hd3", Measure::Height, 3),
("hd4", Measure::Height, 4),
("hd5", Measure::Height, 5),
("hd6", Measure::Height, 6),
("hd8", Measure::Height, 8),
("l", Measure::Origin, 1),
("ls", Measure::Longest, 1),
("r", Measure::Width, 1),
("ss", Measure::Shortest, 1),
("ssd2", Measure::Shortest, 2),
("ssd4", Measure::Shortest, 4),
("ssd6", Measure::Shortest, 6),
("ssd8", Measure::Shortest, 8),
("ssd16", Measure::Shortest, 16),
("ssd32", Measure::Shortest, 32),
("t", Measure::Origin, 1),
("vc", Measure::Height, 2),
("w", Measure::Width, 1),
("wd2", Measure::Width, 2),
("wd3", Measure::Width, 3),
("wd4", Measure::Width, 4),
("wd5", Measure::Width, 5),
("wd6", Measure::Width, 6),
("wd8", Measure::Width, 8),
("wd10", Measure::Width, 10),
("wd32", Measure::Width, 32),
];
impl Measure {
fn of(self, [width, height]: [i128; 2]) -> i128 {
match self {
Self::Width => width,
Self::Height => height,
Self::Shortest => width.min(height),
Self::Longest => width.max(height),
Self::Origin => 0,
Self::Angle(angle) => i128::from(angle) * ONE,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Formula {
operation: Operation,
operands: [Operand; 3],
}
impl Formula {
fn value(self, values: &[i128]) -> Option<i128> {
let [x, y, z] = self.operands.map(|operand| value(values, operand));
let result = match self.operation {
Operation::MultiplyDivide => rounded(x * y, z),
Operation::AddSubtract => x + y - z,
Operation::AddDivide => rounded((x + y) * ONE, z),
Operation::IfElse => {
if x > 0 {
y
} else {
z
}
}
Operation::Absolute => x.abs(),
Operation::ArcTangent => fixed::angle_of(x, y),
Operation::CosineArcTangent => match hypotenuse(y, z) {
0 => x,
side => rounded(x * y, side),
},
Operation::Cosine => product(x, fixed::sin_cos(y)[1]),
Operation::Maximum => x.max(y),
Operation::Minimum => x.min(y),
Operation::Modulus => root(square(x) + square(y) + square(z)),
Operation::Pin => pinned(x, y, z),
Operation::SineArcTangent => rounded(x * z, hypotenuse(y, z)),
Operation::Sine => product(x, fixed::sin_cos(y)[0]),
Operation::SquareRoot => {
let x = u128::try_from(x).ok()?;
root(x * ONE.cast_unsigned())
}
Operation::Tangent => {
let [sin, cos] = fixed::sin_cos(y);
rounded(x * sin, cos)
}
Operation::Value => x,
};
(result.abs() <= fixed::LIMIT).then_some(result)
}
}
fn square(value: i128) -> u128 {
value.unsigned_abs() * value.unsigned_abs()
}
fn hypotenuse(a: i128, b: i128) -> i128 {
root(square(a) + square(b))
}
fn pinned(low: i128, value: i128, high: i128) -> i128 {
if value < low {
low
} else if value > high {
high
} else {
value
}
}
pub(crate) fn value(values: &[i128], operand: Operand) -> i128 {
match operand {
Operand::Number(number) => i128::from(number) * ONE,
Operand::Guide(place) => values.get(place).copied().unwrap_or_default(),
}
}
pub(crate) fn values(formulas: &[Formula], size: [i128; 2]) -> Option<Vec<i128>> {
let mut values: Vec<i128> = BUILT_IN
.iter()
.map(|&(_, measure, divisor)| rounded(measure.of(size), i128::from(divisor)))
.collect();
values.reserve(formulas.len());
for formula in formulas {
let value = formula.value(&values)?;
values.push(value);
}
Some(values)
}
#[derive(Debug, Default)]
pub(crate) struct Guides<'a> {
names: Vec<&'a str>,
formulas: Vec<Formula>,
}
impl<'a> Guides<'a> {
pub(crate) fn add(&mut self, name: &'a str, text: &str) -> Option<()> {
let mut words = text.split_whitespace();
let first = words.next()?;
let &(_, operation, count) = OPERATIONS.iter().find(|(name, ..)| *name == first)?;
let mut operands = [Operand::Number(0); 3];
for operand in operands.iter_mut().take(count) {
*operand = self.operand(words.next()?)?;
}
self.names.push(name);
self.formulas.push(Formula {
operation,
operands,
});
Some(())
}
pub(crate) fn operand(&self, text: &str) -> Option<Operand> {
match text.parse::<i64>() {
Ok(number) => (-COORDINATE_LIMIT..=COORDINATE_LIMIT)
.contains(&number)
.then_some(Operand::Number(number)),
Err(_) => self.guide(text),
}
}
pub(crate) fn guide(&self, name: &str) -> Option<Operand> {
match self.names.iter().rposition(|own| *own == name) {
Some(place) => Some(Operand::Guide(BUILT_IN.len() + place)),
None => BUILT_IN
.iter()
.position(|(built_in, ..)| *built_in == name)
.map(Operand::Guide),
}
}
pub(crate) fn into_formulas(self) -> Vec<Formula> {
self.formulas
}
}
#[cfg(test)]
mod tests;