Files
Graphite/node-graph/nodes/math/src/lib.rs
T
Timon da2c5a2d13 Prepare the executor and runtime for a node graph drawn by Graphene (#5044)
* Borrow the input in LazyInput::eval, as Node::eval does

* Allow wrapping a network in scope without the render node

* Implement CacheHash for BTreeMap

* Replace the CanvasFrame render output with canvas info on the response

* Add OwnedContextImpl::with_varargs for a context with several varargs
2026-11-30 17:43:42 +00:00

2947 lines
113 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
use core_types::context::{CloneVarArgs, ExtractAll};
use core_types::list::{Bundle, Item, List};
use core_types::transform::Footprint;
use core_types::{Color, Ctx, OwnedContextImpl, num_traits};
use core_types::{Context, Interrupt};
use glam::{DAffine2, DMat2, DVec2};
use graphic_types::raster_types::{CPU, GPU, Raster};
use graphic_types::{Artboard, Generator, Graphic, Vector};
use math_parser::ast;
use math_parser::context::{EvalContext, NothingMap, ValueProvider};
use math_parser::executer::EvalError;
use math_parser::lexer::Constant;
use math_parser::matrix::{Affine2, Linear2, Matrix};
use math_parser::object::Object;
use math_parser::parser::{MessagePart, ParseError};
use math_parser::reducer::{Reducer, classify_reducer};
use math_parser::value::{Value, Vector2, Vector3};
use rand::{RngExt, SeedableRng};
use std::sync::{Arc, Mutex, PoisonError};
use vector_types::Gradient;
/// Why a math node's expression or operator gives no result.
#[derive(Debug, thiserror::Error)]
pub enum MathExpressionError {
#[error("The expression is empty")]
Empty,
#[error("The expression is invalid: {0}")]
Invalid(String),
#[error(transparent)]
Evaluation(#[from] EvalError),
#[error("The result {result} can't be read as {output_type}")]
OutputType { result: String, output_type: String },
#[error("The input can't be read as {0}")]
InputType(String),
#[error("`{0}` alone is an operator, which the Math Aggregate node applies across all the items")]
LoneOperator(String),
#[error("The operator must be a lone operator or function name, like `+` or `max`")]
NotAnOperator,
#[error("`{reducer}` gives no result for an empty list")]
EmptyReduction { reducer: String },
#[error("`{reducer}` gives no result across these items")]
NoReduction { reducer: String },
}
/// A parse error's messages without the byte ranges they point at, which only mean something beside the source.
fn parse_error_message(error: &ParseError) -> String {
let message = |parts: &[MessagePart]| {
parts
.iter()
.map(|part| match part {
MessagePart::Text(text) => text.clone(),
MessagePart::Code(code) => format!("`{code}`"),
})
.collect::<String>()
};
error.messages().iter().map(|error| message(error.parts())).collect::<Vec<_>>().join("; ")
}
/// A parsed source and its tree, or the message of why it doesn't parse.
type ParsedSource = Option<(String, Result<Arc<ast::Node>, String>)>;
/// The last expression a node parsed, reused while its source stays the same, so a list of thousands of items or a run of
/// frames parses once. An invalid source is remembered too, so it is parsed once rather than per item.
#[derive(Debug, Clone, Default)]
pub struct ParseCache(Arc<Mutex<ParsedSource>>);
impl ParseCache {
/// The parse tree of `source`, or why it isn't a valid math expression.
fn parse(&self, source: &str) -> Result<Arc<ast::Node>, MathExpressionError> {
if source.trim().is_empty() {
return Err(MathExpressionError::Empty);
}
// A lock poisoned by a panic elsewhere still guards a usable cache
let mut cached = self.0.lock().unwrap_or_else(PoisonError::into_inner);
if let Some((cached_source, tree)) = cached.as_ref()
&& cached_source == source
{
return tree.clone().map_err(MathExpressionError::Invalid);
}
let tree = ast::Node::try_parse_from_str(source).map(Arc::new).map_err(|error| parse_error_message(&error));
*cached = Some((source.to_string(), tree.clone()));
tree.map_err(MathExpressionError::Invalid)
}
}
/// Evaluates a parsed expression with the given variable bindings.
fn evaluate_expression(expression: &ast::Node, provider: impl ValueProvider) -> Result<Object, MathExpressionError> {
Ok(expression.eval(&EvalContext::new(provider, NothingMap))?)
}
/// Converts a node item type to and from the objects, values or matrices, the expression evaluator runs on.
trait ExpressionValue: Copy + Default + 'static {
fn into_object(self) -> Object;
/// Reads an evaluated result as this type, seeing only the parts this type has, or `None` when it does not fit, like 0.5 read as a Bool or a matrix read as a Number.
fn from_object(object: &Object) -> Option<Self>;
/// Gathers a list of this type as the items of its sort.
fn items(items: impl Iterator<Item = Self>) -> Items;
}
/// The items of a math node's list, of one sort throughout, which "Math Formula" binds positionally as `a`, `b`, `c` or as `A`, `B`, `C`.
enum Items {
Values(Vec<Value>),
Matrices(Vec<Matrix>),
}
impl Items {
fn len(&self) -> usize {
match self {
Self::Values(values) => values.len(),
Self::Matrices(matrices) => matrices.len(),
}
}
}
/// A node item type that is a value in the expression language, so a list of them binds positionally.
trait ExpressionItem: Copy + Default + 'static {
/// Binds this value into the expression language, exactly for an integer.
fn into_value(self) -> Value;
fn from_value(value: &Value) -> Option<Self>;
}
impl<T: ExpressionItem> ExpressionValue for T {
fn into_object(self) -> Object {
Object::Value(self.into_value())
}
fn from_object(object: &Object) -> Option<Self> {
T::from_value(object.as_value()?)
}
fn items(items: impl Iterator<Item = Self>) -> Items {
Items::Values(items.map(T::into_value).collect())
}
}
/// The value's real part alone, the only part a scalar type has, keeping an integer's exact storage.
fn real_part(value: &Value) -> Value {
if value.as_real().is_some() { *value } else { Value::from_f64(value.as_particle3().w) }
}
impl ExpressionItem for f64 {
fn into_value(self) -> Value {
Value::from_f64(self)
}
fn from_value(value: &Value) -> Option<Self> {
real_part(value).as_real()
}
}
/// Reads an expression's result as the node's output type.
fn output<T: ExpressionValue>(result: &Object) -> Result<T, MathExpressionError> {
T::from_object(result).ok_or_else(|| MathExpressionError::OutputType {
result: result.to_string(),
output_type: core_types::concrete!(T).to_string(),
})
}
impl ExpressionItem for i64 {
fn into_value(self) -> Value {
Value::from_i64(self)
}
// A fractional result snaps to the nearest whole number (the graph's one Number to Integer rule)
fn from_value(value: &Value) -> Option<Self> {
real_part(value).as_i64()
}
}
impl ExpressionItem for bool {
fn into_value(self) -> Value {
Value::from_bool(self)
}
// A truth value is exactly 0 or 1 in the expression language, so any other real part does not fit
fn from_value(value: &Value) -> Option<Self> {
real_part(value).as_bool()
}
}
impl ExpressionItem for DVec2 {
fn into_value(self) -> Value {
Value::from(Vector2(self.to_array()))
}
// Projects onto the plane, dropping the real and `k` parts
fn from_value(value: &Value) -> Option<Self> {
let Vector3([x, y, _]) = value.as_particle3().vector;
Some(DVec2::new(x, y))
}
}
/// A transform as the `i, j` block with its translation.
fn transform_matrix(transform: DAffine2) -> Matrix {
Matrix::from(Affine2 {
linear: Linear2(transform.matrix2.to_cols_array_2d()),
translation: transform.translation.to_array(),
})
}
impl ExpressionValue for DAffine2 {
fn into_object(self) -> Object {
Object::from(transform_matrix(self))
}
// A map of the plane leaving the weight and `z` alone, which no other matrix fits
fn from_object(object: &Object) -> Option<Self> {
let Affine2 {
linear: Linear2(columns),
translation,
} = object.as_matrix()?.as_affine2()?;
Some(DAffine2::from_mat2_translation(DMat2::from_cols_array_2d(&columns), DVec2::from_array(translation)))
}
fn items(items: impl Iterator<Item = Self>) -> Items {
Items::Matrices(items.map(transform_matrix).collect())
}
}
/// Supplies the value of `x`, or the matrix of `X`, for the "Math Function" node's expression.
struct SingleVariableMathContext<'a> {
x: &'a Object,
}
impl ValueProvider for SingleVariableMathContext<'_> {
fn get_value(&self, name: &str) -> Option<Value> {
// Bound by exact spelling, per the language's rule that a binding shadows the builtin of exactly its spelling
(name == "x").then(|| self.x.as_value().copied()).flatten()
}
fn get_matrix(&self, name: &str) -> Option<Matrix> {
(name == "X").then(|| self.x.as_matrix().copied()).flatten()
}
}
/// Maps a value through a math expression written as a function of `x`, which stands for the value, or of `X` when it's a Transform. Each item of a list is mapped on its own.
///
/// The result is read as the chosen output type: an Integer rounds to the nearest whole number, a Bool reads exactly 0 or 1 as false or true, a Vec2 takes the X and Y of a vector like `3i + 4j`, and a Transform takes a matrix like `rotation(pi/4) + 5i`. A boolean input reads as 0 or 1 and a Vec2 input as such a vector.
#[node_macro::node(category("Math"), icon("NodeMathFunction"), version(2))]
fn math_function<T: ExpressionValue, U: ExpressionValue>(
_: impl Ctx,
/// The value passed into the expression as `x`.
#[implementations(
f64, f64, f64, f64, f64, i64, i64, i64, i64, i64, bool, bool, bool, bool, bool, DVec2, DVec2, DVec2, DVec2, DVec2, DAffine2, DAffine2, DAffine2, DAffine2, DAffine2
)]
value: Item<T>,
/// The expression evaluated for the input value, in terms of `x`, such as `4sin(x/2)`, or of `X` for a Transform.
#[name("f(x) =")]
#[default("x")]
#[widget(ParsedWidgetOverride::Custom = "math_expression")]
fx: Item<String>,
/// The type the result is read as.
#[implementations(
f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2
)]
#[widget(ParsedWidgetOverride::Custom = "type_choice")]
#[name("Output Type")]
output_type: Item<U>,
#[data] parsed: ParseCache,
) -> Result<Item<U>, (Item<U>, MathExpressionError)> {
// The output type input is a type witness: its type selects the implementation, and its value is never read
let _ = output_type;
let (value, attributes) = value.into_parts();
let x = value.into_object();
// The default `x` passes any input through, including a Transform, which an expression names `X`
let source = if x.as_matrix().is_some() && fx.element().trim() == "x" { "X" } else { fx.element() };
let result = parsed
.parse(source)
.and_then(|expression| evaluate_expression(&expression, SingleVariableMathContext { x: &x }))
.and_then(|result| output(&result));
match result {
Ok(result) => Ok(Item::from_parts(result, attributes)),
// The input passes through as the default `x` reads it, unless the output type can't hold it
Err(error) => match U::from_object(&x) {
Some(input) => Err((Item::from_parts(input, attributes), error)),
None => Err((Item::from_parts(U::default(), attributes), MathExpressionError::InputType(core_types::concrete!(U).to_string()))),
},
}
}
/// Binds the items of the "Math Formula" node's list to the positional variables `a`, `b`, `c`, and so on, or `A`, `B`, `C` for matrices.
struct PositionalMathContext {
items: Items,
}
/// The position a single-letter name of the given case binds, `a` or `A` being the first.
fn position(name: &str, is_letter_case: fn(&char) -> bool) -> Option<usize> {
let mut characters = name.chars();
let letter = characters.next()?;
(characters.next().is_none() && is_letter_case(&letter)).then(|| (letter.to_ascii_lowercase() as u8 - b'a') as usize)
}
impl ValueProvider for PositionalMathContext {
fn get_value(&self, name: &str) -> Option<Value> {
let Items::Values(items) = &self.items else { return None };
// A wired item shadows the constant spelled by its letter (`e` as the fifth item, `i` as the ninth), which stay reachable
// as `\e` and `\i`; an unwired letter reads as its default of 0, except that a constant's letter stays the constant
match items.get(position(name, char::is_ascii_lowercase)?) {
Some(item) => Some(*item),
None if Constant::from_name(name).is_some() => None,
None => Some(Value::from_i64(0)),
}
}
fn get_matrix(&self, name: &str) -> Option<Matrix> {
let Items::Matrices(items) = &self.items else { return None };
// Likewise `I` as the ninth item shadows the identity, and an unwired letter reads as a Transform's default, the identity
Some(items.get(position(name, char::is_ascii_uppercase)?).copied().unwrap_or(Matrix::IDENTITY))
}
}
/// Evaluates one math expression over all the items, taking them in order as its arguments `a`, `b`, `c`, …, or `A`, `B`, `C`, … for Transforms.
///
/// The result is read as the chosen output type: an Integer rounds to the nearest whole number, a Bool reads exactly 0 or 1 as false or true, a Vec2 takes the X and Y of a vector like `3i + 4j`, and a Transform takes a matrix like `rotation(pi/4) + 5i`. Boolean items read as 0 or 1 and Vec2 items as such vectors.
#[node_macro::node(category("Math"), icon("NodeMathFormula"), version(2))]
fn math_formula<T: ExpressionValue, U: ExpressionValue>(
_: impl Ctx,
/// The items the expression reads.
#[implementations(
List<f64>, List<f64>, List<f64>, List<f64>, List<f64>,
List<i64>, List<i64>, List<i64>, List<i64>, List<i64>,
List<bool>, List<bool>, List<bool>, List<bool>, List<bool>,
List<DVec2>, List<DVec2>, List<DVec2>, List<DVec2>, List<DVec2>,
List<DAffine2>, List<DAffine2>, List<DAffine2>, List<DAffine2>, List<DAffine2>,
)]
values: List<T>,
/// The expression evaluated over the items, such as `a * b + c`.
#[name("f(…) =")]
#[widget(ParsedWidgetOverride::Custom = "math_expression")]
f: Item<String>,
/// The type the result is read as.
#[implementations(
f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2
)]
#[widget(ParsedWidgetOverride::Custom = "type_choice")]
#[name("Output Type")]
output_type: Item<U>,
#[data] parsed: ParseCache,
) -> Result<Item<U>, MathExpressionError> {
// The output type input is a type witness: its type selects the implementation, and its value is never read
let _ = output_type;
let expression = f.element();
if classify_reducer(expression, NothingMap).is_some() {
return Err(MathExpressionError::LoneOperator(expression.trim().to_string()));
}
let bindings = PositionalMathContext {
items: T::items(values.iter_element_values().copied()),
};
let tree = parsed.parse(expression)?;
let result = evaluate_expression(&tree, bindings)?;
Ok(Item::new_from_element(output(&result)?))
}
/// The operator or function name a "Math Aggregate" or "Math Running" node applies across its items.
fn operator_reducer(operator: &str) -> Result<Reducer, MathExpressionError> {
classify_reducer(operator, NothingMap).ok_or(MathExpressionError::NotAnOperator)
}
/// Reduces all the items to a single value by folding an operator like `+` or `*` across them, or by passing them all to a function like `max` or `mean`.
///
/// The result is read as the chosen output type: an Integer rounds to the nearest whole number, a Bool reads exactly 0 or 1 as false or true, a Vec2 takes the X and Y of a vector like `3i + 4j`, and a Transform takes a matrix like `rotation(pi/4) + 5i`. Boolean items read as 0 or 1 and Vec2 items as such vectors. Across Transforms, `*` and `/` compose in order, `mean` averages, and `count` counts.
#[node_macro::node(category("Math"), icon("NodeMathAggregate"), footprint_invariant)]
fn math_aggregate<T: ExpressionValue, U: ExpressionValue>(
_: impl Ctx,
/// The items reduced to one value.
#[implementations(
List<f64>, List<f64>, List<f64>, List<f64>, List<f64>,
List<i64>, List<i64>, List<i64>, List<i64>, List<i64>,
List<bool>, List<bool>, List<bool>, List<bool>, List<bool>,
List<DVec2>, List<DVec2>, List<DVec2>, List<DVec2>, List<DVec2>,
List<DAffine2>, List<DAffine2>, List<DAffine2>, List<DAffine2>, List<DAffine2>,
)]
values: List<T>,
/// The operator folded across the items, like `+` or `*`, or a function given all of them, like `max` or `mean`.
#[default("+")]
#[widget(ParsedWidgetOverride::Custom = "math_operator")]
operator: Item<String>,
/// The type the result is read as.
#[implementations(
f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2
)]
#[widget(ParsedWidgetOverride::Custom = "type_choice")]
#[name("Output Type")]
output_type: Item<U>,
) -> Result<Item<U>, MathExpressionError> {
// The output type input is a type witness: its type selects the implementation, and its value is never read
let _ = output_type;
let operator = operator.element();
let reducer = operator_reducer(operator)?;
let items = T::items(values.iter_element_values().copied());
let result = match &items {
Items::Values(values) => reducer.evaluate(values).map(Object::Value),
Items::Matrices(matrices) => reducer.evaluate_matrices(matrices),
};
let Some(result) = result else {
let name = operator.trim();
return match items.len() {
// Like the dedicated nodes, the minimum, maximum and mean of no values are 0
0 if matches!(items, Items::Values(_)) && matches!(name.trim_start_matches('\\'), "min" | "max" | "mean") => Ok(Item::new_from_element(U::default())),
0 => Err(MathExpressionError::EmptyReduction { reducer: name.to_string() }),
_ => Err(MathExpressionError::NoReduction { reducer: name.to_string() }),
};
};
Ok(Item::new_from_element(output(&result)?))
}
/// Scans along the items, giving each one the result of folding an operator like `+` over it and every item before it, such as a running total, or of a function like `max`, such as the highest value so far.
///
/// The result is read as the chosen output type: an Integer rounds to the nearest whole number, a Bool reads exactly 0 or 1 as false or true, a Vec2 takes the X and Y of a vector like `3i + 4j`, and a Transform takes a matrix like `rotation(pi/4) + 5i`. Boolean items read as 0 or 1 and Vec2 items as such vectors. Across Transforms, `*` composes in order, which turns a list of steps into where each step ends up.
#[node_macro::node(category("Math"), icon("NodeMathRunning"), footprint_invariant)]
fn math_running<T: ExpressionValue, U: ExpressionValue>(
_: impl Ctx,
/// The items scanned along, each giving one result.
#[implementations(
List<f64>, List<f64>, List<f64>, List<f64>, List<f64>,
List<i64>, List<i64>, List<i64>, List<i64>, List<i64>,
List<bool>, List<bool>, List<bool>, List<bool>, List<bool>,
List<DVec2>, List<DVec2>, List<DVec2>, List<DVec2>, List<DVec2>,
List<DAffine2>, List<DAffine2>, List<DAffine2>, List<DAffine2>, List<DAffine2>,
)]
values: List<T>,
/// The operator folded along the items, like `+` or `*`, or a function given the items so far, like `max` or `mean`.
#[default("+")]
#[widget(ParsedWidgetOverride::Custom = "math_operator")]
operator: Item<String>,
/// The type each result is read as.
#[implementations(
f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2, f64, i64, bool, DVec2, DAffine2
)]
#[widget(ParsedWidgetOverride::Custom = "type_choice")]
#[name("Output Type")]
output_type: Item<U>,
) -> Result<List<U>, (List<U>, MathExpressionError)> {
// The output type input is a type witness: its type selects the implementation, and its value is never read
let _ = output_type;
let operator = operator.element();
let reducer = match operator_reducer(operator) {
Ok(reducer) => reducer,
Err(error) => return Err((values.into_iter().map(|item| Item::from_parts(U::default(), item.into_parts().1)).collect(), error)),
};
// Each item's run is folded on from the run before it, where a failed fold fails every run after it
let items = T::items(values.iter_element_values().copied());
let running = match &items {
Items::Values(values) => reducer.evaluate_running(values).into_iter().map(|result| result.map(Object::Value)).collect(),
Items::Matrices(matrices) => reducer.evaluate_running_matrices(matrices),
};
// A failing item takes the default, and the first failure is the one reported
let mut first_error = None;
let results = running.into_iter().map(|result| {
let no_reduction = || MathExpressionError::NoReduction { reducer: operator.trim().to_string() };
result.ok_or_else(no_reduction).and_then(|result| output(&result)).unwrap_or_else(|error| {
first_error.get_or_insert(error);
U::default()
})
});
let list = values.into_iter().zip(results).map(|(item, result)| Item::from_parts(result, item.into_parts().1)).collect();
match first_error {
Some(error) => Err((list, error)),
None => Ok(list),
}
}
/// An Integer result too large or too small for the Integer type to hold.
#[derive(Debug, thiserror::Error)]
pub enum IntegerOverflowError {
#[error("The result is outside the Integer range")]
OutOfRange,
}
pub trait TryAdd<Rhs = Self> {
type Output;
fn try_add(self, addend: Rhs) -> Result<Self::Output, IntegerOverflowError>;
}
impl TryAdd for f64 {
type Output = f64;
fn try_add(self, addend: f64) -> Result<f64, IntegerOverflowError> {
Ok(self + addend)
}
}
impl TryAdd for i64 {
type Output = i64;
fn try_add(self, addend: i64) -> Result<i64, IntegerOverflowError> {
self.checked_add(addend).ok_or(IntegerOverflowError::OutOfRange)
}
}
impl TryAdd for DVec2 {
type Output = DVec2;
fn try_add(self, addend: DVec2) -> Result<DVec2, IntegerOverflowError> {
Ok(self + addend)
}
}
impl TryAdd<f64> for DVec2 {
type Output = DVec2;
fn try_add(self, addend: f64) -> Result<DVec2, IntegerOverflowError> {
Ok(self + addend)
}
}
impl TryAdd<DVec2> for f64 {
type Output = DVec2;
fn try_add(self, addend: DVec2) -> Result<DVec2, IntegerOverflowError> {
Ok(self + addend)
}
}
pub trait TrySub<Rhs = Self> {
type Output;
fn try_sub(self, subtrahend: Rhs) -> Result<Self::Output, IntegerOverflowError>;
}
impl TrySub for f64 {
type Output = f64;
fn try_sub(self, subtrahend: f64) -> Result<f64, IntegerOverflowError> {
Ok(self - subtrahend)
}
}
impl TrySub for i64 {
type Output = i64;
fn try_sub(self, subtrahend: i64) -> Result<i64, IntegerOverflowError> {
self.checked_sub(subtrahend).ok_or(IntegerOverflowError::OutOfRange)
}
}
impl TrySub for DVec2 {
type Output = DVec2;
fn try_sub(self, subtrahend: DVec2) -> Result<DVec2, IntegerOverflowError> {
Ok(self - subtrahend)
}
}
impl TrySub<f64> for DVec2 {
type Output = DVec2;
fn try_sub(self, subtrahend: f64) -> Result<DVec2, IntegerOverflowError> {
Ok(self - subtrahend)
}
}
impl TrySub<DVec2> for f64 {
type Output = DVec2;
fn try_sub(self, subtrahend: DVec2) -> Result<DVec2, IntegerOverflowError> {
Ok(self - subtrahend)
}
}
pub trait TryMul<Rhs = Self> {
type Output;
fn try_mul(self, multiplicand: Rhs) -> Result<Self::Output, IntegerOverflowError>;
}
impl TryMul for f64 {
type Output = f64;
fn try_mul(self, multiplicand: f64) -> Result<f64, IntegerOverflowError> {
Ok(self * multiplicand)
}
}
impl TryMul for i64 {
type Output = i64;
fn try_mul(self, multiplicand: i64) -> Result<i64, IntegerOverflowError> {
self.checked_mul(multiplicand).ok_or(IntegerOverflowError::OutOfRange)
}
}
impl TryMul for DVec2 {
type Output = DVec2;
fn try_mul(self, multiplicand: DVec2) -> Result<DVec2, IntegerOverflowError> {
Ok(self * multiplicand)
}
}
impl TryMul<f64> for DVec2 {
type Output = DVec2;
fn try_mul(self, multiplicand: f64) -> Result<DVec2, IntegerOverflowError> {
Ok(self * multiplicand)
}
}
impl TryMul<DVec2> for f64 {
type Output = DVec2;
fn try_mul(self, multiplicand: DVec2) -> Result<DVec2, IntegerOverflowError> {
Ok(self * multiplicand)
}
}
impl TryMul for DAffine2 {
type Output = DAffine2;
fn try_mul(self, multiplicand: DAffine2) -> Result<DAffine2, IntegerOverflowError> {
Ok(self * multiplicand)
}
}
/// The addition operation (`+`) calculates the sum of two scalar numbers or vec2s.
#[node_macro::node(category("Math: Arithmetic"), icon("NodeAdd"))]
fn add<A: TryAdd<B>, B>(
_: impl Ctx,
/// The left-hand side of the addition operation.
#[implementations(f64, i64, DVec2, f64, DVec2)]
augend: Item<A>,
/// The right-hand side of the addition operation.
#[implementations(f64, i64, DVec2, DVec2, f64)]
addend: Item<B>,
) -> Result<Item<<A as TryAdd<B>>::Output>, IntegerOverflowError> {
let (augend, attributes) = augend.into_parts();
Ok(Item::from_parts(augend.try_add(addend.into_element())?, attributes))
}
/// The subtraction operation (`-`) calculates the difference between two scalar numbers or vec2s.
#[node_macro::node(category("Math: Arithmetic"), icon("NodeSubtract"))]
fn subtract<A: TrySub<B>, B>(
_: impl Ctx,
/// The left-hand side of the subtraction operation.
#[implementations(f64, i64, DVec2, f64, DVec2)]
minuend: Item<A>,
/// The right-hand side of the subtraction operation.
#[implementations(f64, i64, DVec2, DVec2, f64)]
subtrahend: Item<B>,
) -> Result<Item<<A as TrySub<B>>::Output>, IntegerOverflowError> {
let (minuend, attributes) = minuend.into_parts();
Ok(Item::from_parts(minuend.try_sub(subtrahend.into_element())?, attributes))
}
/// The multiplication operation (`×`) calculates the product of two scalar numbers, vec2s, or transforms.
#[node_macro::node(category("Math: Arithmetic"), icon("NodeMultiply"))]
fn multiply<A: TryMul<B>, B>(
_: impl Ctx,
/// The left-hand side of the multiplication operation.
#[implementations(f64, i64, DVec2, f64, DVec2, DAffine2)]
multiplier: Item<A>,
/// The right-hand side of the multiplication operation.
#[default(1.)]
#[implementations(f64, i64, DVec2, DVec2, f64, DAffine2)]
multiplicand: Item<B>,
) -> Result<Item<<A as TryMul<B>>::Output>, IntegerOverflowError> {
let (multiplier, attributes) = multiplier.into_parts();
Ok(Item::from_parts(multiplier.try_mul(multiplicand.into_element())?, attributes))
}
pub trait SafeDivide<Rhs = Self> {
type Output;
fn safe_divide(self, denominator: Rhs) -> Result<Self::Output, IntegerOverflowError>;
}
impl SafeDivide for f64 {
type Output = f64;
fn safe_divide(self, denominator: f64) -> Result<f64, IntegerOverflowError> {
Ok(if denominator == 0. { 0. } else { self / denominator })
}
}
impl SafeDivide for i64 {
type Output = i64;
fn safe_divide(self, denominator: i64) -> Result<i64, IntegerOverflowError> {
if denominator == 0 {
return Ok(0);
}
self.checked_div(denominator).ok_or(IntegerOverflowError::OutOfRange)
}
}
impl SafeDivide for DVec2 {
type Output = DVec2;
fn safe_divide(self, denominator: DVec2) -> Result<DVec2, IntegerOverflowError> {
Ok(DVec2::new(self.x.safe_divide(denominator.x)?, self.y.safe_divide(denominator.y)?))
}
}
impl SafeDivide<f64> for DVec2 {
type Output = DVec2;
fn safe_divide(self, denominator: f64) -> Result<DVec2, IntegerOverflowError> {
Ok(DVec2::new(self.x.safe_divide(denominator)?, self.y.safe_divide(denominator)?))
}
}
impl SafeDivide<DVec2> for f64 {
type Output = DVec2;
fn safe_divide(self, denominator: DVec2) -> Result<DVec2, IntegerOverflowError> {
Ok(DVec2::new(self.safe_divide(denominator.x)?, self.safe_divide(denominator.y)?))
}
}
/// The division operation (`÷`) calculates the quotient of two scalar numbers or vec2s.
///
/// Produces 0 for any division by 0. With vec2 inputs, this applies separately to the X and Y components.
#[node_macro::node(category("Math: Arithmetic"), icon("NodeDivide"))]
fn divide<A: SafeDivide<B>, B>(
_: impl Ctx,
/// The left-hand side of the division operation.
#[implementations(f64, i64, DVec2, DVec2, f64)]
numerator: Item<A>,
/// The right-hand side of the division operation.
#[default(1.)]
#[implementations(f64, i64, DVec2, f64, DVec2)]
denominator: Item<B>,
) -> Result<Item<<A as SafeDivide<B>>::Output>, IntegerOverflowError> {
let (numerator, attributes) = numerator.into_parts();
Ok(Item::from_parts(numerator.safe_divide(denominator.into_element())?, attributes))
}
trait Componentwise {
fn componentwise(self, f: impl Fn(f64) -> f64) -> Self;
}
impl Componentwise for f64 {
fn componentwise(self, f: impl Fn(f64) -> f64) -> Self {
f(self)
}
}
impl Componentwise for DVec2 {
fn componentwise(self, f: impl Fn(f64) -> f64) -> Self {
DVec2::new(f(self.x), f(self.y))
}
}
/// The reciprocal operation (`1/x`) calculates the multiplicative inverse of a number.
///
/// Produces 0 if the input is 0. With a vec2 input, this applies separately to the X and Y components.
#[node_macro::node(category("Math: Arithmetic"), icon("NodeReciprocal"))]
fn reciprocal<T: Componentwise>(
_: impl Ctx,
/// The number for which the reciprocal is calculated.
#[implementations(f64, DVec2)]
value: Item<T>,
) -> Item<T> {
let (value, attributes) = value.into_parts();
Item::from_parts(value.componentwise(|value| if value == 0. { 0. } else { 1. / value }), attributes)
}
/// Why a modulo has no result.
#[derive(Debug, thiserror::Error)]
pub enum ModuloError {
#[error("The modulus can't be 0")]
ZeroModulus,
}
pub trait Modulo<Rhs = Self> {
type Output;
fn modulo(self, modulus: Rhs, always_positive: bool) -> Result<Self::Output, ModuloError>;
}
fn scalar_modulo(numerator: f64, modulus: f64, always_positive: bool) -> Result<f64, ModuloError> {
if modulus == 0. {
return Err(ModuloError::ZeroModulus);
}
Ok(if always_positive { (numerator % modulus + modulus) % modulus } else { numerator % modulus })
}
impl Modulo for f64 {
type Output = f64;
fn modulo(self, modulus: f64, always_positive: bool) -> Result<f64, ModuloError> {
scalar_modulo(self, modulus, always_positive)
}
}
impl Modulo for i64 {
type Output = i64;
fn modulo(self, modulus: i64, always_positive: bool) -> Result<i64, ModuloError> {
if modulus == 0 {
return Err(ModuloError::ZeroModulus);
}
// Only `i64::MIN % -1` wraps, to its true remainder of 0
let remainder = self.wrapping_rem(modulus);
// Adding the modulus only to a remainder of the opposite sign gives it the modulus's sign without overflowing
Ok(if always_positive && remainder != 0 && (remainder < 0) != (modulus < 0) {
remainder + modulus
} else {
remainder
})
}
}
impl Modulo for DVec2 {
type Output = DVec2;
fn modulo(self, modulus: DVec2, always_positive: bool) -> Result<DVec2, ModuloError> {
Ok(DVec2::new(scalar_modulo(self.x, modulus.x, always_positive)?, scalar_modulo(self.y, modulus.y, always_positive)?))
}
}
impl Modulo<f64> for DVec2 {
type Output = DVec2;
fn modulo(self, modulus: f64, always_positive: bool) -> Result<DVec2, ModuloError> {
Ok(DVec2::new(scalar_modulo(self.x, modulus, always_positive)?, scalar_modulo(self.y, modulus, always_positive)?))
}
}
impl Modulo<DVec2> for f64 {
type Output = DVec2;
fn modulo(self, modulus: DVec2, always_positive: bool) -> Result<DVec2, ModuloError> {
Ok(DVec2::new(scalar_modulo(self, modulus.x, always_positive)?, scalar_modulo(self, modulus.y, always_positive)?))
}
}
/// The modulo operation (`%`) calculates the remainder from the division of two scalar numbers or vec2s.
///
/// The sign of the result shares the sign of the numerator, or of the modulus if *Always Positive* is enabled.
#[node_macro::node(category("Math: Arithmetic"), icon("NodeModulo"))]
fn modulo<A: Modulo<B>, B>(
_: impl Ctx,
/// The left-hand side of the modulo operation.
#[implementations(f64, i64, DVec2, DVec2, f64)]
numerator: Item<A>,
/// The right-hand side of the modulo operation.
#[default(2.)]
#[implementations(f64, i64, DVec2, f64, DVec2)]
modulus: Item<B>,
/// Ensures the result is positive for a positive modulus, even if the numerator is negative.
#[default(true)]
always_positive: Item<bool>,
) -> Result<Item<<A as Modulo<B>>::Output>, ModuloError> {
let (numerator, attributes) = numerator.into_parts();
Ok(Item::from_parts(numerator.modulo(modulus.into_element(), *always_positive.element())?, attributes))
}
pub trait Exponent<Rhs = Self> {
type Output;
fn power(self, power: Rhs) -> Result<Self::Output, IntegerOverflowError>;
}
impl Exponent for f64 {
type Output = f64;
fn power(self, power: f64) -> Result<f64, IntegerOverflowError> {
Ok(self.powf(power))
}
}
impl Exponent for i64 {
type Output = i64;
fn power(self, power: i64) -> Result<i64, IntegerOverflowError> {
if let Ok(power) = u32::try_from(power) {
return self.checked_pow(power).ok_or(IntegerOverflowError::OutOfRange);
}
// A negative power truncates toward 0, which only ±1 escape, and a power beyond 32 bits overflows for any other base but 0
match self {
1 => Ok(1),
-1 if power % 2 == 0 => Ok(1),
-1 => Ok(-1),
0 => Ok(0),
_ if power < 0 => Ok(0),
_ => Err(IntegerOverflowError::OutOfRange),
}
}
}
impl Exponent for DVec2 {
type Output = DVec2;
fn power(self, power: DVec2) -> Result<DVec2, IntegerOverflowError> {
Ok(DVec2::new(self.x.powf(power.x), self.y.powf(power.y)))
}
}
impl Exponent<f64> for DVec2 {
type Output = DVec2;
fn power(self, power: f64) -> Result<DVec2, IntegerOverflowError> {
Ok(DVec2::new(self.x.powf(power), self.y.powf(power)))
}
}
impl Exponent<DVec2> for f64 {
type Output = DVec2;
fn power(self, power: DVec2) -> Result<DVec2, IntegerOverflowError> {
Ok(DVec2::new(self.powf(power.x), self.powf(power.y)))
}
}
/// The exponent operation (`^`) calculates the result of raising a number to a power.
///
/// With vec2 inputs, this applies separately to the X and Y components.
#[node_macro::node(category("Math: Arithmetic"), icon("NodeExponent"))]
fn exponent<A: Exponent<B>, B>(
_: impl Ctx,
/// The base number that is raised to the power.
#[implementations(f64, i64, DVec2, DVec2, f64)]
base: Item<A>,
/// The power to which the base number is raised.
#[implementations(f64, i64, DVec2, f64, DVec2)]
#[default(2.)]
power: Item<B>,
) -> Result<Item<<A as Exponent<B>>::Output>, IntegerOverflowError> {
let (base, attributes) = base.into_parts();
Ok(Item::from_parts(base.power(power.into_element())?, attributes))
}
fn scalar_nth_root(radicand: f64, degree: f64) -> f64 {
if degree == 2. {
radicand.sqrt()
} else if degree == 3. {
radicand.cbrt()
} else if degree <= 0. {
0.
} else if radicand < 0. && degree % 2. == 1. {
-(-radicand).powf(1. / degree)
} else {
radicand.powf(1. / degree)
}
}
pub trait NthRoot<Degree = Self> {
type Output;
fn nth_root(self, degree: Degree) -> Self::Output;
}
impl NthRoot for f64 {
type Output = f64;
fn nth_root(self, degree: f64) -> f64 {
scalar_nth_root(self, degree)
}
}
impl NthRoot for DVec2 {
type Output = DVec2;
fn nth_root(self, degree: DVec2) -> DVec2 {
DVec2::new(scalar_nth_root(self.x, degree.x), scalar_nth_root(self.y, degree.y))
}
}
impl NthRoot<f64> for DVec2 {
type Output = DVec2;
fn nth_root(self, degree: f64) -> DVec2 {
DVec2::new(scalar_nth_root(self.x, degree), scalar_nth_root(self.y, degree))
}
}
impl NthRoot<DVec2> for f64 {
type Output = DVec2;
fn nth_root(self, degree: DVec2) -> DVec2 {
DVec2::new(scalar_nth_root(self, degree.x), scalar_nth_root(self, degree.y))
}
}
/// The `n`th root operation (`√`) calculates the inverse of exponentiation. Square root inverts squaring, cube root inverts cubing, and so on.
///
/// This is equivalent to raising the number to the power of `1/n`. With vec2 inputs, this applies separately to the X and Y components.
#[node_macro::node(category("Math: Arithmetic"), icon("NodeRoot"))]
fn root<A: NthRoot<B>, B>(
_: impl Ctx,
/// The number inside the radical for which the `n`th root is calculated.
#[default(2.)]
#[implementations(f64, DVec2, DVec2, f64)]
radicand: Item<A>,
/// The degree of the root to be calculated. Square root is 2, cube root is 3, and so on.
/// Degrees 0 or less are invalid and will produce an output of 0.
#[default(2.)]
#[implementations(f64, f64, DVec2, DVec2)]
degree: Item<B>,
) -> Item<<A as NthRoot<B>>::Output> {
let (radicand, attributes) = radicand.into_parts();
Item::from_parts(radicand.nth_root(degree.into_element()), attributes)
}
fn scalar_logarithm(value: f64, base: f64) -> f64 {
if base == 2. {
value.log2()
} else if base == 10. {
value.log10()
} else if (base - std::f64::consts::E).abs() < f64::EPSILON * 1e6 {
value.ln()
} else {
value.log(base)
}
}
pub trait Logarithm<Base = Self> {
type Output;
fn logarithm(self, base: Base) -> Self::Output;
}
impl Logarithm for f64 {
type Output = f64;
fn logarithm(self, base: f64) -> f64 {
scalar_logarithm(self, base)
}
}
impl Logarithm for DVec2 {
type Output = DVec2;
fn logarithm(self, base: DVec2) -> DVec2 {
DVec2::new(scalar_logarithm(self.x, base.x), scalar_logarithm(self.y, base.y))
}
}
impl Logarithm<f64> for DVec2 {
type Output = DVec2;
fn logarithm(self, base: f64) -> DVec2 {
DVec2::new(scalar_logarithm(self.x, base), scalar_logarithm(self.y, base))
}
}
impl Logarithm<DVec2> for f64 {
type Output = DVec2;
fn logarithm(self, base: DVec2) -> DVec2 {
DVec2::new(scalar_logarithm(self, base.x), scalar_logarithm(self, base.y))
}
}
/// The logarithmic function (`log`) calculates the logarithm of a number with a specified base. If the natural logarithm function (`ln`) is desired, set the base to "e".
///
/// With vec2 inputs, this applies separately to the X and Y components.
#[node_macro::node(category("Math: Arithmetic"), icon("NodeLogarithm"))]
fn logarithm<A: Logarithm<B>, B>(
_: impl Ctx,
/// The number for which the logarithm is calculated.
#[implementations(f64, DVec2, DVec2, f64)]
value: Item<A>,
/// The base of the logarithm, such as 2 (binary), 10 (decimal), and e (natural logarithm).
#[default(2.)]
#[implementations(f64, f64, DVec2, DVec2)]
base: Item<B>,
) -> Item<<A as Logarithm<B>>::Output> {
let (value, attributes) = value.into_parts();
Item::from_parts(value.logarithm(base.into_element()), attributes)
}
/// The sine trigonometric function (`sin`) calculates the ratio of the angle's opposite side length to its hypotenuse length.
///
/// With a vec2 input, this applies separately to the X and Y components.
#[node_macro::node(category("Math: Trig"), icon("NodeSine"))]
fn sine<T: Componentwise>(
_: impl Ctx,
/// The given angle.
#[implementations(f64, DVec2)]
theta: Item<T>,
/// Whether the given angle should be interpreted as radians instead of degrees.
radians: Item<bool>,
) -> Item<T> {
let (theta, attributes) = theta.into_parts();
let radians = *radians.element();
let result = theta.componentwise(|theta| if radians { theta.sin() } else { theta.to_radians().sin() });
Item::from_parts(result, attributes)
}
/// The cosine trigonometric function (`cos`) calculates the ratio of the angle's adjacent side length to its hypotenuse length.
///
/// With a vec2 input, this applies separately to the X and Y components.
#[node_macro::node(category("Math: Trig"), icon("NodeCosine"))]
fn cosine<T: Componentwise>(
_: impl Ctx,
/// The given angle.
#[implementations(f64, DVec2)]
theta: Item<T>,
/// Whether the given angle should be interpreted as radians instead of degrees.
radians: Item<bool>,
) -> Item<T> {
let (theta, attributes) = theta.into_parts();
let radians = *radians.element();
let result = theta.componentwise(|theta| if radians { theta.cos() } else { theta.to_radians().cos() });
Item::from_parts(result, attributes)
}
/// The tangent trigonometric function (`tan`) calculates the ratio of the angle's opposite side length to its adjacent side length.
///
/// With a vec2 input, this applies separately to the X and Y components.
#[node_macro::node(category("Math: Trig"), icon("NodeTangent"))]
fn tangent<T: Componentwise>(
_: impl Ctx,
/// The given angle.
#[implementations(f64, DVec2)]
theta: Item<T>,
/// Whether the given angle should be interpreted as radians instead of degrees.
radians: Item<bool>,
) -> Item<T> {
let (theta, attributes) = theta.into_parts();
let radians = *radians.element();
let result = theta.componentwise(|theta| if radians { theta.tan() } else { theta.to_radians().tan() });
Item::from_parts(result, attributes)
}
/// The inverse sine trigonometric function (`asin`) calculates the angle whose sine is the input value.
#[node_macro::node(category("Math: Trig"), icon("NodeSineInverse"))]
fn sine_inverse(
_: impl Ctx,
/// The given value for which the angle is calculated. Must be in the domain `[-1, 1]` (it will be clamped to -1 or 1 otherwise).
#[range]
#[hard(-1..1)]
value: Item<f64>,
/// Whether the resulting angle should be given in radians instead of degrees.
radians: Item<bool>,
) -> Item<f64> {
let (value, attributes) = value.into_parts();
let angle = value.asin();
let result = if *radians.element() { angle } else { angle.to_degrees() };
Item::from_parts(result, attributes)
}
/// The inverse cosine trigonometric function (`acos`) calculates the angle whose cosine is the input value.
#[node_macro::node(category("Math: Trig"), icon("NodeCosineInverse"))]
fn cosine_inverse(
_: impl Ctx,
/// The given value for which the angle is calculated. Must be in the domain `[-1, 1]` (it will be clamped to -1 or 1 otherwise).
#[range]
#[hard(-1..1)]
value: Item<f64>,
/// Whether the resulting angle should be given in radians instead of degrees.
radians: Item<bool>,
) -> Item<f64> {
let (value, attributes) = value.into_parts();
let angle = value.acos();
let result = if *radians.element() { angle } else { angle.to_degrees() };
Item::from_parts(result, attributes)
}
/// The inverse tangent trigonometric function (`atan` or `atan2`, depending on input type) calculates:
/// `atan`: the angle whose tangent is the input scalar number.
/// `atan2`: the angle of a ray from the origin to the input vec2.
///
/// The resulting `atan` angle is always in the range `[-90°, 90°]` or, in radians, `[-π/2, π/2]`.
/// The resulting `atan2` angle is always in the range `[-180°, 180°]` or, in radians, `[-π, π]`.
#[node_macro::node(category("Math: Trig"), icon("NodeTangentInverse"))]
fn tangent_inverse<T: TangentInverse>(
_: impl Ctx,
/// The given value for which the angle is calculated.
#[implementations(f64, DVec2)]
value: Item<T>,
/// Whether the resulting angle should be given in radians instead of degrees.
radians: Item<bool>,
) -> Item<T::Output> {
let (value, attributes) = value.into_parts();
Item::from_parts(value.atan(*radians.element()), attributes)
}
pub trait TangentInverse {
type Output: num_traits::float::Float;
fn atan(self, radians: bool) -> Self::Output;
}
impl TangentInverse for f64 {
type Output = f64;
fn atan(self, radians: bool) -> Self::Output {
if radians { self.atan() } else { self.atan().to_degrees() }
}
}
impl TangentInverse for DVec2 {
type Output = f64;
fn atan(self, radians: bool) -> Self::Output {
if radians { self.y.atan2(self.x) } else { self.y.atan2(self.x).to_degrees() }
}
}
/// Why a remap has no result.
#[derive(Debug, thiserror::Error)]
pub enum RemapError {
#[error("Input Min and Input Max can't be equal")]
FlatInputRange,
}
/// Linearly maps an input value from one range to another. The ranges may be reversed.
///
/// For example, 0.5 in the input range `[0, 1]` would map to 0 in the output range `[-180, 180]`.
#[node_macro::node(category("Math: Numeric"), icon("NodeRemap"))]
fn remap(
_: impl Ctx,
/// The value to be mapped between ranges.
value: Item<f64>,
/// The lower bound of the input range.
input_min: Item<f64>,
/// The upper bound of the input range.
#[default(1.)]
input_max: Item<f64>,
/// The lower bound of the output range.
output_min: Item<f64>,
/// The upper bound of the output range.
#[default(1.)]
output_max: Item<f64>,
/// Whether to constrain the result within the output range instead of extrapolating beyond its bounds.
clamped: Item<bool>,
) -> Result<Item<f64>, RemapError> {
let (value, attributes) = value.into_parts();
let (input_min, input_max, output_min, output_max) = (*input_min.element(), *input_max.element(), *output_min.element(), *output_max.element());
if input_min == input_max {
return Err(RemapError::FlatInputRange);
}
let input_range = input_max - input_min;
let normalized = (value - input_min) / input_range;
let output_range = output_max - output_min;
let result = output_min + normalized * output_range;
let result = if *clamped.element() {
// Handle both normal and inverted ranges, since we want to allow the user to use this node to also reverse a range.
if output_min <= output_max {
result.clamp(output_min, output_max)
} else if output_max < output_min {
result.clamp(output_max, output_min)
} else {
// A NaN bound gives no range to clamp within, and has already made the result NaN
result
}
} else {
result
};
Ok(Item::from_parts(result, attributes))
}
trait Lerp {
fn lerp(self, end: Self, factor: f64) -> Self;
}
impl Lerp for f64 {
fn lerp(self, end: Self, factor: f64) -> Self {
self * (1. - factor) + end * factor
}
}
impl Lerp for DVec2 {
fn lerp(self, end: Self, factor: f64) -> Self {
self * (1. - factor) + end * factor
}
}
/// Linearly interpolates between the start and end values, where a factor of 0 gives the start value, 1 gives the end value, and 0.5 gives their midpoint.
///
/// With vec2 inputs, this traces the straight line path between the two points.
#[node_macro::node(category("Math: Numeric"), icon("NodeLerp"))]
fn lerp<T: Lerp>(
_: impl Ctx,
/// The value produced when the factor is 0.
#[implementations(f64, DVec2)]
start: Item<T>,
/// The value produced when the factor is 1.
#[default(1.)]
#[implementations(f64, DVec2)]
end: Item<T>,
/// The mix between the start (at 0) and end (at 1) values.
#[default(0.5)]
factor: Item<f64>,
/// Whether to constrain the factor within 0 to 1, preventing extrapolation beyond the start and end values.
#[default(true)]
clamped: Item<bool>,
) -> Item<T> {
let (start, attributes) = start.into_parts();
let factor = if *clamped.element() { factor.element().clamp(0., 1.) } else { *factor.element() };
// Exact endpoint factors pass the endpoint through untouched, since the unused operand would otherwise contaminate the weighted sum (NaN or infinity times 0 is NaN)
let result = if factor == 0. {
start
} else if factor == 1. {
end.into_element()
} else {
start.lerp(end.into_element(), factor)
};
Item::from_parts(result, attributes)
}
/// The random function (`rand`) converts a seed into a random number within the specified range, inclusive of the minimum and exclusive of the maximum. The minimum and maximum values are automatically swapped if they are reversed.
#[node_macro::node(category("Math"), icon("NodeRandom"))]
fn random(
_: impl Ctx,
_primary: (),
/// Seed to determine the unique variation of which number is generated.
#[hard(0..)]
seed: Item<i64>,
/// The smaller end of the range within which the random number is generated.
min: Item<f64>,
/// The larger end of the range within which the random number is generated.
#[default(1.)]
max: Item<f64>,
) -> Item<f64> {
let mut rng = rand::rngs::StdRng::seed_from_u64(*seed.element() as u64);
let result = rng.random::<f64>();
let (min, max) = (*min.element(), *max.element());
let (min, max) = if min < max { (min, max) } else { (max, min) };
Item::new_from_element(result * (max - min) + min)
}
// TODO: Test that these are no longer needed in all circumstances, then remove them and add a migration to convert these into Passthrough nodes. Note: these act more as type annotations than as identity functions.
/// Converts a `Number` to the `Integer` type, which may be the required type for certain node inputs.
#[node_macro::node(category("Data: Type Assertion"), icon("NodeAsInteger"))]
fn as_integer(_: impl Ctx, value: Item<i64>) -> Item<i64> {
value
}
// TODO: Test that these are no longer needed in all circumstances, then remove them and add a migration to convert these into Passthrough nodes. Note: these act more as type annotations than as identity functions.
/// Converts an `Integer` or `Bool` to the `Number` type, which may be the required type for certain node inputs. A `Bool` becomes 0 (false) or 1 (true).
#[node_macro::node(category("Data: Type Assertion"), icon("NodeAsNumber"))]
fn as_number(_: impl Ctx, value: Item<f64>) -> Item<f64> {
value
}
// TODO: Test that these are no longer needed in all circumstances, then remove them and add a migration to convert these into Passthrough nodes. Note: these act more as type annotations than as identity functions.
/// Passes a true or false value through as the type `Bool`, which may be the required type for certain node inputs.
#[node_macro::node(category("Data: Type Assertion"), icon("NodeAsBool"))]
fn as_bool(_: impl Ctx, value: Item<bool>) -> Item<bool> {
value
}
/// The rounding function (`round`) maps an input value to its nearest whole number. Halfway values are rounded away from zero.
///
/// With a vec2 input, this applies separately to the X and Y components.
#[node_macro::node(category("Math: Numeric"), icon("NodeRound"))]
fn round<T: Componentwise>(
_: impl Ctx,
/// The number to be rounded to the nearest whole number.
#[implementations(f64, DVec2)]
value: Item<T>,
) -> Item<T> {
let (value, attributes) = value.into_parts();
Item::from_parts(value.componentwise(f64::round), attributes)
}
/// The floor function (`floor`) rounds down an input value to the nearest whole number, unless the input number is already whole.
///
/// With a vec2 input, this applies separately to the X and Y components.
#[node_macro::node(category("Math: Numeric"), icon("NodeFloor"))]
fn floor<T: Componentwise>(
_: impl Ctx,
/// The number to be rounded down.
#[implementations(f64, DVec2)]
value: Item<T>,
) -> Item<T> {
let (value, attributes) = value.into_parts();
Item::from_parts(value.componentwise(f64::floor), attributes)
}
/// The ceiling function (`ceil`) rounds up an input value to the nearest whole number, unless the input number is already whole.
///
/// With a vec2 input, this applies separately to the X and Y components.
#[node_macro::node(category("Math: Numeric"), icon("NodeCeiling"))]
fn ceiling<T: Componentwise>(
_: impl Ctx,
/// The number to be rounded up.
#[implementations(f64, DVec2)]
value: Item<T>,
) -> Item<T> {
let (value, attributes) = value.into_parts();
Item::from_parts(value.componentwise(f64::ceil), attributes)
}
trait AbsoluteValue: Sized {
fn abs(self) -> Result<Self, IntegerOverflowError>;
}
impl AbsoluteValue for DVec2 {
fn abs(self) -> Result<Self, IntegerOverflowError> {
Ok(DVec2::new(self.x.abs(), self.y.abs()))
}
}
impl AbsoluteValue for f64 {
fn abs(self) -> Result<Self, IntegerOverflowError> {
Ok(self.abs())
}
}
impl AbsoluteValue for i64 {
fn abs(self) -> Result<Self, IntegerOverflowError> {
self.checked_abs().ok_or(IntegerOverflowError::OutOfRange)
}
}
/// The absolute value function (`abs`) removes the negative sign from an input value, if present.
///
/// With a vec2 input, this applies separately to the X and Y components. For the overall length of a vec2, see the "Magnitude" node instead.
#[node_macro::node(category("Math: Numeric"), icon("NodeAbsoluteValue"))]
fn absolute_value<T: AbsoluteValue>(
_: impl Ctx,
/// The number to be made positive.
#[implementations(f64, i64, DVec2)]
value: Item<T>,
) -> Result<Item<T>, IntegerOverflowError> {
let (value, attributes) = value.into_parts();
Ok(Item::from_parts(value.abs()?, attributes))
}
/// The sign function (`sign`) reports whether an input value is positive (1), negative (-1), or zero (0).
///
/// With a vec2 input, this applies separately to the X and Y components.
#[node_macro::node(category("Math: Numeric"), icon("NodeSign"))]
fn sign<T: Componentwise>(
_: impl Ctx,
/// The number whose sign is checked.
#[implementations(f64, DVec2)]
value: Item<T>,
) -> Item<T> {
let (value, attributes) = value.into_parts();
let result = value.componentwise(|value| if value == 0. { 0. } else { value.signum() });
Item::from_parts(result, attributes)
}
pub trait MinMax<Rhs = Self> {
type Output;
fn minimum(self, other: Rhs) -> Self::Output;
fn maximum(self, other: Rhs) -> Self::Output;
}
impl MinMax for f64 {
type Output = f64;
fn minimum(self, other: f64) -> f64 {
if self < other { self } else { other }
}
fn maximum(self, other: f64) -> f64 {
if self > other { self } else { other }
}
}
impl MinMax for i64 {
type Output = i64;
fn minimum(self, other: i64) -> i64 {
if self < other { self } else { other }
}
fn maximum(self, other: i64) -> i64 {
if self > other { self } else { other }
}
}
impl MinMax for String {
type Output = String;
fn minimum(self, other: Self) -> String {
if self < other { self } else { other }
}
fn maximum(self, other: Self) -> String {
if self > other { self } else { other }
}
}
impl MinMax for DVec2 {
type Output = DVec2;
fn minimum(self, other: DVec2) -> DVec2 {
self.min(other)
}
fn maximum(self, other: DVec2) -> DVec2 {
self.max(other)
}
}
impl MinMax<f64> for DVec2 {
type Output = DVec2;
fn minimum(self, other: f64) -> DVec2 {
self.min(DVec2::splat(other))
}
fn maximum(self, other: f64) -> DVec2 {
self.max(DVec2::splat(other))
}
}
impl MinMax<DVec2> for f64 {
type Output = DVec2;
fn minimum(self, other: DVec2) -> DVec2 {
DVec2::splat(self).min(other)
}
fn maximum(self, other: DVec2) -> DVec2 {
DVec2::splat(self).max(other)
}
}
/// The minimum function (`min`) picks the smaller of two numbers.
///
/// With vec2 inputs, this applies separately to the X and Y components.
#[node_macro::node(category("Math: Numeric"), icon("NodeMin"))]
fn min<A: MinMax<B>, B>(
_: impl Ctx,
/// One of the two numbers, of which the lesser is returned.
#[implementations(f64, i64, String, DVec2, DVec2, f64)]
value: Item<A>,
/// The other of the two numbers, of which the lesser is returned.
#[implementations(f64, i64, String, DVec2, f64, DVec2)]
other_value: Item<B>,
) -> Item<<A as MinMax<B>>::Output> {
let (value, attributes) = value.into_parts();
Item::from_parts(value.minimum(other_value.into_element()), attributes)
}
/// The maximum function (`max`) picks the larger of two numbers.
///
/// With vec2 inputs, this applies separately to the X and Y components.
#[node_macro::node(category("Math: Numeric"), icon("NodeMax"))]
fn max<A: MinMax<B>, B>(
_: impl Ctx,
/// One of the two numbers, of which the greater is returned.
#[implementations(f64, i64, String, DVec2, DVec2, f64)]
value: Item<A>,
/// The other of the two numbers, of which the greater is returned.
#[implementations(f64, i64, String, DVec2, f64, DVec2)]
other_value: Item<B>,
) -> Item<<A as MinMax<B>>::Output> {
let (value, attributes) = value.into_parts();
Item::from_parts(value.maximum(other_value.into_element()), attributes)
}
/// The clamp function (`clamp`) restricts a number to a specified range between a minimum and maximum value. The minimum and maximum values are automatically swapped if they are reversed.
///
/// With vec2 inputs, this applies separately to the X and Y components.
#[node_macro::node(category("Math: Numeric"), icon("NodeClamp"))]
fn clamp<A: MinMax<B>, B: MinMax<Output = B> + Clone>(
_: impl Ctx,
/// The number to be clamped, which is restricted to the range between the minimum and maximum values.
#[implementations(f64, i64, String, DVec2, DVec2, f64)]
value: Item<A>,
/// The left (smaller) side of the range. The output is never less than this number.
#[implementations(f64, i64, String, DVec2, f64, DVec2)]
min: Item<B>,
/// The right (greater) side of the range. The output is never greater than this number.
#[implementations(f64, i64, String, DVec2, f64, DVec2)]
#[default(1)]
max: Item<B>,
) -> Item<<A as MinMax<B>>::Output>
where
<A as MinMax<B>>::Output: MinMax<B, Output = <A as MinMax<B>>::Output>,
{
let (value, attributes) = value.into_parts();
let (min, max) = (min.into_element(), max.into_element());
let (min, max) = (min.clone().minimum(max.clone()), min.maximum(max));
Item::from_parts(value.maximum(min).minimum(max), attributes)
}
/// The greatest common divisor (GCD) calculates the largest positive integer that divides both of the two input numbers without leaving a remainder.
#[node_macro::node(category("Math: Numeric"), icon("NodeGreatestCommonDivisor"))]
fn greatest_common_divisor(
_: impl Ctx,
/// One of the two numbers for which the GCD is calculated.
value: Item<i64>,
/// The other of the two numbers for which the GCD is calculated.
other_value: Item<i64>,
) -> Item<i64> {
let (value, attributes) = value.into_parts();
let other_value = *other_value.element();
let gcd = math_parser::constants::gcd(value.unsigned_abs() as u128, other_value.unsigned_abs() as u128);
// A result too large for the output type (like the GCD of `i64::MIN` and 0) saturates at the type's maximum
Item::from_parts(i64::try_from(gcd).unwrap_or(i64::MAX), attributes)
}
/// The least common multiple (LCM) calculates the smallest positive integer that is a multiple of both of the two input numbers.
#[node_macro::node(category("Math: Numeric"), icon("NodeLeastCommonMultiple"))]
fn least_common_multiple(
_: impl Ctx,
/// One of the two numbers for which the LCM is calculated.
value: Item<i64>,
/// The other of the two numbers for which the LCM is calculated.
other_value: Item<i64>,
) -> Item<i64> {
let (value, attributes) = value.into_parts();
let other_value = *other_value.element();
let lcm = math_parser::constants::lcm(value.unsigned_abs() as u128, other_value.unsigned_abs() as u128);
// A result too large for the output type saturates at the type's maximum rather than overflowing
Item::from_parts(i64::try_from(lcm).unwrap_or(i64::MAX), attributes)
}
/// Adds together all the numbers in the input list, producing their total.
#[node_macro::node(category("Math: Arithmetic"), icon("NodeSum"), footprint_invariant)]
fn sum(_: impl Ctx, values: List<f64>) -> Item<f64> {
Item::new_from_element(values.iter_element_values().sum())
}
/// Averages all the numbers in the input list. An empty list gives 0.
#[node_macro::node(category("Math: Numeric"), icon("NodeAverage"), footprint_invariant)]
fn average(_: impl Ctx, values: List<f64>) -> Item<f64> {
let count = values.len();
let average = if count == 0 { 0. } else { values.iter_element_values().sum::<f64>() / count as f64 };
Item::new_from_element(average)
}
/// Gives the smallest number in the input list. An empty list gives 0.
#[node_macro::node(category("Math: Numeric"), icon("NodeMinimum"), footprint_invariant)]
fn minimum(_: impl Ctx, values: List<f64>) -> Item<f64> {
Item::new_from_element(values.iter_element_values().copied().reduce(f64::min).unwrap_or_default())
}
/// Gives the largest number in the input list. An empty list gives 0.
#[node_macro::node(category("Math: Numeric"), icon("NodeMaximum"), footprint_invariant)]
fn maximum(_: impl Ctx, values: List<f64>) -> Item<f64> {
Item::new_from_element(values.iter_element_values().copied().reduce(f64::max).unwrap_or_default())
}
/// Outputs true if at least one value in the input list is true. An empty list gives false.
#[node_macro::node(category("Math: Logic"), icon("NodeAny"))]
fn any(_: impl Ctx, values: List<bool>) -> Item<bool> {
Item::new_from_element(values.iter_element_values().any(|&value| value))
}
/// Outputs true only if every value in the input list is true. An empty list gives true.
#[node_macro::node(category("Math: Logic"), icon("NodeAll"))]
fn all(_: impl Ctx, values: List<bool>) -> Item<bool> {
Item::new_from_element(values.iter_element_values().all(|&value| value))
}
/// Outputs true if the value is anything other than zero. A vector counts as zero only when every component is zero.
#[node_macro::node(category("Math: Logic"), icon("NodeIsNonzero"))]
fn is_nonzero<T: Default + std::cmp::PartialEq>(
_: impl Ctx,
/// The value compared against zero.
#[implementations(f64, i64, DVec2)]
value: Item<T>,
) -> Item<bool> {
let (value, attributes) = value.into_parts();
Item::from_parts(value != T::default(), attributes)
}
/// The less-than operation (`<`) compares two values and returns true if the first value is less than the second, or false if it is not.
/// If enabled with *Or Equal*, the less-than-or-equal operation (`<=`) is used instead.
#[node_macro::node(category("Math: Logic"), icon("NodeLessThan"))]
fn less_than<T: std::cmp::PartialOrd<T>>(
_: impl Ctx,
/// The number on the left-hand side of the comparison.
#[implementations(f64, i64)]
value: Item<T>,
/// The number on the right-hand side of the comparison.
#[implementations(f64, i64)]
other_value: Item<T>,
/// Uses the less-than-or-equal operation (`<=`) instead of the less-than operation (`<`).
or_equal: Item<bool>,
) -> Item<bool> {
let (value, attributes) = value.into_parts();
let other_value = other_value.into_element();
let result = if *or_equal.element() { value <= other_value } else { value < other_value };
Item::from_parts(result, attributes)
}
/// The greater-than operation (`>`) compares two values and returns true if the first value is greater than the second, or false if it is not.
/// If enabled with *Or Equal*, the greater-than-or-equal operation (`>=`) is used instead.
#[node_macro::node(category("Math: Logic"), icon("NodeGreaterThan"))]
fn greater_than<T: std::cmp::PartialOrd<T>>(
_: impl Ctx,
/// The number on the left-hand side of the comparison.
#[implementations(f64, i64)]
value: Item<T>,
/// The number on the right-hand side of the comparison.
#[implementations(f64, i64)]
other_value: Item<T>,
/// Uses the greater-than-or-equal operation (`>=`) instead of the greater-than operation (`>`).
or_equal: Item<bool>,
) -> Item<bool> {
let (value, attributes) = value.into_parts();
let other_value = other_value.into_element();
let result = if *or_equal.element() { value >= other_value } else { value > other_value };
Item::from_parts(result, attributes)
}
/// The equality operation (`==`, `XNOR`) compares two values and returns true if they are equal, or false if they are not.
#[node_macro::node(category("Math: Logic"), icon("NodeEquals"))]
fn equals<T: std::cmp::PartialEq<T>>(
_: impl Ctx,
/// One of the two values to compare for equality.
#[implementations(f64, i64, DVec2, bool, String)]
value: Item<T>,
/// The other of the two values to compare for equality.
#[implementations(f64, i64, DVec2, bool, String)]
other_value: Item<T>,
) -> Item<bool> {
let value = value.into_element();
Item::new_from_element(other_value.into_element() == value)
}
/// The inequality operation (`!=`, `XOR`) compares two values and returns true if they are not equal, or false if they are.
#[node_macro::node(category("Math: Logic"), icon("NodeNotEquals"))]
fn not_equals<T: std::cmp::PartialEq<T>>(
_: impl Ctx,
/// One of the two values to compare for inequality.
#[implementations(f64, i64, DVec2, bool, String)]
value: Item<T>,
/// The other of the two values to compare for inequality.
#[implementations(f64, i64, DVec2, bool, String)]
other_value: Item<T>,
) -> Item<bool> {
let value = value.into_element();
Item::new_from_element(other_value.into_element() != value)
}
/// The logical OR operation (`||`) returns true if either of the two inputs are true, or false if both are false.
#[node_macro::node(category("Math: Logic"), icon("NodeLogicalOr"))]
fn logical_or(
_: impl Ctx,
/// One of the two boolean values, either of which may be true for the node to output true.
value: Item<bool>,
/// The other of the two boolean values, either of which may be true for the node to output true.
#[expose]
other_value: Item<bool>,
) -> Item<bool> {
let (value, attributes) = value.into_parts();
Item::from_parts(value || *other_value.element(), attributes)
}
/// The logical AND operation (`&&`) returns true if both of the two inputs are true, or false if any are false.
#[node_macro::node(category("Math: Logic"), icon("NodeLogicalAnd"))]
fn logical_and(
_: impl Ctx,
/// One of the two boolean values, both of which must be true for the node to output true.
value: Item<bool>,
/// The other of the two boolean values, both of which must be true for the node to output true.
#[expose]
other_value: Item<bool>,
) -> Item<bool> {
let (value, attributes) = value.into_parts();
Item::from_parts(value && *other_value.element(), attributes)
}
/// The logical NOT operation (`!`) reverses true and false value of the input.
#[node_macro::node(category("Math: Logic"), icon("NodeLogicalNot"))]
fn logical_not(
_: impl Ctx,
/// The boolean value to be reversed.
input: Item<bool>,
) -> Item<bool> {
let (input, attributes) = input.into_parts();
Item::from_parts(!input, attributes)
}
/// Evaluates either the "If True" or "If False" input branch based on whether the input condition is true or false.
#[node_macro::node(category("Routing"), icon("NodeSwitch"))]
fn switch<T: Send>(
ctx: impl Ctx + CloneVarArgs + ExtractAll,
condition: Item<bool>,
#[expose]
#[implementations(
Context -> Item<String>,
Context -> Item<bool>,
Context -> Item<f64>,
Context -> Item<i64>,
Context -> Item<DVec2>,
Context -> Item<DAffine2>,
Context -> Item<Vector>,
Context -> Item<Graphic>,
Context -> Item<Raster<CPU>>,
Context -> Item<Raster<GPU>>,
Context -> Item<Color>,
Context -> Item<Gradient>,
Context -> Item<Generator>,
Context -> Item<Artboard>,
Context -> Item<Bundle<String>>,
Context -> Item<Bundle<bool>>,
Context -> Item<Bundle<f64>>,
Context -> Item<Bundle<i64>>,
Context -> Item<Bundle<DVec2>>,
Context -> Item<Bundle<DAffine2>>,
Context -> Item<Bundle<Vector>>,
Context -> Item<Bundle<Graphic>>,
Context -> Item<Bundle<Raster<CPU>>>,
Context -> Item<Bundle<Raster<GPU>>>,
Context -> Item<Bundle<Color>>,
Context -> Item<Bundle<Gradient>>,
Context -> Item<Bundle<Generator>>,
Context -> Item<Bundle<Artboard>>,
)]
if_true: impl Node<Context<'static>, Output = Item<T>>,
#[expose]
#[implementations(
Context -> Item<String>,
Context -> Item<bool>,
Context -> Item<f64>,
Context -> Item<i64>,
Context -> Item<DVec2>,
Context -> Item<DAffine2>,
Context -> Item<Vector>,
Context -> Item<Graphic>,
Context -> Item<Raster<CPU>>,
Context -> Item<Raster<GPU>>,
Context -> Item<Color>,
Context -> Item<Gradient>,
Context -> Item<Generator>,
Context -> Item<Artboard>,
Context -> Item<Bundle<String>>,
Context -> Item<Bundle<bool>>,
Context -> Item<Bundle<f64>>,
Context -> Item<Bundle<i64>>,
Context -> Item<Bundle<DVec2>>,
Context -> Item<Bundle<DAffine2>>,
Context -> Item<Bundle<Vector>>,
Context -> Item<Bundle<Graphic>>,
Context -> Item<Bundle<Raster<CPU>>>,
Context -> Item<Bundle<Raster<GPU>>>,
Context -> Item<Bundle<Color>>,
Context -> Item<Bundle<Gradient>>,
Context -> Item<Bundle<Generator>>,
Context -> Item<Bundle<Artboard>>,
)]
if_false: impl Node<Context<'static>, Output = Item<T>>,
) -> Result<Item<T>, Interrupt> {
let ctx = OwnedContextImpl::from(ctx).into_context();
if *condition.element() { if_true.eval(&ctx) } else { if_false.eval(&ctx) }
}
/// Constructs a `Bool` value which may be set to true or false.
#[node_macro::node(category("Value"), icon("NodeBoolValue"))]
fn bool_value(_: impl Ctx, _primary: (), #[name("Bool")] bool_value: Item<bool>) -> Item<bool> {
bool_value
}
/// Constructs a number value which may be set to any real number.
#[node_macro::node(category("Value"), icon("NodeNumberValue"))]
fn number_value(_: impl Ctx, _primary: (), number: Item<f64>) -> Item<f64> {
number
}
/// Constructs a number value which may be set to any value from 0% to 100% by dragging the slider.
#[node_macro::node(category("Value"), icon("NodePercentageValue"))]
fn percentage_value(
_: impl Ctx,
_primary: (),
#[unit("%")]
#[range]
#[hard(0..100)]
percentage: Item<f64>,
) -> Item<f64> {
percentage
}
/// Constructs a vec2 value, a two-dimensional quantity which may be set to any XY pair.
#[node_macro::node(category("Value"), icon("NodeVec2Value"), name("Vec2 Value"))]
fn vec2_value(_: impl Ctx, _primary: (), #[name("Vec2")] vec2: Item<DVec2>) -> Item<DVec2> {
vec2
}
/// Constructs a color value which may be set to any color.
#[node_macro::node(category("Value"), icon("NodeColorValue"))]
fn color_value(_: impl Ctx, _primary: (), #[default(Color::BLACK)] color: Item<Color>) -> Item<Color> {
color
}
/// Constructs a color value from red, green, blue, and alpha components given as numbers from 0 to 1.
#[node_macro::node(category("Color"), icon("NodeRgbaToColor"), name("RGBA to Color"))]
fn rgba_to_color(
_: impl Ctx,
_primary: (),
#[range]
#[hard(0..1)]
red: Item<f64>,
#[range]
#[hard(0..1)]
green: Item<f64>,
#[range]
#[hard(0..1)]
blue: Item<f64>,
#[range]
#[hard(0..1)]
#[default(1.)]
alpha: Item<f64>,
) -> Item<Color> {
let red = *red.element() as f32;
let green = *green.element() as f32;
let blue = *blue.element() as f32;
let alpha = *alpha.element() as f32;
// RGB user inputs are interpreted as sRGB display values; lift to linear-light for the internal `Color`
Item::new_from_element(Color::from_gamma_srgb_channels(red, green, blue, alpha))
}
/// Constructs a color value from hue, saturation, value, and alpha components given as numbers from 0 to 1.
#[node_macro::node(category("Color"), icon("NodeHsvaToColor"), name("HSVA to Color"))]
fn hsva_to_color(
_: impl Ctx,
_primary: (),
// Hue is periodic, so a value past either end wraps around instead of clamping
#[range]
#[soft(0..1)]
hue: Item<f64>,
#[range]
#[hard(0..1)]
#[default(1.)]
saturation: Item<f64>,
#[range]
#[hard(0..1)]
#[default(1.)]
value: Item<f64>,
#[range]
#[hard(0..1)]
#[default(1.)]
alpha: Item<f64>,
) -> Item<Color> {
let hue = (*hue.element() as f32) - (*hue.element() as f32).floor();
let saturation = *saturation.element() as f32;
let value = *value.element() as f32;
let alpha = *alpha.element() as f32;
Item::new_from_element(Color::from_hsva(hue, saturation, value, alpha))
}
/// Constructs a color value from hue, saturation, lightness, and alpha components given as numbers from 0 to 1.
#[node_macro::node(category("Color"), icon("NodeHslaToColor"), name("HSLA to Color"))]
fn hsla_to_color(
_: impl Ctx,
_primary: (),
#[range]
#[soft(0..1)]
hue: Item<f64>,
#[range]
#[hard(0..1)]
#[default(1.)]
saturation: Item<f64>,
#[range]
#[hard(0..1)]
#[default(0.5)]
lightness: Item<f64>,
#[range]
#[hard(0..1)]
#[default(1.)]
alpha: Item<f64>,
) -> Item<Color> {
let hue = (*hue.element() as f32) - (*hue.element() as f32).floor();
let saturation = *saturation.element() as f32;
let lightness = *lightness.element() as f32;
let alpha = *alpha.element() as f32;
Item::new_from_element(Color::from_hsla(hue, saturation, lightness, alpha))
}
/// A string that isn't a CSS color.
#[derive(Debug, thiserror::Error)]
pub enum StringToColorError {
#[error("`{0}` isn't a valid color")]
InvalidColor(String),
}
/// Constructs a color value from a CSS color string. Accepts hex (`#RRGGBB`, `#RRGGBBAA`, plus bare and shorthand variants), CSS named colors (like `red`), and functional notations (`rgb(...)`, `hsl(...)`, etc.). An empty string produces a transparent color.
#[node_macro::node(category("Color"), icon("NodeStringToColor"), name("String to Color"))]
fn string_to_color(_: impl Ctx, string: Item<String>) -> Result<Item<Color>, StringToColorError> {
let string = string.into_element();
if string.trim().is_empty() {
return Ok(Item::new_from_element(Color::default()));
}
let color = core_types::misc::parse_css_color(&string).ok_or(StringToColorError::InvalidColor(string))?;
Ok(Item::new_from_element(color))
}
/// Constructs a gradient value which may be set to any sequence of color stops to represent the transition between colors.
#[node_macro::node(category("Value"), icon("NodeGradientValue"))]
fn gradient_value(_: impl Ctx, _primary: (), #[default(Color::BLACK, Color::WHITE)] gradient: Item<Gradient>) -> Item<Gradient> {
gradient
}
/// Sets the form (linear or radial) of each gradient in the input list.
#[node_macro::node(category("Gradient"), icon("NodeGradientForm"))]
fn gradient_form(_: impl Ctx, gradient: Item<Gradient>, gradient_form: Item<vector_types::GradientForm>) -> Item<Gradient> {
let mut gradient = gradient;
gradient.set_attribute(core_types::ATTR_GRADIENT_FORM, *gradient_form.element());
gradient
}
/// Sets how each gradient in the input list extends past its endpoints: Pad, Reflect, Repeat, or Clear.
#[node_macro::node(category("Gradient"), icon("NodeGradientSpread"))]
fn gradient_spread(_: impl Ctx, gradient: Item<Gradient>, gradient_spread: Item<vector_types::GradientSpread>) -> Item<Gradient> {
let mut gradient = gradient;
gradient.set_attribute(core_types::ATTR_GRADIENT_SPREAD, *gradient_spread.element());
gradient
}
/// Sets the color space in which each gradient in the input list interpolates between its stops.
#[node_macro::node(category("Gradient"), icon("NodeGradientSpace"))]
fn gradient_space(_: impl Ctx, gradient: Item<Gradient>, space: Item<vector_types::GradientSpace>) -> Item<Gradient> {
let mut gradient = gradient;
gradient.set_attribute(core_types::ATTR_GRADIENT_SPACE, *space.element());
gradient
}
/// Sets the path each gradient in the input list interpolates along, deciding whether it jumps, turns corners, or flows smoothly through its stops.
#[node_macro::node(category("Gradient"), icon("NodeGradientInterpolation"))]
fn gradient_interpolation(_: impl Ctx, gradient: Item<Gradient>, interpolation: Item<vector_types::GradientInterpolation>) -> Item<Gradient> {
let mut gradient = gradient;
gradient.set_attribute(core_types::ATTR_GRADIENT_INTERPOLATION, *interpolation.element());
gradient
}
/// Sets whether each gradient in the input list treats its stops as a cycle, interpolating from the last stop back around to the first.
#[node_macro::node(category("Gradient"), icon("NodeGradientCyclic"))]
fn gradient_cyclic(_: impl Ctx, gradient: Item<Gradient>, cyclic: Item<bool>) -> Item<Gradient> {
let mut gradient = gradient;
gradient.set_attribute(core_types::ATTR_GRADIENT_CYCLIC, *cyclic.element());
gradient
}
/// Sets which way around the hue wheel each gradient in the input list interpolates, for polar color spaces.
#[node_macro::node(category("Gradient"), icon("NodeGradientHueDirection"))]
fn gradient_hue_direction(_: impl Ctx, gradient: Item<Gradient>, hue_direction: Item<vector_types::GradientHueDirection>) -> Item<Gradient> {
let mut gradient = gradient;
gradient.set_attribute(core_types::ATTR_GRADIENT_HUE_DIRECTION, *hue_direction.element());
gradient
}
/// Sets the position of each of a gradient's stops, a factor from 0 to 1 along the gradient.
///
/// A list shorter than the stop count repeats its last value, a longer list is truncated, and an empty list sets each stop to its default evenly spaced position.
#[node_macro::node(category("Gradient"), icon("NodeGradientPositions"))]
fn gradient_positions(_: impl Ctx, gradient: Item<Gradient>, positions: List<f64>) -> Item<Gradient> {
let mut gradient = gradient;
let positions: Vec<f64> = positions.iter_element_values().copied().collect();
gradient.element_mut().set_positions(&positions);
gradient
}
/// Skews how rapidly the color flows across each interval between color stops, bunching up the transition toward one end instead of progressing uniformly. Each value places the halfway color within its corresponding interval, measured as a fraction of the distance (0 to 1) between the adjacent stops. A 0.5 midpoint keeps a uniform transition rate through the interval.
///
/// Non-cyclic gradients have no interval following the last stop, meaning the midpoint is ignored in that position.
///
/// A list shorter than the stop count repeats its last value, a longer list is truncated, and an empty list sets each midpoint to its default of 0.5.
#[node_macro::node(category("Gradient"), icon("NodeGradientMidpoints"))]
fn gradient_midpoints(_: impl Ctx, gradient: Item<Gradient>, midpoints: List<f64>) -> Item<Gradient> {
let mut gradient = gradient;
let midpoints: Vec<f64> = midpoints.iter_element_values().copied().collect();
gradient.element_mut().set_midpoints(&midpoints);
gradient
}
/// Reverses the order of each gradient's stops, moving the color at the start of the ramp to the end and vice versa.
#[node_macro::node(category("Gradient"), icon("NodeGradientReverse"))]
fn gradient_reverse(_: impl Ctx, gradient: Item<Gradient>) -> Item<Gradient> {
let settings = vector_types::GradientSettings::from(&gradient);
let mut gradient = gradient;
let reversed = gradient.element().reversed(settings.cyclic);
*gradient.element_mut() = reversed;
gradient
}
/// Shifts every stop along each gradient's ramp, sliding the colors within the gradient without moving the gradient itself.
///
/// The fraction is measured against the whole ramp. A cyclic gradient spins, wrapping past the end back around to the start so 1 is a full turn that lands where it began. A gradient that isn't cyclic has no loop to spin around, so its stops slide off the end and keep going, leaving the visible ramp to blend between whichever colors still span it.
#[node_macro::node(category("Gradient"), icon("NodeGradientShift"))]
fn gradient_shift(
_: impl Ctx,
gradient: Item<Gradient>,
#[range]
#[soft(-1..1)]
fraction: Item<f64>,
) -> Item<Gradient> {
let settings = vector_types::GradientSettings::from(&gradient);
let mut gradient = gradient;
gradient.element_mut().shift_positions(*fraction.element(), settings.cyclic);
gradient
}
/// Stretches or squeezes the spacing of each gradient's stops around a pivot, spreading the colors within the gradient without moving the gradient itself.
///
/// The factor multiplies every stop's distance from the pivot, so 2 spreads the ramp over twice its span while 0.5 packs it into half. A negative factor mirrors the stops across the pivot, reversing the order of the colors.
///
/// The pivot is the one point that stays put, measured against the whole ramp from 0 at the start to 1 at the end.
#[node_macro::node(category("Gradient"), icon("NodeGradientStretch"))]
fn gradient_stretch(
_: impl Ctx,
gradient: Item<Gradient>,
#[default(1.)]
#[unit("x")]
factor: Item<f64>,
#[default(0.5)]
#[range]
#[soft(0..1)]
pivot: Item<f64>,
) -> Item<Gradient> {
let settings = vector_types::GradientSettings::from(&gradient);
let mut gradient = gradient;
gradient.element_mut().stretch_positions(*factor.element(), *pivot.element(), settings.cyclic);
gradient
}
/// Evaluates the color at the specified position along the gradient, given a position from 0 (left) to 1 (right). Positions beyond that range follow the gradient's `gradient_spread` attribute: Pad (default), Reflect, Repeat, or Clear. Colors between stops interpolate in the gradient's `gradient_space` color space.
#[node_macro::node(category("Color"), icon("NodeEvaluateGradient"))]
fn evaluate_gradient(
_: impl Ctx,
_primary: (),
#[default(Color::BLACK, Color::WHITE)] gradient: Item<Gradient>,
#[range]
#[soft(0..1)]
position: Item<f64>,
) -> Item<Color> {
let gradient = raster_kernels::evaluate_gradient_effects(gradient);
let settings = vector_types::GradientSettings::from(&gradient);
let color = gradient.element().evaluate(*position.element(), settings);
Item::new_from_element(color)
}
/// Constructs a footprint value which may be set to any transformation of a unit square describing a render area, and a render resolution at least 1x1 integer pixels.
#[node_macro::node(category("Value"), icon("NodeFootprintValue"))]
fn footprint_value(
_: impl Ctx,
_primary: (),
transform: Item<DAffine2>,
#[unit(" px")]
#[hard(1..)]
#[default(100., 100.)]
resolution: Item<DVec2>,
) -> Item<Footprint> {
Item::new_from_element(Footprint {
transform: *transform.element(),
resolution: resolution.element().as_uvec2(),
..Default::default()
})
}
/// Composes a vec2 from its X and Y components.
///
/// The inverse of this node is **Vec2 to Numbers**, which decomposes a vec2 back into its X and Y components.
#[node_macro::node(category("Math: Vec2"), icon("NodeNumbersToVec2"), name("Numbers to Vec2"))]
fn numbers_to_vec2(
_: impl Ctx,
_primary: (),
/// The X component of the vec2.
#[expose]
x: Item<f64>,
/// The Y component of the vec2.
#[expose]
y: Item<f64>,
) -> Item<DVec2> {
Item::new_from_element(DVec2::new(*x.element(), *y.element()))
}
/// The X and Y components of a vec2, split into separate node outputs.
#[derive(Debug, Clone, PartialEq, dyn_any::DynAny, node_macro::Destructure)]
pub struct Vec2Components {
/// The X component of the vec2.
pub x: Item<f64>,
/// The Y component of the vec2.
pub y: Item<f64>,
}
/// Decomposes the X and Y components of a vec2.
///
/// The inverse of this node is **Numbers to Vec2**, which composes a vec2 from its X and Y components.
#[node_macro::node(category("Math: Vec2"), icon("NodeVec2ToNumbers"), name("Vec2 to Numbers"))]
fn vec2_to_numbers(_: impl Ctx, #[name("Vec2")] vec2: Item<DVec2>) -> Vec2Components {
let (vec2, attributes) = vec2.into_parts();
Vec2Components {
x: Item::from_parts(vec2.x, attributes.clone()),
y: Item::from_parts(vec2.y, attributes),
}
}
/// Divides a vec2 by its largest absolute component, so normalizing it can't overflow or underflow; a zero or non-finite vec2 gets a NaN component.
fn scaled_to_unit_box(vec2: DVec2) -> DVec2 {
vec2 / vec2.abs().max_element()
}
/// The dot product operation (`·`) calculates the degree of similarity of a vec2 pair based on their angles and lengths.
///
/// Calculated as `‖a‖‖b‖cos(θ)`, it represents the product of their lengths (`‖a‖‖b‖`) scaled by the alignment of their directions (`cos(θ)`).
/// The output ranges from the positive to negative product of their lengths based on when they are pointing in the same or opposite directions.
/// If either vec2 has zero length, the output is 0.
#[node_macro::node(category("Math: Vec2"), icon("NodeDotProduct"))]
fn dot_product(
_: impl Ctx,
/// An operand of the dot product operation.
value: Item<DVec2>,
/// The other operand of the dot product operation.
#[default(1., 0.)]
other_value: Item<DVec2>,
/// Whether to normalize both input vec2s so the calculation ranges in `[-1, 1]` by considering only their degree of directional alignment.
normalize: Item<bool>,
) -> Item<f64> {
let (value, attributes) = value.into_parts();
let other_value = *other_value.element();
let result = if *normalize.element() {
scaled_to_unit_box(value).normalize_or_zero().dot(scaled_to_unit_box(other_value).normalize_or_zero())
} else {
value.dot(other_value)
};
Item::from_parts(result, attributes)
}
/// The cross product operation (`×`) calculates the signed area of the parallelogram formed by a vec2 pair.
///
/// The sign gives the rotation direction from the first vec2 to the second: positive for clockwise, negative for counterclockwise, and 0 when both are parallel, as drawn in the viewport.
#[node_macro::node(category("Math: Vec2"), icon("NodeCrossProduct"))]
fn cross_product(
_: impl Ctx,
/// The vec2 on the left-hand side of the cross product operation.
value: Item<DVec2>,
/// The vec2 on the right-hand side of the cross product operation.
#[default(1., 0.)]
other_value: Item<DVec2>,
) -> Item<f64> {
let (value, attributes) = value.into_parts();
Item::from_parts(value.perp_dot(*other_value.element()), attributes)
}
/// Calculates the angle swept between two vec2s.
///
/// The angle ranges from -180° to 180° (or -π to π radians) and its sign gives the sweep direction from the "Direction From" input to the "Direction To" input: positive for clockwise, negative for counterclockwise, as drawn in the viewport and matching the direction convention of the Transform node's rotation.
#[node_macro::node(category("Math: Vec2"), icon("NodeAngleBetween"))]
fn angle_between(
_: impl Ctx,
/// The direction the angle is measured from.
direction_from: Item<DVec2>,
/// The direction the angle is measured to.
#[default(1., 0.)]
direction_to: Item<DVec2>,
/// Whether the resulting angle should be given in radians instead of degrees.
radians: Item<bool>,
) -> Item<f64> {
let (direction_from, attributes) = direction_from.into_parts();
let direction_to = *direction_to.element();
if direction_from == DVec2::ZERO || direction_to == DVec2::ZERO {
return Item::from_parts(0., attributes);
}
let (from, to) = (scaled_to_unit_box(direction_from), scaled_to_unit_box(direction_to));
let angle = from.perp_dot(to).atan2(from.dot(to));
let result = if *radians.element() { angle } else { angle.to_degrees() };
Item::from_parts(result, attributes)
}
pub trait ToPosition {
fn to_position(self) -> DVec2;
}
impl ToPosition for DVec2 {
fn to_position(self) -> DVec2 {
self
}
}
impl ToPosition for DAffine2 {
fn to_position(self) -> DVec2 {
self.translation
}
}
/// Calculates the angle needed for a rightward-facing object placed at the "Position From" point to turn so it points toward the "Position To" point.
#[node_macro::node(category("Math: Vec2"), icon("NodeAngleTo"))]
fn angle_to<T: ToPosition, U: ToPosition>(
_: impl Ctx,
/// The position from which the angle is measured.
#[implementations(DVec2, DAffine2, DVec2, DAffine2)]
position_from: Item<T>,
/// The position toward which the angle is measured.
#[expose]
#[implementations(DVec2, DVec2, DAffine2, DAffine2)]
position_to: Item<U>,
/// Whether the resulting angle should be given in radians instead of degrees.
radians: Item<bool>,
) -> Item<f64> {
let (position_from, attributes) = position_from.into_parts();
let from = position_from.to_position();
let to = position_to.into_element().to_position();
let delta = to - from;
let angle = delta.y.atan2(delta.x);
let result = if *radians.element() { angle } else { angle.to_degrees() };
Item::from_parts(result, attributes)
}
/// The magnitude operator (`‖x‖`) calculates the length of a vec2, which is the distance from the base to the tip of the arrow it represents.
#[node_macro::node(category("Math: Vec2"), icon("NodeMagnitude"))]
fn magnitude(_: impl Ctx, vec2: Item<DVec2>) -> Item<f64> {
let (vec2, attributes) = vec2.into_parts();
Item::from_parts(vec2.length(), attributes)
}
/// Measures the distance between two points, which is the length of the straight line segment connecting them.
#[node_macro::node(category("Math: Vec2"), icon("NodeDistance"))]
fn distance(
_: impl Ctx,
/// The point the distance is measured from.
position_from: Item<DVec2>,
/// The point the distance is measured to.
position_to: Item<DVec2>,
) -> Item<f64> {
let (position_from, attributes) = position_from.into_parts();
Item::from_parts(position_from.distance(*position_to.element()), attributes)
}
/// Scales the input vec2 to unit length while preserving its direction. This is equivalent to dividing the input vec2 by its own magnitude.
///
/// Returns 0 when the input vec2 has zero length.
#[node_macro::node(category("Math: Vec2"), icon("NodeNormalize"))]
fn normalize(_: impl Ctx, vec2: Item<DVec2>) -> Item<DVec2> {
let (vec2, attributes) = vec2.into_parts();
Item::from_parts(scaled_to_unit_box(vec2).normalize_or_zero(), attributes)
}
#[cfg(test)]
mod test {
use super::*;
use core_types::generic::FnNode;
use core_types::{Node, concrete};
#[test]
pub fn dot_product_function() {
let vector_a = Item::new_from_element(DVec2::new(1., 2.));
let vector_b = Item::new_from_element(DVec2::new(3., 4.));
assert_eq!(dot_product((), vector_a, vector_b, Item::new_from_element(false)).into_element(), 11.);
}
#[test]
pub fn magnitude_function() {
let vector = Item::new_from_element(DVec2::new(3., 4.));
assert_eq!(magnitude((), vector).into_element(), 5.);
}
#[test]
pub fn distance_function() {
let (position_from, position_to) = (Item::new_from_element(DVec2::new(1., 2.)), Item::new_from_element(DVec2::new(4., 6.)));
assert_eq!(distance((), position_from, position_to).into_element(), 5.);
}
#[test]
pub fn cross_product_sign() {
let vec2 = |x, y| Item::new_from_element(DVec2::new(x, y));
assert_eq!(cross_product((), vec2(1., 0.), vec2(0., 1.)).into_element(), 1.);
assert_eq!(cross_product((), vec2(0., 1.), vec2(1., 0.)).into_element(), -1.);
assert_eq!(cross_product((), vec2(2., 2.), vec2(1., 1.)).into_element(), 0.);
}
#[test]
pub fn sign_of_negative_zero_is_positive_zero() {
let result = sign((), Item::new_from_element(-0.0_f64)).into_element();
assert_eq!(result, 0.);
assert!(result.is_sign_positive());
}
#[test]
pub fn sign_componentwise() {
assert_eq!(sign((), Item::new_from_element(DVec2::new(-5., 3.))).into_element(), DVec2::new(-1., 1.));
}
#[test]
pub fn lerp_endpoints_are_exact() {
let lerp_between = |factor, clamped| {
lerp(
(),
Item::new_from_element(3.),
Item::new_from_element(7.),
Item::new_from_element(factor),
Item::new_from_element(clamped),
)
.into_element()
};
assert_eq!(lerp_between(0., true), 3.);
assert_eq!(lerp_between(1., true), 7.);
assert_eq!(lerp_between(0.5, true), 5.);
}
#[test]
pub fn lerp_clamped_and_extrapolated() {
let lerp_between = |factor, clamped| {
lerp(
(),
Item::new_from_element(0.),
Item::new_from_element(10.),
Item::new_from_element(factor),
Item::new_from_element(clamped),
)
.into_element()
};
assert_eq!(lerp_between(2., true), 10.);
assert_eq!(lerp_between(2., false), 20.);
}
#[test]
pub fn lerp_endpoint_factors_pass_endpoints_through() {
let lerp_between = |start: f64, end: f64, factor| {
lerp(
(),
Item::new_from_element(start),
Item::new_from_element(end),
Item::new_from_element(factor),
Item::new_from_element(true),
)
.into_element()
};
assert_eq!(lerp_between(3., f64::INFINITY, 0.), 3.);
assert_eq!(lerp_between(f64::NAN, 7., 1.), 7.);
assert_eq!(lerp_between(3., f64::INFINITY, 1.), f64::INFINITY);
assert!(lerp_between(-0., 7., 0.).is_sign_negative());
assert!(lerp_between(5., -0., 1.).is_sign_negative());
}
#[test]
pub fn angle_between_signed() {
let right = DVec2::new(1., 0.);
let down = DVec2::new(0., 1.);
let angle = |a, b, radians| angle_between((), Item::new_from_element(a), Item::new_from_element(b), Item::new_from_element(radians)).into_element();
assert_eq!(angle(right, down, false), 90.);
assert_eq!(angle(down, right, false), -90.);
}
#[test]
pub fn angle_between_zero_vector() {
let (zero, right) = (Item::new_from_element(DVec2::ZERO), Item::new_from_element(DVec2::new(1., 0.)));
assert_eq!(angle_between((), zero, right, Item::new_from_element(false)).into_element(), 0.);
}
#[test]
pub fn clamp_vec2_within_swapped_bounds() {
let vec2 = |x, y| Item::new_from_element(DVec2::new(x, y));
assert_eq!(clamp((), vec2(-5., 5.), vec2(1., 1.), vec2(0., 2.)).into_element(), DVec2::new(0., 2.));
}
#[test]
pub fn min_max_vec2_with_scalar() {
let vec2 = |x, y| Item::new_from_element(DVec2::new(x, y));
assert_eq!(super::min((), vec2(-5., 5.), Item::new_from_element(0_f64)).into_element(), DVec2::new(-5., 0.));
assert_eq!(super::max((), vec2(-5., 5.), Item::new_from_element(0_f64)).into_element(), DVec2::new(0., 5.));
}
#[test]
pub fn scalar_with_vec2_operand_orders() {
let vec2 = |x, y| Item::new_from_element(DVec2::new(x, y));
assert_eq!(super::min((), Item::new_from_element(0_f64), vec2(-5., 5.)).into_element(), DVec2::new(-5., 0.));
assert_eq!(super::max((), Item::new_from_element(0_f64), vec2(-5., 5.)).into_element(), DVec2::new(0., 5.));
assert_eq!(exponent((), Item::new_from_element(2_f64), vec2(2., 3.)).unwrap().into_element(), DVec2::new(4., 8.));
assert_eq!(root((), Item::new_from_element(64_f64), vec2(2., 3.)).into_element(), DVec2::new(8., 4.));
assert_eq!(logarithm((), Item::new_from_element(8_f64), vec2(2., 10.)).into_element(), DVec2::new(3., 8_f64.log10()));
assert_eq!(clamp((), Item::new_from_element(5_f64), vec2(0., 6.), vec2(1., 10.)).into_element(), DVec2::new(1., 6.));
}
#[test]
pub fn vec2_degrees_and_bases() {
let vec2 = |x, y| Item::new_from_element(DVec2::new(x, y));
assert_eq!(root((), vec2(64., 27.), vec2(2., 3.)).into_element(), DVec2::new(8., 3.));
assert_eq!(logarithm((), vec2(8., 100.), vec2(2., 10.)).into_element(), DVec2::new(3., 2.));
}
#[test]
fn integer_lane_keeps_integers_and_rounds_fractions() {
let integer = |value: i64, expression: &str| {
math_function(
(),
&ParseCache::default(),
Item::new_from_element(value),
Item::new_from_element(expression.to_string()),
Item::new_from_element(0_i64),
)
.unwrap()
.into_element()
};
assert_eq!(integer(3, "x * 2"), 6);
assert_eq!(integer(3, "x / 2"), 2, "1.5 rounds away from zero");
assert_eq!(integer(-3, "x / 2"), -2, "-1.5 rounds away from zero");
assert_eq!(integer(3, "x * 1.1 / 1.1"), 3, "float noise snaps back to the whole number");
let items: List<i64> = [1_i64, 2, 4].into_iter().map(Item::new_from_element).collect();
assert_eq!(
math_aggregate((), items, Item::new_from_element("mean".to_string()), Item::new_from_element(0_i64))
.unwrap()
.into_element(),
2,
"7/3 rounds to 2"
);
}
#[test]
fn output_type_witness_picks_the_output_rung() {
// The witness input's type, not the input value's, decides how the result is read
assert_eq!(
math_function(
(),
&ParseCache::default(),
Item::new_from_element(2.5),
Item::new_from_element("x * 2".to_string()),
Item::new_from_element(0_i64)
)
.unwrap()
.into_element(),
5
);
assert!(
math_function(
(),
&ParseCache::default(),
Item::new_from_element(3_i64),
Item::new_from_element("x > 2".to_string()),
Item::new_from_element(false)
)
.unwrap()
.into_element()
);
assert_eq!(
math_function(
(),
&ParseCache::default(),
Item::new_from_element(true),
Item::new_from_element("x / 2".to_string()),
Item::new_from_element(0.)
)
.unwrap()
.into_element(),
0.5
);
let items: List<f64> = [1., 2.].into_iter().map(Item::new_from_element).collect();
assert_eq!(
math_aggregate((), items, Item::new_from_element("mean".to_string()), Item::new_from_element(0_i64))
.unwrap()
.into_element(),
2,
"1.5 rounds to 2"
);
}
#[test]
pub fn round_floor_ceiling_vec2() {
let vec2 = |x, y| Item::new_from_element(DVec2::new(x, y));
assert_eq!(round((), vec2(1.5, -1.4)).into_element(), DVec2::new(2., -1.));
assert_eq!(floor((), vec2(1.9, -1.1)).into_element(), DVec2::new(1., -2.));
assert_eq!(ceiling((), vec2(1.1, -1.9)).into_element(), DVec2::new(2., -1.));
}
#[test]
fn test_basic_expression() {
let result = math_function(
(),
&ParseCache::default(),
Item::new_from_element(0.),
Item::new_from_element("2 + 2".to_string()),
Item::new_from_element(0.),
);
assert_eq!(result.unwrap().into_element(), 4.);
}
#[test]
fn test_complex_expression() {
let result = math_function(
(),
&ParseCache::default(),
Item::new_from_element(0.),
Item::new_from_element("(5 * 3) + (10 / 2)".to_string()),
Item::new_from_element(0.),
);
assert_eq!(result.unwrap().into_element(), 20.);
}
#[test]
fn test_variable_binding() {
let result = math_function(
(),
&ParseCache::default(),
Item::new_from_element(7.),
Item::new_from_element("x * 2".to_string()),
Item::new_from_element(0.),
);
assert_eq!(result.unwrap().into_element(), 14.);
}
#[test]
fn test_invalid_expression() {
let result = math_function(
(),
&ParseCache::default(),
Item::new_from_element(0.),
Item::new_from_element("invalid".to_string()),
Item::new_from_element(0.),
);
assert_eq!(result.unwrap_err().0.into_element(), 0.);
}
#[test]
fn expressions_parse_once_per_source() {
let cache = ParseCache::default();
let first = cache.parse("x * 2").unwrap();
assert!(Arc::ptr_eq(&first, &cache.parse("x * 2").unwrap()));
assert!(!Arc::ptr_eq(&first, &cache.parse("x * 3").unwrap()));
assert!(cache.parse("invalid(").is_err());
}
#[test]
fn test_boolean_items() {
// Booleans read as exactly 0 and 1, and logical results convert back
let as_bool = Item::new_from_element(false);
assert!(
!math_function((), &ParseCache::default(), Item::new_from_element(true), Item::new_from_element("!x".to_string()), as_bool.clone())
.unwrap()
.into_element()
);
assert!(
math_function((), &ParseCache::default(), Item::new_from_element(false), Item::new_from_element("x == 0".to_string()), as_bool.clone())
.unwrap()
.into_element()
);
// A result that is not exactly 0 or 1 cannot be a truth value, so the input passes through
let (stand_in, error) = math_function((), &ParseCache::default(), Item::new_from_element(true), Item::new_from_element("x + 1".to_string()), as_bool.clone()).unwrap_err();
assert!(stand_in.into_element());
assert!(matches!(&error, MathExpressionError::OutputType { output_type, .. } if output_type == "Bool"));
// An input that is not exactly 0 or 1 cannot pass through as a truth value either, so the output falls back to false
let (stand_in, error) = math_function((), &ParseCache::default(), Item::new_from_element(2.), Item::new_from_element("x + 1".to_string()), as_bool.clone()).unwrap_err();
assert!(!stand_in.into_element());
assert!(matches!(&error, MathExpressionError::InputType(output_type) if output_type == "Bool"));
let bools = || [true, true, false].into_iter().map(Item::new_from_element).collect::<List<bool>>();
assert!(!math_aggregate((), bools(), Item::new_from_element("&&".to_string()), as_bool.clone()).unwrap().into_element());
assert!(math_aggregate((), bools(), Item::new_from_element("||".to_string()), as_bool.clone()).unwrap().into_element());
assert!(!math_aggregate((), bools(), Item::new_from_element("xor".to_string()), as_bool).unwrap().into_element());
}
#[test]
fn test_transform_items() {
fn fx<T: ExpressionValue, U: ExpressionValue>(value: T, expression: &str, output_type: U) -> Result<U, U> {
math_function(
(),
&ParseCache::default(),
Item::new_from_element(value),
Item::new_from_element(expression.to_string()),
Item::new_from_element(output_type),
)
.map(Item::into_element)
.map_err(|(stand_in, _)| stand_in.into_element())
}
let shear = DAffine2::from_cols(DVec2::new(1., 0.), DVec2::new(0.5, 1.), DVec2::new(5., 4.));
// A Transform binds as `X`, and a matrix result reads back as one, so the default `x` passes it through
assert_eq!(fx(shear, "x", shear), Ok(shear));
assert_eq!(fx(shear, "X (2i + 2j)", DVec2::ZERO), Ok(DVec2::new(8., 6.)));
assert_eq!(fx(shear, "X^-1 X", shear), Ok(DAffine2::IDENTITY));
assert_eq!(
fx(shear, "linear(X) + 1i", DAffine2::IDENTITY),
Ok(DAffine2::from_cols(DVec2::new(1., 0.), DVec2::new(0.5, 1.), DVec2::X))
);
assert_eq!(fx(2., "rotation(pi/2) + x i", DAffine2::IDENTITY).unwrap().translation, DVec2::new(2., 0.));
assert_eq!(fx(shear, "det(X)", 0.), Ok(1.));
// A value, or a matrix touching the weight, is no Transform, so the input passes through
assert_eq!(fx(shear, "X 0", DAffine2::IDENTITY), Err(shear));
assert_eq!(fx(shear, "[1;i] + X 0", DAffine2::IDENTITY), Err(shear));
// A Transform can't pass through as a Number, so the output falls back to its default
assert_eq!(fx(shear, "x", 0.), Err(0.));
// A Transform list binds as `A`, `B`, `C` in a formula, and an operator composes, averages, or counts across it
let scale = DAffine2::from_scale(DVec2::splat(2.));
let items = || [shear, scale].into_iter().map(Item::new_from_element).collect::<List<DAffine2>>();
fn formula<U: ExpressionValue>(items: List<DAffine2>, expression: &str, output_type: U) -> Result<U, MathExpressionError> {
math_formula((), &ParseCache::default(), items, Item::new_from_element(expression.to_string()), Item::new_from_element(output_type)).map(Item::into_element)
}
fn aggregate<U: ExpressionValue>(items: List<DAffine2>, operator: &str, output_type: U) -> Result<U, MathExpressionError> {
math_aggregate((), items, Item::new_from_element(operator.to_string()), Item::new_from_element(output_type)).map(Item::into_element)
}
assert_eq!(formula(items(), "A B", DAffine2::IDENTITY).unwrap(), shear * scale);
assert_eq!(formula(items(), "A C", DAffine2::IDENTITY).unwrap(), shear);
assert_eq!(aggregate(items(), "*", DAffine2::IDENTITY).unwrap(), shear * scale);
assert_eq!(aggregate(items(), "/", DAffine2::IDENTITY).unwrap(), shear * scale.inverse());
assert_eq!(aggregate(items(), "mean", DAffine2::IDENTITY).unwrap().translation, DVec2::new(2.5, 2.));
assert_eq!(aggregate(items(), "count", 0.).unwrap(), 2.);
assert_eq!(formula(items(), "det(A)", 0.).unwrap(), 1.);
assert!(matches!(aggregate(items(), "min", DAffine2::IDENTITY), Err(MathExpressionError::NoReduction { .. })));
assert!(formula(items(), "a", DAffine2::IDENTITY).is_err());
// A sum of Transforms doubles the weight row, so it reads as no Transform
assert!(matches!(
aggregate(items(), "+", DAffine2::IDENTITY),
Err(MathExpressionError::OutputType { output_type, .. }) if output_type == "Transform"
));
}
#[test]
fn test_vec2_items() {
fn fx<T: ExpressionValue, U: ExpressionValue>(value: T, expression: &str, output_type: U) -> U {
math_function(
(),
&ParseCache::default(),
Item::new_from_element(value),
Item::new_from_element(expression.to_string()),
Item::new_from_element(output_type),
)
.unwrap_or_else(|(_, error)| panic!("`{expression}` fails: {error}"))
.into_element()
}
let items = || [DVec2::new(1., 5.), DVec2::new(3., 2.)].into_iter().map(Item::new_from_element).collect::<List<DVec2>>();
fn formula<U: ExpressionValue>(items: List<DVec2>, expression: &str, output_type: U) -> U {
math_formula((), &ParseCache::default(), items, Item::new_from_element(expression.to_string()), Item::new_from_element(output_type))
.unwrap()
.into_element()
}
fn aggregate<U: ExpressionValue>(items: List<DVec2>, operator: &str, output_type: U) -> U {
math_aggregate((), items, Item::new_from_element(operator.to_string()), Item::new_from_element(output_type))
.unwrap()
.into_element()
}
assert_eq!(fx(DVec2::new(3., 4.), "2x + i", DVec2::ZERO), DVec2::new(7., 8.));
assert_eq!(fx(DVec2::new(3., 4.), "perp(x)", DVec2::ZERO), DVec2::new(-4., 3.));
assert_eq!(fx(DVec2::new(3., 4.), "|x|", 0.), 5.);
assert_eq!(fx(2., "x i + j", DVec2::ZERO), DVec2::new(2., 1.));
assert_eq!(DVec2::from_value(&Value::from_f64(2.5)), Some(DVec2::ZERO));
assert_eq!(fx(DVec2::new(3., 4.), "x + 1", DVec2::ZERO), DVec2::new(3., 4.));
assert_eq!(DVec2::from_value(&Value::from(Vector3([1., 2., 3.]))), Some(DVec2::new(1., 2.)));
assert_eq!(fx(DVec2::new(3., 4.), "x + 2.6", 0.), 2.6);
assert_eq!(fx(DVec2::new(3., 4.), "x + 2.6", 0_i64), 3);
assert!(fx(DVec2::new(3., 4.), "x + 1", false));
assert_eq!(aggregate(items(), "+", DVec2::ZERO), DVec2::new(4., 7.));
assert_eq!(aggregate(items(), "min", DVec2::ZERO), DVec2::new(1., 2.));
assert_eq!(formula(items(), "a - b", DVec2::ZERO), DVec2::new(-2., 3.));
assert_eq!(formula(items(), "dot(a, b)", 0.), 13.);
}
#[test]
fn test_is_nonzero() {
assert!(!is_nonzero((), Item::new_from_element(0.)).into_element());
assert!(is_nonzero((), Item::new_from_element(0.5)).into_element());
assert!(is_nonzero((), Item::new_from_element(-3_i64)).into_element());
assert!(!is_nonzero((), Item::new_from_element(DVec2::ZERO)).into_element());
assert!(is_nonzero((), Item::new_from_element(DVec2::new(0., 1.))).into_element());
// Negative zero is zero, while NaN, being unequal to zero, is nonzero
assert!(!is_nonzero((), Item::new_from_element(-0.)).into_element());
assert!(is_nonzero((), Item::new_from_element(f64::NAN)).into_element());
}
#[test]
fn formula_reads_positions_and_aggregate_folds_operators() {
let values = || [4., 1., 7.].into_iter().map(Item::new_from_element).collect::<List<f64>>();
let formula = |expression: &str| math_formula((), &ParseCache::default(), values(), Item::new_from_element(expression.to_string()), Item::new_from_element(0.)).map(Item::into_element);
let aggregate = |operator: &str| math_aggregate((), values(), Item::new_from_element(operator.to_string()), Item::new_from_element(0.)).map(Item::into_element);
// A formula reads the items positionally as `a`, `b`, `c`, while an aggregate applies its operator across all of them
assert_eq!(formula("a - b + c").unwrap(), 10.);
assert_eq!(aggregate("min").unwrap(), 1.);
assert_eq!(aggregate("+").unwrap(), 12.);
// Each node takes only its own kind of string
assert!(matches!(formula(" + "), Err(MathExpressionError::LoneOperator(operator)) if operator == "+"));
assert!(matches!(formula("max"), Err(MathExpressionError::LoneOperator(_))));
assert!(matches!(aggregate("a + b"), Err(MathExpressionError::NotAnOperator)));
assert!(matches!(aggregate(""), Err(MathExpressionError::NotAnOperator)));
}
#[test]
fn running_results_follow_each_item() {
let numbers = |values: &[f64]| values.iter().copied().map(Item::new_from_element).collect::<List<f64>>();
let running = |items: List<f64>, operator: &str| {
math_running((), items, Item::new_from_element(operator.to_string()), Item::new_from_element(0.))
.map(|list| list.iter_element_values().copied().collect::<Vec<_>>())
.map_err(|(_, error)| error)
};
// Each item gets the fold of it and those before it, like a running total or the highest value so far
assert_eq!(running(numbers(&[3., 1., 4., 1., 5.]), "+").unwrap(), [3., 4., 8., 9., 14.]);
assert_eq!(running(numbers(&[3., 1., 4., 1., 5.]), "max").unwrap(), [3., 3., 4., 4., 5.]);
assert_eq!(running(numbers(&[]), "-").unwrap(), Vec::<f64>::new());
assert!(matches!(running(numbers(&[1., 2.]), "a + b"), Err(MathExpressionError::NotAnOperator)));
let increasing = math_running((), numbers(&[1., 2., 5., 4., 6.]), Item::new_from_element("<".to_string()), Item::new_from_element(false)).unwrap();
assert_eq!(increasing.iter_element_values().copied().collect::<Vec<_>>(), [true, true, true, false, false]);
}
#[test]
fn running_results_keep_attributes_and_fail_only_where_they_fail() {
let items = [1., 2., 3.]
.into_iter()
.map(|value| Item::new_from_element(value).with_attribute("weight", value * 10.))
.collect::<List<f64>>();
let totals = math_running((), items, Item::new_from_element("+".to_string()), Item::new_from_element(0.)).unwrap();
assert_eq!(totals.iter_element_values().copied().collect::<Vec<_>>(), [1., 3., 6.]);
assert_eq!(
(0..3).map(|index| totals.attribute::<f64>("weight", index).copied()).collect::<Vec<_>>(),
[Some(10.), Some(20.), Some(30.)]
);
// Only the running total 2 can't be read as a Bool, so it alone takes the default
let items = [0., 1., 1., -1.].into_iter().map(Item::new_from_element).collect::<List<f64>>();
let (stand_in, error) = math_running((), items, Item::new_from_element("+".to_string()), Item::new_from_element(false)).unwrap_err();
assert_eq!(stand_in.iter_element_values().copied().collect::<Vec<_>>(), [false, true, false, true]);
assert!(matches!(error, MathExpressionError::OutputType { .. }));
}
#[test]
fn running_transform_products_place_each_step() {
// Each step turns in place and then moves forward in its own direction, so the running product is where each step ends up
let forward = DAffine2::from_translation(DVec2::X);
let turn_then_forward = DAffine2::from_angle(std::f64::consts::FRAC_PI_2) * forward;
let steps = [forward, turn_then_forward, turn_then_forward].into_iter().map(Item::new_from_element).collect::<List<DAffine2>>();
let placed = math_running((), steps, Item::new_from_element("*".to_string()), Item::new_from_element(DAffine2::IDENTITY)).unwrap();
let translations = placed.iter_element_values().map(|transform| transform.translation).collect::<Vec<_>>();
for (translation, expected) in translations.into_iter().zip([DVec2::new(1., 0.), DVec2::new(1., 1.), DVec2::new(0., 1.)]) {
assert!(translation.abs_diff_eq(expected, 1e-12), "{translation} is not {expected}");
}
}
#[test]
pub fn foo() {
let fnn = FnNode::new(|&(a, b): &(u32, u32)| (b, a));
assert_eq!(fnn.eval(&(1u32, 2u32)).value(), Some((2, 1)));
}
#[test]
pub fn add_vectors() {
assert_eq!(
super::add((), Item::new_from_element(DVec2::ONE), Item::new_from_element(DVec2::ONE)).unwrap().into_element(),
DVec2::ONE * 2.
);
}
#[test]
pub fn subtract_f64() {
assert_eq!(super::subtract((), Item::new_from_element(5_f64), Item::new_from_element(3_f64)).unwrap().into_element(), 2.);
}
#[test]
pub fn divide_vectors() {
assert_eq!(
super::divide((), Item::new_from_element(DVec2::ONE), Item::new_from_element(2_f64)).unwrap().into_element(),
DVec2::ONE / 2.
);
}
#[test]
pub fn divide_vector_by_partially_zero_vector() {
let (numerator, denominator) = (Item::new_from_element(DVec2::new(1., 2.)), Item::new_from_element(DVec2::new(2., 0.)));
assert_eq!(super::divide((), numerator, denominator).unwrap().into_element(), DVec2::new(0.5, 0.));
}
#[test]
pub fn modulo_positive() {
assert_eq!(
super::modulo((), Item::new_from_element(-5_f64), Item::new_from_element(2_f64), Item::new_from_element(true))
.unwrap()
.into_element(),
1_f64
);
}
#[test]
pub fn modulo_negative() {
assert_eq!(
super::modulo((), Item::new_from_element(-5_f64), Item::new_from_element(2_f64), Item::new_from_element(false))
.unwrap()
.into_element(),
-1_f64
);
}
#[test]
fn expression_errors() {
assert_eq!(
[concrete!(f64), concrete!(i64), concrete!(bool), concrete!(DVec2), concrete!(DAffine2)].map(|ty| ty.to_string()),
["Number", "Integer", "Bool", "Vec2", "Transform"]
);
let fx = |value: f64, expression: &str| {
math_function(
(),
&ParseCache::default(),
Item::new_from_element(value),
Item::new_from_element(expression.to_string()),
Item::new_from_element(0.),
)
.map(Item::into_element)
.map_err(|(stand_in, error)| (stand_in.into_element(), error))
};
assert!(matches!(fx(3., " "), Err((3., MathExpressionError::Empty))));
assert!(matches!(fx(3., "y * 2"), Err((3., MathExpressionError::Evaluation(_)))));
let Err((3., MathExpressionError::Invalid(message))) = fx(3., "x +") else {
panic!("`x +` doesn't parse")
};
assert!(!message.contains(", at "), "{message}");
let values = |values: &[f64]| values.iter().copied().map(Item::new_from_element).collect::<List<f64>>();
let formula = |items, expression: &str| math_formula((), &ParseCache::default(), items, Item::new_from_element(expression.to_string()), Item::new_from_element(0.)).map(Item::into_element);
let aggregate = |items, operator: &str| math_aggregate((), items, Item::new_from_element(operator.to_string()), Item::new_from_element(0.)).map(Item::into_element);
assert!(matches!(formula(values(&[1.]), ""), Err(MathExpressionError::Empty)));
assert!(matches!(formula(values(&[1.]), "a +"), Err(MathExpressionError::Invalid(_))));
assert_eq!(aggregate(values(&[]), "min").unwrap(), 0.);
assert_eq!(aggregate(values(&[]), "mean").unwrap(), 0.);
assert!(matches!(aggregate(values(&[]), "-"), Err(MathExpressionError::EmptyReduction { .. })));
assert!(matches!(aggregate(values(&[0., 0.]), "/"), Err(MathExpressionError::NoReduction { .. })));
}
#[test]
fn integer_overflow_is_an_error() {
let integer = Item::new_from_element;
assert!(super::add((), integer(i64::MAX), integer(1)).is_err());
assert!(super::subtract((), integer(i64::MIN), integer(1)).is_err());
assert!(super::multiply((), integer(i64::MAX), integer(2)).is_err());
assert!(super::divide((), integer(i64::MIN), integer(-1)).is_err());
assert_eq!(super::divide((), integer(5), integer(0)).unwrap().into_element(), 0);
assert!(exponent((), integer(2), integer(63)).is_err());
assert!(exponent((), integer(2), integer(1 << 40)).is_err());
assert_eq!(exponent((), integer(-1), integer(1 << 40)).unwrap().into_element(), 1);
assert_eq!(exponent((), integer(0), integer(1 << 40)).unwrap().into_element(), 0);
assert_eq!(exponent((), integer(2), integer(-1)).unwrap().into_element(), 0);
assert!(absolute_value((), integer(i64::MIN)).is_err());
assert_eq!(absolute_value((), integer(i64::MIN + 1)).unwrap().into_element(), i64::MAX);
}
#[test]
fn modulo_of_zero_is_an_error_and_integer_extremes_are_exact() {
let modulo = |numerator: i64, modulus: i64, always_positive| {
super::modulo((), Item::new_from_element(numerator), Item::new_from_element(modulus), Item::new_from_element(always_positive)).map(Item::into_element)
};
assert!(modulo(5, 0, true).is_err());
assert_eq!(modulo(i64::MIN, -1, false).unwrap(), 0);
assert_eq!(modulo(i64::MIN, -1, true).unwrap(), 0);
assert_eq!(modulo(-1, i64::MIN, true).unwrap(), -1);
assert_eq!(modulo(-5, 3, true).unwrap(), 1);
assert_eq!(modulo(5, -3, true).unwrap(), -1);
assert_eq!(modulo(-5, 3, false).unwrap(), -2);
assert!(super::modulo((), Item::new_from_element(1.), Item::new_from_element(0.), Item::new_from_element(false)).is_err());
let vec2 = |x, y| Item::new_from_element(DVec2::new(x, y));
assert!(super::modulo((), vec2(1., 2.), vec2(2., 0.), Item::new_from_element(true)).is_err());
}
#[test]
fn remap_refuses_a_flat_input_range_and_leaves_nan_bounds_unclamped() {
let remap = |input_min: f64, input_max: f64, output_min: f64, output_max: f64| {
super::remap(
(),
Item::new_from_element(0.5),
Item::new_from_element(input_min),
Item::new_from_element(input_max),
Item::new_from_element(output_min),
Item::new_from_element(output_max),
Item::new_from_element(true),
)
.map(Item::into_element)
};
assert!(remap(1., 1., 0., 1.).is_err());
assert_eq!(remap(0., 1e-17, 0., 1.).unwrap(), 1.);
assert!(remap(0., 1., f64::NAN, 1.).unwrap().is_nan());
assert!(remap(0., 1., 0., f64::NAN).unwrap().is_nan());
}
#[test]
fn odd_roots_of_negative_numbers_are_real() {
let root_of = |radicand: f64, degree: f64| root((), Item::new_from_element(radicand), Item::new_from_element(degree)).into_element();
assert_eq!(root_of(-32., 5.), -root_of(32., 5.));
assert_eq!(root_of(-8., 3.), -2.);
assert!(root_of(-16., 4.).is_nan());
assert!(root_of(-16., 2.5).is_nan());
}
#[test]
fn sign_of_nan_is_nan() {
assert!(sign((), Item::new_from_element(f64::NAN)).into_element().is_nan());
}
#[test]
fn vec2_directions_of_extreme_length() {
let vec2 = |x, y| Item::new_from_element(DVec2::new(x, y));
for scale in [1e200, 1e-200, 1.] {
assert!((normalize((), vec2(3. * scale, 4. * scale)).into_element() - DVec2::new(0.6, 0.8)).length() < 1e-15);
assert!((dot_product((), vec2(scale, scale), vec2(scale, 0.), Item::new_from_element(true)).into_element() - std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-15);
assert!((angle_between((), vec2(scale, scale), vec2(scale, 0.), Item::new_from_element(false)).into_element() + 45.).abs() < 1e-12);
}
assert_eq!(normalize((), vec2(f64::INFINITY, 1.)).into_element(), DVec2::ZERO);
assert!(angle_between((), vec2(f64::NAN, 1.), vec2(1., 0.), Item::new_from_element(false)).into_element().is_nan());
}
#[test]
fn string_to_color_refuses_invalid_strings() {
let color = |string: &str| string_to_color((), Item::new_from_element(string.to_string())).map(Item::into_element);
assert_eq!(color("").unwrap(), Color::default());
assert!(color("not a color").is_err());
assert!(color("red").is_ok());
}
}