New nodes: 'L-System' and 'Turtle Path' (#4920)

* New node: 'L-System'

* New node: 'Turtle Path'

* Give 'L-System' arrow rules, computed chances, cuts, and a Max Symbols input

* Add half steps, scaling, tropism, randomness, polygons, and UV counters to 'Turtle Path'

* Make 'L-System' chances probabilities out of 1

* Give 'Turtle Path' fixed command letters and make `!` and `?` scale the width

* Extend `.` in 'Turtle Path' to place free points with a `kind`
This commit is contained in:
Keavon Chambers authored and GitHub committed 2026-11-09 12:08:49 +00:00
1 parent a7ac19fd6b
commit c6cdc7fe92
12 files changed
+1625 -3

No files matched your search

Generated
+1
View File
@@ -7265,6 +7265,7 @@ dependencies = [
"graphene-hash",
"graphene-resource",
"ipsum",
"math-parser",
"node-macro",
"parley",
"rand",
@@ -1448,6 +1448,13 @@ fn static_input_inspector() -> InputInspector {
Ok(vec![choices])
}),
);
map.insert(
"vec2_uv".to_string(),
Box::new(|node_id, index, context| {
let parameter_widgets_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
Ok(vec![node_inspector::vec2_widget(parameter_widgets_info, "U", "V", "", None, false)])
}),
);
map
}
+4
View File
@@ -230,6 +230,7 @@ import NodeIsNonzero from "/../branding/assets/16x16-nodes/node-is-nonzero.svg";
import NodeItemAtIndex from "/../branding/assets/16x16-nodes/node-item-at-index.svg";
import NodeIterate from "/../branding/assets/16x16-nodes/node-iterate.svg";
import NodeJitterPoints from "/../branding/assets/16x16-nodes/node-jitter-points.svg";
import NodeLSystem from "/../branding/assets/16x16-nodes/node-l-system.svg";
import NodeLeastCommonMultiple from "/../branding/assets/16x16-nodes/node-least-common-multiple.svg";
import NodeLerp from "/../branding/assets/16x16-nodes/node-lerp.svg";
import NodeLessThan from "/../branding/assets/16x16-nodes/node-less-than.svg";
@@ -375,6 +376,7 @@ import NodeText from "/../branding/assets/16x16-nodes/node-text.svg";
import NodeThreshold from "/../branding/assets/16x16-nodes/node-threshold.svg";
import NodeTransform from "/../branding/assets/16x16-nodes/node-transform.svg";
import NodeTriangulate from "/../branding/assets/16x16-nodes/node-triangulate.svg";
import NodeTurtlePath from "/../branding/assets/16x16-nodes/node-turtle-path.svg";
import NodeUngroup from "/../branding/assets/16x16-nodes/node-ungroup.svg";
import NodeUnweld from "/../branding/assets/16x16-nodes/node-unweld.svg";
import NodeVaryFillColors from "/../branding/assets/16x16-nodes/node-vary-fill-colors.svg";
@@ -524,6 +526,7 @@ export const ICON_16X16_NODES = {
NodeLogicalNot: { svg: NodeLogicalNot, size: 16 },
NodeLogicalOr: { svg: NodeLogicalOr, size: 16 },
NodeLoremIpsum: { svg: NodeLoremIpsum, size: 16 },
NodeLSystem: { svg: NodeLSystem, size: 16 },
NodeMagnitude: { svg: NodeMagnitude, size: 16 },
NodeMakeOpaque: { svg: NodeMakeOpaque, size: 16 },
NodeMandelbrot: { svg: NodeMandelbrot, size: 16 },
@@ -657,6 +660,7 @@ export const ICON_16X16_NODES = {
NodeThreshold: { svg: NodeThreshold, size: 16 },
NodeTransform: { svg: NodeTransform, size: 16 },
NodeTriangulate: { svg: NodeTriangulate, size: 16 },
NodeTurtlePath: { svg: NodeTurtlePath, size: 16 },
NodeUngroup: { svg: NodeUngroup, size: 16 },
NodeUnweld: { svg: NodeUnweld, size: 16 },
NodeVaryFillColors: { svg: NodeVaryFillColors, size: 16 },
+2 -2
View File
@@ -629,8 +629,8 @@ impl TaggedValue {
pub fn from_primitive_string(string: &str, ty: &Type) -> Option<Self> {
fn to_number<T: FromStr>(input: &str) -> Option<T> {
// Stringified tokens separate a negative number's minus sign from its digits (e.g. "- 180.")
input.split_whitespace().collect::<String>().parse().ok()
// Ignores stringified tokens' spacing (e.g. "- 180.") and digit separators (e.g. "1_000_000")
input.chars().filter(|character| !character.is_whitespace() && *character != '_').collect::<String>().parse().ok()
}
fn to_dvec2(input: &str) -> Option<DVec2> {
@@ -124,6 +124,21 @@ pub const ATTR_SMOOTH: &str = "smooth";
/// the internal addressing: a `PointId` on a `Vector`'s point pool, or a `SegmentId` on the `List<i64>`
/// inside a `Path` at the anchor reference the segment departs from.
pub const ATTR_ID: &str = "id";
/// Point's `i64` count of the `[` branches the turtle was nested in when drawing it, on a `Vector`'s point pool from Turtle Path.
pub const ATTR_DEPTH: &str = "depth";
/// Point's `f64` distance the turtle traveled from its start to reach it, on a `Vector`'s point pool from Turtle Path.
pub const ATTR_DISTANCE: &str = "distance";
/// Point's `f64` direction in degrees the turtle faced arriving at it (`0.` along +X, clockwise on screen), on a `Vector`'s
/// point pool from Turtle Path.
pub const ATTR_HEADING: &str = "heading";
/// Point's `f64` width the turtle drew with there, on a `Vector`'s point pool from Turtle Path.
pub const ATTR_WIDTH: &str = "width";
/// Point's `DVec2` U and V numbers, counted up by `'` and `#`, on a `Vector`'s point pool from Turtle Path.
pub const ATTR_UV: &str = "uv";
/// Point's `f64` turtle step length, scaled by `"` and `_`, on a `Vector`'s point pool from Turtle Path.
pub const ATTR_STEP: &str = "step";
/// Point's `i64` kind set by a `.` outside a shape (default `1`), or `0` for a drawn point, on a `Vector`'s point pool from Turtle Path.
pub const ATTR_KIND: &str = "kind";
/// Text item's font size in document-space units (`f64`, implicit default `24.`).
pub const ATTR_FONT_SIZE: &str = "font_size";
/// Text item's font, as a `Resource` of the loaded font file.
+1
View File
@@ -26,6 +26,7 @@ graphene-hash = { workspace = true }
graphene-resource = { workspace = true }
vector-types = { workspace = true }
node-macro = { workspace = true }
math-parser = { workspace = true }
# Workspace dependencies
dyn-any = { workspace = true }
+820
View File
@@ -0,0 +1,820 @@
use core_types::Ctx;
use core_types::list::Item;
use core_types::math::float_noise::round_away_float_noise;
use core_types::misc::{format_f64, parse_f64};
use math_parser::ast;
use math_parser::context::{EvalContext, NothingMap, ValueProvider};
use math_parser::value::Value;
use rand::rngs::StdRng;
use rand::{RngExt, SeedableRng};
use std::collections::HashMap;
use std::ops::Range;
/// Why the "L-System" node's string stops short of what its inputs describe.
#[derive(Debug, thiserror::Error)]
pub enum LSystemError {
#[error("Line {line} of the rules isn't a valid rule: {reason}")]
InvalidRule { line: usize, reason: String },
#[error("The axiom isn't valid: {0}")]
InvalidAxiom(String),
#[error("A rule's math gives no number: {0}")]
Evaluation(String),
#[error("A rule's chance came out as {0}, which isn't from 0 to 1")]
InvalidChance(f64),
#[error("The chances of the rules for `{symbol}` add up to {total}, which is more than 1")]
ChancesOverOne { symbol: char, total: f64 },
#[error("Stopped after {completed} generations, since the next would grow past the Max Symbols limit of {limit}")]
TooLong { completed: i64, limit: usize },
#[error("Stopped after {limit} generations, since Max Symbols also limits how many generations run")]
TooManyGenerations { limit: usize },
}
/// Grows a string by rewriting all of its symbols at once with the rules, once per generation, for drawing with the **Turtle Path** node.
///
/// Since every symbol with a rule is replaced in each generation, patterns repeat inside themselves at ever finer scales, like the branching of plants or the folds of fractal curves.
#[node_macro::node(name("L-System"), category("String"), icon("NodeLSystem"))]
fn l_system(
_: impl Ctx,
/// The string to start growing from.
axiom: Item<String>,
/// One rule per line, like `F = F+F-F-F+F` (or `F -> F+F-F-F+F`), which replaces every `F` with `F+F-F-F+F` in each generation. Symbols without a rule stay as they are.
///
/// A rule can also check the symbols around one, as in `A < B > C = D`, which rewrites a `B` only between an `A` and a `C`. A rule ending with a chance from 0 to 1, like `F = F[+F]F : 0.6`, applies only that often and otherwise leaves the symbol as it is. The chances of a symbol's rules can add up to 1 at most.
///
/// Symbols can carry numbers, like `F(10)`. A rule names them to work out new numbers with math, and to apply only when the condition after `:` holds, as in `F(x) : x > 2 = F(x/2)[+F(x/2)]`. A chance can be worked out from them too.
///
/// A `%` cuts off the rest of its branch, up to the `]` that ends it.
///
/// Lines starting with `//` are skipped.
#[default("F = F+F-F-F+F")]
#[widget(ParsedWidgetOverride::Custom = "text_area")]
rules: Item<String>,
/// Symbols to look past when a rule checks the symbols around one, usually the turns between them.
///
/// Listing `[` and `]` reads the string straight through its branches, as if it had no brackets.
#[default("+-")]
ignored_symbols: Item<String>,
/// How many times the rules rewrite the whole string. Each generation can multiply its length.
#[default(3)]
#[hard(0..)]
generations: Item<i64>,
/// Seed to determine unique variations on where the rules with chances apply.
#[hard(0..)]
seed: Item<i64>,
/// The longest the string may grow, in symbols, and the most generations that run. A generation past either is left out, guarding against a number of generations that would freeze the editor.
#[default(1_000_000)]
#[hard(1..)]
max_symbols: Item<i64>,
) -> Result<Item<String>, (Item<String>, LSystemError)> {
// The grown string takes the axiom's place in its item, keeping the attributes it carries
let mut string = axiom;
let mut axiom = match parse_axiom(string.element()) {
Ok(axiom) => axiom,
Err(reason) => {
string.element_mut().clear();
return Err((string, LSystemError::InvalidAxiom(reason)));
}
};
cut_branches(&mut axiom);
let (rule_set, rule_error) = RuleSet::parse(rules.element());
let ignored_symbols: Vec<char> = ignored_symbols.element().chars().filter(|symbol| !symbol.is_whitespace()).collect();
let max_symbols = (*max_symbols.element()).max(1) as usize;
let (modules, rewrite_error) = rewrite(axiom, &rule_set, *generations.element(), max_symbols, &ignored_symbols, *seed.element() as u64);
*string.element_mut() = modules_to_string(&modules);
// An invalid rule is reported first, since it is usually being typed and explains any other surprise
match rule_error.or(rewrite_error) {
Some(error) => Err((string, error)),
None => Ok(string),
}
}
/// One symbol of an L-system string, with the numbers in parentheses after it, like `F(10, 2)`.
#[derive(Clone, Debug, PartialEq)]
struct Module {
symbol: char,
parameters: Vec<f64>,
}
/// A symbol a rule matches, with names for the numbers it carries, like `F(x, y)`.
struct Pattern {
symbol: char,
parameter_names: Vec<String>,
}
/// A symbol a rule writes, with the math that works out each of its numbers.
struct WrittenSymbol {
symbol: char,
parameters: Vec<ast::Node>,
}
/// One line of the rules: `left < symbol > right : condition = successor : chance`, where all but the symbol and successor are optional.
struct Rule {
/// The symbols that must come before the rewritten one, in reading order.
left_context: Vec<Pattern>,
predecessor: Pattern,
/// The symbols that must come after the rewritten one, in reading order.
right_context: Vec<Pattern>,
condition: Option<ast::Node>,
successor: Vec<WrittenSymbol>,
/// How often this rule applies, from 0 to 1, where it matches.
chance: Option<Chance>,
}
/// A rule's chance, as a written number or as math to work out from the numbers it names.
enum Chance {
Fixed(f64),
Computed(ast::Node),
}
/// The rules, looked up by the symbol each one rewrites.
struct RuleSet {
rules: Vec<Rule>,
by_symbol: HashMap<char, Vec<usize>>,
uses_context: bool,
}
impl RuleSet {
/// Parses one rule per line, keeping the valid rules and the error of the first invalid one.
fn parse(text: &str) -> (Self, Option<LSystemError>) {
let mut rules = Vec::new();
let mut first_error = None;
for (index, line) in text.lines().enumerate() {
let line = line.trim();
if line.is_empty() || line.starts_with("//") {
continue;
}
match parse_rule(line) {
Ok(rule) => rules.push(rule),
Err(reason) if first_error.is_none() => first_error = Some(LSystemError::InvalidRule { line: index + 1, reason }),
Err(_) => {}
}
}
let mut by_symbol: HashMap<char, Vec<usize>> = HashMap::new();
for (index, rule) in rules.iter().enumerate() {
by_symbol.entry(rule.predecessor.symbol).or_default().push(index);
}
let uses_context = rules.iter().any(|rule| !rule.left_context.is_empty() || !rule.right_context.is_empty());
(Self { rules, by_symbol, uses_context }, first_error)
}
}
/// The numbers a matched rule's names stand for.
#[derive(Default)]
struct Bindings<'a>(Vec<(&'a str, f64)>);
impl ValueProvider for Bindings<'_> {
fn get_value(&self, name: &str) -> Option<Value> {
self.0.iter().find(|(bound_name, _)| *bound_name == name).map(|&(_, value)| Value::from_f64(value))
}
}
impl<'a> Bindings<'a> {
/// Names the numbers of a module that matches the pattern, or gives `false` when the symbol or count of numbers differs.
fn bind(&mut self, pattern: &'a Pattern, module: &Module) -> bool {
if pattern.symbol != module.symbol || pattern.parameter_names.len() != module.parameters.len() {
return false;
}
self.0.extend(pattern.parameter_names.iter().map(String::as_str).zip(module.parameters.iter().copied()));
true
}
}
/// Rewrites every module once per generation, giving the last complete generation and why it stopped early, if it did.
fn rewrite(axiom: Vec<Module>, rule_set: &RuleSet, generations: i64, max_symbols: usize, ignored_symbols: &[char], seed: u64) -> (Vec<Module>, Option<LSystemError>) {
let mut rng = StdRng::seed_from_u64(seed);
let mut modules = axiom;
for generation in 0..generations {
// Running more generations than Max Symbols without passing it takes a string that stopped growing, which could otherwise run long enough to freeze the editor
if generation >= max_symbols as i64 {
return (modules, Some(LSystemError::TooManyGenerations { limit: max_symbols }));
}
let partners = if rule_set.uses_context { bracket_partners(&modules) } else { Vec::new() };
let neighbors = Neighbors {
modules: &modules,
partners: &partners,
ignored_symbols,
};
let mut next = Vec::with_capacity(modules.len());
let mut rolled = false;
for (index, module) in modules.iter().enumerate() {
let chosen = match choose_rule(rule_set, &neighbors, index, &mut rng, &mut rolled) {
Ok(chosen) => chosen,
Err(error) => return (modules, Some(error)),
};
let Some((rule, bindings)) = chosen else {
next.push(module.clone());
continue;
};
for written in &rule.successor {
let parameters = match written.parameters.iter().map(|expression| evaluate_number(expression, &bindings)).collect() {
Ok(parameters) => parameters,
Err(reason) => return (modules, Some(LSystemError::Evaluation(reason))),
};
next.push(Module { symbol: written.symbol, parameters });
}
if next.len() > max_symbols {
return (
modules,
Some(LSystemError::TooLong {
completed: generation,
limit: max_symbols,
}),
);
}
}
cut_branches(&mut next);
// A generation that changed nothing without rolling any chances would repeat forever, so growth has settled
let settled = !rolled && next == modules;
modules = next;
if settled {
break;
}
}
(modules, None)
}
/// Erases each `%` along with the rest of its branch, up to the `]` that ends it, or to the end of the string outside any branch. O(n).
fn cut_branches(modules: &mut Vec<Module>) {
if !modules.iter().any(|module| module.symbol == '%') {
return;
}
// While cutting, the count of branches opened since the `%`, so the `]` ending the cut branch is kept
let mut cut_depth: Option<usize> = None;
modules.retain(|module| match (cut_depth, module.symbol) {
(None, '%') => {
cut_depth = Some(0);
false
}
(None, _) => true,
(Some(0), ']') => {
cut_depth = None;
true
}
(Some(depth), '[') => {
cut_depth = Some(depth + 1);
false
}
(Some(depth), ']') => {
cut_depth = Some(depth - 1);
false
}
(Some(_), _) => false,
});
}
/// The rule that rewrites the module at `index` with its names bound. The first matching rule applies, unless it gives a chance, in which case one roll picks among the matching rules that give chances, or none with the chance left over.
/// Making that roll sets `rolled`.
fn choose_rule<'a>(rule_set: &'a RuleSet, neighbors: &Neighbors, index: usize, rng: &mut StdRng, rolled: &mut bool) -> Result<Option<(&'a Rule, Bindings<'a>)>, LSystemError> {
let module = &neighbors.modules[index];
let Some(candidates) = rule_set.by_symbol.get(&module.symbol) else { return Ok(None) };
let mut chance_matches = Vec::new();
for &rule_index in candidates {
let rule = &rule_set.rules[rule_index];
let Some(bindings) = matching_bindings(rule, neighbors, index).map_err(LSystemError::Evaluation)? else {
continue;
};
let chance = match &rule.chance {
Some(Chance::Fixed(chance)) => *chance,
Some(Chance::Computed(expression)) => evaluate_number(expression, &bindings).map_err(LSystemError::Evaluation)?,
None if chance_matches.is_empty() => return Ok(Some((rule, bindings))),
None => continue,
};
if !(0. ..=1.).contains(&chance) {
return Err(LSystemError::InvalidChance(chance));
}
chance_matches.push((rule, bindings, chance));
}
// Rounding lets chances like 0.7 and 0.2 and 0.1 add up to exactly 1
let total = round_away_float_noise(chance_matches.iter().map(|(_, _, chance)| chance).sum());
if total > 1. {
return Err(LSystemError::ChancesOverOne { symbol: module.symbol, total });
}
if total == 0. {
return Ok(None);
}
// When the chances add up to 1, the last rule also takes any sliver that float rounding leaves past it
*rolled = true;
let mut roll = rng.random::<f64>();
let last = chance_matches.len() - 1;
for (position, (rule, bindings, chance)) in chance_matches.into_iter().enumerate() {
if roll < chance || (position == last && total == 1.) {
return Ok(Some((rule, bindings)));
}
roll -= chance;
}
Ok(None)
}
/// The rule's names bound to the numbers of the module at `index` and its context, or `None` when the rule doesn't match there.
fn matching_bindings<'a>(rule: &'a Rule, neighbors: &Neighbors, index: usize) -> Result<Option<Bindings<'a>>, String> {
let mut bindings = Bindings::default();
if !bindings.bind(&rule.predecessor, &neighbors.modules[index]) {
return Ok(None);
}
// The left context is checked from the nearest symbol outward, so in reverse reading order
let mut position = index;
for pattern in rule.left_context.iter().rev() {
let Some(previous) = neighbors.previous(position) else { return Ok(None) };
if !bindings.bind(pattern, &neighbors.modules[previous]) {
return Ok(None);
}
position = previous;
}
let mut position = index;
for pattern in &rule.right_context {
let Some(next) = neighbors.next(position) else { return Ok(None) };
if !bindings.bind(pattern, &neighbors.modules[next]) {
return Ok(None);
}
position = next;
}
if let Some(condition) = &rule.condition
&& evaluate_number(condition, &bindings)? == 0.
{
return Ok(None);
}
Ok(Some(bindings))
}
/// A generation's modules, read the way context sees them: along the turtle's path, past side branches and ignored symbols.
struct Neighbors<'a> {
modules: &'a [Module],
/// The index of each bracket's partner, from [`bracket_partners`].
partners: &'a [Option<usize>],
ignored_symbols: &'a [char],
}
impl Neighbors<'_> {
/// The nearest module before `index` on the way back toward the start, stepping over whole branches and out of the one `index` sits in.
fn previous(&self, index: usize) -> Option<usize> {
let mut current = index;
while current > 0 {
current -= 1;
match self.modules[current].symbol {
symbol if self.ignored_symbols.contains(&symbol) => {}
']' => current = self.partners[current]?,
'[' => {}
_ => return Some(current),
}
}
None
}
/// The nearest module after `index` along the same branch, stepping over side branches, or `None` where the branch ends.
fn next(&self, index: usize) -> Option<usize> {
let mut current = index + 1;
while current < self.modules.len() {
match self.modules[current].symbol {
symbol if self.ignored_symbols.contains(&symbol) => current += 1,
'[' => current = self.partners[current]? + 1,
']' => return None,
_ => return Some(current),
}
}
None
}
}
/// The index of each `[` and `]` module's partner, so context matching can step over whole branches in O(1).
fn bracket_partners(modules: &[Module]) -> Vec<Option<usize>> {
let mut partners = vec![None; modules.len()];
let mut open = Vec::new();
for (index, module) in modules.iter().enumerate() {
match module.symbol {
'[' => open.push(index),
']' => {
if let Some(opening) = open.pop() {
partners[index] = Some(opening);
partners[opening] = Some(index);
}
}
_ => {}
}
}
partners
}
/// Writes modules back out as a string, with each one's numbers in parentheses after it.
fn modules_to_string(modules: &[Module]) -> String {
let mut text = String::with_capacity(modules.len());
for module in modules {
text.push(module.symbol);
if !module.parameters.is_empty() {
let numbers: Vec<String> = module.parameters.iter().map(|&number| format_f64(number)).collect();
text.push('(');
text.push_str(&numbers.join(","));
text.push(')');
}
}
text
}
/// Reads the axiom's modules, whose numbers may be written as math like `F(10*2)`.
fn parse_axiom(text: &str) -> Result<Vec<Module>, String> {
split_symbols(text)?
.into_iter()
.map(|(symbol, parameters)| {
let parameters = arguments(parameters).into_iter().map(evaluate_constant).collect::<Result<_, _>>()?;
Ok(Module { symbol, parameters })
})
.collect()
}
/// Parses one line of the rules.
fn parse_rule(line: &str) -> Result<Rule, String> {
let Some(separator) = rule_separator(line) else {
return Err("it needs an `=` between the symbol and what it becomes".to_string());
};
let (left_side, right_side) = (&line[..separator.start], &line[separator.end..]);
if rule_separator(right_side).is_some() {
return Err("it has a second `=`, but a condition checks equality with `==`".to_string());
}
// The left side reads `left < symbol > right : condition`, where all but the symbol are optional
let (pattern_text, condition_text) = split_at_first(left_side, ':');
let (left_context_text, rest) = match split_at_first(pattern_text, '<') {
(left_context, Some(rest)) => (Some(left_context), rest),
(rest, None) => (None, rest),
};
let (predecessor_text, right_context_text) = split_at_first(rest, '>');
let mut predecessor = parse_patterns(predecessor_text)?;
if predecessor.len() != 1 {
return Err("the left side must name exactly one symbol to rewrite".to_string());
}
let predecessor = predecessor.remove(0);
let left_context = left_context_text.map(parse_patterns).transpose()?.unwrap_or_default();
let right_context = right_context_text.map(parse_patterns).transpose()?.unwrap_or_default();
let condition = condition_text.map(parse_expression).transpose()?;
// The right side reads `successor : chance`, where the chance is optional
let (successor_text, chance_text) = match right_side.rfind(':') {
Some(colon) => (&right_side[..colon], Some(right_side[colon + 1..].trim())),
None => (right_side, None),
};
let chance = chance_text
.map(|text| match parse_f64(text) {
Some(chance) if (0. ..=1.).contains(&chance) => Ok(Chance::Fixed(chance)),
Some(_) => Err(format!("the chance `{text}` isn't a number from 0 to 1")),
None => parse_expression(text).map(Chance::Computed),
})
.transpose()?;
let successor = split_symbols(successor_text)?
.into_iter()
.map(|(symbol, parameters)| {
let parameters = arguments(parameters).into_iter().map(parse_expression).collect::<Result<_, _>>()?;
Ok(WrittenSymbol { symbol, parameters })
})
.collect::<Result<_, String>>()?;
Ok(Rule {
left_context,
predecessor,
right_context,
condition,
successor,
chance,
})
}
/// Reads symbols with names for their numbers, like `A(x)B`, as a rule's predecessor or context.
fn parse_patterns(text: &str) -> Result<Vec<Pattern>, String> {
split_symbols(text)?
.into_iter()
.map(|(symbol, parameters)| {
let parameter_names = arguments(parameters)
.into_iter()
.map(|name| {
let name = name.trim();
let mut characters = name.chars();
let valid = characters.next().is_some_and(|first| first.is_ascii_lowercase()) && characters.all(|character| character.is_ascii_alphanumeric() || character == '_');
if valid {
Ok(name.to_string())
} else {
Err(format!("`{name}` can't name a number, since names start with a lowercase letter, like `x`"))
}
})
.collect::<Result<_, _>>()?;
Ok(Pattern { symbol, parameter_names })
})
.collect()
}
/// The bytes of the first `=` or `->` outside parentheses, which separates a rule's two sides, passing over comparisons like `==`, `<=`, `>=` and `!=`.
fn rule_separator(text: &str) -> Option<Range<usize>> {
let bytes = text.as_bytes();
let mut depth = 0;
for (index, &byte) in bytes.iter().enumerate() {
let previous = index.checked_sub(1).map(|previous| bytes[previous]);
let next = bytes.get(index + 1).copied();
match byte {
b'(' => depth += 1,
b')' => depth -= 1,
b'-' if depth == 0 && next == Some(b'>') => return Some(index..index + 2),
b'=' if depth == 0 && !matches!(previous, Some(b'=' | b'<' | b'>' | b'!')) && next != Some(b'=') => return Some(index..index + 1),
_ => {}
}
}
None
}
/// Splits the text at the first `delimiter` outside parentheses, giving the text before it and, if found, the text after it.
fn split_at_first(text: &str, delimiter: char) -> (&str, Option<&str>) {
let mut depth = 0;
for (index, character) in text.char_indices() {
match character {
'(' => depth += 1,
')' => depth -= 1,
_ if character == delimiter && depth == 0 => return (&text[..index], Some(&text[index + character.len_utf8()..])),
_ => {}
}
}
(text, None)
}
/// Reads a string as symbols, each with the text inside any parentheses right after it. Whitespace between symbols is skipped.
fn split_symbols(text: &str) -> Result<Vec<(char, Option<&str>)>, String> {
let mut symbols = Vec::new();
let mut characters = text.char_indices().peekable();
while let Some((index, character)) = characters.next() {
if character.is_whitespace() {
continue;
}
if matches!(character, '(' | ')') {
return Err(format!("`{character}` must come right after a symbol, like `F(10)`"));
}
let after = index + character.len_utf8();
if !text[after..].starts_with('(') {
symbols.push((character, None));
continue;
}
let Some(close) = closing_parenthesis(text, after) else {
return Err(format!("the `(` after `{character}` is never closed"));
};
symbols.push((character, Some(&text[after + 1..close])));
while characters.next_if(|&(index, _)| index <= close).is_some() {}
}
Ok(symbols)
}
/// The byte index of the `)` that closes the `(` at `open`.
fn closing_parenthesis(text: &str, open: usize) -> Option<usize> {
let mut depth = 0;
for (index, character) in text[open..].char_indices() {
match character {
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
return Some(open + index);
}
}
_ => {}
}
}
None
}
/// Splits the text inside a symbol's parentheses at its top-level commas, keeping the commas of nested calls like `max(a, b)`.
fn arguments(parameters: Option<&str>) -> Vec<&str> {
let Some(text) = parameters.filter(|text| !text.trim().is_empty()) else { return Vec::new() };
let mut pieces = Vec::new();
let mut depth = 0;
let mut start = 0;
for (index, character) in text.char_indices() {
match character {
'(' => depth += 1,
')' => depth -= 1,
',' if depth == 0 => {
pieces.push(&text[start..index]);
start = index + 1;
}
_ => {}
}
}
pieces.push(&text[start..]);
pieces
}
fn parse_expression(text: &str) -> Result<ast::Node, String> {
ast::Node::try_parse_from_str(text.trim()).map_err(|error| error.to_string())
}
/// Reads a written number, or works out the math of an expression like `10*2`.
fn evaluate_constant(text: &str) -> Result<f64, String> {
if let Some(number) = parse_f64(text.trim()) {
return Ok(number);
}
evaluate_number(&parse_expression(text)?, &Bindings::default())
}
/// Works out the math of an expression as a number, rounding away float noise so the string stays readable.
fn evaluate_number(expression: &ast::Node, bindings: &Bindings) -> Result<f64, String> {
let result = expression.eval(&EvalContext::new(bindings, NothingMap)).map_err(|error| error.to_string())?;
let number = result.as_value().and_then(|value| value.as_real()).ok_or_else(|| format!("`{result}` isn't a number"))?;
Ok(round_away_float_noise(number))
}
#[cfg(test)]
mod tests {
use super::*;
fn grow(axiom: &str, rules: &str, generations: i64) -> Result<String, (String, String)> {
grow_with(axiom, rules, generations, "+-", 0)
}
fn grow_with(axiom: &str, rules: &str, generations: i64, ignored_symbols: &str, seed: i64) -> Result<String, (String, String)> {
grow_up_to(axiom, rules, generations, ignored_symbols, seed, 1_000_000)
}
fn grow_up_to(axiom: &str, rules: &str, generations: i64, ignored_symbols: &str, seed: i64, max_symbols: i64) -> Result<String, (String, String)> {
let item = |text: &str| Item::new_from_element(text.to_string());
let number = Item::new_from_element;
l_system((), item(axiom), item(rules), item(ignored_symbols), number(generations), number(seed), number(max_symbols))
.map(Item::into_element)
.map_err(|(result, error)| (result.into_element(), error.to_string()))
}
#[test]
fn accepts_an_arrow_between_a_rules_sides() {
assert_eq!(grow("F", "F -> F+F", 1).unwrap(), "F+F");
assert_eq!(grow("F(3)", "F(x) : x > 2 -> F(x-1)", 1).unwrap(), "F(2)");
}
#[test]
fn rejects_a_single_equals_comparing_in_a_condition() {
let (_, error) = grow("F(0)", "F(m) : m=0 = X", 1).unwrap_err();
assert_eq!(error, "Line 1 of the rules isn't a valid rule: it has a second `=`, but a condition checks equality with `==`");
// Neither comparisons nor a `where` inside a symbol's parentheses separate the sides
assert_eq!(grow("F(0)", "F(m) : m == 0 = F(n where n = m + 1)", 1).unwrap(), "F(1)");
}
#[test]
fn rewrites_every_symbol_at_once() {
assert_eq!(grow("F", "F = F+F-F-F+F", 1).unwrap(), "F+F-F-F+F");
assert_eq!(grow("FX", "X = X+YF+\nY = -FX-Y", 2).unwrap(), "FX+YF++-FX-YF+");
assert_eq!(grow("FX", "X = X+YF+", 0).unwrap(), "FX");
}
#[test]
fn skips_whitespace_and_comment_lines() {
assert_eq!(grow("F G", "// F = G\n\nF = F + F", 1).unwrap(), "F+FG");
}
#[test]
fn matches_context_past_ignored_symbols_and_branches() {
assert_eq!(grow("ABC", "A < B > C = X", 1).unwrap(), "AXC");
assert_eq!(grow("ABD", "A < B > C = X", 1).unwrap(), "ABD");
assert_eq!(grow("A+BC", "A < B > C = X", 1).unwrap(), "A+XC");
// Left context steps out of the branch a symbol starts and over whole branches before it
assert_eq!(grow("A[B]", "A < B = X", 1).unwrap(), "A[X]");
assert_eq!(grow("A[C]B", "A < B = X", 1).unwrap(), "A[C]X");
// Right context ends with the branch
assert_eq!(grow("[AB]", "A > B = X", 1).unwrap(), "[XB]");
assert_eq!(grow("[A]B", "A > B = X", 1).unwrap(), "[A]B");
// Ignoring the brackets reads straight through branches
assert_eq!(grow_with("A[B]", "A > B = X", 1, "[]", 0).unwrap(), "X[B]");
assert_eq!(grow_with("A[Q]B", "A > B = X", 1, "[]", 0).unwrap(), "A[Q]B");
assert_eq!(grow_with("A[Q]B", "Q < B = X", 1, "[]", 0).unwrap(), "A[Q]X");
}
#[test]
fn cuts_the_rest_of_a_branch_after_a_percent_sign() {
assert_eq!(grow("[AB[C]D]E", "A = F%", 1).unwrap(), "[F]E");
assert_eq!(grow("AB[C]D", "A = F%", 1).unwrap(), "F");
assert_eq!(grow("F[%G]%H", "", 0).unwrap(), "F[]");
}
#[test]
fn the_first_matching_rule_applies() {
assert_eq!(grow("ABB", "A < B = X\nB = Y", 1).unwrap(), "AXY");
}
#[test]
fn works_out_parameters_and_conditions() {
let rules = "F(x) : x > 2 = F(x/2)[+F(x/2)]";
assert_eq!(grow("F(10)", rules, 1).unwrap(), "F(5)[+F(5)]");
assert_eq!(grow("F(5*2)", rules, 2).unwrap(), "F(2.5)[+F(2.5)][+F(2.5)[+F(2.5)]]");
// Below the condition's threshold, nothing changes
assert_eq!(grow("F(1)", rules, 3).unwrap(), "F(1)");
// A symbol carrying a different count of numbers doesn't match
assert_eq!(grow("F(1,2)F", rules, 1).unwrap(), "F(1,2)F");
// Context binds its own names
assert_eq!(grow("A(3)B(4)", "A(x) < B(y) = B(x+y)", 1).unwrap(), "A(3)B(7)");
}
#[test]
fn picks_among_chances_the_same_way_for_a_seed() {
let rules = "F = A : 0.5\nF = B : 0.5";
let first = grow_with("FFFFFFFFFFFFFFFFFFFF", rules, 1, "", 7).unwrap();
assert_eq!(first, grow_with("FFFFFFFFFFFFFFFFFFFF", rules, 1, "", 7).unwrap());
assert!(first.contains('A') && first.contains('B') && !first.contains('F'));
// A chance of zero is never picked
assert_eq!(grow_with("FFFF", "F = A : 0\nF = B : 1", 1, "", 3).unwrap(), "BBBB");
// A chance can be worked out from the symbol's numbers
assert_eq!(grow_with("F(1)F(0)", "F(x) = A : x\nF(x) = B : 1 - x", 1, "", 0).unwrap(), "AB");
let (_, error) = grow_with("F(2)", "F(x) = A : 1 - x", 1, "", 0).unwrap_err();
assert_eq!(error, "A rule's chance came out as -1, which isn't from 0 to 1");
}
#[test]
fn leaves_a_symbol_unchanged_with_the_chance_left_over() {
let grown = grow_with("FFFFFFFFFFFFFFFFFFFF", "F = A : 0.5", 1, "", 7).unwrap();
assert!(grown.contains('A') && grown.contains('F'));
// Chances adding up to exactly 1 always apply one of the rules
let grown = grow_with("FFFFFFFFFFFFFFFFFFFF", "F = A : 0.7\nF = B : 0.2\nF = C : 0.1", 1, "", 7).unwrap();
assert!(!grown.contains('F'));
let (_, error) = grow_with("F", "F = A : 0.6\nF = B : 0.6", 1, "", 0).unwrap_err();
assert_eq!(error, "The chances of the rules for `F` add up to 1.2, which is more than 1");
let (_, error) = grow("F", "F = A : 2", 1).unwrap_err();
assert_eq!(error, "Line 1 of the rules isn't a valid rule: the chance `2` isn't a number from 0 to 1");
}
#[test]
fn reports_the_first_invalid_line_and_keeps_the_valid_rules() {
let (result, error) = grow("F", "F = FF\nnonsense\nG(X) = G", 1).unwrap_err();
assert_eq!(result, "FF");
assert_eq!(error, "Line 2 of the rules isn't a valid rule: it needs an `=` between the symbol and what it becomes");
let (_, error) = grow("F", "G(X) = G", 1).unwrap_err();
assert!(error.starts_with("Line 1 of the rules isn't a valid rule: `X` can't name a number"));
let (result, error) = grow("F(", "", 1).unwrap_err();
assert_eq!(result, "");
assert_eq!(error, "The axiom isn't valid: the `(` after `F` is never closed");
}
#[test]
fn stops_before_a_generation_grows_past_max_symbols() {
let (result, error) = grow_up_to("F", "F = FFFFFFFFFF", 7, "", 0, 1000).unwrap_err();
assert_eq!(result.len(), 1000);
assert_eq!(error, "Stopped after 3 generations, since the next would grow past the Max Symbols limit of 1000");
}
#[test]
fn settled_growth_ends_early_and_max_symbols_caps_generations() {
// Once nothing changes, any number of generations finishes at once
assert_eq!(grow("F", "F = F", i64::MAX), Ok("F".to_string()));
assert_eq!(grow("A(1)", "A(n) : n < 3 = A(n+1)", i64::MAX), Ok("A(3)".to_string()));
// A string that keeps changing without growing stops at as many generations as Max Symbols
let (result, error) = grow_up_to("A(0)", "A(n) = A(n+1)", i64::MAX, "", 0, 100).unwrap_err();
assert_eq!(result, "A(100)");
assert_eq!(error, "Stopped after 100 generations, since Max Symbols also limits how many generations run");
// A generation left unchanged by a chance can still change in a later one
assert_eq!(grow("F", "F = F : 0.99\nF = G : 0.01", 2000), Ok("G".to_string()));
}
}
+1
View File
@@ -1,6 +1,7 @@
pub mod fallback;
mod font;
pub mod json;
pub mod l_system;
mod path_builder;
pub mod regex;
mod text_context;
+316 -1
View File
@@ -459,10 +459,93 @@ fn grid<T: GridSpacing>(
.into_item())
}
/// Draws paths by following a string of turtle commands, like the ones an **L-System** grows. `F` and `G` move forward a step while drawing, `f` and `g` move without drawing, `+` and `-` turn left and right, `|` turns around, and `[` and `]` begin and end a branch.
///
/// A number in parentheses gives one command its own amount, like `F(25)` or `+(30)`, and a second number on `F` or `G` is the width it draws to, like `F(25, 3)`.
///
/// `H` and `h` go half a step, drawing or not. `"` and `_` multiply and divide the step from then on, as `;` and `@` do the angle and `!` and `?` the width. `~` turns a random amount, and `T` bends the heading toward the ground. `'` and `#` count up two numbers, U and V, for coloring or anything else downstream.
///
/// `{` begins a filled shape, `.` adds an anchor where the turtle stands, and `}` closes it. Outside a shape, `.` places a point on no path instead, for **Vector to Points** and **Transform** to copy shapes onto. Its kind is 1, or a number like `.(2)` gives another, so different shapes can go to different points.
///
/// Each point records its branch depth, distance traveled, heading, width, step length, UV, and kind as attributes. Drawn points have a kind of 0.
#[node_macro::node(category("String"), icon("NodeTurtlePath"))]
fn turtle_path(
_: impl Ctx,
/// The commands for the turtle to follow, starting at the origin and facing up. Symbols without a meaning are skipped.
commands: Item<String>,
/// How far each step forward moves, unless a command gives its own distance like `F(25)`.
#[unit(" px")]
#[default(10.)]
step: Item<f64>,
/// The factor that `"` multiplies the step by and `_` divides it by, unless a command gives its own like `"(0.8)`.
#[unit("x")]
#[default(0.5)]
step_scale: Item<f64>,
/// How much longer or shorter each step may randomly be, as a fraction of its length.
#[range]
#[hard(0..1)]
step_jitter: Item<f64>,
/// How far `+` and `-` turn, unless a command gives its own angle like `+(30)`.
#[unit("°")]
#[default(90.)]
angle: Item<f64>,
/// The factor that `;` multiplies the angle by and `@` divides it by, unless a command gives its own like `;(0.8)`.
#[unit("x")]
#[default(0.5)]
angle_scale: Item<f64>,
/// How much wider or narrower each turn by `+` and `-` may randomly be, as a fraction of its angle.
#[range]
#[hard(0..1)]
angle_jitter: Item<f64>,
/// The width the turtle starts drawing with.
#[unit(" px")]
#[default(1.)]
width: Item<f64>,
/// The factor that `!` multiplies the width by and `?` divides it by, unless a command gives its own like `!(0.8)`.
#[unit("x")]
#[default(0.5)]
width_scale: Item<f64>,
/// How much thicker or thinner each line's width may randomly be, as a fraction of it.
#[range]
#[hard(0..1)]
width_jitter: Item<f64>,
/// How far `T` bends a sideways heading toward the ground like branches sagging under gravity, and less the nearer it is to vertical, unless a command gives its own amount like `T(5)`. A negative amount bends toward the sky instead.
#[unit("°")]
#[default(10.)]
#[range]
#[soft(-90..90)]
tropism: Item<f64>,
/// How much `'` and `#` count up U and V, unless a command gives its own amount like `'(2)`.
#[name("UV Increment")]
#[default(1., 1.)]
#[widget(ParsedWidgetOverride::Custom = "vec2_uv")]
uv_increment: Item<DVec2>,
/// Seed to determine unique variations on the random turns of `~` and the step, angle, and width jitters.
#[hard(0..)]
seed: Item<i64>,
) -> Item<Vector> {
let settings = crate::turtle::TurtleSettings {
step: *step.element(),
step_scale: *step_scale.element(),
step_jitter: *step_jitter.element(),
angle: *angle.element(),
angle_scale: *angle_scale.element(),
angle_jitter: *angle_jitter.element(),
width: *width.element(),
width_scale: *width_scale.element(),
width_jitter: *width_jitter.element(),
tropism: *tropism.element(),
uv_increment: *uv_increment.element(),
seed: *seed.element() as u64,
};
crate::turtle::turtle_path(commands.element(), &settings)
}
#[cfg(test)]
mod tests {
use super::*;
use core_types::list::ATTR_SMOOTH;
use core_types::list::{ATTR_DEPTH, ATTR_DISTANCE, ATTR_HEADING, ATTR_KIND, ATTR_SMOOTH, ATTR_STEP, ATTR_UV, ATTR_WIDTH};
use kurbo::ParamCurve;
use vector_types::vector::misc::point_to_dvec2;
use vector_types::vector::shared_paths_from_item_attributes;
@@ -706,4 +789,236 @@ mod tests {
assert!(anchors.iter().all(|anchor| (anchor.length() - 25.).abs() < 1e-9));
}
}
fn turtle(commands: &str) -> Item<Vector> {
turtle_varied(commands, 0., 0)
}
fn turtle_varied(commands: &str, step_jitter: f64, seed: i64) -> Item<Vector> {
let text = |text: &str| item(text.to_string());
turtle_path(
(),
text(commands),
item(10.),
item(0.5),
item(step_jitter),
item(90.),
item(0.5),
item(0.),
item(1.),
item(0.5),
item(0.),
item(10.),
item(DVec2::ONE),
item(seed),
)
}
fn positions(drawing: &Item<Vector>) -> Vec<DVec2> {
drawing.element().positions().collect()
}
/// Each path's pool references and whether it closes.
fn turtle_runs(drawing: &Item<Vector>) -> Vec<(Vec<u32>, bool)> {
let paths = shared_paths_from_item_attributes(drawing);
paths.iter_element_values().map(|path| (path.references().collect(), path.is_closed())).collect()
}
fn point_attributes<T: Copy + 'static>(drawing: &Item<Vector>, key: &str) -> Vec<T> {
drawing.element().0.iter_attribute_values::<T>(key).map(|values| values.copied().collect()).unwrap_or_default()
}
#[test]
fn turtle_square_closes_on_its_start() {
let square = turtle("F+F+F+F");
assert_eq!(turtle_runs(&square), [(vec![0, 1, 2, 3, 0], true)]);
assert_eq!(
square.element().positions().collect::<Vec<_>>(),
[DVec2::ZERO, DVec2::new(0., -10.), DVec2::new(-10., -10.), DVec2::new(-10., 0.)]
);
// Drawing on after closing leaves the square closed and starts a new path from its first point
assert_eq!(turtle_runs(&turtle("F+F+F+F+F")), [(vec![0, 1, 2, 3, 0], true), (vec![0, 4], false)]);
}
#[test]
fn turtle_branches_weld_to_one_trunk() {
let tree = turtle("F[+F]F");
// The trunk stays one run through the junction, where the branch begins
assert_eq!(turtle_runs(&tree), [(vec![0, 1, 3], false), (vec![1, 2], false)]);
assert_eq!(point_attributes::<i64>(&tree, ATTR_DEPTH), [0, 0, 1, 0]);
assert_eq!(point_attributes::<f64>(&tree, ATTR_DISTANCE), [0., 10., 20., 20.]);
assert_eq!(point_attributes::<f64>(&tree, ATTR_HEADING), [-90., -90., 180., -90.]);
// Branches leaving before anything is drawn still share their starting point
assert_eq!(turtle_runs(&turtle("[+F][-F]F")), [(vec![0, 1], false), (vec![0, 2], false), (vec![0, 3], false)]);
}
#[test]
fn turtle_moves_break_paths_and_parameters_override_amounts() {
let drawing = turtle("FfF(25)+(45)F");
assert_eq!(turtle_runs(&drawing), [(vec![0, 1], false), (vec![2, 3, 4], false)]);
let positions: Vec<DVec2> = drawing.element().positions().collect();
assert_eq!(positions[3], DVec2::new(0., -45.));
assert!((positions[4] - DVec2::new(-10. * 0.5_f64.sqrt(), -45. - 10. * 0.5_f64.sqrt())).length() < 1e-9);
// `g` moves just like `f`
let moved = turtle("FgF");
assert_eq!(turtle_runs(&moved), [(vec![0, 1], false), (vec![2, 3], false)]);
assert_eq!(moved.element().positions().nth(2), Some(DVec2::new(0., -20.)));
}
#[test]
fn turtle_width_scales_and_is_restored_after_a_branch() {
let drawing = turtle("F[!(3)F]F");
assert_eq!(point_attributes::<f64>(&drawing, ATTR_WIDTH), [1., 1., 3., 1.]);
// The width halves and doubles back, and dividing by zero leaves it alone
assert_eq!(point_attributes::<f64>(&turtle("F!F?F?(0)F"), ATTR_WIDTH), [1., 1., 0.5, 1., 1.]);
// `G` draws like `F`, and other letters mean nothing to the turtle
assert_eq!(turtle_runs(&turtle("FGAF")), [(vec![0, 1, 2, 3], false)]);
assert_eq!(point_attributes::<f64>(&turtle(""), ATTR_WIDTH), Vec::<f64>::new());
assert!(turtle("").element().0.iter_attribute_values::<f64>(ATTR_WIDTH).is_some(), "an empty drawing still has the attribute");
// A draw's second number stamps only the point it draws to
assert_eq!(point_attributes::<f64>(&turtle("F(10, 3)F"), ATTR_WIDTH), [1., 3., 1.]);
}
#[test]
fn turtle_half_steps_and_scaled_steps() {
let halves = turtle("HhH");
assert_eq!(turtle_runs(&halves), [(vec![0, 1], false), (vec![2, 3], false)]);
assert_eq!(positions(&halves), [DVec2::ZERO, DVec2::new(0., -5.), DVec2::new(0., -10.), DVec2::new(0., -15.)]);
// The step halves and doubles back, and dividing by zero leaves it alone
let ys: Vec<f64> = positions(&turtle("F\"F_F_(0)F")).iter().map(|position| position.y).collect();
assert_eq!(ys, [0., -10., -15., -25., -35.]);
// The angle halves to 45°, then doubles back to 90° once the branch ends
let angled = positions(&turtle("[;+F]+F"));
assert!((angled[1] - DVec2::new(-10. * 0.5_f64.sqrt(), -10. * 0.5_f64.sqrt())).length() < 1e-9);
assert_eq!(angled[2], DVec2::new(-10., 0.));
}
#[test]
fn turtle_bends_toward_the_ground_without_passing_it() {
// Heading left, the turtle bends 10° down
let bent = positions(&turtle("+T(10)F"));
assert!((bent[1] - 10. * DVec2::from_angle(170_f64.to_radians())).length() < 1e-9);
// A vertical heading doesn't bend, and a strong pull stops at straight down
assert_eq!(positions(&turtle("T(10)F"))[1], DVec2::new(0., -10.));
assert_eq!(positions(&turtle("+T(1000)F"))[1], DVec2::new(0., 10.));
}
#[test]
fn turtle_closes_polygons_through_recorded_anchors() {
let square = turtle("{.f.+f.+f.}");
assert_eq!(turtle_runs(&square), [(vec![0, 1, 2, 3, 0], true)]);
assert_eq!(positions(&square), [DVec2::ZERO, DVec2::new(0., -10.), DVec2::new(-10., -10.), DVec2::new(-10., 0.)]);
// A last anchor back on the first isn't repeated, and too few anchors make no shape
assert_eq!(turtle_runs(&turtle("{.f.+f.+f.+f.}")), [(vec![0, 1, 2, 3, 0], true)]);
assert_eq!(positions(&turtle("{.f.}")), []);
// A shape the commands leave open still closes, as if its `}` came last
assert_eq!(turtle_runs(&turtle("{.f.+f.+f.")), [(vec![0, 1, 2, 3, 0], true)]);
}
#[test]
fn turtle_counts_up_uv() {
let drawing = turtle("F'F#F'(2)F");
let expected = [DVec2::ZERO, DVec2::ZERO, DVec2::new(1., 0.), DVec2::new(1., 1.), DVec2::new(3., 1.)];
assert_eq!(point_attributes::<DVec2>(&drawing, ATTR_UV), expected);
}
#[test]
fn turtle_places_points_of_a_kind_on_no_path() {
let drawing = turtle("F[+F.(2)]\"F.");
// The placed points 3 and 5 join no path, but carry the turtle's state and their kind
assert_eq!(turtle_runs(&drawing), [(vec![0, 1, 4], false), (vec![1, 2], false)]);
assert_eq!(positions(&drawing)[3], DVec2::new(-10., -10.));
assert_eq!(positions(&drawing)[5], DVec2::new(0., -15.));
assert_eq!(point_attributes::<i64>(&drawing, ATTR_KIND), [0, 0, 0, 2, 0, 1]);
assert_eq!(point_attributes::<i64>(&drawing, ATTR_DEPTH), [0, 0, 1, 1, 0, 0]);
assert_eq!(point_attributes::<f64>(&drawing, ATTR_HEADING)[3], 180.);
assert_eq!(point_attributes::<f64>(&drawing, ATTR_STEP), [10., 10., 10., 10., 5., 5.]);
// Inside a shape, `.` adds an anchor, but a branch saved there can return after the shape closes to place a point
let shape = turtle("{.f.[+f.+f.}].");
assert_eq!(turtle_runs(&shape), [(vec![0, 1, 2, 3, 0], true)]);
assert_eq!(positions(&shape)[4], DVec2::new(0., -10.));
assert_eq!(point_attributes::<i64>(&shape, ATTR_KIND), [0, 0, 0, 0, 1]);
// Several spots saved inside a shape come back last first, one per `]`
let saved_twice = turtle("{.f.[+f.[+f.}].].");
assert_eq!(turtle_runs(&saved_twice), [(vec![0, 1, 2, 3, 0], true)]);
assert_eq!(positions(&saved_twice)[4..], [DVec2::new(-10., -10.), DVec2::new(0., -10.)]);
assert_eq!(point_attributes::<i64>(&saved_twice, ATTR_KIND), [0, 0, 0, 0, 1, 1]);
assert_eq!(point_attributes::<i64>(&saved_twice, ATTR_DEPTH), [0, 0, 1, 2, 1, 0]);
}
#[test]
fn turtle_randomness_follows_the_seed() {
let wander = |seed: i64| positions(&turtle_varied("~(30)F~(30)F", 0.2, seed));
assert_eq!(wander(3), wander(3));
assert_ne!(wander(3), wander(4));
// The first step stays within 20% of its length and 30° of straight up
let first = wander(3)[1];
assert!((8. ..=12.).contains(&first.length()));
assert!(first.angle_to(DVec2::NEG_Y).abs() <= 30_f64.to_radians() + 1e-9);
assert!((0..8).any(|seed| (wander(seed)[1].length() - 10.).abs() > 1.), "some seed should stray past 10%");
}
#[test]
fn turtle_jitters_turns_and_widths() {
let jittered = |seed: u64| {
let settings = crate::turtle::TurtleSettings {
angle_jitter: 0.5,
width_jitter: 0.5,
seed,
..Default::default()
};
crate::turtle::turtle_path("F+F", &settings)
};
let turn = |seed: u64| {
let points = positions(&jittered(seed));
(points[1] - points[0]).angle_to(points[2] - points[1]).to_degrees().abs()
};
// A 90° turn stays within half of itself either way, and so does the width each line draws to
assert!((0..8).all(|seed| (45. - 1e-9..=135. + 1e-9).contains(&turn(seed))));
assert!((0..8).any(|seed| (turn(seed) - 90.).abs() > 10.), "some seed should turn well off 90°");
let widths: Vec<f64> = (0..8).flat_map(|seed| point_attributes::<f64>(&jittered(seed), ATTR_WIDTH)[1..].to_vec()).collect();
assert!(widths.iter().all(|width| (0.5..=1.5).contains(width)));
assert!(widths.iter().any(|width| (width - 1.).abs() > 0.1), "some seed should vary the width");
}
#[test]
fn turtle_jitters_grow_gradually_and_leave_random_turns_alone() {
let drawn = |step_jitter: f64, angle_jitter: f64, width_jitter: f64| {
let settings = crate::turtle::TurtleSettings {
step_jitter,
angle_jitter,
width_jitter,
seed: 3,
..Default::default()
};
positions(&crate::turtle::turtle_path("~F+F~F", &settings))
};
let unjittered = drawn(0., 0., 0.);
// Width moves no points, so turning it up keeps the `~` turns as they were
assert_eq!(drawn(0., 0., 0.5), unjittered);
// Barely turning up the step and angle jitters barely moves the points
let nudged = drawn(1e-6, 1e-6, 0.);
assert!(nudged.iter().zip(&unjittered).all(|(nudged, unjittered)| nudged.distance(*unjittered) < 1e-3));
}
}
+1
View File
@@ -1,6 +1,7 @@
pub mod generator_nodes;
mod grid_topology;
pub mod merge_qr_squares;
mod turtle;
pub mod vector_modification_nodes;
mod vector_nodes;
mod voronoi;
+419
View File
@@ -0,0 +1,419 @@
use core_types::list::{ATTR_DEPTH, ATTR_DISTANCE, ATTR_HEADING, ATTR_ID, ATTR_KIND, ATTR_STEP, ATTR_UV, ATTR_WIDTH, Item, List};
use core_types::misc::parse_f64;
use glam::DVec2;
use graphic_types::Vector;
use rand::rngs::StdRng;
use rand::{RngExt, SeedableRng};
use vector_types::vector::{CurveType, Path, PointId, SegmentId, SetVectorPaths, push_paths};
/// How close, as a fraction of the step just drawn, a draw must land on its path's first point to close the path there.
const CLOSURE_TOLERANCE: f64 = 1e-6;
/// How far `~` may turn either way, unless a command gives its own limit like `~(30)`.
const RANDOM_TURN_LIMIT: f64 = 180.;
/// The kind assigned to every drawn point, matching what points from elsewhere without a kind read as.
const DRAWN_KIND: i64 = 0;
/// The kind of a point that `.` places outside a shape without a number of its own.
const PLACED_KIND: i64 = 1;
/// The node's inputs, which the commands fall back to when they don't give their own numbers.
pub(crate) struct TurtleSettings {
pub step: f64,
pub step_scale: f64,
/// The most a step's length varies at random, as a fraction of it.
pub step_jitter: f64,
pub angle: f64,
pub angle_scale: f64,
/// The most a turn's angle varies at random, as a fraction of it.
pub angle_jitter: f64,
pub width: f64,
pub width_scale: f64,
/// The most the width a line draws to varies at random, as a fraction of it.
pub width_jitter: f64,
pub tropism: f64,
pub uv_increment: DVec2,
pub seed: u64,
}
#[cfg(test)]
impl Default for TurtleSettings {
/// The node's default inputs.
fn default() -> Self {
Self {
step: 10.,
step_scale: 0.5,
step_jitter: 0.,
angle: 90.,
angle_scale: 0.5,
angle_jitter: 0.,
width: 1.,
width_scale: 0.5,
width_jitter: 0.,
tropism: 10.,
uv_increment: DVec2::ONE,
seed: 0,
}
}
}
/// The turtle's place, direction, and pen, which `[` saves and `]` restores.
#[derive(Clone, Copy)]
struct Turtle {
position: DVec2,
/// Degrees, with `0.` along +X and positive angles turning clockwise on screen.
heading: f64,
distance: f64,
depth: i64,
/// The length of a step, which `"` and `_` scale.
step: f64,
/// The angle of a turn, which `;` and `@` scale.
angle: f64,
/// The width of the line, which `!` and `?` scale.
width: f64,
/// The U and V numbers, which `'` and `#` count up.
uv: DVec2,
/// The drawing's slot for the point the turtle stands on, which a branch shares with its parent so both weld there.
anchor_slot: usize,
/// The run being drawn, as an index into the drawing's runs.
run: Option<usize>,
}
impl Turtle {
fn turn(&mut self, degrees: f64) {
self.heading = (self.heading + degrees).rem_euclid(360.);
}
/// Turns a sideways heading `tropism` degrees toward straight down, and less the nearer it is to vertical, without turning past it.
/// A negative tropism bends toward straight up instead.
fn bend_down(&mut self, tropism: f64) {
let target = if tropism >= 0. { 90. } else { 270. };
let remaining = (target - self.heading + 180.).rem_euclid(360.) - 180.;
// The sideways part of the heading, which is exactly zero when vertical
let sideways = direction(self.heading).x;
self.turn((tropism * sideways).clamp(-remaining.abs(), remaining.abs()));
}
/// Moves forward regardless of the pen, counting the distance traveled.
fn advance(&mut self, length: f64) {
self.position += length * direction(self.heading);
self.distance += length.abs();
}
}
/// The unit vector a heading in degrees points along, exact for multiples of 90° so square lattices stay on whole numbers.
fn direction(heading: f64) -> DVec2 {
let quarter_turns = heading / 90.;
if quarter_turns.fract() == 0. {
return match (quarter_turns as i64).rem_euclid(4) {
0 => DVec2::X,
1 => DVec2::Y,
2 => DVec2::NEG_X,
_ => DVec2::NEG_Y,
};
}
DVec2::from_angle(heading.to_radians())
}
/// Scales an amount by a random factor within `jitter` of 1, only drawing from the generator when there's variation to give.
fn vary(amount: f64, jitter: f64, rng: &mut StdRng) -> f64 {
if jitter == 0. {
return amount;
}
amount * (1. + jitter * rng.random_range(-1. ..=1.))
}
/// A place the turtle has stood, which gains its point the first time something is drawn from it.
#[derive(Clone, Copy)]
enum AnchorSlot {
Drawn(u32),
/// The turtle as it arrived, whose state stamps the point once one is drawn.
Undrawn(Turtle),
}
/// The points and path runs a turtle lays down, with each point's attributes alongside.
#[derive(Default)]
struct Drawing {
positions: Vec<DVec2>,
depths: Vec<i64>,
distances: Vec<f64>,
headings: Vec<f64>,
widths: Vec<f64>,
uvs: Vec<DVec2>,
steps: Vec<f64>,
kinds: Vec<i64>,
/// Pool indices of each run, in the order the runs began.
runs: Vec<Vec<u32>>,
anchor_slots: Vec<AnchorSlot>,
}
impl Drawing {
fn new_anchor_slot(&mut self, slot: AnchorSlot) -> usize {
self.anchor_slots.push(slot);
self.anchor_slots.len() - 1
}
/// Adds a point where the turtle stands, stamped with its state and a kind, and gives its pool index.
fn push_point(&mut self, turtle: &Turtle, kind: i64) -> u32 {
self.positions.push(turtle.position);
self.depths.push(turtle.depth);
self.distances.push(turtle.distance);
// Reported from -180° to 180°, so the starting heading up the screen reads as -90°
self.headings.push(180. - (180. - turtle.heading).rem_euclid(360.));
self.widths.push(turtle.width);
self.uvs.push(turtle.uv);
self.steps.push(turtle.step);
self.kinds.push(kind);
(self.positions.len() - 1) as u32
}
/// The point of the place the turtle stands, drawing it there if this is the first time it's needed.
fn anchor_point(&mut self, turtle: &Turtle) -> u32 {
let arrival = match self.anchor_slots.get(turtle.anchor_slot) {
Some(AnchorSlot::Drawn(anchor)) => return *anchor,
Some(AnchorSlot::Undrawn(arrival)) => *arrival,
None => {
log::error!("The turtle stands at a place the drawing has no slot for");
*turtle
}
};
let anchor = self.push_point(&arrival, DRAWN_KIND);
if let Some(slot) = self.anchor_slots.get_mut(turtle.anchor_slot) {
*slot = AnchorSlot::Drawn(anchor);
}
anchor
}
/// Draws a segment forward from the turtle, continuing its run or beginning one from the point it stands on.
/// The `width` stamps only the point drawn to, leaving the turtle's own width as it was.
fn draw(&mut self, turtle: &mut Turtle, length: f64, width: f64) {
let start = self.anchor_point(turtle);
let run = match turtle.run {
Some(run) => run,
None => {
self.runs.push(vec![start]);
self.runs.len() - 1
}
};
turtle.advance(length);
// Landing back on the run's first point closes the run there rather than adding a duplicate point
let first = self.runs[run][0];
let closes = self.runs[run].len() >= 3 && turtle.position.distance(self.positions[first as usize]) <= CLOSURE_TOLERANCE * length.abs();
let end = if closes {
turtle.position = self.positions[first as usize];
first
} else {
self.push_point(&Turtle { width, ..*turtle }, DRAWN_KIND)
};
self.runs[run].push(end);
turtle.anchor_slot = self.new_anchor_slot(AnchorSlot::Drawn(end));
// A closed run is finished, so drawing on begins a new one from the point it closed on
turtle.run = if closes { None } else { Some(run) };
}
/// Moves the turtle forward without drawing, so its next draw begins a new run.
fn travel(&mut self, turtle: &mut Turtle, length: f64) {
turtle.advance(length);
turtle.run = None;
turtle.anchor_slot = self.new_anchor_slot(AnchorSlot::Undrawn(*turtle));
}
/// Adds a closed path through the places the turtle recorded with `.`, leaving out a last one that returns to the first.
fn add_polygon(&mut self, mut anchors: Vec<Turtle>) {
if let [first, .., before_last, last] = anchors.as_slice()
&& last.position.distance(first.position) <= CLOSURE_TOLERANCE * last.position.distance(before_last.position)
{
anchors.pop();
}
if anchors.len() < 3 {
return;
}
let mut references: Vec<u32> = anchors.iter().map(|anchor| self.push_point(anchor, DRAWN_KIND)).collect();
references.push(references[0]);
self.runs.push(references);
}
/// Builds the vector, numbering the points and then the segments in the order they were drawn.
fn into_item(self) -> Item<Vector> {
let point_count = self.positions.len();
let mut vector = Vector(List::new_from_elements(self.positions));
if point_count > 0 {
let mut point_id = PointId::ZERO;
vector.0.set_attribute_values(ATTR_ID, (0..point_count).map(|_| point_id.next_id()).collect::<Vec<_>>());
}
vector.0.set_attribute_values(ATTR_DEPTH, self.depths);
vector.0.set_attribute_values(ATTR_DISTANCE, self.distances);
vector.0.set_attribute_values(ATTR_HEADING, self.headings);
vector.0.set_attribute_values(ATTR_WIDTH, self.widths);
vector.0.set_attribute_values(ATTR_UV, self.uvs);
vector.0.set_attribute_values(ATTR_STEP, self.steps);
vector.0.set_attribute_values(ATTR_KIND, self.kinds);
let mut segment_id = SegmentId::ZERO;
let runs = self.runs.into_iter().filter(|references| references.len() > 1).map(|references| {
let ids = (1..references.len()).map(|_| segment_id.next_id()).collect();
(CurveType::Linear, references, ids)
});
let mut paths = List::<Path>::new();
push_paths(&mut paths, runs);
Item::new_from_element(vector).with_paths(paths)
}
}
/// Splits a parenthesized parameter list off the front of the commands, giving its insides and the commands after it.
/// An unclosed list runs to the end of the commands.
fn split_parameters(commands: &str) -> (&str, &str) {
let mut nesting = 0;
for (index, character) in commands.char_indices() {
match character {
'(' => nesting += 1,
')' => {
nesting -= 1;
if nesting == 0 {
return (&commands[1..index], &commands[index + 1..]);
}
}
_ => {}
}
}
(&commands[1..], "")
}
/// Follows turtle commands from the origin, facing up the screen, and gives the paths it draws.
pub(crate) fn turtle_path(commands: &str, settings: &TurtleSettings) -> Item<Vector> {
let mut drawing = Drawing::default();
let mut turtle = Turtle {
position: DVec2::ZERO,
heading: 270.,
distance: 0.,
depth: 0,
step: settings.step,
angle: settings.angle,
width: settings.width,
uv: DVec2::ZERO,
anchor_slot: 0,
run: None,
};
turtle.anchor_slot = drawing.new_anchor_slot(AnchorSlot::Undrawn(turtle));
let mut saved = Vec::new();
// Each source of randomness gets its own generator, seeded far from the others, so a jitter turned up from 0 changes the drawing gradually and leaves the rest alone
let generator = |source: u64| StdRng::seed_from_u64(settings.seed ^ source.wrapping_mul(0x9E37_79B9_7F4A_7C15));
let mut random_turn_rng = generator(0);
let mut step_jitter_rng = generator(1);
let mut angle_jitter_rng = generator(2);
let mut width_jitter_rng = generator(3);
// The anchors recorded by `.` for each shape that `{` began and `}` hasn't yet closed, innermost last
let mut polygons: Vec<Vec<Turtle>> = Vec::new();
let mut remaining = commands;
while let Some(symbol) = remaining.chars().next() {
remaining = &remaining[symbol.len_utf8()..];
// A parenthesized list after a symbol belongs to it
let parameters = if remaining.starts_with('(') {
let (parameters, after) = split_parameters(remaining);
remaining = after;
parameters
} else {
""
};
let number = |index: usize| parameters.split(',').nth(index).and_then(|parameter| parse_f64(parameter.trim()));
match symbol {
'F' | 'G' => {
let length = vary(number(0).unwrap_or(turtle.step), settings.step_jitter, &mut step_jitter_rng);
let width = vary(number(1).unwrap_or(turtle.width), settings.width_jitter, &mut width_jitter_rng);
drawing.draw(&mut turtle, length, width);
}
'f' | 'g' => {
let length = vary(number(0).unwrap_or(turtle.step), settings.step_jitter, &mut step_jitter_rng);
drawing.travel(&mut turtle, length);
}
'H' => {
let length = vary(number(0).unwrap_or(turtle.step) / 2., settings.step_jitter, &mut step_jitter_rng);
let width = vary(number(1).unwrap_or(turtle.width), settings.width_jitter, &mut width_jitter_rng);
drawing.draw(&mut turtle, length, width);
}
'h' => {
let length = vary(number(0).unwrap_or(turtle.step) / 2., settings.step_jitter, &mut step_jitter_rng);
drawing.travel(&mut turtle, length);
}
'+' => turtle.turn(-vary(number(0).unwrap_or(turtle.angle), settings.angle_jitter, &mut angle_jitter_rng)),
'-' => turtle.turn(vary(number(0).unwrap_or(turtle.angle), settings.angle_jitter, &mut angle_jitter_rng)),
'|' => turtle.turn(180.),
'~' => turtle.turn(number(0).unwrap_or(RANDOM_TURN_LIMIT) * random_turn_rng.random_range(-1. ..=1.)),
'T' => turtle.bend_down(number(0).unwrap_or(settings.tropism)),
'"' => turtle.step *= number(0).unwrap_or(settings.step_scale),
'_' => {
let divisor = number(0).unwrap_or(settings.step_scale);
if divisor != 0. {
turtle.step /= divisor;
}
}
';' => turtle.angle *= number(0).unwrap_or(settings.angle_scale),
'@' => {
let divisor = number(0).unwrap_or(settings.angle_scale);
if divisor != 0. {
turtle.angle /= divisor;
}
}
'!' => turtle.width *= number(0).unwrap_or(settings.width_scale),
'?' => {
let divisor = number(0).unwrap_or(settings.width_scale);
if divisor != 0. {
turtle.width /= divisor;
}
}
'\'' => turtle.uv.x += number(0).unwrap_or(settings.uv_increment.x),
'#' => turtle.uv.y += number(0).unwrap_or(settings.uv_increment.y),
'[' => {
saved.push(turtle);
turtle.depth += 1;
turtle.run = None;
}
']' => {
if let Some(restored) = saved.pop() {
turtle = restored;
}
}
'{' => polygons.push(Vec::new()),
'.' => match polygons.last_mut() {
Some(anchors) => anchors.push(turtle),
// Outside a shape, the point joins no path, so it marks a position without drawing anything
None => {
let kind = number(0).map_or(PLACED_KIND, |kind| kind.round() as i64);
drawing.push_point(&turtle, kind);
}
},
'}' => {
if let Some(anchors) = polygons.pop() {
drawing.add_polygon(anchors);
}
}
_ => {}
}
}
// Shapes still open when the commands end close as if their `}` came last, innermost first
while let Some(anchors) = polygons.pop() {
drawing.add_polygon(anchors);
}
drawing.into_item()
}
@@ -4296,6 +4296,44 @@ mod test {
assert_eq!(positions, [DVec2::new(-15., -13.), DVec2::new(25., -13.), DVec2::new(25., 27.), DVec2::new(-15., 27.)]);
}
#[test]
fn vector_to_points_and_open_ends_keep_point_attributes() {
use core_types::list::{ATTR_DEPTH, ATTR_HEADING, ATTR_KIND};
// A trunk with a branch to the left, placed 100 px to the right
let tree = crate::turtle::turtle_path("F[+F]F", &Default::default()).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::new(100., 0.)));
let points = super::vector_to_points((), tree.clone());
assert_eq!(points.iter_element_values().count(), 4);
assert_eq!(
points.iter_attribute_values::<i64>(ATTR_DEPTH).map(|depths| depths.copied().collect::<Vec<_>>()),
Some(vec![0, 0, 1, 0])
);
// The root and both tips, but not the junction where the branch leaves the trunk
let ends = super::open_ends((), tree);
let positions: Vec<DVec2> = ends.iter_element_values().copied().collect();
assert_eq!(positions, [DVec2::new(100., 0.), DVec2::new(90., -10.), DVec2::new(100., -20.)]);
assert_eq!(
ends.iter_attribute_values::<f64>(ATTR_HEADING).map(|headings| headings.copied().collect::<Vec<_>>()),
Some(vec![-90., 180., -90.])
);
// A closed path has no open ends
let square = crate::turtle::turtle_path("F+F+F+F", &Default::default());
assert_eq!(super::open_ends((), square).len(), 0);
// A point placed by `.` outside a shape is listed with the anchors, but isn't an open end
let marked = crate::turtle::turtle_path("F.(3)", &Default::default());
assert_eq!(
super::vector_to_points((), marked.clone())
.iter_attribute_values::<i64>(ATTR_KIND)
.map(|kinds| kinds.copied().collect::<Vec<_>>()),
Some(vec![0, 0, 3])
);
assert_eq!(super::open_ends((), marked).len(), 2);
}
fn convex_hull_of(bezpath: BezPath, transform: DAffine2, curvature: f64) -> Item<Vector> {
let hull = super::convex_hull((), create_vector_item(bezpath, transform), item(curvature));
assert_eq!(hull.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM), transform, "the hull should keep its item's transform");