mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c403654745 | ||
|
|
6c3232ee8c |
No files matched your search
Generated
-1
@@ -1226,7 +1226,6 @@ dependencies = [
|
||||
"kurbo",
|
||||
"log",
|
||||
"lyon_geom",
|
||||
"math-parser",
|
||||
"node-macro",
|
||||
"num-derive",
|
||||
"num-traits",
|
||||
|
||||
@@ -57,10 +57,6 @@ pub mod network {
|
||||
pub const IMPORT_METADATA: &str = "ui::import_metadata";
|
||||
pub const EXPORT_NAMES: &str = "ui::export_names";
|
||||
pub const EXPORT_DESCRIPTIONS: &str = "ui::export_descriptions";
|
||||
|
||||
/// How many pixels make an inch in the network's document, which sizes lengths typed in a physical unit. Absent where it
|
||||
/// is the default, CSS's 96. Only the root network's applies.
|
||||
pub const PIXELS_PER_INCH: &str = "pixels_per_inch";
|
||||
}
|
||||
|
||||
pub mod delta {
|
||||
|
||||
@@ -473,12 +473,6 @@ fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(
|
||||
.map_err(map_serialization_error(network::PINNED_ORDER))?;
|
||||
}
|
||||
|
||||
if let Some(pixels_per_inch) = metadata.pixels_per_inch(location) {
|
||||
attributes
|
||||
.set_serialized(network::PIXELS_PER_INCH, &pixels_per_inch, timestamp)
|
||||
.map_err(map_serialization_error(network::PIXELS_PER_INCH))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -38,8 +38,6 @@ pub struct NetworkMetadataEntry {
|
||||
pub import_metadata: Vec<InputMetadataEntry>,
|
||||
pub export_names: Vec<String>,
|
||||
pub export_descriptions: Vec<String>,
|
||||
/// The document's pixels per inch, where it differs from the default.
|
||||
pub pixels_per_inch: Option<f64>,
|
||||
}
|
||||
|
||||
/// Editor metadata for one import of a subgraph. Mirrors `InputPersistentMetadata` but wraps strings in `Option` so
|
||||
@@ -80,11 +78,6 @@ pub trait NodeMetadataSource {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// The network's pixels per inch, where it differs from the default.
|
||||
fn pixels_per_inch(&self, _network: NetworkLocation) -> Option<f64> {
|
||||
None
|
||||
}
|
||||
|
||||
fn import_metadata(&self, _network: NetworkLocation) -> Vec<InputMetadataEntry> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
@@ -12,25 +12,9 @@ use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry, from_valu
|
||||
/// Note: This only works for complete networks with all inputs resolved.
|
||||
/// Test networks with Import inputs will fail compilation (which is expected).
|
||||
fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
|
||||
let mut network = network.clone();
|
||||
network.inline_definitions().map_err(|e| format!("Inlining failed: {e}"))?;
|
||||
|
||||
// Nodes measuring in physical units read the document's resolution from the scope the runtime wraps every document in
|
||||
let resolution_node = NodeId(u64::MAX);
|
||||
network.nodes.insert(
|
||||
resolution_node,
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::value(TaggedValue::Number(core_types::units::DEFAULT_PIXELS_PER_INCH), false)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::PassthroughNode")),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
network
|
||||
.scope_injections
|
||||
.insert(core_types::units::PIXELS_PER_INCH_SCOPE.to_string(), (resolution_node, core_types::item!(f64)));
|
||||
|
||||
let compiler = Compiler {};
|
||||
compiler.compile_single(network).map_err(|e| format!("Compilation failed: {:?}", e))?;
|
||||
Ok(())
|
||||
|
||||
@@ -417,7 +417,6 @@ fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes,
|
||||
import_metadata: attributes.get_or_default(network::IMPORT_METADATA),
|
||||
export_names: attributes.get_or_default(network::EXPORT_NAMES),
|
||||
export_descriptions: attributes.get_or_default(network::EXPORT_DESCRIPTIONS),
|
||||
pixels_per_inch: attributes.get_typed(network::PIXELS_PER_INCH),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
use migration_core::{Inputs, NodeInput, migration};
|
||||
|
||||
/// Reads the document's resolution from the scope, which sizes the physical lengths an expression measures.
|
||||
#[migration("math_nodes::MathFunctionNode"@2 => @3)]
|
||||
pub fn math_function_v2(inputs: &mut Inputs) {
|
||||
inputs.push(NodeInput::Scope("pixels-per-inch".into()));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::{decl, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants the node's inputs hold in version 2.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Number(f64),
|
||||
String(String),
|
||||
}
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(3, |random, slot| match slot {
|
||||
1 => literal(Tagged::String("x".to_string())),
|
||||
_ => literal(Tagged::Number(random.below(10) as f64)),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&MathFunctionV2, &contract());
|
||||
check_undo(&MathFunctionV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_resolution_is_read_from_the_scope() {
|
||||
let inputs = vec![literal(Tagged::Number(2.)), literal(Tagged::String("x * 2".to_string())), literal(Tagged::Number(0.))];
|
||||
|
||||
let mut fixture = Fixture::new(&MathFunctionV2);
|
||||
let function = fixture.add(decl!("math_nodes::MathFunctionNode"@2), inputs.clone());
|
||||
let migrated = fixture.migrate(&MathFunctionV2).unwrap();
|
||||
|
||||
let expected: Vec<NodeInput> = inputs.into_iter().chain([NodeInput::Scope("pixels-per-inch".into())]).collect();
|
||||
assert_eq!(fixture.inputs(&migrated, function), expected);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
//! Migrations of the nodes in `math_nodes`.
|
||||
|
||||
mod math_formula_from_math_f;
|
||||
mod math_function_v2;
|
||||
mod renames;
|
||||
@@ -1,65 +0,0 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const RADIUS: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The radius is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("vector_nodes::generator_nodes::CircleNode"@1 => @2)]
|
||||
pub fn circle_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(RADIUS) else { return };
|
||||
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(
|
||||
RADIUS as u32,
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&CircleV1, &contract());
|
||||
check_undo(&CircleV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&CircleV1);
|
||||
let circle = fixture.add(decl!("vector_nodes::generator_nodes::CircleNode"@1), vec![literal(Tagged::None), literal(Tagged::Number(50.))]);
|
||||
let migrated = fixture.migrate(&CircleV1).unwrap();
|
||||
|
||||
let radius = literal(Tagged::Length(TypedLength { value: 50., unit: LengthUnit::Pixel }));
|
||||
assert_eq!(fixture.inputs(&migrated, circle), [literal(Tagged::None), radius]);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
//! Migrations of the nodes in `vector_nodes`.
|
||||
|
||||
mod circle_v1;
|
||||
mod path_from_path_network;
|
||||
mod renames;
|
||||
@@ -6,8 +6,6 @@ use crate::messages::prelude::*;
|
||||
pub enum DialogMessage {
|
||||
// Sub-messages
|
||||
#[child]
|
||||
DocumentSetupDialog(DocumentSetupDialogMessage),
|
||||
#[child]
|
||||
ExportDialog(ExportDialogMessage),
|
||||
#[child]
|
||||
NewDocumentDialog(NewDocumentDialogMessage),
|
||||
@@ -36,7 +34,6 @@ pub enum DialogMessage {
|
||||
localized_commit_year: String,
|
||||
},
|
||||
RequestDemoArtworkDialog,
|
||||
RequestDocumentSetupDialog,
|
||||
RequestExportDialog,
|
||||
RequestLicensesDialogWithLocalizedCommitDate {
|
||||
localized_commit_year: String,
|
||||
|
||||
@@ -4,7 +4,6 @@ use crate::messages::dialog::simple_dialogs::{ConfirmRestartDialog, LicensesThir
|
||||
use crate::messages::frontend::utility_types::ExportBounds;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::prelude::*;
|
||||
use graphene_std::units::{DEFAULT_PIXELS_PER_INCH, TypedLength};
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct DialogMessageContext<'a> {
|
||||
@@ -17,7 +16,6 @@ pub struct DialogMessageContext<'a> {
|
||||
pub struct DialogMessageHandler {
|
||||
on_dismiss: Option<Message>,
|
||||
redisplay: Option<Message>,
|
||||
document_setup_dialog: DocumentSetupDialogMessageHandler,
|
||||
export_dialog: ExportDialogMessageHandler,
|
||||
new_document_dialog: NewDocumentDialogMessageHandler,
|
||||
preferences_dialog: PreferencesDialogMessageHandler,
|
||||
@@ -29,7 +27,6 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
|
||||
let DialogMessageContext { portfolio, preferences } = context;
|
||||
|
||||
match message {
|
||||
DialogMessage::DocumentSetupDialog(message) => self.document_setup_dialog.process_message(message, responses, ()),
|
||||
DialogMessage::ExportDialog(message) => self.export_dialog.process_message(message, responses, ExportDialogMessageContext { portfolio }),
|
||||
DialogMessage::NewDocumentDialog(message) => self.new_document_dialog.process_message(message, responses, ()),
|
||||
DialogMessage::PreferencesDialog(message) => self.preferences_dialog.process_message(message, responses, PreferencesDialogMessageContext { preferences }),
|
||||
@@ -103,15 +100,6 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
|
||||
let dialog = DemoArtworkDialog;
|
||||
dialog.send_dialog_to_frontend(responses);
|
||||
}
|
||||
DialogMessage::RequestDocumentSetupDialog => {
|
||||
self.on_dismiss = Some(DialogMessage::Close.into());
|
||||
if let Some(document) = portfolio.active_document() {
|
||||
self.document_setup_dialog = DocumentSetupDialogMessageHandler {
|
||||
pixels_per_inch: document.network_interface.pixels_per_inch(),
|
||||
};
|
||||
self.document_setup_dialog.send_dialog_to_frontend(responses);
|
||||
}
|
||||
}
|
||||
DialogMessage::RequestExportDialog => {
|
||||
self.on_dismiss = Some(DialogMessage::Close.into());
|
||||
if let Some(document) = portfolio.active_document() {
|
||||
@@ -157,9 +145,7 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
|
||||
self.new_document_dialog = NewDocumentDialogMessageHandler {
|
||||
name: portfolio.generate_new_document_name(None),
|
||||
infinite: false,
|
||||
width: TypedLength::pixels(1920.),
|
||||
height: TypedLength::pixels(1080.),
|
||||
pixels_per_inch: DEFAULT_PIXELS_PER_INCH,
|
||||
dimensions: glam::UVec2::new(1920, 1080),
|
||||
};
|
||||
self.new_document_dialog.send_dialog_to_frontend(responses);
|
||||
}
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[impl_message(Message, DialogMessage, DocumentSetupDialog)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum DocumentSetupDialogMessage {
|
||||
Resolution { pixels_per_inch: f64 },
|
||||
|
||||
Submit,
|
||||
}
|
||||
-158
@@ -1,158 +0,0 @@
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::prelude::*;
|
||||
use graphene_std::units::DEFAULT_PIXELS_PER_INCH;
|
||||
|
||||
/// A dialog to allow users to change the settings of the active document.
|
||||
#[derive(Debug, Clone, ExtractField)]
|
||||
pub struct DocumentSetupDialogMessageHandler {
|
||||
pub pixels_per_inch: f64,
|
||||
}
|
||||
|
||||
impl Default for DocumentSetupDialogMessageHandler {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
pixels_per_inch: DEFAULT_PIXELS_PER_INCH,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<DocumentSetupDialogMessage, ()> for DocumentSetupDialogMessageHandler {
|
||||
fn process_message(&mut self, message: DocumentSetupDialogMessage, responses: &mut VecDeque<Message>, _: ()) {
|
||||
match message {
|
||||
DocumentSetupDialogMessage::Resolution { pixels_per_inch } => self.pixels_per_inch = pixels_per_inch,
|
||||
|
||||
DocumentSetupDialogMessage::Submit => {
|
||||
// The settings apply as one undo step, which ending the transaction drops if nothing changed
|
||||
responses.add(DocumentMessage::StartTransaction);
|
||||
responses.add(DocumentMessage::SetPixelsPerInch {
|
||||
pixels_per_inch: self.pixels_per_inch,
|
||||
});
|
||||
responses.add(DocumentMessage::EndTransaction);
|
||||
}
|
||||
}
|
||||
|
||||
self.send_dialog_to_frontend(responses);
|
||||
}
|
||||
|
||||
advertise_actions!(DocumentSetupDialogUpdate;
|
||||
);
|
||||
}
|
||||
|
||||
impl DialogLayoutHolder for DocumentSetupDialogMessageHandler {
|
||||
const ICON: &'static str = "File";
|
||||
const TITLE: &'static str = "Document Setup";
|
||||
|
||||
fn layout_buttons(&self) -> Layout {
|
||||
let widgets = vec![
|
||||
TextButton::new("OK")
|
||||
.emphasized(true)
|
||||
.on_update(|_| {
|
||||
DialogMessage::CloseAndThen {
|
||||
followups: vec![DocumentSetupDialogMessage::Submit.into()],
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
TextButton::new("Cancel").on_update(|_| DialogMessage::Close.into()).widget_instance(),
|
||||
];
|
||||
|
||||
Layout(vec![LayoutGroup::row(widgets)])
|
||||
}
|
||||
}
|
||||
|
||||
impl LayoutHolder for DocumentSetupDialogMessageHandler {
|
||||
fn layout(&self) -> Layout {
|
||||
let resolution = resolution_row(self.pixels_per_inch, |pixels_per_inch| DocumentSetupDialogMessage::Resolution { pixels_per_inch }.into());
|
||||
|
||||
Layout(vec![LayoutGroup::row(resolution)])
|
||||
}
|
||||
}
|
||||
|
||||
/// The labeled field for a document's resolution in pixels per inch, shared by the dialogs that set it.
|
||||
pub fn resolution_row(pixels_per_inch: f64, on_update: impl Fn(f64) -> Message + Send + Sync + 'static) -> Vec<WidgetInstance> {
|
||||
let description = "How many pixels make an inch, which sizes the lengths typed in physical units like millimeters and inches, and the physical size of exported files.";
|
||||
|
||||
vec![
|
||||
TextLabel::new("Resolution")
|
||||
.table_align(true)
|
||||
.sizing(WidgetSizing::fixed(90))
|
||||
.tooltip_label("Resolution")
|
||||
.tooltip_description(description)
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(pixels_per_inch))
|
||||
.unit(" PPI")
|
||||
.min(1.)
|
||||
.max(100_000.)
|
||||
.tooltip_label("Resolution")
|
||||
.tooltip_description(description)
|
||||
// Matches the width of the New Document dialog's Name field
|
||||
.sizing(WidgetSizing::default().min_width(204))
|
||||
.on_update(move |number_input: &NumberInput| on_update(number_input.value.unwrap_or(DEFAULT_PIXELS_PER_INCH)))
|
||||
.widget_instance(),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
fn pixels_per_inch(editor: &EditorTestUtils) -> f64 {
|
||||
editor.active_document().network_interface.pixels_per_inch()
|
||||
}
|
||||
|
||||
async fn open_and_set_resolution(editor: &mut EditorTestUtils, pixels_per_inch: f64) {
|
||||
editor.handle_message(DialogMessage::RequestDocumentSetupDialog).await;
|
||||
editor.handle_message(DocumentSetupDialogMessage::Resolution { pixels_per_inch }).await;
|
||||
}
|
||||
|
||||
async fn confirm(editor: &mut EditorTestUtils) {
|
||||
editor
|
||||
.handle_message(DialogMessage::CloseAndThen {
|
||||
followups: vec![DocumentSetupDialogMessage::Submit.into()],
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn confirming_a_resolution_applies_it_as_one_undo_step() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
let layer_count = editor.active_document().metadata().all_layers().count();
|
||||
|
||||
open_and_set_resolution(&mut editor, 300.).await;
|
||||
assert_eq!(pixels_per_inch(&editor), 96., "the dialog applies nothing before it is confirmed");
|
||||
confirm(&mut editor).await;
|
||||
assert_eq!(pixels_per_inch(&editor), 300.);
|
||||
|
||||
// Undoing reverts only the resolution, leaving the rectangle drawn before it
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
assert_eq!(pixels_per_inch(&editor), 96.);
|
||||
assert_eq!(editor.active_document().metadata().all_layers().count(), layer_count);
|
||||
|
||||
editor.handle_message(DocumentMessage::Redo).await;
|
||||
assert_eq!(pixels_per_inch(&editor), 300.);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn canceling_or_confirming_an_unchanged_resolution_adds_no_undo_step() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
open_and_set_resolution(&mut editor, 300.).await;
|
||||
confirm(&mut editor).await;
|
||||
|
||||
open_and_set_resolution(&mut editor, 150.).await;
|
||||
editor.handle_message(DialogMessage::Close).await;
|
||||
assert_eq!(pixels_per_inch(&editor), 300., "canceling discards the dialog's resolution");
|
||||
|
||||
// Reopening starts from the document's resolution, so confirming it unchanged has nothing to apply
|
||||
editor.handle_message(DialogMessage::RequestDocumentSetupDialog).await;
|
||||
confirm(&mut editor).await;
|
||||
assert_eq!(pixels_per_inch(&editor), 300.);
|
||||
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
assert_eq!(pixels_per_inch(&editor), 96., "the one undo step is the resolution's first change");
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
mod document_setup_dialog_message;
|
||||
mod document_setup_dialog_message_handler;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use document_setup_dialog_message::{DocumentSetupDialogMessage, DocumentSetupDialogMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
pub use document_setup_dialog_message_handler::{DocumentSetupDialogMessageHandler, resolution_row};
|
||||
@@ -8,7 +8,6 @@
|
||||
mod dialog_message;
|
||||
mod dialog_message_handler;
|
||||
|
||||
pub mod document_setup_dialog;
|
||||
pub mod export_dialog;
|
||||
pub mod new_document_dialog;
|
||||
pub mod preferences_dialog;
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
use crate::messages::prelude::*;
|
||||
use graphene_std::units::TypedLength;
|
||||
|
||||
#[impl_message(Message, DialogMessage, NewDocumentDialog)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum NewDocumentDialogMessage {
|
||||
Name { name: String },
|
||||
Infinite { infinite: bool },
|
||||
DimensionsX { width: TypedLength },
|
||||
DimensionsY { height: TypedLength },
|
||||
Resolution { pixels_per_inch: f64 },
|
||||
DimensionsX { width: f64 },
|
||||
DimensionsY { height: f64 },
|
||||
|
||||
Submit,
|
||||
}
|
||||
+29
-177
@@ -1,33 +1,16 @@
|
||||
use crate::messages::dialog::document_setup_dialog::resolution_row;
|
||||
use crate::messages::layout::layout_message_handler::unit_suffix;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use glam::DVec2;
|
||||
use glam::UVec2;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::units::{DEFAULT_PIXELS_PER_INCH, LengthUnit, TypedLength};
|
||||
|
||||
/// A dialog to allow users to set some initial options about a new document.
|
||||
#[derive(Debug, Clone, ExtractField)]
|
||||
#[derive(Debug, Clone, Default, ExtractField)]
|
||||
pub struct NewDocumentDialogMessageHandler {
|
||||
pub name: String,
|
||||
pub infinite: bool,
|
||||
pub width: TypedLength,
|
||||
pub height: TypedLength,
|
||||
pub pixels_per_inch: f64,
|
||||
}
|
||||
|
||||
impl Default for NewDocumentDialogMessageHandler {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
name: String::new(),
|
||||
infinite: false,
|
||||
width: TypedLength::default(),
|
||||
height: TypedLength::default(),
|
||||
pixels_per_inch: DEFAULT_PIXELS_PER_INCH,
|
||||
}
|
||||
}
|
||||
pub dimensions: UVec2,
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
@@ -36,37 +19,24 @@ impl MessageHandler<NewDocumentDialogMessage, ()> for NewDocumentDialogMessageHa
|
||||
match message {
|
||||
NewDocumentDialogMessage::Name { name } => self.name = name,
|
||||
NewDocumentDialogMessage::Infinite { infinite } => self.infinite = infinite,
|
||||
NewDocumentDialogMessage::DimensionsX { width } => {
|
||||
self.width = whole_pixels(width);
|
||||
self.height = self.in_unit(self.height, self.width.unit);
|
||||
}
|
||||
NewDocumentDialogMessage::DimensionsY { height } => {
|
||||
self.height = whole_pixels(height);
|
||||
self.width = self.in_unit(self.width, self.height.unit);
|
||||
}
|
||||
NewDocumentDialogMessage::Resolution { pixels_per_inch } => self.pixels_per_inch = pixels_per_inch,
|
||||
NewDocumentDialogMessage::DimensionsX { width } => self.dimensions.x = width as u32,
|
||||
NewDocumentDialogMessage::DimensionsY { height } => self.dimensions.y = height as u32,
|
||||
NewDocumentDialogMessage::Submit => {
|
||||
responses.add(PortfolioMessage::NewDocumentWithName { name: self.name.clone() });
|
||||
|
||||
// Like the artboard, the resolution is part of the document's starting state rather than an undo step
|
||||
responses.add(DocumentMessage::SetPixelsPerInch {
|
||||
pixels_per_inch: self.pixels_per_inch,
|
||||
});
|
||||
|
||||
let dimensions = self.artboard_dimensions();
|
||||
if self.infinite {
|
||||
// Infinite canvas: add a locked white background layer
|
||||
graph_modification_utils::new_background_layer(0, responses);
|
||||
} else if dimensions.x > 0. && dimensions.y > 0. {
|
||||
} else if self.dimensions.x > 0 && self.dimensions.y > 0 {
|
||||
// Finite canvas: create an artboard with the specified dimensions
|
||||
responses.add(GraphOperationMessage::NewArtboard {
|
||||
id: NodeId::new(),
|
||||
location: DVec2::ZERO,
|
||||
dimensions,
|
||||
location: glam::DVec2::ZERO,
|
||||
dimensions: self.dimensions.as_dvec2(),
|
||||
background: Color::WHITE,
|
||||
clip: true,
|
||||
});
|
||||
responses.add(NavigationMessage::CanvasPan { delta: dimensions });
|
||||
responses.add(NavigationMessage::CanvasPan { delta: self.dimensions.as_dvec2() });
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
@@ -137,150 +107,32 @@ impl LayoutHolder for NewDocumentDialogMessageHandler {
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
// Each dimension shows the unit it was typed in and keeps any length unit typed into it
|
||||
let dimension_field = |length: TypedLength, label: &str| {
|
||||
NumberInput::new(Some(length.value))
|
||||
.label(label)
|
||||
.unit(unit_suffix(length.unit.symbol()))
|
||||
.kept_units(LengthUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
|
||||
.pixels_per_inch(self.pixels_per_inch)
|
||||
.min(0.)
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.disabled(self.infinite)
|
||||
.sizing(WidgetSizing::default().min_width(100))
|
||||
};
|
||||
let dimensions = vec![
|
||||
let scale = vec![
|
||||
TextLabel::new("Dimensions").table_align(true).sizing(WidgetSizing::fixed(90)).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
dimension_field(self.width, "W")
|
||||
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsX { width: typed_length(number_input) }.into())
|
||||
NumberInput::new(Some(self.dimensions.x as f64))
|
||||
.label("W")
|
||||
.unit(" px")
|
||||
.min(0.)
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.is_integer(true)
|
||||
.disabled(self.infinite)
|
||||
.sizing(WidgetSizing::default().min_width(100))
|
||||
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsX { width: number_input.value.unwrap() }.into())
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
dimension_field(self.height, "H")
|
||||
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsY { height: typed_length(number_input) }.into())
|
||||
NumberInput::new(Some(self.dimensions.y as f64))
|
||||
.label("H")
|
||||
.unit(" px")
|
||||
.min(0.)
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.is_integer(true)
|
||||
.disabled(self.infinite)
|
||||
.sizing(WidgetSizing::default().min_width(100))
|
||||
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsY { height: number_input.value.unwrap() }.into())
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
let resolution = resolution_row(self.pixels_per_inch, |pixels_per_inch| NewDocumentDialogMessage::Resolution { pixels_per_inch }.into());
|
||||
|
||||
Layout(vec![LayoutGroup::row(name), LayoutGroup::row(infinite), LayoutGroup::row(dimensions), LayoutGroup::row(resolution)])
|
||||
}
|
||||
}
|
||||
|
||||
impl NewDocumentDialogMessageHandler {
|
||||
/// A dimension converted into `unit` at the chosen resolution, keeping its size.
|
||||
fn in_unit(&self, length: TypedLength, unit: LengthUnit) -> TypedLength {
|
||||
whole_pixels(TypedLength {
|
||||
value: length.unit.convert(length.value, unit, self.pixels_per_inch),
|
||||
unit,
|
||||
})
|
||||
}
|
||||
|
||||
/// The artboard's size in whole pixels, converting a dimension typed in a physical unit at the chosen resolution.
|
||||
pub fn artboard_dimensions(&self) -> DVec2 {
|
||||
let pixels = |length: TypedLength| length.to_length(self.pixels_per_inch).pixels().round();
|
||||
DVec2::new(pixels(self.width), pixels(self.height))
|
||||
}
|
||||
}
|
||||
|
||||
/// The length a dimension field holds, in the unit it shows.
|
||||
fn typed_length(number_input: &NumberInput) -> TypedLength {
|
||||
let unit = math_parser::units::Unit::named(number_input.unit.trim()).and_then(LengthUnit::from_unit).unwrap_or_default();
|
||||
TypedLength {
|
||||
value: number_input.value.unwrap_or_default(),
|
||||
unit,
|
||||
}
|
||||
}
|
||||
|
||||
/// Rounds a dimension typed in pixels to a whole number of them, leaving one in a physical unit as typed.
|
||||
fn whole_pixels(length: TypedLength) -> TypedLength {
|
||||
if length.unit == LengthUnit::Pixel { TypedLength::pixels(length.value.round()) } else { length }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::NewDocumentDialogMessageHandler;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::ARTBOARD_DIMENSIONS_INPUT_INDEX;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Commits text into the dialog's number field with this label or tooltip label, as the frontend sends a typed entry.
|
||||
fn type_into_field(editor: &mut EditorTestUtils, label: &str, text: &str) {
|
||||
// A widget's ID follows from its place in the layout, which the dialog's state doesn't change
|
||||
let mut layout = NewDocumentDialogMessageHandler::default().layout();
|
||||
layout.replace_widget_ids(LayoutTarget::DialogColumn1, &mut Vec::new(), &HashMap::new());
|
||||
let widget_id = layout.iter().find_map(|instance| match &*instance.widget {
|
||||
Widget::NumberInput(number_input) if number_input.label == label || number_input.tooltip_label == label => Some(instance.widget_id),
|
||||
_ => None,
|
||||
});
|
||||
let Some(widget_id) = widget_id else {
|
||||
panic!("the dialog has no number field labeled \"{label}\"")
|
||||
};
|
||||
|
||||
editor.dispatch(LayoutMessage::WidgetValueUpdate {
|
||||
layout_target: LayoutTarget::DialogColumn1,
|
||||
widget_id,
|
||||
value: serde_json::Value::String(text.into()),
|
||||
});
|
||||
}
|
||||
|
||||
async fn create_document(editor: &mut EditorTestUtils) {
|
||||
editor
|
||||
.handle_message(DialogMessage::CloseAndThen {
|
||||
followups: vec![NewDocumentDialogMessage::Submit.into()],
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
fn artboard_dimensions(editor: &EditorTestUtils) -> Option<DVec2> {
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
let artboard = network_interface.all_artboards().into_iter().next()?;
|
||||
let node = network_interface.document_network().nodes.get(&artboard.to_node())?;
|
||||
|
||||
match node.inputs.get(ARTBOARD_DIMENSIONS_INPUT_INDEX)?.as_value()? {
|
||||
TaggedValue::DVec2(dimensions) => Some(*dimensions),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_new_document_starts_at_the_chosen_resolution_without_an_undo_step() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.dispatch(DialogMessage::RequestNewDocumentDialog);
|
||||
type_into_field(&mut editor, "Resolution", "300");
|
||||
create_document(&mut editor).await;
|
||||
assert_eq!(editor.active_document().network_interface.pixels_per_inch(), 300.);
|
||||
assert_eq!(artboard_dimensions(&editor), Some(DVec2::new(1920., 1080.)));
|
||||
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
assert_eq!(editor.active_document().network_interface.pixels_per_inch(), 300.);
|
||||
assert_eq!(artboard_dimensions(&editor), Some(DVec2::new(1920., 1080.)));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn typing_a_unit_into_one_dimension_converts_the_other_into_it() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.dispatch(DialogMessage::RequestNewDocumentDialog);
|
||||
type_into_field(&mut editor, "W", "210mm");
|
||||
|
||||
// The height of 1080 px at 96 PPI became 285.75 mm, so it grows with the resolution like the width
|
||||
type_into_field(&mut editor, "Resolution", "300");
|
||||
create_document(&mut editor).await;
|
||||
assert_eq!(artboard_dimensions(&editor), Some(DVec2::new(2480., 3375.)));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dimensions_typed_in_millimeters_convert_to_pixels_at_the_chosen_resolution() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.dispatch(DialogMessage::RequestNewDocumentDialog);
|
||||
type_into_field(&mut editor, "W", "210mm");
|
||||
type_into_field(&mut editor, "H", "297mm");
|
||||
|
||||
// The lengths stay in millimeters, so their size in pixels follows a resolution chosen after them
|
||||
type_into_field(&mut editor, "Resolution", "300");
|
||||
create_document(&mut editor).await;
|
||||
assert_eq!(artboard_dimensions(&editor), Some(DVec2::new(2480., 3508.)));
|
||||
Layout(vec![LayoutGroup::row(name), LayoutGroup::row(infinite), LayoutGroup::row(scale)])
|
||||
}
|
||||
}
|
||||
@@ -417,20 +417,16 @@ impl LayoutMessageHandler {
|
||||
}
|
||||
// A text-field commit sends the user's raw entry as a math expression to evaluate and validate.
|
||||
Value::String(expression) => {
|
||||
let Some((evaluated, kept_unit)) = evaluate_and_validate_number_input(&expression, number_input) else {
|
||||
return;
|
||||
};
|
||||
let unit = kept_unit.map_or_else(|| number_input.unit.clone(), |symbol| unit_suffix(&symbol));
|
||||
let Some(evaluated) = evaluate_and_validate_number_input(&expression, number_input) else { return };
|
||||
|
||||
// Skip the update (and its history transaction) when the value is unchanged, since the network interface would short-circuit it anyway.
|
||||
if number_input.value == Some(evaluated) && number_input.unit == unit {
|
||||
if number_input.value == Some(evaluated) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Snapshot the pre-change state for undo via `on_commit`, then apply the new value via `on_update`.
|
||||
responses.add((number_input.on_commit.callback)(&()));
|
||||
number_input.value = Some(evaluated);
|
||||
number_input.unit = unit;
|
||||
responses.add((number_input.on_update.callback)(number_input));
|
||||
}
|
||||
// The increment arrows send `{ "increment": "Increase" | "Decrease" }` to invoke the backend's directional step callback.
|
||||
@@ -708,41 +704,21 @@ fn populate_computed_display_fields(layout: &mut Layout) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The suffix a field shows after a number in this unit: a space before a word like `mm`, and none before a symbol like `°` or `%`.
|
||||
pub fn unit_suffix(symbol: &str) -> String {
|
||||
if symbol.starts_with(char::is_alphabetic) { format!(" {symbol}") } else { symbol.to_string() }
|
||||
}
|
||||
|
||||
/// Evaluates a math expression committed in a `NumberInput`'s text field, then clamps and rounds it to the widget's constraints, giving
|
||||
/// the unit it keeps where the field keeps the unit a value is typed in. Returns `None` if the expression fails to parse, fails to
|
||||
/// evaluate, yields a non-real number (such as `sqrt(-1)`), or measures something the field doesn't (such as `5s` in a length field).
|
||||
fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInput) -> Option<(f64, Option<String>)> {
|
||||
let context = math_parser::context::EvalContext::default().with_pixels_per_inch(number_input.pixels_per_inch);
|
||||
let value = math_parser::ast::Node::try_parse_from_str(expression)
|
||||
/// Evaluates a math expression committed in a `NumberInput`'s text field, then clamps and rounds it to the widget's constraints.
|
||||
/// Returns `None` if the expression fails to parse, fails to evaluate, or yields a non-real number (such as `sqrt(-1)`).
|
||||
fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInput) -> Option<f64> {
|
||||
let value = math_parser::evaluate(expression)
|
||||
.inspect_err(|err| error!("Math parser error on \"{expression}\": {err}"))
|
||||
.ok()?
|
||||
.eval(&context)
|
||||
.inspect_err(|err| error!("Math evaluate error on \"{expression}\": {err}"))
|
||||
.ok()?;
|
||||
|
||||
// The result reads in the field's unit, where a plain number is already in it and a unit like `mm` converts into it
|
||||
let field_unit = math_parser::units::Unit::named(number_input.unit.trim());
|
||||
let (in_field_unit, quantity) = match (value.as_quantity(), field_unit) {
|
||||
(Some(quantity), Some(unit)) => {
|
||||
let read = quantity
|
||||
.read_in(unit, number_input.pixels_per_inch)
|
||||
.inspect_err(|_| error!("\"{expression}\" is {}, which a field in `{unit}` can't hold", quantity.dimension().description()))
|
||||
.ok()?
|
||||
.as_real()?;
|
||||
(read, Some(*quantity))
|
||||
}
|
||||
_ => (value.as_real()?, None),
|
||||
};
|
||||
if in_field_unit.is_nan() {
|
||||
let real = value.as_real()?;
|
||||
if real.is_nan() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut validated = in_field_unit;
|
||||
let mut validated = real;
|
||||
if let Some(min) = number_input.min {
|
||||
validated = validated.max(min);
|
||||
}
|
||||
@@ -753,17 +729,5 @@ fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInp
|
||||
validated = validated.round();
|
||||
}
|
||||
|
||||
// A value typed in a unit the field keeps stays in it, unless the field's limits moved it
|
||||
let kept_unit = quantity.and_then(|quantity| {
|
||||
let symbol = quantity.unit.single()?.definition().symbol;
|
||||
number_input.kept_units.iter().any(|kept| kept == symbol).then_some((quantity, symbol))
|
||||
});
|
||||
if let Some((quantity, symbol)) = kept_unit
|
||||
&& validated == in_field_unit
|
||||
&& let Some(kept_value) = quantity.value.as_real()
|
||||
{
|
||||
return Some((kept_value, Some(symbol.to_string())));
|
||||
}
|
||||
|
||||
Some((validated, None))
|
||||
Some(validated)
|
||||
}
|
||||
@@ -247,14 +247,6 @@ pub struct NumberInput {
|
||||
#[serde(rename = "unitIsHiddenWhenEditing")]
|
||||
#[derivative(Default(value = "true"))]
|
||||
pub unit_is_hidden_when_editing: bool,
|
||||
/// The units, by symbol, that a typed value keeps rather than converting into the field's `unit`, like `mm` in a length field
|
||||
/// that remembers the unit a length was typed in. A kept unit becomes the field's `unit`.
|
||||
#[serde(skip)]
|
||||
pub kept_units: Vec<String>,
|
||||
/// The size of a pixel against an inch for converting a typed physical length, the document's resolution.
|
||||
#[serde(skip)]
|
||||
#[derivative(Default(value = "96."))]
|
||||
pub pixels_per_inch: f64,
|
||||
|
||||
// Tooltips
|
||||
#[serde(rename = "tooltipLabel")]
|
||||
@@ -615,7 +607,6 @@ pub enum MathExpressionRole {
|
||||
Function,
|
||||
Keyword,
|
||||
Operator,
|
||||
Unit,
|
||||
Bracket,
|
||||
MatrixLiteral,
|
||||
Error,
|
||||
@@ -632,7 +623,6 @@ impl From<math_parser::highlight::Role> for MathExpressionRole {
|
||||
Role::Function => Self::Function,
|
||||
Role::Keyword => Self::Keyword,
|
||||
Role::Operator => Self::Operator,
|
||||
Role::Unit => Self::Unit,
|
||||
Role::Bracket => Self::Bracket,
|
||||
Role::MatrixLiteral => Self::MatrixLiteral,
|
||||
Role::Error => Self::Error,
|
||||
|
||||
@@ -181,13 +181,6 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.on_commit(|_| DialogMessage::RequestExportDialog.into())
|
||||
.disabled(no_active_document),
|
||||
],
|
||||
vec![
|
||||
MenuListEntry::new("Document Setup…")
|
||||
.label("Document Setup…")
|
||||
.icon("Settings")
|
||||
.on_commit(|_| DialogMessage::RequestDocumentSetupDialog.into())
|
||||
.disabled(no_active_document),
|
||||
],
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
vec![preferences],
|
||||
])
|
||||
|
||||
@@ -25,7 +25,6 @@ use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
|
||||
use graphene_std::transfer_curve::TransferCurve;
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::transform::{ReferencePoint, ScaleType};
|
||||
use graphene_std::units::{Angle, Length};
|
||||
use graphene_std::vector::misc::{
|
||||
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod,
|
||||
WeldMethod,
|
||||
@@ -402,8 +401,6 @@ macro_rules! inspectable_types {
|
||||
List<Generator>,
|
||||
List<String>,
|
||||
List<f64>,
|
||||
List<Length>,
|
||||
List<Angle>,
|
||||
List<i64>,
|
||||
List<bool>,
|
||||
List<DVec2>,
|
||||
@@ -464,8 +461,6 @@ macro_rules! inspectable_types {
|
||||
Item<Generator>,
|
||||
Item<String>,
|
||||
Item<f64>,
|
||||
Item<Length>,
|
||||
Item<Angle>,
|
||||
Item<i64>,
|
||||
Item<bool>,
|
||||
Item<DVec2>,
|
||||
@@ -1105,30 +1100,6 @@ impl TableItemLayout for f64 {
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for Length {
|
||||
fn type_name() -> &'static str {
|
||||
"Length"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("{} px", format_f64(round_away_float_noise(self.pixels())))
|
||||
}
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for Angle {
|
||||
fn type_name() -> &'static str {
|
||||
"Angle"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("{}°", format_f64(round_away_float_noise(self.degrees())))
|
||||
}
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for u8 {
|
||||
fn type_name() -> &'static str {
|
||||
"Byte"
|
||||
|
||||
@@ -266,11 +266,6 @@ pub enum DocumentMessage {
|
||||
SetRenderMode {
|
||||
render_mode: RenderMode,
|
||||
},
|
||||
/// Sets how many pixels make an inch, which sizes the lengths typed in a physical unit and the physical size of exports.
|
||||
/// The caller wraps it in a transaction to make it one undo step.
|
||||
SetPixelsPerInch {
|
||||
pixels_per_inch: f64,
|
||||
},
|
||||
ShowNodeInGraph {
|
||||
node_id: NodeId,
|
||||
},
|
||||
|
||||
@@ -53,7 +53,6 @@ use graphene_std::vector::misc::dvec2_to_point;
|
||||
use graphene_std::vector::style::{GradientStops, RenderMode};
|
||||
use kurbo::{Affine, BezPath, Line, PathSeg, Shape};
|
||||
use std::collections::HashSet;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
@@ -1695,16 +1694,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
self.render_mode = render_mode;
|
||||
responses.add_front(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
DocumentMessage::SetPixelsPerInch { pixels_per_inch } => {
|
||||
if !pixels_per_inch.is_finite() || pixels_per_inch <= 0. || pixels_per_inch == self.network_interface.pixels_per_inch() {
|
||||
return;
|
||||
}
|
||||
self.network_interface.set_pixels_per_inch(pixels_per_inch);
|
||||
|
||||
// Lengths typed in a physical unit change their size in pixels, so the graph runs again
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(InspectorMessage::Refresh);
|
||||
}
|
||||
DocumentMessage::ShowNodeInGraph { node_id } => {
|
||||
// The node is in the document network, so the graph first leaves any nested network it's showing
|
||||
if !self.breadcrumb_network_path.is_empty() {
|
||||
@@ -3241,10 +3230,7 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
|
||||
pub fn current_hash(&self) -> u64 {
|
||||
// The resolution lives in the network's metadata rather than the network, but changing it changes the document
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
(self.network_interface.document_network().current_hash(), self.network_interface.pixels_per_inch().to_bits()).hash(&mut hasher);
|
||||
hasher.finish()
|
||||
self.network_interface.document_network().current_hash()
|
||||
}
|
||||
|
||||
pub fn is_auto_saved(&self) -> bool {
|
||||
|
||||
@@ -5,19 +5,16 @@ use super::node_inspector::{self, ParameterWidgetsInfo, SliderRange};
|
||||
use super::utility_types::{FrontendNodeType, InputTypeConstraint};
|
||||
use crate::messages::frontend::IconName;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||
InputMetadata, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, Vec2InputSettings, WidgetOverride,
|
||||
};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{NodeNetworkInterface, NodeTemplate, NodeTemplateImplementation};
|
||||
use crate::messages::portfolio::ingest::utility_types::TypeFilter;
|
||||
use crate::messages::prelude::{DocumentId, FontsMessage, FontsMessageHandler, Message, ResourceMessageHandler, Responses};
|
||||
use crate::node_graph_executor::NodeGraphExecutor;
|
||||
use glam::DVec2;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::concrete;
|
||||
use graph_craft::document::value::*;
|
||||
use graph_craft::document::*;
|
||||
use graph_craft::{concrete, list};
|
||||
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType};
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, NoiseType};
|
||||
use graphene_std::*;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
|
||||
@@ -40,6 +37,11 @@ impl NodeInspectorContext<'_> {
|
||||
let input_inspector_row = self.network_interface.persistent_input_metadata(node_id, index, self.selection_network_path)?;
|
||||
let widget_override = input_inspector_row.widget_override.clone()?;
|
||||
|
||||
// Older documents store number and Vec2 widget settings this way, but they come from the definition's parameter
|
||||
if matches!(widget_override.as_str(), "number" | "vec2") {
|
||||
return None;
|
||||
}
|
||||
|
||||
let Some(widget_override_lambda) = INPUT_OVERRIDES.get(&widget_override) else {
|
||||
log::error!("Could not get widget override '{widget_override}' lambda in call_widget_override");
|
||||
return None;
|
||||
@@ -51,11 +53,11 @@ impl NodeInspectorContext<'_> {
|
||||
}
|
||||
|
||||
/// Input position of the location parameter on the "Artboard" layer template, which follows the two layer-shaped inputs (stack and content) and maps through to the inner Create Artboard proto node.
|
||||
pub const ARTBOARD_LOCATION_INPUT_INDEX: usize = 2;
|
||||
pub const ARTBOARD_LOCATION_INPUT_INDEX: usize = graphene_std::subgraphs::artboard::LocationInput::INDEX;
|
||||
/// Input position of the dimensions parameter on the "Artboard" layer template, which follows the two layer-shaped inputs (stack and content) and maps through to the inner Create Artboard proto node.
|
||||
pub const ARTBOARD_DIMENSIONS_INPUT_INDEX: usize = 3;
|
||||
pub const ARTBOARD_DIMENSIONS_INPUT_INDEX: usize = graphene_std::subgraphs::artboard::DimensionsInput::INDEX;
|
||||
/// Input position of the control path parameter on the "Blend" network node template.
|
||||
pub const BLEND_PATH_INPUT_INDEX: usize = 4;
|
||||
pub const BLEND_PATH_INPUT_INDEX: usize = graphene_std::subgraphs::blend::PathInput::INDEX;
|
||||
|
||||
/// The key used to access definitions for a network node or proto node.
|
||||
/// For proto nodes, this is their [`ProtoNodeIdentifier`].
|
||||
@@ -107,8 +109,7 @@ pub struct DocumentNodeDefinition {
|
||||
/// Used to create the [`DefinitionIdentifier::Network`] identifier.
|
||||
pub identifier: &'static str,
|
||||
|
||||
/// The definition's position in its lineage. Bump it, with a `network` migration, when a change would load existing instances wrongly.
|
||||
/// Instances store it next to their reference. Proto-node definitions take theirs from the node macro.
|
||||
/// The definition's position in its lineage, from `version(N)` on its `#[node]` or `#[graph]`. Instances store it next to their reference.
|
||||
pub version: u32,
|
||||
|
||||
/// The default [`NodeTemplate`] this definition instantiates.
|
||||
@@ -136,541 +137,9 @@ static DOCUMENT_NODE_TYPES: once_cell::sync::Lazy<HashMap<DefinitionIdentifier,
|
||||
|
||||
/// Defines the "signature" or "header file"-like metadata for the document nodes, but not the implementation (which is defined in the node registry).
|
||||
/// The [`DocumentNode`] is the instance while these [`DocumentNodeDefinition`]s are the "classes" or "blueprints" from which the instances are built.
|
||||
/// Only the position can be set for protonodes within a definition. The rest of the metadata comes from the node macro in NODE_METADATA
|
||||
/// A proto node within a definition takes its input and output metadata from the node macro in NODE_METADATA, and its display name too unless the definition gives one.
|
||||
fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||
let custom = vec![
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Custom Node",
|
||||
version: 1,
|
||||
category: "Routing",
|
||||
icon: Some("NodeCustomNode"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("An empty node network you can use to create your own custom nodes."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Merge",
|
||||
version: 1,
|
||||
category: "Graphic",
|
||||
icon: Some("NodeMerge"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(2), 0)],
|
||||
nodes: [
|
||||
// Primary (bottom) input type coercion
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::import(generic!(T), 0)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::as_graphic::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -2)),
|
||||
..Default::default()
|
||||
},
|
||||
// Secondary (left) input type coercion
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::import(generic!(T), 1)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::into_group::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -1)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
call_argument: generic!(T),
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -2)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::type_default(list!(Graphic), true), NodeInput::type_default(list!(Graphic), true)],
|
||||
input_metadata: vec![
|
||||
("Base", "The stack of layers below this one, which the content is placed above.").into(),
|
||||
("Content", "The artwork this layer adds to the stack as a single item.").into(),
|
||||
],
|
||||
output_names: vec!["Out".to_string()],
|
||||
output_descriptions: vec!["The stack of layers with this layer's content placed on top.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::layer(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Merges the provided content as a new item in the layer's compositing stack."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Artboard",
|
||||
version: 1,
|
||||
category: "Graphic",
|
||||
icon: Some("NodeArtboard"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
NodeTemplate {
|
||||
call_argument: generic!(T),
|
||||
implementation: NodeTemplateImplementation::ProtoNode(artboard::create_artboard::IDENTIFIER),
|
||||
inputs: vec![
|
||||
NodeInput::import(Type::Fn(concrete!(Context).into(), generic!(T).into()), 1),
|
||||
NodeInput::import(item!(TaggedValue), 2),
|
||||
NodeInput::import(item!(TaggedValue), 3),
|
||||
NodeInput::import(item!(TaggedValue), 4),
|
||||
NodeInput::import(item!(TaggedValue), 5),
|
||||
],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -3)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
inputs: vec![
|
||||
NodeInput::import(graphene_std::Type::Fn(Box::new(concrete!(Context)), Box::new(list!(Artboard))), 0),
|
||||
NodeInput::node(NodeId(0), 0),
|
||||
],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -4)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::type_default(list!(Artboard), true),
|
||||
NodeInput::type_default(list!(Graphic), true),
|
||||
NodeInput::value(TaggedValue::DVec2(DVec2::ZERO), false),
|
||||
NodeInput::value(TaggedValue::DVec2(DVec2::new(1920., 1080.)), false),
|
||||
NodeInput::value(TaggedValue::Color(Color::WHITE), false),
|
||||
NodeInput::value(TaggedValue::Bool(true), false),
|
||||
],
|
||||
input_metadata: vec![
|
||||
("Base", "The stack of artboards below this one, which this artboard is placed above.").into(),
|
||||
("Content", "Graphics to include within the artboard.").into(),
|
||||
InputMetadata::with_name_description_override(
|
||||
"Location",
|
||||
"Coordinate of the top-left corner of the artboard within the document.",
|
||||
WidgetOverride::Vec2(Vec2InputSettings {
|
||||
x: "X".to_string(),
|
||||
y: "Y".to_string(),
|
||||
unit: " px".to_string(),
|
||||
is_integer: true,
|
||||
..Default::default()
|
||||
}),
|
||||
),
|
||||
InputMetadata::with_name_description_override(
|
||||
"Dimensions",
|
||||
"Width and height of the artboard within the document.",
|
||||
WidgetOverride::Vec2(Vec2InputSettings {
|
||||
x: "W".to_string(),
|
||||
y: "H".to_string(),
|
||||
unit: " px".to_string(),
|
||||
is_integer: true,
|
||||
..Default::default()
|
||||
}),
|
||||
),
|
||||
InputMetadata::with_name_description_override("Background", "Color of the artboard background.", WidgetOverride::Custom("artboard_background".to_string())),
|
||||
("Clip", "Whether to cut off the contained content that extends outside the artboard, or keep it visible.").into(),
|
||||
],
|
||||
output_names: vec!["Out".to_string()],
|
||||
output_descriptions: vec!["The stack of artboards with this artboard placed on top.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::layer(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Creates a new Artboard which can be used as a working surface."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Blend",
|
||||
version: 1,
|
||||
category: "Vector: Deform",
|
||||
icon: Some("NodeBlend"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(16), 0)],
|
||||
nodes: [
|
||||
// 0: Separate Paths (split the vector into its individual paths)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::separate_paths::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(generic!(T), 4)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 1: Count (number of subpaths)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::count::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
// 2: Max (clamp subpath count to at least 1 for empty path case)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
// 3: As Number (the integer count enters the network's decimal math)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(item!(i64), 1)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 13)),
|
||||
..Default::default()
|
||||
},
|
||||
// 4: Multiply (total_instances = count × subpath_count)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::node(NodeId(2), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 5: Subtract (count - 1, open subpath denominator)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::subtract::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 14)),
|
||||
..Default::default()
|
||||
},
|
||||
// 6: Read Index (current repetition index)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(context::read_index::IDENTIFIER),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::Integer(0), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
// 7: Divide (index / count)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::divide::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::node(NodeId(17), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 10)),
|
||||
..Default::default()
|
||||
},
|
||||
// 8: Floor (floor(index / count) = subpath index)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::floor::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(7), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 4)),
|
||||
..Default::default()
|
||||
},
|
||||
// 9: Modulo (index % count = local index within subpath)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::modulo::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::Bool(true), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
// 10: Path Is Closed (check if current subpath is closed)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::path_is_closed::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(generic!(T), 4), NodeInput::node(NodeId(8), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
// 11: Switch (closed → count, open → max(count - 1, 1) as denominator)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::switch::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(10), 0), NodeInput::node(NodeId(17), 0), NodeInput::node(NodeId(18), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 12)),
|
||||
..Default::default()
|
||||
},
|
||||
// 12: Divide (local_index / denominator = within-subpath fraction)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::divide::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(9), 0), NodeInput::node(NodeId(11), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
// 13: Multiply (fraction × 0.9999999999 to avoid overflowing to the next subpath)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(12), 0), NodeInput::value(TaggedValue::Number(0.9999999999), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
// 14: Add (subpath_index + clamped fraction = progression)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::add::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(8), 0), NodeInput::node(NodeId(13), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(37, 4)),
|
||||
..Default::default()
|
||||
},
|
||||
// 15: Morph (content, progression, reverse, distribution, path)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::morph::IDENTIFIER),
|
||||
inputs: vec![
|
||||
NodeInput::import(generic!(T), 0),
|
||||
NodeInput::node(NodeId(14), 0),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
NodeInput::import(item!(vector::misc::InterpolationDistribution), 3),
|
||||
NodeInput::import(item!(Vector), 4),
|
||||
],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(44, 3)),
|
||||
..Default::default()
|
||||
},
|
||||
// 16: Repeat
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(repeat_nodes::repeat::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(15), 0), NodeInput::node(NodeId(4), 0), NodeInput::import(generic!(T), 2)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(51, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 17: Max (clamp count to at least 1)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(3), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 13)),
|
||||
..Default::default()
|
||||
},
|
||||
// 18: Max (clamp open-path denominator to at least 1 to avoid division by zero when count = 1)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 14)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::type_default(list!(Vector), true),
|
||||
NodeInput::value(TaggedValue::Integer(10), false),
|
||||
NodeInput::value(TaggedValue::Bool(Default::default()), false),
|
||||
NodeInput::value(TaggedValue::InterpolationDistribution(Default::default()), false),
|
||||
NodeInput::type_default(item!(Vector), false),
|
||||
],
|
||||
input_metadata: vec![
|
||||
("Content", "The vector objects to create intermediate shapes between.").into(),
|
||||
(
|
||||
"Count",
|
||||
"The number of shapes spanning from the first object to the last, repeated for each subpath of the control path.",
|
||||
)
|
||||
.into(),
|
||||
("Reverse", "Flip the stacking order of the shapes, so the ones nearest the first object are on top.").into(),
|
||||
("Distribution", "What changes evenly from one shape to the next, which sets how the intermediate shapes are spaced.").into(),
|
||||
(
|
||||
"Path",
|
||||
"An optional control path with one anchor point per object. Curved segments shape the trajectory of the blend instead of traveling straight.",
|
||||
)
|
||||
.into(),
|
||||
],
|
||||
output_names: vec!["Out".to_string()],
|
||||
output_descriptions: vec!["The blended shapes, from the first object to the last.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Creates a series of intermediate shapes that gradually transition between vector objects, optionally along a control path."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Origins to Polyline",
|
||||
version: 1,
|
||||
category: "Vector: Path",
|
||||
icon: Some("NodeOriginsToPolyline"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(7), 0)],
|
||||
nodes: [
|
||||
// 0: Read Vector
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(context::read_vector::IDENTIFIER),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 1: Extract Transform
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(transform_nodes::extract_transform::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 2: Decompose Translation
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(transform_nodes::decompose_translation::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(1), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(14, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 3: As Vector (auto-converts the decomposed translation into a single-anchor List<Vector>)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::as_vector::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(2), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(21, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 4: Flatten Vector
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic_nodes::graphic::flatten_vector::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(generic!(T), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(21, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 5: Map
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::map::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(4), 0), NodeInput::node(NodeId(3), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(28, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 6: Combine Paths
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::combine_paths::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(5), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(35, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 7: Points to Polyline
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::points_to_polyline::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::value(TaggedValue::Bool(false), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(42, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::type_default(list!(Vector), true)],
|
||||
input_metadata: vec![("Vector", "The vector objects to connect in order by their origins.").into()],
|
||||
output_names: vec!["Vector".to_string()],
|
||||
output_descriptions: vec!["An open polyline with an anchor point at the origin of each object.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Connects the origins of vector objects in order with an open polyline, such as to make a control path for the **Blend** and **Morph** nodes."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Load Image",
|
||||
version: 1,
|
||||
category: "Data: I/O",
|
||||
icon: Some("NodeLoadImage"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::import(item!(String), 1)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::load_resource::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::bytes_to_image::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::String(String::new()), false)],
|
||||
input_metadata: vec![
|
||||
("Empty", "Has no effect, since the image is loaded from the URL.").into(),
|
||||
("URL", "The web address or local asset path of the image to load.").into(),
|
||||
],
|
||||
output_names: vec!["Image".to_string()],
|
||||
output_descriptions: vec!["The loaded image.".to_string()],
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Loads an image from a given URL."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Regex Find",
|
||||
version: 1,
|
||||
category: "String: Regex",
|
||||
icon: Some("NodeRegexFind"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![
|
||||
// Primary output: the whole match (String)
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
// Secondary output: capture groups (List<String>), each item carries `start`/`end`/`name` attributes from `regex_find`
|
||||
NodeInput::node(NodeId(2), 0),
|
||||
],
|
||||
nodes: [
|
||||
// Node 0: regex_find proto node — returns List<String> of [whole_match, ...capture_groups]
|
||||
NodeTemplate {
|
||||
inputs: vec![
|
||||
NodeInput::import(item!(String), 0),
|
||||
NodeInput::import(item!(String), 1),
|
||||
NodeInput::import(item!(i64), 2),
|
||||
NodeInput::import(item!(bool), 3),
|
||||
NodeInput::import(item!(bool), 4),
|
||||
],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(text_nodes::regex::regex_find::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// Node 1: item_at_index at index 0, extracts the whole match as a bare String (drops the item's start/end/name attributes since the unwrapped String can't carry them)
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::item_at_index::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// Node 2: remove_at_index at index 0, returns the capture group items as a List<String>, preserving each item's start/end/name attributes
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::remove_at_index::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::value(TaggedValue::String(String::new()), true),
|
||||
NodeInput::value(TaggedValue::String(String::new()), false),
|
||||
NodeInput::value(TaggedValue::Integer(0), false),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
],
|
||||
input_metadata: vec![
|
||||
("String", "The string to search within.").into(),
|
||||
("Pattern", "The regular expression pattern to search for.").into(),
|
||||
(
|
||||
"Match Index",
|
||||
"Which non-overlapping occurrence of the pattern to return, starting from 0 for the first match. Negative indices count backwards from the last match.",
|
||||
)
|
||||
.into(),
|
||||
("Case Insensitive", "Match letters regardless of case.").into(),
|
||||
("Multiline", "Make `^` and `$` match the start and end of each line, not just the whole string.").into(),
|
||||
],
|
||||
output_names: vec!["Match".to_string(), "Captures".to_string()],
|
||||
output_descriptions: vec![
|
||||
"The whole portion of the string matching the pattern, or empty if there is no match.".to_string(),
|
||||
"The text matched by each capture group in the pattern, in order.".to_string(),
|
||||
],
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed(
|
||||
r#"Finds a portion of the string matching a regular expression pattern. With "Match Index" at its default 0, it selects the first non-overlapping occurrence, but others may be selected. Capture groups, if any, are produced as a list in the "Captures" output."#,
|
||||
),
|
||||
inspector: None,
|
||||
},
|
||||
];
|
||||
|
||||
document_node_derive::post_process_nodes(custom)
|
||||
document_node_derive::derive_definitions()
|
||||
}
|
||||
|
||||
type NodeInspector = HashMap<String, Box<dyn Fn(NodeId, &mut NodeInspectorContext) -> Vec<LayoutGroup> + Send + Sync>>;
|
||||
@@ -738,91 +207,10 @@ fn static_input_inspector() -> InputInspector {
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"number".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let mut number_input = NumberInput::default();
|
||||
if let Some(unit) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "unit", context.selection_network_path)
|
||||
.and_then(|value| value.as_str())
|
||||
{
|
||||
number_input = number_input.unit(unit);
|
||||
}
|
||||
if let Some(min) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "min", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.min(min);
|
||||
}
|
||||
if let Some(max) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "max", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.max(max);
|
||||
}
|
||||
if let Some(step) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "step", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.step(step);
|
||||
}
|
||||
if let Some(mode) = context.network_interface.input_data(&node_id, index, "mode", context.selection_network_path).map(|value| {
|
||||
let mode: NumberInputMode = serde_json::from_value(value.clone()).unwrap();
|
||||
mode
|
||||
}) {
|
||||
number_input = number_input.mode(mode);
|
||||
}
|
||||
if let Some(range_min) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "range_min", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.range_min(Some(range_min));
|
||||
}
|
||||
if let Some(range_max) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "range_max", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.range_max(Some(range_max));
|
||||
}
|
||||
if let Some(is_integer) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "is_integer", context.selection_network_path)
|
||||
.and_then(|value| value.as_bool())
|
||||
{
|
||||
number_input = number_input.is_integer(is_integer);
|
||||
}
|
||||
let blank_assist = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "blank_assist", context.selection_network_path)
|
||||
.and_then(|value| value.as_bool())
|
||||
.unwrap_or_else(|| {
|
||||
log::error!("Could not get blank assist when displaying number input for node {node_id}, index {index}");
|
||||
true
|
||||
});
|
||||
|
||||
Ok(vec![LayoutGroup::row(node_inspector::number_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, blank_assist, context),
|
||||
number_input,
|
||||
))])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
// The custom number input settings are only available on proto nodes
|
||||
"optional_f64".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let mut number_input = NumberInput::default();
|
||||
// The field is cloned so the lock is released before building the row below, which locks the node metadata again
|
||||
if let Some(field) = context
|
||||
.network_interface
|
||||
.implementation(&node_id, context.selection_network_path)
|
||||
.and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None })
|
||||
.and_then(|proto_node_identifier| registry::NODE_METADATA.lock().unwrap().get(proto_node_identifier)?.fields.get(index).cloned())
|
||||
{
|
||||
if let Some(field) = context.network_interface.field_metadata(&node_id, index, context.selection_network_path) {
|
||||
if let Some(unit) = field.unit {
|
||||
number_input = number_input.unit(unit);
|
||||
}
|
||||
@@ -917,57 +305,6 @@ fn static_input_inspector() -> InputInspector {
|
||||
"type_choice".to_string(),
|
||||
Box::new(|node_id, index, context| Ok(vec![node_inspector::type_choice_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context))])),
|
||||
);
|
||||
map.insert(
|
||||
"vec2".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let x = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "x", context.selection_network_path)
|
||||
.and_then(|value| value.as_str())
|
||||
.unwrap_or_else(|| {
|
||||
log::error!("Could not get x for vec2 input");
|
||||
""
|
||||
})
|
||||
.to_string();
|
||||
let y = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "y", context.selection_network_path)
|
||||
.and_then(|value| value.as_str())
|
||||
.unwrap_or_else(|| {
|
||||
log::error!("Could not get y for vec2 input");
|
||||
""
|
||||
})
|
||||
.to_string();
|
||||
let unit = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "unit", context.selection_network_path)
|
||||
.and_then(|value| value.as_str())
|
||||
.unwrap_or_else(|| {
|
||||
log::error!("Could not get unit for vec2 input");
|
||||
""
|
||||
})
|
||||
.to_string();
|
||||
let min = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "min", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64());
|
||||
let is_integer = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "is_integer", context.selection_network_path)
|
||||
.and_then(|value| value.as_bool())
|
||||
.unwrap_or_default();
|
||||
|
||||
Ok(vec![node_inspector::vec2_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||
&x,
|
||||
&y,
|
||||
&unit,
|
||||
min,
|
||||
is_integer,
|
||||
false,
|
||||
)])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"noise_inspector_scale".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
@@ -1140,6 +477,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
"Y",
|
||||
"",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
mandelbrot_to_julia.is_some_and(|percent| percent >= 100.),
|
||||
)])
|
||||
@@ -1156,6 +494,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
"Y",
|
||||
"",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
mandelbrot_to_julia.is_some_and(|percent| percent <= 0.),
|
||||
)])
|
||||
@@ -1262,6 +601,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
"Y",
|
||||
" px",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
false,
|
||||
)])
|
||||
@@ -1277,6 +617,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
"H",
|
||||
"x",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
false,
|
||||
)])
|
||||
@@ -1397,7 +738,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
"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, false)])
|
||||
Ok(vec![node_inspector::vec2_widget(parameter_widgets_info, "U", "V", "", None, None, false, false)])
|
||||
}),
|
||||
);
|
||||
map
|
||||
@@ -1645,6 +986,18 @@ mod test {
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::document::NodeId;
|
||||
|
||||
// A `#[graph]` node with an inner node that has no definition is left out of the catalog with only a logged error
|
||||
#[test]
|
||||
fn every_registered_graph_has_a_definition() {
|
||||
// Released before resolving, since building the catalog locks the registry too
|
||||
let identifiers: Vec<&str> = graphene_std::registry::GRAPH_METADATA.lock().unwrap().iter().map(|graph| graph.identifier).collect();
|
||||
assert!(!identifiers.is_empty(), "the `#[graph]` nodes in `graphene_std::subgraphs` should be registered");
|
||||
|
||||
for identifier in identifiers {
|
||||
assert!(resolve_network_node_type(identifier).is_some(), "the '{identifier}' graph should have a definition");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rasterize_defaults_to_a_1000_px_square_at_full_resolution() {
|
||||
use glam::{DAffine2, UVec2};
|
||||
@@ -1785,21 +1138,36 @@ mod test_type_constraints {
|
||||
|
||||
#[test]
|
||||
fn every_definition_default_value_satisfies_its_constraint() {
|
||||
let mut violations = Vec::new();
|
||||
for definition in super::DOCUMENT_NODE_TYPES.values() {
|
||||
let name = &definition.node_template.display_name;
|
||||
let constraints = InputTypeConstraint::constraints_for_all_inputs(&definition.node_template, name);
|
||||
// Checks a node's inputs against what its implementations accept, then each node inside it, whose values a subgraph's author writes too
|
||||
fn check(node_template: &NodeTemplate, name: &str, violations: &mut Vec<String>) {
|
||||
let constraints = InputTypeConstraint::constraints_for_all_inputs(node_template, name);
|
||||
|
||||
for (index, (constraint, input)) in constraints.iter().zip(&definition.node_template.inputs).enumerate() {
|
||||
for (index, (constraint, input)) in constraints.iter().zip(&node_template.inputs).enumerate() {
|
||||
if let Some(value) = input.as_value()
|
||||
&& !constraint.accepts_default_value(&value.ty())
|
||||
{
|
||||
violations.push(format!("{name} input {index}: {} does not satisfy {constraint:?}", value.ty()));
|
||||
}
|
||||
|
||||
let takes_nothing = matches!(constraint, InputTypeConstraint::Limited(types) if !types.is_empty() && types.iter().all(|ty| ty == "()"));
|
||||
if takes_nothing && matches!(input, NodeInput::Node { .. } | NodeInput::Import { .. }) {
|
||||
violations.push(format!("{name} input {index}: a wire feeds it, but it takes nothing"));
|
||||
}
|
||||
}
|
||||
|
||||
if let NodeTemplateImplementation::Network(network) = &node_template.implementation {
|
||||
for (node_id, inner) in &network.nodes {
|
||||
check(inner, &format!("{name}, node {node_id}"), violations);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assert!(violations.is_empty(), "Default values rejected by their input constraints:\n{}", violations.join("\n"));
|
||||
let mut violations = Vec::new();
|
||||
for definition in super::DOCUMENT_NODE_TYPES.values() {
|
||||
check(&definition.node_template, &definition.node_template.display_name, &mut violations);
|
||||
}
|
||||
|
||||
assert!(violations.is_empty(), "Values rejected by their input constraints:\n{}", violations.join("\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1816,7 +1184,7 @@ mod test_type_constraints {
|
||||
|
||||
#[test]
|
||||
fn single_protonode() {
|
||||
let node_type = resolve_proto_node_type(test_node_accept_f_32_f_64_dvec_2::IDENTIFIER).expect("test node to exist");
|
||||
let node_type = resolve_proto_node_type(test_node_accept_f32_f64_dvec2::IDENTIFIER).expect("test node to exist");
|
||||
let constraint = InputTypeConstraint::constraints_for_all_inputs(&node_type.node_template, "name");
|
||||
all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(glam::DVec2)]);
|
||||
assert!(!constraint[0].satisfies(&concrete!(String)));
|
||||
@@ -1830,7 +1198,7 @@ mod test_type_constraints {
|
||||
|
||||
#[test]
|
||||
fn single_protonode2() {
|
||||
let node_type = resolve_proto_node_type(test_node_accept_f_32_f_64_string::IDENTIFIER).expect("test node to exist");
|
||||
let node_type = resolve_proto_node_type(test_node_accept_f32_f64_string::IDENTIFIER).expect("test node to exist");
|
||||
let constraint = InputTypeConstraint::constraints_for_all_inputs(&node_type.node_template, "name");
|
||||
all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(String)]);
|
||||
assert!(!constraint[0].satisfies(&concrete!(glam::DVec2)));
|
||||
@@ -1839,8 +1207,8 @@ mod test_type_constraints {
|
||||
|
||||
#[test]
|
||||
fn network() {
|
||||
let atan_definition = resolve_proto_node_type(test_node_accept_f_32_f_64_dvec_2::IDENTIFIER).expect("test node to exist");
|
||||
let min_definition = resolve_proto_node_type(test_node_accept_f_32_f_64_string::IDENTIFIER).expect("test node to exist");
|
||||
let atan_definition = resolve_proto_node_type(test_node_accept_f32_f64_dvec2::IDENTIFIER).expect("test node to exist");
|
||||
let min_definition = resolve_proto_node_type(test_node_accept_f32_f64_string::IDENTIFIER).expect("test node to exist");
|
||||
let atan_node = atan_definition.node_template_input_override([Some(NodeInput::import(generic!(X), 0))]);
|
||||
let min_node = min_definition.node_template_input_override([Some(NodeInput::import(generic!(X), 0))]);
|
||||
let inner_network = NodeNetworkTemplate {
|
||||
|
||||
+421
-30
@@ -1,11 +1,17 @@
|
||||
use super::DocumentNodeDefinition;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputMetadata, NodeTemplate, NodeTemplateImplementation, WidgetOverride};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||
InputMetadata, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, WidgetOverride,
|
||||
};
|
||||
use glam::IVec2;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_std::registry::*;
|
||||
use graphene_std::*;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||
/// Generates every definition, from the node macro's metadata for proto nodes and the graph macro's for built-in subgraphs.
|
||||
pub(super) fn derive_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||
let mut definitions_map = HashMap::new();
|
||||
|
||||
// Add the protonodes from the macro.
|
||||
@@ -75,16 +81,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
inputs,
|
||||
call_argument: input_type.clone(),
|
||||
implementation: NodeTemplateImplementation::ProtoNode(id.clone()),
|
||||
// TODO: Store information for input overrides in the node macro
|
||||
input_metadata: fields
|
||||
.iter()
|
||||
.map(|f| match f.widget_override {
|
||||
RegistryWidgetOverride::None => (f.name, f.description).into(),
|
||||
RegistryWidgetOverride::Hidden => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Hidden),
|
||||
RegistryWidgetOverride::String(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::String(str.to_string())),
|
||||
RegistryWidgetOverride::Custom(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Custom(str.to_string())),
|
||||
})
|
||||
.collect(),
|
||||
input_metadata: input_metadata(fields),
|
||||
output_names,
|
||||
..Default::default()
|
||||
},
|
||||
@@ -96,25 +93,242 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
);
|
||||
}
|
||||
|
||||
// Add the hand-written network nodes to the map and add the metadata for their internal protonodes
|
||||
for mut network_node in custom {
|
||||
fill_proto_node_metadata(&mut network_node.node_template, &definitions_map);
|
||||
|
||||
// Set the reference to the node identifier
|
||||
if let NodeTemplateImplementation::Network(network_template) = &mut network_node.node_template.implementation {
|
||||
network_template.reference = Some(network_node.identifier.to_string());
|
||||
// If it is not a merge node, then set the display name to the identifier/reference
|
||||
if network_node.identifier != "Merge" {
|
||||
network_node.node_template.display_name = network_node.identifier.to_string();
|
||||
}
|
||||
}
|
||||
definitions_map.insert(DefinitionIdentifier::Network(network_node.identifier.to_string()), network_node);
|
||||
}
|
||||
let graphs = GRAPH_METADATA.lock().unwrap().clone();
|
||||
add_graph_definitions(graphs, &mut definitions_map);
|
||||
|
||||
definitions_map
|
||||
}
|
||||
|
||||
/// Recursively fills each nested proto node's editor metadata from its definition, preserving only the authored position.
|
||||
/// The name, description, and any widget override of each parameter, for a proto node's fields or a graph's imports.
|
||||
/// The rest of a parameter's widget settings are read from its field when the Inspector draws it.
|
||||
fn input_metadata(fields: &[FieldMetadata]) -> Vec<InputMetadata> {
|
||||
fields
|
||||
.iter()
|
||||
.map(|field| {
|
||||
let (name, description) = (field.name, field.description);
|
||||
match field.widget_override {
|
||||
RegistryWidgetOverride::None => (name, description).into(),
|
||||
RegistryWidgetOverride::Hidden => InputMetadata::with_name_description_override(name, description, WidgetOverride::Hidden),
|
||||
RegistryWidgetOverride::String(text) => InputMetadata::with_name_description_override(name, description, WidgetOverride::String(text.to_string())),
|
||||
RegistryWidgetOverride::Custom(key) => InputMetadata::with_name_description_override(name, description, WidgetOverride::Custom(key.to_string())),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Why a `#[graph]` node has no definition yet, or can't have one.
|
||||
enum GraphDefinitionError {
|
||||
/// A node inside it has no definition, which may be another graph not yet added.
|
||||
MissingNode(String),
|
||||
/// The graph's wiring is invalid, so it's left out of the catalog.
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
/// Adds the nodes defined as subgraphs by `#[graph]`, each once the definitions of the nodes inside it exist.
|
||||
fn add_graph_definitions(graphs: Vec<GraphMetadata>, definitions_map: &mut HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
|
||||
// Every graph sharing an identifier is left out, so the catalog doesn't depend on registration order
|
||||
let mut identifier_counts = HashMap::new();
|
||||
for graph in &graphs {
|
||||
*identifier_counts.entry(graph.identifier).or_insert(0) += 1;
|
||||
}
|
||||
let mut rejected = HashSet::new();
|
||||
let mut pending_graphs: Vec<(GraphMetadata, String)> = graphs
|
||||
.into_iter()
|
||||
.filter(|graph| {
|
||||
let taken = identifier_counts[graph.identifier] > 1;
|
||||
if taken {
|
||||
log::error!("The '{}' graph has no definition, since another graph has the same identifier", graph.identifier);
|
||||
rejected.insert(graph.identifier);
|
||||
}
|
||||
!taken
|
||||
})
|
||||
.map(|graph| (graph, String::new()))
|
||||
.collect();
|
||||
|
||||
loop {
|
||||
let pending_count = pending_graphs.len();
|
||||
|
||||
let mut ready = Vec::new();
|
||||
pending_graphs.retain_mut(|(graph, missing)| {
|
||||
// A graph built on a left-out graph is left out too, rather than embedding another definition of that name
|
||||
let rejected_inner_graph = graph.nodes.iter().find_map(|node| match node.implementation {
|
||||
GraphNodeImplementation::Graph(identifier) if rejected.contains(identifier) => Some(identifier),
|
||||
_ => None,
|
||||
});
|
||||
if let Some(inner_graph) = rejected_inner_graph {
|
||||
log::error!("The '{}' graph has no definition, since the '{inner_graph}' graph inside it has none", graph.identifier);
|
||||
rejected.insert(graph.identifier);
|
||||
return false;
|
||||
}
|
||||
|
||||
match graph_definition(graph, definitions_map) {
|
||||
Ok(definition) => {
|
||||
ready.push(definition);
|
||||
false
|
||||
}
|
||||
Err(GraphDefinitionError::MissingNode(missing_node)) => {
|
||||
*missing = missing_node;
|
||||
true
|
||||
}
|
||||
Err(GraphDefinitionError::Invalid(reason)) => {
|
||||
log::error!("The '{}' graph has no definition, since {reason}", graph.identifier);
|
||||
rejected.insert(graph.identifier);
|
||||
false
|
||||
}
|
||||
}
|
||||
});
|
||||
for definition in ready {
|
||||
let definition = prepare_network_definition(definition, definitions_map);
|
||||
definitions_map.insert(DefinitionIdentifier::Network(definition.identifier.to_string()), definition);
|
||||
}
|
||||
|
||||
if pending_graphs.is_empty() || pending_graphs.len() == pending_count {
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (graph, missing_node) in pending_graphs {
|
||||
log::error!("The '{}' graph has no definition, since the '{missing_node}' node inside it has none", graph.identifier);
|
||||
}
|
||||
}
|
||||
|
||||
/// Fills a network definition's nested proto node metadata and points its network at the definition.
|
||||
fn prepare_network_definition(mut network_node: DocumentNodeDefinition, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) -> DocumentNodeDefinition {
|
||||
fill_proto_node_metadata(&mut network_node.node_template, definitions_map);
|
||||
|
||||
// Set the reference to the node identifier
|
||||
if let NodeTemplateImplementation::Network(network_template) = &mut network_node.node_template.implementation {
|
||||
network_template.reference = Some(network_node.identifier.to_string());
|
||||
// If it is not a merge node, then set the display name to the identifier/reference
|
||||
if network_node.identifier != "Merge" {
|
||||
network_node.node_template.display_name = network_node.identifier.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
network_node
|
||||
}
|
||||
|
||||
/// Builds the catalog definition of a node defined as a subgraph by `#[graph]`.
|
||||
fn graph_definition(graph: &GraphMetadata, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) -> Result<DocumentNodeDefinition, GraphDefinitionError> {
|
||||
let mut nodes = HashMap::new();
|
||||
for (index, node) in graph.nodes.iter().enumerate() {
|
||||
// Start from the node's own definition, so each input the graph leaves out matches a new instance of it
|
||||
let (identifier, name) = match &node.implementation {
|
||||
GraphNodeImplementation::ProtoNode(identifier) => (DefinitionIdentifier::ProtoNode(identifier.clone()), identifier.as_str().to_string()),
|
||||
GraphNodeImplementation::Graph(identifier) => (DefinitionIdentifier::Network(identifier.to_string()), identifier.to_string()),
|
||||
};
|
||||
let Some(definition) = definitions_map.get(&identifier) else {
|
||||
return Err(GraphDefinitionError::MissingNode(name));
|
||||
};
|
||||
let mut template = definition.default_node_template();
|
||||
|
||||
if let Some(call_argument) = &node.call_argument {
|
||||
template.call_argument = call_argument.clone();
|
||||
}
|
||||
template.visible = !node.hidden;
|
||||
template.locked = node.locked;
|
||||
template.pinned = node.pinned;
|
||||
if let Some(display_name) = node.display_name {
|
||||
template.display_name = display_name.to_string();
|
||||
}
|
||||
|
||||
let position = node.position.map_or(IVec2::ZERO, |(x, y)| IVec2::new(x, y));
|
||||
template.node_type_metadata = if node.layer {
|
||||
NodeTypePersistentMetadata::layer(position)
|
||||
} else {
|
||||
NodeTypePersistentMetadata::node(position)
|
||||
};
|
||||
|
||||
for (input_index, source) in &node.inputs {
|
||||
let Some(input) = template.inputs.get_mut(*input_index) else {
|
||||
return Err(GraphDefinitionError::Invalid(format!("its node {index}, '{name}', has no input {input_index} for it to set")));
|
||||
};
|
||||
|
||||
// An input the compiler fills in can't be set, which the macro already prevents for the graphs it builds
|
||||
if matches!(input, NodeInput::Scope(_) | NodeInput::Reflection(_)) {
|
||||
return Err(GraphDefinitionError::Invalid(format!(
|
||||
"it sets input {input_index} of its node {index}, '{name}', which the compiler fills in"
|
||||
)));
|
||||
}
|
||||
|
||||
*input = graph_input(source, input);
|
||||
}
|
||||
|
||||
nodes.insert(NodeId(index as u64), template);
|
||||
}
|
||||
|
||||
// Each import starts from its `#[default(...)]` or else its type, as a proto node's parameter does
|
||||
let inputs = preprocessor::node_inputs(&graph.imports, &NodeIOTypes::empty());
|
||||
|
||||
let exports = graph.exports.iter().map(|export| graph_input(&export.source, &NodeInput::value(TaggedValue::None, false))).collect();
|
||||
|
||||
Ok(DocumentNodeDefinition {
|
||||
identifier: graph.identifier,
|
||||
version: graph.version,
|
||||
category: graph.category,
|
||||
icon: graph.icon,
|
||||
description: Cow::Borrowed(graph.description),
|
||||
inspector: None,
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate { exports, nodes, ..Default::default() }),
|
||||
inputs,
|
||||
input_metadata: input_metadata(&graph.imports),
|
||||
output_names: graph.exports.iter().map(|export| export.name.to_string()).collect(),
|
||||
output_descriptions: graph.exports.iter().map(|export| export.description.to_string()).collect(),
|
||||
node_type_metadata: if graph.layer {
|
||||
NodeTypePersistentMetadata::layer(IVec2::ZERO)
|
||||
} else {
|
||||
NodeTypePersistentMetadata::node(IVec2::ZERO)
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/// The input a graph definition writes, where `default` is what the node's own definition starts that input with.
|
||||
fn graph_input(source: &GraphInputSource, default: &NodeInput) -> NodeInput {
|
||||
match source {
|
||||
GraphInputSource::Node { node, output } => NodeInput::node(NodeId(*node as u64), *output),
|
||||
GraphInputSource::Import { index, ty } => NodeInput::import(ty.clone(), *index),
|
||||
GraphInputSource::Value { value, exposed } => {
|
||||
let ty = match default {
|
||||
NodeInput::Value { tagged_value, .. } => tagged_value.ty(),
|
||||
NodeInput::Import { import_type, .. } => import_type.clone(),
|
||||
_ => generic!(T),
|
||||
};
|
||||
NodeInput::value(graph_value(value, &ty), exposed.unwrap_or(default.is_exposed()))
|
||||
}
|
||||
GraphInputSource::Scope(key) => NodeInput::scope(*key),
|
||||
GraphInputSource::NodePath => NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath),
|
||||
GraphInputSource::SourceId => NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId),
|
||||
}
|
||||
}
|
||||
|
||||
/// The type of the elements a wire of this type carries, past any `Item`, `List`, or lazy wrapping.
|
||||
fn element_type(ty: &Type) -> &Type {
|
||||
let mut element = ty;
|
||||
while let Type::Item(inner) | Type::List(inner) | Type::Fn(_, inner) = element {
|
||||
element = inner;
|
||||
}
|
||||
element
|
||||
}
|
||||
|
||||
/// Converts a value written in a graph definition to the type of the input it feeds.
|
||||
fn graph_value(value: &GraphValue, ty: &Type) -> TaggedValue {
|
||||
// An integer literal feeds an integer input as an integer, and any other as a number
|
||||
let is_integer = *element_type(ty) == concrete!(i64);
|
||||
|
||||
match value {
|
||||
GraphValue::Integer(integer) if is_integer => TaggedValue::Integer(*integer),
|
||||
GraphValue::Integer(integer) => TaggedValue::Number(*integer as f64),
|
||||
GraphValue::Number(number) => TaggedValue::Number(*number),
|
||||
GraphValue::Bool(boolean) => TaggedValue::Bool(*boolean),
|
||||
GraphValue::String(string) => TaggedValue::String(string.clone()),
|
||||
GraphValue::Vec2(vec2) => TaggedValue::DVec2(*vec2),
|
||||
GraphValue::Color(color) => TaggedValue::Color(*color),
|
||||
}
|
||||
}
|
||||
|
||||
/// Recursively gives each nested proto node its definition's input and output metadata, and its display name if the network's author gave none.
|
||||
fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
|
||||
match &mut node_template.implementation {
|
||||
NodeTemplateImplementation::Network(network_template) => {
|
||||
@@ -128,13 +342,190 @@ fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &
|
||||
return;
|
||||
};
|
||||
|
||||
// A display name, lock, or pin the network's author gave the node is kept
|
||||
let definition_template = &definition.node_template;
|
||||
node_template.display_name = definition_template.display_name.clone();
|
||||
if node_template.display_name.is_empty() {
|
||||
node_template.display_name = definition_template.display_name.clone();
|
||||
}
|
||||
node_template.input_metadata = definition_template.input_metadata.clone();
|
||||
node_template.output_names = definition_template.output_names.clone();
|
||||
node_template.locked = definition_template.locked;
|
||||
node_template.pinned = definition_template.pinned;
|
||||
node_template.locked |= definition_template.locked;
|
||||
node_template.pinned |= definition_template.pinned;
|
||||
}
|
||||
NodeTemplateImplementation::Definition(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
|
||||
|
||||
fn number_import() -> FieldMetadata {
|
||||
FieldMetadata {
|
||||
name: "Value",
|
||||
description: "",
|
||||
internal: false,
|
||||
exposed: true,
|
||||
widget_override: RegistryWidgetOverride::None,
|
||||
value_source: RegistryValueSource::None,
|
||||
default_colors: None,
|
||||
default_type: Some(Type::Item(Box::new(concrete!(f64)))),
|
||||
number_soft_min: None,
|
||||
number_soft_max: None,
|
||||
number_hard_min: None,
|
||||
number_hard_max: None,
|
||||
number_mode_range: false,
|
||||
number_display_decimal_places: None,
|
||||
number_step: None,
|
||||
unit: None,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// A graph exporting one node, which is fed by the given inputs.
|
||||
fn one_node_graph(identifier: &'static str, implementation: GraphNodeImplementation, inputs: Vec<(usize, GraphInputSource)>) -> GraphMetadata {
|
||||
GraphMetadata {
|
||||
identifier,
|
||||
category: "Test",
|
||||
icon: None,
|
||||
description: "",
|
||||
version: 1,
|
||||
layer: false,
|
||||
imports: vec![number_import()],
|
||||
exports: vec![GraphExportMetadata {
|
||||
name: "Out",
|
||||
description: "",
|
||||
source: GraphInputSource::Node { node: 0, output: 0 },
|
||||
}],
|
||||
nodes: vec![GraphNodeMetadata {
|
||||
implementation,
|
||||
inputs,
|
||||
position: None,
|
||||
layer: false,
|
||||
display_name: None,
|
||||
hidden: false,
|
||||
locked: false,
|
||||
pinned: false,
|
||||
call_argument: None,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn from_import() -> Vec<(usize, GraphInputSource)> {
|
||||
let ty = Type::Item(Box::new(concrete!(f64)));
|
||||
vec![(0, GraphInputSource::Import { index: 0, ty })]
|
||||
}
|
||||
|
||||
/// The definitions a test graph builds on: only the As Number proto node.
|
||||
fn proto_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||
let identifier = DefinitionIdentifier::ProtoNode(math_nodes::as_number::IDENTIFIER);
|
||||
let definition = resolve_document_node_type(&identifier).expect("As Number should have a definition").clone();
|
||||
HashMap::from([(identifier, definition)])
|
||||
}
|
||||
|
||||
fn has_graph(definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>, identifier: &str) -> bool {
|
||||
definitions_map.contains_key(&DefinitionIdentifier::Network(identifier.to_string()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graph_resolves_when_registered_before_a_graph_inside_it() {
|
||||
let outer = one_node_graph("Test Outer", GraphNodeImplementation::Graph("Test Inner"), from_import());
|
||||
let inner = one_node_graph("Test Inner", math_nodes::as_number::IDENTIFIER.into(), from_import());
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![outer, inner], &mut definitions_map);
|
||||
|
||||
assert!(has_graph(&definitions_map, "Test Inner"));
|
||||
assert!(has_graph(&definitions_map, "Test Outer"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graph_setting_an_input_its_node_lacks_is_left_out() {
|
||||
let mut inputs = from_import();
|
||||
inputs.push((
|
||||
100,
|
||||
GraphInputSource::Value {
|
||||
value: GraphValue::Number(1.),
|
||||
exposed: None,
|
||||
},
|
||||
));
|
||||
let graph = one_node_graph("Test Missing Input", math_nodes::as_number::IDENTIFIER.into(), inputs);
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![graph], &mut definitions_map);
|
||||
|
||||
assert!(!has_graph(&definitions_map, "Test Missing Input"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graphs_sharing_an_identifier_and_graphs_built_on_them_are_left_out() {
|
||||
let first = one_node_graph("Test Twin", math_nodes::as_number::IDENTIFIER.into(), from_import());
|
||||
let second = one_node_graph("Test Twin", math_nodes::as_number::IDENTIFIER.into(), from_import());
|
||||
let dependent = one_node_graph("Test Dependent", GraphNodeImplementation::Graph("Test Twin"), from_import());
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![first, second, dependent], &mut definitions_map);
|
||||
|
||||
assert!(!has_graph(&definitions_map, "Test Twin"));
|
||||
assert!(!has_graph(&definitions_map, "Test Dependent"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_integer_value_takes_the_type_of_the_input_it_feeds() {
|
||||
let integer = Type::Item(Box::new(concrete!(i64)));
|
||||
let number = Type::Item(Box::new(concrete!(f64)));
|
||||
|
||||
assert!(matches!(graph_value(&GraphValue::Integer(3), &integer), TaggedValue::Integer(3)));
|
||||
assert!(matches!(graph_value(&GraphValue::Integer(3), &number), TaggedValue::Number(value) if value == 3.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_start_from_their_default_or_type() {
|
||||
let unit_primary = FieldMetadata {
|
||||
default_type: Some(concrete!(())),
|
||||
..number_import()
|
||||
};
|
||||
let with_default = FieldMetadata {
|
||||
value_source: RegistryValueSource::Default("2.5"),
|
||||
..number_import()
|
||||
};
|
||||
let graph = GraphMetadata {
|
||||
imports: vec![unit_primary, with_default],
|
||||
..one_node_graph("Test Defaults", math_nodes::as_number::IDENTIFIER.into(), from_import())
|
||||
};
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![graph], &mut definitions_map);
|
||||
let inputs = &definitions_map[&DefinitionIdentifier::Network("Test Defaults".to_string())].node_template.inputs;
|
||||
|
||||
// A `()` primary has nothing to connect, and an exposed parameter's default is parsed by its type
|
||||
assert!(!inputs[0].is_exposed());
|
||||
assert!(matches!(inputs[1].as_value(), Some(TaggedValue::Number(value)) if *value == 2.5));
|
||||
assert!(inputs[1].is_exposed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graph_nodes_widget_settings_come_from_its_import() {
|
||||
use crate::messages::prelude::DocumentMessageHandler;
|
||||
|
||||
let node_id = NodeId(1);
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let artboard = resolve_document_node_type(&DefinitionIdentifier::Network("Artboard".into())).expect("Artboard should exist");
|
||||
document.network_interface.insert_node(node_id, artboard.default_node_template(), &[]);
|
||||
|
||||
let location = graphene_std::subgraphs::artboard::LocationInput::INDEX;
|
||||
let field = document
|
||||
.network_interface
|
||||
.field_metadata(&node_id, location, &[])
|
||||
.expect("the location input should have its import's settings");
|
||||
assert_eq!(field.labels, Some(("X", "Y")));
|
||||
assert!(field.integer);
|
||||
assert!(!document.network_interface.is_internal_input(&node_id, location, &[]));
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,11 @@ pub enum NodeGraphMessage {
|
||||
xy: Option<(i32, i32)>,
|
||||
add_transaction: bool,
|
||||
},
|
||||
/// Adds a subgraph with nothing in it, at the given grid position or else in view, and selects it.
|
||||
CreateEmptySubgraph {
|
||||
node_id: Option<NodeId>,
|
||||
xy: Option<(i32, i32)>,
|
||||
},
|
||||
CreateWire {
|
||||
output_connector: OutputConnector,
|
||||
input_connector: InputConnector,
|
||||
@@ -383,6 +388,7 @@ impl NodeGraphMessage {
|
||||
| Self::SetImportExportDescriptionImpl { .. } => Some(breadcrumb_network_path),
|
||||
Self::AddNodes { .. }
|
||||
| Self::CreateNodeFromContextMenu { .. }
|
||||
| Self::CreateEmptySubgraph { .. }
|
||||
| Self::CreateWire { .. }
|
||||
| Self::CreateWires { .. }
|
||||
| Self::ConnectUpstreamOutputToInput { .. }
|
||||
|
||||
@@ -5,13 +5,14 @@ use crate::messages::input_mapper::utility_types::macros::{action_shortcut, acti
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::document_message_handler::navigation_controls;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type, resolve_network_node_type};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type};
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, FrontendGraphDataType, NodeEvaluationError, NodeGraphErrorDiagnostic};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
|
||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||
self, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeNetworkInterface, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint, TransactionStatus,
|
||||
self, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeNetworkInterface, NodeTemplate, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint,
|
||||
TransactionStatus,
|
||||
};
|
||||
use crate::messages::portfolio::document::utility_types::nodes::{CollapsedLayers, LayerPanelChainInsertion, LayerPanelChainNode, LayerPanelEntry};
|
||||
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_vector_wire};
|
||||
@@ -422,6 +423,23 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
});
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
NodeGraphMessage::CreateEmptySubgraph { node_id, xy } => {
|
||||
let node_id = node_id.unwrap_or_else(NodeId::new);
|
||||
let (x, y) = xy.unwrap_or_else(|| {
|
||||
network_interface
|
||||
.node_graph_ptz(breadcrumb_network_path)
|
||||
.map_or((0, 0), |ptz| ((-ptz.pan.x / GRID_SIZE as f64) as i32, (-ptz.pan.y / GRID_SIZE as f64) as i32))
|
||||
});
|
||||
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::InsertNode {
|
||||
node_id,
|
||||
node_template: Box::new(NodeTemplate::empty_subgraph()),
|
||||
});
|
||||
responses.add(NodeGraphMessage::ShiftNodePosition { node_id, x, y });
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] });
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
NodeGraphMessage::ConnectUpstreamOutputToInput { downstream_input, input_connector } => {
|
||||
let Some(upstream_node) = network_interface.upstream_output_connector(&downstream_input, selection_network_path) else {
|
||||
log::error!("Failed to find upstream node for downstream_input");
|
||||
@@ -769,24 +787,19 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
}
|
||||
}
|
||||
|
||||
// Use the network interface to add a default node, then set the imports, exports, paste the nodes inside, and connect them to the imports/exports
|
||||
// Add an empty subgraph, then set its imports and exports, paste the nodes inside, and connect them to the imports and exports
|
||||
let encapsulating_node_id = NodeId::new();
|
||||
let mut default_node_template = resolve_network_node_type("Custom Node").expect("Custom Node should exist").default_node_template();
|
||||
let mut subgraph_template = NodeTemplate::empty_subgraph();
|
||||
let Some(center_of_selected_nodes) = network_interface.selected_nodes_bounding_box(breadcrumb_network_path).map(|[a, b]| (a + b) / 2.) else {
|
||||
log::error!("Could not get center of selected_nodes");
|
||||
return;
|
||||
};
|
||||
let center_of_selected_nodes_grid_space = IVec2::new((center_of_selected_nodes.x / 24. + 0.5).floor() as i32, (center_of_selected_nodes.y / 24. + 0.5).floor() as i32);
|
||||
default_node_template.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1));
|
||||
subgraph_template.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1));
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::InsertNode {
|
||||
node_id: encapsulating_node_id,
|
||||
node_template: Box::new(default_node_template),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetDisplayNameImpl {
|
||||
node_id: encapsulating_node_id,
|
||||
network_path: selection_network_path.to_vec(),
|
||||
alias: "Untitled Node".to_string(),
|
||||
node_template: Box::new(subgraph_template),
|
||||
});
|
||||
|
||||
responses.add(DocumentMessage::EnterNestedNetwork { node_id: encapsulating_node_id });
|
||||
@@ -3426,6 +3439,13 @@ impl NodeGraphMessageHandler {
|
||||
})
|
||||
.disabled(read_only)
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
TextButton::new("New Custom Node")
|
||||
.tooltip_label("New Custom Node")
|
||||
.tooltip_description("Add an empty subgraph, which can be entered to build a node of your own out of other nodes.")
|
||||
.on_update(|_| NodeGraphMessage::CreateEmptySubgraph { node_id: None, xy: None }.into())
|
||||
.disabled(read_only)
|
||||
.widget_instance(),
|
||||
//
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
//
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
use super::document_node_definitions::{NODE_OVERRIDES, NodeInspectorContext};
|
||||
use super::utility_types::FrontendGraphDataType;
|
||||
use crate::messages::layout::layout_message_handler::unit_suffix;
|
||||
use crate::messages::layout::utility_types::math_expression::{MathExpressionTokens, math_expression_error, math_expression_error_ranges, math_expression_tokens};
|
||||
use crate::messages::layout::utility_types::tooltip_markdown::{escape_markdown, markdown_code_span};
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
@@ -32,7 +31,6 @@ use graphene_std::text::{Font, TextAlign};
|
||||
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
|
||||
use graphene_std::transfer_curve::TransferCurve;
|
||||
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType, Transform};
|
||||
use graphene_std::units::{Angle, AngleUnit, Length, LengthUnit, TypedAngle, TypedLength};
|
||||
use graphene_std::vector::misc::BooleanOperation;
|
||||
use graphene_std::vector::misc::{
|
||||
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod,
|
||||
@@ -240,7 +238,7 @@ pub fn start_widgets(parameter_widgets_info: &ParameterWidgetsInfo) -> Vec<Widge
|
||||
}
|
||||
|
||||
/// The presentation of a parameter's widget, sourced from the node's field metadata: numeric bounds, widget modes, and unit of measure.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct ParameterOptions {
|
||||
pub soft_min: Option<f64>,
|
||||
pub soft_max: Option<f64>,
|
||||
@@ -252,6 +250,50 @@ pub(crate) struct ParameterOptions {
|
||||
pub unit: Option<&'static str>,
|
||||
pub display_decimal_places: Option<u32>,
|
||||
pub step: Option<f64>,
|
||||
pub labels: Option<(&'static str, &'static str)>,
|
||||
pub integer: bool,
|
||||
pub blank_assist: bool,
|
||||
}
|
||||
|
||||
impl Default for ParameterOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
soft_min: None,
|
||||
soft_max: None,
|
||||
hard_min: None,
|
||||
hard_max: None,
|
||||
slider: false,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
unit: None,
|
||||
display_decimal_places: None,
|
||||
step: None,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ParameterOptions {
|
||||
/// The options a proto node's field or a graph's import gives its widget.
|
||||
pub(crate) fn from_field(field: &graphene_std::registry::FieldMetadata) -> Self {
|
||||
Self {
|
||||
soft_min: field.number_soft_min,
|
||||
soft_max: field.number_soft_max,
|
||||
hard_min: field.number_hard_min,
|
||||
hard_max: field.number_hard_max,
|
||||
slider: field.number_mode_range,
|
||||
multiline: field.multiline,
|
||||
progression: field.progression,
|
||||
unit: field.unit,
|
||||
display_decimal_places: field.number_display_decimal_places,
|
||||
step: field.number_step,
|
||||
labels: field.labels,
|
||||
integer: field.integer,
|
||||
blank_assist: field.blank_assist,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The values a range slider's two ends map to linearly and the one its double-click restores, if known.
|
||||
@@ -305,9 +347,12 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
unit,
|
||||
display_decimal_places,
|
||||
step,
|
||||
labels,
|
||||
integer,
|
||||
blank_assist,
|
||||
} = options;
|
||||
|
||||
let mut number_input = NumberInput::default().pixels_per_inch(context.network_interface.pixels_per_inch());
|
||||
let mut number_input = NumberInput::default().is_integer(integer);
|
||||
if slider {
|
||||
number_input = number_input.mode_range();
|
||||
}
|
||||
@@ -350,7 +395,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
}
|
||||
};
|
||||
|
||||
let default_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
let default_info = ParameterWidgetsInfo::at_index(node_id, index, blank_assist, context);
|
||||
|
||||
// A type with no widget can only be supplied through the graph, labeled with a placeholder row
|
||||
let unsupported_widgets = |default_info: ParameterWidgetsInfo, type_label: String| {
|
||||
@@ -389,14 +434,15 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
false => number_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)),
|
||||
},
|
||||
Some(x) if id_is::<i64>(x) => number_widget(default_info, bounded(number_input.int(), f64::NEG_INFINITY, f64::INFINITY)).into(),
|
||||
Some(x) if id_is::<Length>(x) => length_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)).into(),
|
||||
Some(x) if id_is::<Angle>(x) => angle_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)).into(),
|
||||
Some(x) if id_is::<bool>(x) => bool_widget(default_info, CheckboxInput::default()).into(),
|
||||
Some(x) if id_is::<String>(x) => match multiline {
|
||||
true => text_area_widget(default_info).into(),
|
||||
false => text_widget(default_info).into(),
|
||||
},
|
||||
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false, false),
|
||||
Some(x) if id_is::<DVec2>(x) => {
|
||||
let (x_label, y_label) = labels.unwrap_or(("X", "Y"));
|
||||
vec2_widget(default_info, x_label, y_label, unit.unwrap_or(""), hard_min, hard_max, integer, false)
|
||||
}
|
||||
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
@@ -898,9 +944,8 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
|
||||
}
|
||||
}
|
||||
|
||||
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, is_integer: bool, disabled: bool) -> LayoutGroup {
|
||||
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, max: Option<f64>, is_integer: bool, disabled: bool) -> LayoutGroup {
|
||||
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||
let pixels_per_inch = parameter_widgets_info.network_interface.pixels_per_inch();
|
||||
|
||||
let Some(input) = parameter_widgets_info.input() else {
|
||||
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||
@@ -914,10 +959,9 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.label(x)
|
||||
.unit(unit)
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.pixels_per_inch(pixels_per_inch)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), dvec2.y))))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
@@ -926,10 +970,9 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.label(y)
|
||||
.unit(unit)
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.pixels_per_inch(pixels_per_inch)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(dvec2.x, input.value.unwrap()))))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
@@ -942,10 +985,9 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.label(x)
|
||||
.unit(unit)
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.pixels_per_inch(pixels_per_inch)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), value))))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
@@ -954,10 +996,9 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.label(y)
|
||||
.unit(unit)
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.pixels_per_inch(pixels_per_inch)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(value, input.value.unwrap()))))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
@@ -1326,92 +1367,6 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
|
||||
widgets
|
||||
}
|
||||
|
||||
/// Converts a field's bounds from the unit they're given in into the unit its value is shown in.
|
||||
fn bounds_in_unit(number_input: NumberInput, convert: impl Fn(f64) -> f64) -> NumberInput {
|
||||
let convert = |bound: Option<f64>| bound.map(|bound| if bound.is_finite() { convert(bound) } else { bound });
|
||||
NumberInput {
|
||||
min: convert(number_input.min),
|
||||
max: convert(number_input.max),
|
||||
range_min: convert(number_input.range_min),
|
||||
range_max: convert(number_input.range_max),
|
||||
..number_input
|
||||
}
|
||||
}
|
||||
|
||||
/// A length's number field, which shows the length in the unit it was typed in and keeps any length unit typed into it, with the
|
||||
/// field's bounds given in pixels.
|
||||
pub fn length_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput) -> Vec<WidgetInstance> {
|
||||
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||
|
||||
let Some(input) = parameter_widgets_info.input() else {
|
||||
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||
return vec![];
|
||||
};
|
||||
let length = match input.as_non_exposed_value() {
|
||||
Some(&TaggedValue::Length(length)) => length,
|
||||
Some(&TaggedValue::Number(pixels)) => TypedLength::pixels(pixels),
|
||||
_ => return widgets,
|
||||
};
|
||||
|
||||
let pixels_per_inch = parameter_widgets_info.network_interface.pixels_per_inch();
|
||||
let number_props = bounds_in_unit(number_props, |pixels| LengthUnit::Pixel.convert(pixels, length.unit, pixels_per_inch));
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
number_props
|
||||
.value(Some(length.value))
|
||||
.unit(unit_suffix(length.unit.symbol()))
|
||||
.kept_units(LengthUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
|
||||
.pixels_per_inch(pixels_per_inch)
|
||||
.on_update(parameter_widgets_info.update_value(|input: &NumberInput| {
|
||||
let unit = math_parser::units::Unit::named(input.unit.trim()).and_then(LengthUnit::from_unit).unwrap_or_default();
|
||||
TaggedValue::Length(TypedLength {
|
||||
value: input.value.unwrap_or_default(),
|
||||
unit,
|
||||
})
|
||||
}))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
]);
|
||||
|
||||
widgets
|
||||
}
|
||||
|
||||
/// An angle's number field, which shows the angle in the unit it was typed in and keeps any angle unit typed into it, with the
|
||||
/// field's bounds given in degrees.
|
||||
pub fn angle_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput) -> Vec<WidgetInstance> {
|
||||
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||
|
||||
let Some(input) = parameter_widgets_info.input() else {
|
||||
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||
return vec![];
|
||||
};
|
||||
let angle = match input.as_non_exposed_value() {
|
||||
Some(&TaggedValue::Angle(angle)) => angle,
|
||||
Some(&TaggedValue::Number(degrees)) => TypedAngle::degrees(degrees),
|
||||
_ => return widgets,
|
||||
};
|
||||
|
||||
let number_props = bounds_in_unit(number_props, |degrees| angle.unit.from_angle(Angle::from_degrees(degrees)));
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
number_props
|
||||
.value(Some(angle.value))
|
||||
.unit(unit_suffix(angle.unit.symbol()))
|
||||
.kept_units(AngleUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
|
||||
.on_update(parameter_widgets_info.update_value(|input: &NumberInput| {
|
||||
let unit = math_parser::units::Unit::named(input.unit.trim()).and_then(AngleUnit::from_unit).unwrap_or_default();
|
||||
TaggedValue::Angle(TypedAngle {
|
||||
value: input.value.unwrap_or_default(),
|
||||
unit,
|
||||
})
|
||||
}))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
]);
|
||||
|
||||
widgets
|
||||
}
|
||||
|
||||
// TODO: Auto-generate this enum dropdown menu widget
|
||||
pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> LayoutGroup {
|
||||
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||
@@ -1512,7 +1467,6 @@ fn wire_element(ty: &Type) -> Type {
|
||||
fn type_choice_sections(offered: &[Type]) -> Vec<Vec<Type>> {
|
||||
let vocabulary = [
|
||||
vec![concrete!(bool), concrete!(i64), concrete!(f64)],
|
||||
vec![concrete!(Length), concrete!(Angle)],
|
||||
vec![concrete!(DVec2)],
|
||||
vec![concrete!(DAffine2)],
|
||||
vec![concrete!(Artboard)],
|
||||
@@ -2884,10 +2838,10 @@ pub(crate) fn grid_inspector(node_id: NodeId, context: &mut NodeInspectorContext
|
||||
ParameterWidgetsInfo::new(node_id, SpacingInput, true, context),
|
||||
NumberInput::default().label("H").min(0.).unit(" px"),
|
||||
));
|
||||
let angles = vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", "°", None, false, false);
|
||||
let angles = vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", "°", None, None, false, false);
|
||||
widgets.extend([spacing, angles]);
|
||||
} else {
|
||||
let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), false, false);
|
||||
let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), None, false, false);
|
||||
widgets.push(spacing);
|
||||
}
|
||||
}
|
||||
@@ -3350,40 +3304,20 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
||||
}
|
||||
|
||||
let row = context.call_widget_override(&node_id, input_index).unwrap_or_else(|| {
|
||||
let field = context.network_interface.field_metadata(&node_id, input_index, context.selection_network_path);
|
||||
let options = field.as_ref().map(ParameterOptions::from_field).unwrap_or_default();
|
||||
|
||||
let Some(implementation) = context.network_interface.implementation(&node_id, context.selection_network_path) else {
|
||||
log::error!("Could not get implementation for node {node_id}");
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let mut options = ParameterOptions::default();
|
||||
let input_type = match implementation {
|
||||
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => 'early_return: {
|
||||
// Clone to end the `network_interface` borrow held via `implementation`, freeing the mutable borrow `input_type` needs below
|
||||
let proto_node_identifier = proto_node_identifier.clone();
|
||||
|
||||
let mut default_type = None;
|
||||
if let Some(field) = graphene_std::registry::NODE_METADATA
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(&proto_node_identifier)
|
||||
.and_then(|metadata| metadata.fields.get(input_index))
|
||||
{
|
||||
options = ParameterOptions {
|
||||
soft_min: field.number_soft_min,
|
||||
soft_max: field.number_soft_max,
|
||||
hard_min: field.number_hard_min,
|
||||
hard_max: field.number_hard_max,
|
||||
slider: field.number_mode_range,
|
||||
multiline: field.multiline,
|
||||
progression: field.progression,
|
||||
unit: field.unit,
|
||||
display_decimal_places: field.number_display_decimal_places,
|
||||
step: field.number_step,
|
||||
};
|
||||
default_type = field.default_type.clone();
|
||||
}
|
||||
|
||||
if let Some(default) = default_type {
|
||||
if let Some(default) = field.and_then(|field| field.default_type) {
|
||||
break 'early_return default;
|
||||
}
|
||||
|
||||
@@ -3399,12 +3333,21 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
||||
let Some(input_type) = input_type else { return Vec::new() };
|
||||
input_type.clone()
|
||||
}
|
||||
_ => context
|
||||
.network_interface
|
||||
.input_type(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path)
|
||||
.compiled_nested_type()
|
||||
.cloned()
|
||||
.unwrap_or(concrete!(())),
|
||||
_ => {
|
||||
// A graph import's declared type still picks its widget while its wire's type is unresolved, such as during an error inside the subgraph
|
||||
let declared_type = field.and_then(|field| field.default_type).map(|declared_type| match declared_type {
|
||||
Type::Item(element) => *element,
|
||||
declared_type => declared_type,
|
||||
});
|
||||
|
||||
context
|
||||
.network_interface
|
||||
.input_type(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path)
|
||||
.compiled_nested_type()
|
||||
.cloned()
|
||||
.or(declared_type)
|
||||
.unwrap_or(concrete!(()))
|
||||
}
|
||||
};
|
||||
|
||||
inspector_row_from_type(node_id, input_index, &input_type, options, context).unwrap_or_else(|value| value)
|
||||
@@ -4152,10 +4095,7 @@ mod tests {
|
||||
fn math_expression_errors_quote_the_expression_safely() {
|
||||
// The expression's own text sits in code it can't close, while the message's own code keeps its formatting
|
||||
assert_eq!(description("`abc").as_deref(), Some("`` `abc `` is not recognized"));
|
||||
assert_eq!(
|
||||
description("7 % 3").as_deref(),
|
||||
Some("`%` makes the number before it a percentage, so the remainder is written `mod(a, b)`")
|
||||
);
|
||||
assert_eq!(description("7 % 3").as_deref(), Some("`%` is reserved for percentages, so the remainder is written `mod(a, b)`"));
|
||||
|
||||
// A quoted token like `*` is a code span, so it can't pair with another into italics
|
||||
let error = description("2 * * 3").unwrap();
|
||||
|
||||
@@ -34,7 +34,7 @@ impl FrontendGraphDataType {
|
||||
"Color" => Self::Color,
|
||||
"Gradient" => Self::Gradient,
|
||||
"String" => Self::Typography,
|
||||
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" | "Length" | "Angle" => Self::Number,
|
||||
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
|
||||
// A generator draws pixels like an image, at whatever resolution is needed
|
||||
"Generator" => Self::Raster,
|
||||
raster if raster.starts_with("Raster") => Self::Raster,
|
||||
|
||||
@@ -296,29 +296,6 @@ fn pinned_order_round_trips_through_the_registry() {
|
||||
);
|
||||
}
|
||||
|
||||
/// The document's resolution is shared document state, so it survives a registry round trip, and the default is stored as its absence.
|
||||
#[test]
|
||||
fn pixels_per_inch_round_trips_through_the_registry() {
|
||||
let round_trip = |pixels_per_inch: f64| {
|
||||
let mut document = open_demo("changing-seasons.graphite");
|
||||
document.network_interface.set_pixels_per_inch(pixels_per_inch);
|
||||
|
||||
let network = document.network_interface.document_network().clone();
|
||||
let view = StorageMetadataView::new(&document.network_interface);
|
||||
let conversion = Registry::convert_from_runtime(&network, &view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
|
||||
let declarations = conversion.declarations;
|
||||
let (rebuilt_network, node_entries, network_entries) = conversion.registry.to_runtime_with_full_metadata(&declarations, &conversion.blob_bytes).expect("to_runtime failed");
|
||||
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries);
|
||||
(
|
||||
rebuilt.pixels_per_inch(),
|
||||
rebuilt.network_metadata(&[]).expect("the rebuilt document network should resolve").persistent_metadata.pixels_per_inch,
|
||||
)
|
||||
};
|
||||
|
||||
assert_eq!(round_trip(300.), (300., Some(300.)));
|
||||
assert_eq!(round_trip(96.), (96., None));
|
||||
}
|
||||
|
||||
/// Per-peer view settings (`ui::doc::*`) survive the `session.json` round-trip: serialize them into
|
||||
/// the view map, then apply it onto a fresh handler and confirm each field matches.
|
||||
#[test]
|
||||
|
||||
@@ -57,7 +57,6 @@ use crate::messages::portfolio::document::utility_types::network_interface::reso
|
||||
use crate::messages::portfolio::document::utility_types::text_metrics::text_width;
|
||||
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_thick_wire_center_line, build_vector_wire};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::NumberInputMode;
|
||||
use deserialization::deserialize_node_persistent_metadata;
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::Type;
|
||||
@@ -72,7 +71,7 @@ use graphene_std::vector::click_target::{ClickTarget, ClickTargetType, FreePoint
|
||||
use graphene_std::vector::{Vector, VectorModificationType};
|
||||
use kurbo::BezPath;
|
||||
use memo_network::MemoNetwork;
|
||||
use serde_json::{Value, json};
|
||||
use serde_json::Value;
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::hash::Hash;
|
||||
use std::ops::Deref;
|
||||
|
||||
@@ -105,7 +105,6 @@ impl NodeNetworkInterface {
|
||||
match change {
|
||||
NetworkMetadataChange::Reference(reference) => network.set_reference(reference.clone()),
|
||||
NetworkMetadataChange::PinnedOrder(order) => network.set_pinned_order(order.clone()),
|
||||
NetworkMetadataChange::PixelsPerInch(pixels_per_inch) => network.set_pixels_per_inch(*pixels_per_inch),
|
||||
NetworkMetadataChange::ImportMetadata(import_metadata) => network.set_import_metadata(import_metadata.clone()),
|
||||
NetworkMetadataChange::ExportNames(export_names) => network.set_export_names(export_names.clone()),
|
||||
NetworkMetadataChange::ExportDescriptions(export_descriptions) => network.set_export_descriptions(export_descriptions.clone()),
|
||||
|
||||
+3
-3
@@ -1,4 +1,4 @@
|
||||
use super::template::NodeTemplateImplementation;
|
||||
use super::template::{NodeTemplate, NodeTemplateImplementation};
|
||||
use super::{InputConnector, OutputConnector, catalog};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{network_node_identifiers, resolve_network_node_type};
|
||||
use crate::messages::portfolio::document::storage_tests::test_support::round_trip_through_gdd;
|
||||
@@ -308,7 +308,7 @@ async fn undoing_the_unlock_of_an_open_catalog_node_shows_it_read_only_again() {
|
||||
async fn undoing_the_creation_of_an_open_subgraph_leaves_it() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let subgraph = editor.create_node_by_name(DefinitionIdentifier::Network("Custom Node".to_string())).await;
|
||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||
editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: subgraph }).await;
|
||||
assert_eq!(editor.active_document().breadcrumb_network_path(), [subgraph]);
|
||||
|
||||
@@ -349,7 +349,7 @@ async fn a_subgraph_holding_a_catalog_node_pastes_into_a_document_without_it() {
|
||||
let custom = NodeId::new();
|
||||
let blend = NodeId::new();
|
||||
let interface = &mut editor.active_document_mut().network_interface;
|
||||
interface.insert_node(custom, resolve_network_node_type("Custom Node").expect("Custom Node").default_node_template(), &[]);
|
||||
interface.insert_node(custom, NodeTemplate::empty_subgraph(), &[]);
|
||||
interface.insert_node(blend, resolve_network_node_type("Blend").expect("Blend").default_node_template(), &[custom]);
|
||||
let DocumentNodeImplementation::Definition(shipped) = interface.document_node(&blend, &[custom]).expect("the Blend").implementation else {
|
||||
panic!("the Blend should name a table entry")
|
||||
|
||||
+18
-6
@@ -2614,7 +2614,7 @@ async fn shaking_a_node_spliced_in_by_a_secondary_input_keeps_the_dot_on_its_wir
|
||||
// Numbers to Vec2 hides its primary input, so it takes the flow by its first exposed input instead
|
||||
let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
|
||||
let shaken = editor
|
||||
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER), 10, 0)
|
||||
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER), 10, 0)
|
||||
.await;
|
||||
let dot = editor.create_node_by_name_at(passthrough_definition(), 20, 0).await;
|
||||
let consumer = editor.create_node_by_name_at(fill_definition(), 30, 0).await;
|
||||
@@ -3119,7 +3119,7 @@ async fn imports_and_exports_keep_just_a_grid_cell_from_a_dot() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
|
||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||
let path = [subgraph];
|
||||
editor.enter_editable_network(subgraph).await;
|
||||
|
||||
@@ -3506,7 +3506,7 @@ async fn a_press_right_after_dragging_a_wire_out_of_an_output_drags_another_wire
|
||||
|
||||
/// Opens a new subgraph with one node inside, which is all that lies between its import and its export.
|
||||
async fn subgraph_holding_one_node(editor: &mut EditorTestUtils) -> (NodeId, NodeId) {
|
||||
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
|
||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||
editor.enter_editable_network(subgraph).await;
|
||||
editor.handle_message(NodeGraphMessage::AddImport).await;
|
||||
editor.handle_message(NodeGraphMessage::AddPrimaryExport).await;
|
||||
@@ -4041,18 +4041,30 @@ async fn a_session_preview_of_a_removed_node_is_dropped() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_new_subgraph_is_its_own_definition() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
assert!(matches!(network_interface.implementation(&subgraph, &[]), Some(DocumentNodeImplementation::Definition(_))));
|
||||
assert_eq!(network_interface.reference(&subgraph, &[]), None, "it shouldn't name a catalog definition");
|
||||
assert_eq!(network_interface.display_name(&subgraph, &[]), "Subgraph");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cannot_preview_node_without_outputs() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let custom_node = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
|
||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
|
||||
assert_eq!(network_interface.number_of_outputs(&custom_node, &[]), 0);
|
||||
assert_eq!(network_interface.number_of_outputs(&subgraph, &[]), 0);
|
||||
|
||||
// Attempting to toggle preview on a node without outputs should not enable previewing
|
||||
network_interface.toggle_preview(custom_node, &[]);
|
||||
network_interface.toggle_preview(subgraph, &[]);
|
||||
assert_eq!(network_interface.previewing(&[]), Previewing::No);
|
||||
}
|
||||
|
||||
|
||||
@@ -75,7 +75,6 @@ pub enum NetworkMetadataChange {
|
||||
Reference(Option<String>),
|
||||
/// The whole order, since the encoding is one array-valued attribute rather than a slot each.
|
||||
PinnedOrder(Vec<NodeId>),
|
||||
PixelsPerInch(Option<f64>),
|
||||
ImportMetadata(Vec<InputMetadata>),
|
||||
ExportNames(Vec<String>),
|
||||
ExportDescriptions(Vec<String>),
|
||||
@@ -257,12 +256,6 @@ impl EditorDelta {
|
||||
value: (!stored.is_empty()).then(|| serialize_attribute(network_attr::PINNED_ORDER, &stored)).transpose()?,
|
||||
}
|
||||
}
|
||||
NetworkMetadataChange::PixelsPerInch(pixels_per_inch) => AttributeDelta {
|
||||
key: network_attr::PIXELS_PER_INCH.to_string(),
|
||||
value: pixels_per_inch
|
||||
.map(|pixels_per_inch| serialize_attribute(network_attr::PIXELS_PER_INCH, &pixels_per_inch))
|
||||
.transpose()?,
|
||||
},
|
||||
NetworkMetadataChange::ImportMetadata(import_metadata) => import_metadata_delta(import_metadata)?,
|
||||
NetworkMetadataChange::ExportNames(export_names) => export_names_delta(export_names)?,
|
||||
NetworkMetadataChange::ExportDescriptions(export_descriptions) => export_descriptions_delta(export_descriptions)?,
|
||||
|
||||
@@ -1254,19 +1254,6 @@ impl NodeNetworkInterface {
|
||||
self.transaction_modified();
|
||||
}
|
||||
|
||||
/// Sets how many pixels make an inch in the document, stored only where it differs from the default.
|
||||
pub fn set_pixels_per_inch(&mut self, pixels_per_inch: f64) {
|
||||
let stored = (pixels_per_inch != graphene_std::units::DEFAULT_PIXELS_PER_INCH).then_some(pixels_per_inch);
|
||||
|
||||
let Some(mut network) = self.network_mut(&[]) else {
|
||||
log::error!("Could not get the root network in set_pixels_per_inch");
|
||||
return;
|
||||
};
|
||||
network.set_pixels_per_inch(stored);
|
||||
|
||||
self.transaction_modified();
|
||||
}
|
||||
|
||||
pub fn set_visibility(&mut self, node_id: &NodeId, network_path: &[NodeId], is_visible: bool) {
|
||||
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else {
|
||||
log::error!("Could not get node {node_id} in set_visibility");
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
use super::*;
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
/// Index of the Artboard definition's Clip input, which must match the input order authored in document_node_definitions.rs.
|
||||
pub(crate) const ARTBOARD_CLIP_INPUT_INDEX: usize = 5;
|
||||
|
||||
impl NodeNetworkInterface {
|
||||
/// Runs a query against a resolved [`NetworkView`], logging any error at this message-boundary wrapper and mapping it to None.
|
||||
pub(crate) fn query<'a, 'p, T>(&'a self, network_path: &'p [NodeId], caller: &str, query: impl FnOnce(NetworkView<'a, 'p>) -> Result<T, NetworkError>) -> Option<T> {
|
||||
@@ -128,18 +125,10 @@ impl NodeNetworkInterface {
|
||||
});
|
||||
|
||||
let mut hasher = std::hash::DefaultHasher::new();
|
||||
(self.network.current_hash(), self.previewed_nodes(), layers_hash, self.pixels_per_inch().to_bits()).hash(&mut hasher);
|
||||
(self.network.current_hash(), self.previewed_nodes(), layers_hash).hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
/// How many pixels make an inch in the document, which sizes the lengths typed in a physical unit.
|
||||
pub fn pixels_per_inch(&self) -> f64 {
|
||||
self.network_metadata(&[])
|
||||
.and_then(|metadata| metadata.persistent_metadata.pixels_per_inch)
|
||||
.filter(|pixels_per_inch| pixels_per_inch.is_finite() && *pixels_per_inch > 0.)
|
||||
.unwrap_or(graphene_std::units::DEFAULT_PIXELS_PER_INCH)
|
||||
}
|
||||
|
||||
/// Get the specified document node in the nested network based on node_id and network_path
|
||||
pub fn document_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&DocumentNode> {
|
||||
self.query(network_path, "document_node", |view| view.node(node_id))
|
||||
@@ -810,7 +799,7 @@ impl NodeNetworkInterface {
|
||||
self.query(network_path, "reference", |view| view.reference(node_id)).flatten()
|
||||
}
|
||||
|
||||
/// The icon of the node's definition, or the Custom Node icon when its definition has none or can't be found.
|
||||
/// The icon of the node's definition, or the generic subgraph icon when its definition has none or can't be found.
|
||||
pub fn node_icon(&self, node_id: &NodeId, network_path: &[NodeId]) -> &'static str {
|
||||
self.reference(node_id, network_path)
|
||||
.and_then(|reference| resolve_document_node_type(&reference)?.icon)
|
||||
@@ -837,17 +826,27 @@ impl NodeNetworkInterface {
|
||||
self.view(network_path).ok().and_then(|view| view.persistent_input_metadata(node_id, index).ok())
|
||||
}
|
||||
|
||||
/// Whether the input is internal state of its proto node (named with a leading `_`), which is never exposed to the graph.
|
||||
/// Whether the input is internal state of its node (named with a leading `_`), which is never exposed to the graph.
|
||||
pub fn is_internal_input(&self, node_id: &NodeId, index: usize, network_path: &[NodeId]) -> bool {
|
||||
let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(node_metadata) = graphene_std::registry::NODE_METADATA.lock() else { return false };
|
||||
self.field_metadata(node_id, index, network_path).is_some_and(|field| field.internal)
|
||||
}
|
||||
|
||||
node_metadata
|
||||
.get(proto_node_identifier)
|
||||
.and_then(|metadata| metadata.fields.get(index))
|
||||
.is_some_and(|field| field.internal)
|
||||
/// The metadata the node macro records for a proto node's parameter, or the `#[graph]` macro for a graph node's import.
|
||||
/// A graph node's input has it only while it still has that import's name, since an edited subgraph can reorder its imports.
|
||||
pub fn field_metadata(&self, node_id: &NodeId, index: usize, network_path: &[NodeId]) -> Option<graphene_std::registry::FieldMetadata> {
|
||||
if let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) {
|
||||
let node_metadata = graphene_std::registry::NODE_METADATA.lock().ok()?;
|
||||
return node_metadata.get(proto_node_identifier)?.fields.get(index).cloned();
|
||||
}
|
||||
|
||||
let Some(DefinitionIdentifier::Network(identifier)) = self.reference(node_id, network_path) else {
|
||||
return None;
|
||||
};
|
||||
let input_name = self.persistent_input_metadata(node_id, index, network_path)?.input_name.clone();
|
||||
|
||||
let graphs = graphene_std::registry::GRAPH_METADATA.lock().ok()?;
|
||||
let field = graphs.iter().find(|graph| graph.identifier == identifier)?.imports.get(index)?;
|
||||
(field.name == input_name).then(|| field.clone())
|
||||
}
|
||||
|
||||
/// The description stored for a node's output, or else for a proto node, the doc comment on its field in the struct a multi-output node returns.
|
||||
@@ -883,16 +882,16 @@ impl NodeNetworkInterface {
|
||||
node.set_widget_override(index, widget_override);
|
||||
}
|
||||
|
||||
/// Returns the display name of the node. If the display name is empty, it will return "Untitled Node" or "Untitled Layer" depending on the node type.
|
||||
/// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed.
|
||||
pub fn display_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
|
||||
self.query(network_path, "display_name", |view| Ok(view.display_name(node_id)))
|
||||
.unwrap_or_else(|| "Custom Node".to_string())
|
||||
.unwrap_or_else(|| "Subgraph".to_string())
|
||||
}
|
||||
|
||||
/// The uneditable name in the Inspector which represents the function name of the node implementation.
|
||||
pub fn implementation_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
|
||||
self.query(network_path, "implementation_name", |view| Ok(view.implementation_name(node_id)))
|
||||
.unwrap_or_else(|| "Custom Node".to_string())
|
||||
.unwrap_or_else(|| "Subgraph".to_string())
|
||||
}
|
||||
|
||||
pub fn is_locked(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
|
||||
@@ -1087,7 +1086,7 @@ impl NodeNetworkInterface {
|
||||
/// Whether the artboard layer clips the content inside it to its bounds.
|
||||
fn artboard_clips_content(&self, artboard: LayerNodeIdentifier) -> bool {
|
||||
self.document_node(&artboard.to_node(), &[])
|
||||
.and_then(|artboard| artboard.inputs.get(ARTBOARD_CLIP_INPUT_INDEX))
|
||||
.and_then(|artboard| artboard.inputs.get(graphene_std::subgraphs::artboard::ClipInput::INDEX))
|
||||
.is_some_and(|clip_input| matches!(clip_input, NodeInput::Value { tagged_value, .. } if tagged_value.clone().deref() == &TaggedValue::Bool(true)))
|
||||
}
|
||||
|
||||
|
||||
@@ -143,9 +143,6 @@ impl NodeNetworkInterface {
|
||||
if current_metadata.pinned_node_order != target.metadata.pinned_order {
|
||||
deltas.push(change(NetworkMetadataChange::PinnedOrder(target.metadata.pinned_order.clone())));
|
||||
}
|
||||
if current_metadata.pixels_per_inch != target.metadata.pixels_per_inch {
|
||||
deltas.push(change(NetworkMetadataChange::PixelsPerInch(target.metadata.pixels_per_inch)));
|
||||
}
|
||||
// An empty list states nothing, since a catalog entry's interface comes from the catalog rather than storage
|
||||
let import_metadata: Vec<_> = target.metadata.import_metadata.iter().cloned().map(input_metadata_entry_to_runtime).collect();
|
||||
if !import_metadata.is_empty() && current_metadata.import_metadata != import_metadata {
|
||||
|
||||
-5
@@ -111,10 +111,6 @@ impl NodeMetadataSource for StorageMetadataView<'_> {
|
||||
fn pinned_order(&self, network: NetworkLocation) -> Vec<NodeId> {
|
||||
self.network_persistent(network).map(|persistent| persistent.pinned_node_order.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn pixels_per_inch(&self, network: NetworkLocation) -> Option<f64> {
|
||||
self.network_persistent(network)?.pixels_per_inch
|
||||
}
|
||||
}
|
||||
|
||||
impl DocumentSettings<'_> {
|
||||
@@ -311,7 +307,6 @@ fn apply_network_entries_into_tree(metadata: &mut NodeNetworkMetadata, entries:
|
||||
network_metadata.persistent_metadata.reference = Some(reference);
|
||||
}
|
||||
network_metadata.persistent_metadata.pinned_node_order = entry.pinned_order;
|
||||
network_metadata.persistent_metadata.pixels_per_inch = entry.pixels_per_inch;
|
||||
network_metadata.persistent_metadata.import_metadata = entry.import_metadata.into_iter().map(input_metadata_entry_to_runtime).collect();
|
||||
network_metadata.persistent_metadata.export_names = entry.export_names;
|
||||
network_metadata.persistent_metadata.export_descriptions = entry.export_descriptions;
|
||||
|
||||
-10
@@ -538,16 +538,6 @@ impl NetworkMut<'_> {
|
||||
changed
|
||||
}
|
||||
|
||||
/// How many pixels make an inch in the document, or `None` for the default.
|
||||
pub(crate) fn set_pixels_per_inch(&mut self, pixels_per_inch: Option<f64>) -> bool {
|
||||
let changed = self.metadata.pixels_per_inch != pixels_per_inch;
|
||||
self.metadata.pixels_per_inch = pixels_per_inch;
|
||||
if changed {
|
||||
self.emit(NetworkMetadataChange::PixelsPerInch(pixels_per_inch));
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The display order of pinned nodes in the Inspector.
|
||||
pub(crate) fn set_pinned_order(&mut self, pinned_node_order: Vec<NodeId>) -> bool {
|
||||
let changed = self.metadata.pinned_node_order != pinned_node_order;
|
||||
|
||||
@@ -511,7 +511,6 @@ impl NodeNetworkInterface {
|
||||
.into_iter()
|
||||
.chain([
|
||||
NetworkMetadataChange::PinnedOrder(persistent_metadata.pinned_node_order.clone()),
|
||||
NetworkMetadataChange::PixelsPerInch(persistent_metadata.pixels_per_inch),
|
||||
NetworkMetadataChange::ImportMetadata(persistent_metadata.import_metadata.clone()),
|
||||
NetworkMetadataChange::ExportNames(persistent_metadata.export_names.clone()),
|
||||
NetworkMetadataChange::ExportDescriptions(persistent_metadata.export_descriptions.clone()),
|
||||
|
||||
@@ -38,6 +38,14 @@ pub struct NodeTemplate {
|
||||
}
|
||||
|
||||
impl NodeTemplate {
|
||||
/// A new subgraph with nothing in it, which names no definition since it becomes its own entry in the document's definitions table.
|
||||
pub fn empty_subgraph() -> Self {
|
||||
Self {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The input slot named by the given parameter symbol, mirroring [`DocumentNode::input`].
|
||||
pub fn input<P: graphene_std::NodeParameter>(&self, _parameter: P) -> Option<&NodeInput> {
|
||||
self.inputs.get(P::INDEX)
|
||||
@@ -291,7 +299,6 @@ impl NodeTemplateImplementation {
|
||||
reference,
|
||||
node_metadata,
|
||||
pinned_node_order,
|
||||
pixels_per_inch: None,
|
||||
previewing,
|
||||
navigation_metadata,
|
||||
selection_undo_history: Default::default(),
|
||||
|
||||
@@ -674,9 +674,6 @@ pub struct NodeNetworkPersistentMetadata {
|
||||
/// The display order of pinned nodes in the Inspector (shown when nothing is selected in this network), keyed by node ID.
|
||||
#[serde(default)]
|
||||
pub pinned_node_order: Vec<NodeId>,
|
||||
/// How many pixels make an inch, which sizes lengths typed in a physical unit, or `None` for the default of 96. Only the root network's applies.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub pixels_per_inch: Option<f64>,
|
||||
/// Cached metadata for each node, which is calculated when adding a node to node_metadata
|
||||
/// Indicates whether the network is currently rendered with a particular node that is previewed, and if so, which connection should be restored when the preview ends.
|
||||
pub previewing: Previewing,
|
||||
@@ -870,51 +867,11 @@ impl PartialEq for DocumentNodeMetadata {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct NumberInputSettings {
|
||||
pub unit: Option<String>,
|
||||
pub min: Option<f64>,
|
||||
pub max: Option<f64>,
|
||||
pub step: Option<f64>,
|
||||
pub mode: NumberInputMode,
|
||||
pub range_min: Option<f64>,
|
||||
pub range_max: Option<f64>,
|
||||
pub is_integer: bool,
|
||||
pub blank_assist: bool,
|
||||
}
|
||||
|
||||
impl Default for NumberInputSettings {
|
||||
fn default() -> Self {
|
||||
NumberInputSettings {
|
||||
unit: None,
|
||||
min: None,
|
||||
max: None,
|
||||
step: None,
|
||||
mode: NumberInputMode::default(),
|
||||
range_min: None,
|
||||
range_max: None,
|
||||
is_integer: false,
|
||||
blank_assist: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Vec2InputSettings {
|
||||
pub x: String,
|
||||
pub y: String,
|
||||
pub unit: String,
|
||||
pub min: Option<f64>,
|
||||
pub is_integer: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub enum WidgetOverride {
|
||||
None,
|
||||
Hidden,
|
||||
String(String),
|
||||
Number(NumberInputSettings),
|
||||
Vec2(Vec2InputSettings),
|
||||
Custom(String),
|
||||
}
|
||||
|
||||
@@ -951,40 +908,6 @@ impl InputPersistentMetadata {
|
||||
self.input_data.insert("string_inspector".to_string(), Value::String(string_inspector));
|
||||
self.widget_override = Some("string".to_string());
|
||||
}
|
||||
WidgetOverride::Number(mut number_inspector) => {
|
||||
if let Some(unit) = number_inspector.unit.take() {
|
||||
self.input_data.insert("unit".to_string(), json!(unit));
|
||||
}
|
||||
if let Some(min) = number_inspector.min.take() {
|
||||
self.input_data.insert("min".to_string(), json!(min));
|
||||
}
|
||||
if let Some(max) = number_inspector.max.take() {
|
||||
self.input_data.insert("max".to_string(), json!(max));
|
||||
}
|
||||
if let Some(step) = number_inspector.step.take() {
|
||||
self.input_data.insert("step".to_string(), json!(step));
|
||||
}
|
||||
if let Some(range_min) = number_inspector.range_min.take() {
|
||||
self.input_data.insert("range_min".to_string(), json!(range_min));
|
||||
}
|
||||
if let Some(range_max) = number_inspector.range_max.take() {
|
||||
self.input_data.insert("range_max".to_string(), json!(range_max));
|
||||
}
|
||||
self.input_data.insert("mode".to_string(), json!(number_inspector.mode));
|
||||
self.input_data.insert("is_integer".to_string(), Value::Bool(number_inspector.is_integer));
|
||||
self.input_data.insert("blank_assist".to_string(), Value::Bool(number_inspector.blank_assist));
|
||||
self.widget_override = Some("number".to_string());
|
||||
}
|
||||
WidgetOverride::Vec2(vec2_inspector) => {
|
||||
self.input_data.insert("x".to_string(), json!(vec2_inspector.x));
|
||||
self.input_data.insert("y".to_string(), json!(vec2_inspector.y));
|
||||
self.input_data.insert("unit".to_string(), json!(vec2_inspector.unit));
|
||||
self.input_data.insert("is_integer".to_string(), Value::Bool(vec2_inspector.is_integer));
|
||||
if let Some(min) = vec2_inspector.min {
|
||||
self.input_data.insert("min".to_string(), json!(min));
|
||||
}
|
||||
self.widget_override = Some("vec2".to_string());
|
||||
}
|
||||
WidgetOverride::Custom(lambda_name) => {
|
||||
self.widget_override = Some(lambda_name);
|
||||
}
|
||||
|
||||
@@ -169,7 +169,7 @@ impl<'a, 'p> NetworkView<'a, 'p> {
|
||||
.ok()
|
||||
.flatten()
|
||||
.map(|identifier| identifier.implementation_name_from_identifier())
|
||||
.unwrap_or("Custom Node".to_string())
|
||||
.unwrap_or("Subgraph".to_string())
|
||||
}
|
||||
|
||||
/// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed.
|
||||
|
||||
@@ -472,9 +472,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
],
|
||||
},
|
||||
// The old 'Vec2 Value' node took separate X and Y inputs, a role now filled by 'Numbers to Vec2', while the new 'Vec2 Value' node takes a single vec2 input.
|
||||
// Old references (including these older aliases) are remapped here to `vec_2_value::IDENTIFIER` so the per-node migration in `migrate_node` can detect the leftover 3-input shape and convert it into a 'Numbers to Vec2' node.
|
||||
// Old references (including these older aliases) are remapped here to `vec2_value::IDENTIFIER` so the per-node migration in `migrate_node` can detect the leftover 3-input shape and convert it into a 'Numbers to Vec2' node.
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::vec_2_value::IDENTIFIER,
|
||||
node: graphene_std::math_nodes::vec2_value::IDENTIFIER,
|
||||
aliases: &[
|
||||
"graphene_math_nodes::Vec2ValueNode",
|
||||
"graphene_core::ops::ConstructVector2",
|
||||
@@ -484,7 +484,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER,
|
||||
node: graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER,
|
||||
aliases: &["math_nodes::CombineVec2Node"],
|
||||
},
|
||||
// ================================
|
||||
@@ -1295,7 +1295,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
|
||||
// The "Transform" wrapper network was replaced with the `transform` proto node directly. Convert old `Network("Transform")` instances to the proto node, forwarding the 5 user-facing inputs (Value, Translation, Rotation, Scale, Skew) and dropping the legacy migration sentinels (Origin Offset, Scale Appearance) at indices 5 and 6 if present.
|
||||
// Some old documents store it as a Custom Node subgraph with no reference, where a Monitor feeds the Transform proto node. Those are converted the same way.
|
||||
// Some old documents store it as a subgraph with no reference, where a Monitor feeds the Transform proto node. Those are converted the same way.
|
||||
// Pre-pass for the same reason as the Brush migration above: replacing the outer Transform's network impl orphans its child paths.
|
||||
let transform_layers: Vec<(NodeId, Vec<NodeId>, usize)> = document
|
||||
.network_interface
|
||||
@@ -1468,7 +1468,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
|
||||
// Lex a static expression once, learning both whether it lexes at all and whether it references `B`
|
||||
let static_expression = match expression.as_value() {
|
||||
Some(TaggedValue::String(expression)) => Some(read_old_inverse_functions_as_radians(expression)),
|
||||
Some(TaggedValue::String(expression)) => Some(expression.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let mut references_b = false;
|
||||
@@ -1576,8 +1576,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
// A wrapper saved before these gained a hidden primary output had each field one output lower, so its wires shift up by one.
|
||||
// Pre-pass for the same reason as the Brush, Transform, and Image migrations above: replacing the outer network impl orphans its child paths.
|
||||
let split_wrapper_replacements = [
|
||||
("Split Vec2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
||||
("Split Vector2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
||||
("Split Vec2", graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER),
|
||||
("Split Vector2", graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER),
|
||||
("Split Channels", graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER),
|
||||
];
|
||||
for (old_reference, new_identifier) in split_wrapper_replacements {
|
||||
@@ -1641,7 +1641,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
let DocumentNodeImplementation::ProtoNode(protonode_id) = &node.implementation else { return None };
|
||||
let name = protonode_id.as_str().split('<').next().unwrap_or_default();
|
||||
if EXTRACT_XY.contains(&name) {
|
||||
Some((*node_id, path, graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER, "Extract XY"))
|
||||
Some((*node_id, path, graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER, "Extract XY"))
|
||||
} else if EXTRACT_CHANNEL.contains(&name) {
|
||||
Some((*node_id, path, graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER, "Extract Channel"))
|
||||
} else {
|
||||
@@ -1771,6 +1771,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
})
|
||||
.collect();
|
||||
|
||||
migrate_custom_node_subgraphs(document);
|
||||
|
||||
// Apply upgrades to each unmodified node, except those inside the read-only built-in subgraphs
|
||||
let nodes = document
|
||||
.network_interface
|
||||
@@ -2854,8 +2856,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
|
||||
// Convert the old 'Vec2 Value' node, identified by its leftover 3-input shape with separate X and Y inputs,
|
||||
// into the 'Numbers to Vec2' node which now fills that role (the new 'Vec2 Value' node instead takes a single vec2 input)
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::vec_2_value::IDENTIFIER) && inputs_count == 3 {
|
||||
let numbers_to_vec2_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER);
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::vec2_value::IDENTIFIER) && inputs_count == 3 {
|
||||
let numbers_to_vec2_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER);
|
||||
let mut node_template = resolve_document_node_type(&numbers_to_vec2_reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
|
||||
@@ -4045,86 +4047,23 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// The old "Math" node's inverse trigonometric functions, each with the builtin that replaced it.
|
||||
const OLD_INVERSE_FUNCTIONS: [(&str, &str); 6] = [("invsin", "asin"), ("invcos", "acos"), ("invtan", "atan"), ("invcsc", "acsc"), ("invsec", "asec"), ("invcot", "acot")];
|
||||
/// Gives each subgraph made from the removed Custom Node definition, from the catalog or by merging selected nodes, no reference and no default name, like one made with the New Custom Node button.
|
||||
/// Instances can share a definitions table entry holding the reference, so all of them are found before any is changed.
|
||||
fn migrate_custom_node_subgraphs(document: &mut DocumentMessageHandler) {
|
||||
let custom_node = Some(DefinitionIdentifier::Network("Custom Node".into()));
|
||||
let subgraphs: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter(|(node_id, _, path)| document.network_interface.reference(node_id, path) == custom_node)
|
||||
.map(|(node_id, _, path)| (*node_id, path))
|
||||
.collect();
|
||||
|
||||
/// The old "Math" node's expression with each inverse trigonometric call, like `invsin(A)`, spelled as the builtin that replaced it
|
||||
/// and divided by `rad` as `(asin(A)/rad)`, since the builtin gives an angle where the old function gave plain radians.
|
||||
fn read_old_inverse_functions_as_radians(expression: &str) -> String {
|
||||
rewrite_old_inverse_calls(expression, 0)
|
||||
}
|
||||
|
||||
/// Rewrites the calls in `source`, read by the old grammar's ASCII names and numbers, nested `depth` calls deep.
|
||||
fn rewrite_old_inverse_calls(source: &str, depth: usize) -> String {
|
||||
// Beyond the nesting an expression may have, the rest stays as written
|
||||
const MAX_DEPTH: usize = 32;
|
||||
|
||||
let mut result = String::with_capacity(source.len());
|
||||
let mut position = 0;
|
||||
while let Some(character) = source[position..].chars().next() {
|
||||
let start = position;
|
||||
|
||||
// A number ends before a name juxtaposed after it, as in `2invsin(A)`, though an exponent like `2e3` is part of it
|
||||
if character.is_ascii_digit() || character == '.' {
|
||||
let bytes = &source.as_bytes()[start..];
|
||||
let mut length = bytes.iter().take_while(|byte| byte.is_ascii_digit() || **byte == b'.').count();
|
||||
if matches!(bytes.get(length), Some(b'e' | b'E')) {
|
||||
let sign = usize::from(matches!(bytes.get(length + 1), Some(b'+' | b'-')));
|
||||
let digits = bytes.iter().skip(length + 1 + sign).take_while(|byte| byte.is_ascii_digit()).count();
|
||||
if digits > 0 {
|
||||
length += 1 + sign + digits;
|
||||
}
|
||||
}
|
||||
position += length;
|
||||
result.push_str(&source[start..position]);
|
||||
continue;
|
||||
}
|
||||
|
||||
if !(character.is_ascii_alphabetic() || character == '_') {
|
||||
position += character.len_utf8();
|
||||
result.push(character);
|
||||
continue;
|
||||
}
|
||||
|
||||
let name_length = source[start..]
|
||||
.find(|character: char| !(character.is_ascii_alphanumeric() || character == '_'))
|
||||
.unwrap_or(source.len() - start);
|
||||
position = start + name_length;
|
||||
let name = &source[start..position];
|
||||
|
||||
// The call's arguments run to the parenthesis closing the one after its name, and may hold more calls
|
||||
let after_name = &source[position..];
|
||||
let open = position + after_name.len() - after_name.trim_start().len();
|
||||
if let Some((_, builtin)) = OLD_INVERSE_FUNCTIONS.iter().find(|(old, _)| *old == name)
|
||||
&& depth < MAX_DEPTH
|
||||
&& let Some(close) = closing_parenthesis(&source[open..])
|
||||
{
|
||||
result.push_str(&format!("({builtin}({})/rad)", rewrite_old_inverse_calls(&source[open + 1..open + close], depth + 1)));
|
||||
position = open + close + 1;
|
||||
continue;
|
||||
}
|
||||
result.push_str(name);
|
||||
for (node_id, network_path) in subgraphs {
|
||||
reset_default_display_name(document, &node_id, &network_path, "Custom Node");
|
||||
reset_default_display_name(document, &node_id, &network_path, "Untitled Node");
|
||||
document.network_interface.set_reference(&node_id, &network_path, None);
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
/// The byte offset of the parenthesis closing the one `text` begins with, or `None` where it begins otherwise or never closes.
|
||||
fn closing_parenthesis(text: &str) -> Option<usize> {
|
||||
if !text.starts_with('(') {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut depth = 0;
|
||||
for (index, character) in text.char_indices() {
|
||||
match character {
|
||||
'(' => depth += 1,
|
||||
')' if depth == 1 => return Some(index),
|
||||
')' => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Splits each removed Math f(…) node by the kind of string it held, into Math Aggregate or Math Formula.
|
||||
@@ -4679,6 +4618,45 @@ mod tests {
|
||||
assert!(errors.is_empty(), "opening the document logged errors: {errors:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn opening_custom_node_subgraphs_drops_their_reference_and_default_names() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplateImplementation;
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let from_catalog = editor.create_empty_subgraph_at(0, 0).await;
|
||||
let document = editor.active_document_mut();
|
||||
let Some(DocumentNodeImplementation::Definition(shared)) = document.network_interface.implementation(&from_catalog, &[]).cloned() else {
|
||||
panic!("the subgraph should name a definitions table entry")
|
||||
};
|
||||
|
||||
// A second instance of the same table entry, named as Merge Selected Nodes named the subgraphs it made
|
||||
let from_merging = NodeId::new();
|
||||
let instance = NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Definition(shared),
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.insert_node(from_merging, instance, &[]);
|
||||
document.network_interface.set_reference(&from_catalog, &[], Some("Custom Node".into()));
|
||||
document.network_interface.set_display_name(&from_catalog, "Custom Node".into(), &[]);
|
||||
document.network_interface.set_display_name(&from_merging, "Untitled Node".into(), &[]);
|
||||
let serialized = document.serialize_document();
|
||||
|
||||
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||
let interface = &opened.network_interface;
|
||||
for node_id in [from_catalog, from_merging] {
|
||||
assert!(
|
||||
matches!(interface.implementation(&node_id, &[]), Some(DocumentNodeImplementation::Definition(_))),
|
||||
"the subgraph should still exist"
|
||||
);
|
||||
assert_eq!(interface.reference(&node_id, &[]), None);
|
||||
assert_eq!(interface.display_name(&node_id, &[]), "Subgraph");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_rasterize_node_on_the_export_compiles() {
|
||||
use crate::test_utils::test_prelude::*;
|
||||
@@ -4935,11 +4913,10 @@ mod tests {
|
||||
// The old inputs stay in place and the witness defaults to Number, the output type every such node had
|
||||
let node = &document.network_interface.document_network().nodes[&node_id];
|
||||
let value_at = |index: usize| node.inputs.get(index).and_then(|input| input.as_value()).cloned();
|
||||
assert_eq!(node.inputs.len(), 4);
|
||||
assert_eq!(node.inputs.len(), 3);
|
||||
assert_eq!(value_at(0), Some(TaggedValue::Number(4.)));
|
||||
assert_eq!(value_at(1), Some(TaggedValue::String("x^2".into())));
|
||||
assert_eq!(value_at(2), Some(TaggedValue::Number(0.)));
|
||||
assert_eq!(node.inputs.get(3), Some(&NodeInput::scope(graphene_std::units::PIXELS_PER_INCH_SCOPE)));
|
||||
}
|
||||
|
||||
// The same upgrade on a node whose value comes from upstream, where restoring the inputs has to preserve the wire
|
||||
@@ -4971,7 +4948,7 @@ mod tests {
|
||||
migrate(&mut document);
|
||||
|
||||
let node = &document.network_interface.document_network().nodes[&node_id];
|
||||
assert_eq!(node.inputs.len(), 4);
|
||||
assert_eq!(node.inputs.len(), 3);
|
||||
assert!(
|
||||
matches!(node.inputs.first(), Some(NodeInput::Node { node_id: upstream, .. }) if *upstream == source_id),
|
||||
"the upstream wire was dropped by the upgrade, leaving {:?}",
|
||||
@@ -5019,48 +4996,6 @@ mod tests {
|
||||
assert_eq!(migrated_implementation(vec![items(), expression("a * b + c"), output_type()]), math_formula::IDENTIFIER);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_inverse_functions_read_as_the_plain_radians_they_gave() {
|
||||
let read = read_old_inverse_functions_as_radians;
|
||||
assert_eq!(read("invsin(A) + 1"), "(asin(A)/rad) + 1");
|
||||
assert_eq!(read("2invcos (B)^2"), "2(acos(B)/rad)^2");
|
||||
assert_eq!(read("invtan(invsin(A) * 2)"), "(atan((asin(A)/rad) * 2)/rad)");
|
||||
assert_eq!(read("sin(invcot(A))"), "sin((acot(A)/rad))");
|
||||
assert_eq!(read("2e3invsec(A)"), "2e3(asec(A)/rad)");
|
||||
for unchanged in ["invsinh(A)", "B_invsin(A)", "invsin", "invsin(A", "sin(A) + π", ""] {
|
||||
assert_eq!(read(unchanged), unchanged);
|
||||
}
|
||||
|
||||
// The rewritten expression gives the number the old one did
|
||||
let result = math_parser::evaluate(&read("invtan(1) + 1")).unwrap().unwrap();
|
||||
assert!((result.as_real().unwrap() - (std::f64::consts::FRAC_PI_4 + 1.)).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_old_math_node_keeps_the_plain_radians_its_inverse_functions_gave() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
||||
|
||||
let math_id = NodeId(1);
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
document.network_interface.insert_node(
|
||||
math_id,
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("math_nodes::MathNode")),
|
||||
inputs: vec![
|
||||
NodeInput::value(TaggedValue::Number(1.), false),
|
||||
NodeInput::value(TaggedValue::String("invtan(A) + 1".into()), false),
|
||||
NodeInput::value(TaggedValue::Number(0.), false),
|
||||
],
|
||||
..Default::default()
|
||||
},
|
||||
&[],
|
||||
);
|
||||
migrate(&mut document);
|
||||
|
||||
let node = &document.network_interface.document_network().nodes[&math_id];
|
||||
assert_eq!(node.inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::String("(atan(x)/rad) + 1".into())));
|
||||
}
|
||||
|
||||
// The old Math node's expression decides its replacement: a static string that never reads `B` becomes "Math Function",
|
||||
// while a wired `B` or an uninspectable expression becomes "Extend" feeding "Math Formula"
|
||||
#[test]
|
||||
@@ -5127,8 +5062,8 @@ mod tests {
|
||||
let node = &document.network_interface.document_network().nodes[&math_id];
|
||||
assert_eq!(
|
||||
node.inputs.len(),
|
||||
4,
|
||||
"the old `B` input should be dropped, leaving the value, the expression, the output-type witness, and the resolution"
|
||||
3,
|
||||
"the old `B` input should be dropped, leaving the value, the expression, and the output-type witness"
|
||||
);
|
||||
assert_eq!(node.inputs.first(), Some(&NodeInput::node(source_a_id, 0)));
|
||||
assert_eq!(node.inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::String("2 - 0.2x".into())));
|
||||
@@ -5208,7 +5143,11 @@ mod tests {
|
||||
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
||||
panic!("Blend should be a network node")
|
||||
};
|
||||
let count_conversion = network_template.nodes.get_mut(&NodeId(3)).expect("Blend should have a count conversion node");
|
||||
let (&count_conversion_id, count_conversion) = network_template
|
||||
.nodes
|
||||
.iter_mut()
|
||||
.find(|(_, node)| node.inputs.iter().any(|input| matches!(input, NodeInput::Import { import_index: 1, .. })))
|
||||
.expect("Blend should have a count conversion node");
|
||||
count_conversion.implementation = NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::floor::IDENTIFIER);
|
||||
count_conversion.inputs = vec![NodeInput::import(item!(f64), 1)];
|
||||
document.network_interface.insert_node(node_id, node_template, &[]);
|
||||
@@ -5225,7 +5164,7 @@ mod tests {
|
||||
panic!("Blend should stay a network node")
|
||||
};
|
||||
assert_eq!(
|
||||
inner.nodes[&shipped_node_id("Blend", NodeId(3))].implementation,
|
||||
inner.nodes[&shipped_node_id("Blend", count_conversion_id)].implementation,
|
||||
DocumentNodeImplementation::ProtoNode(graphene_std::math_nodes::as_number::IDENTIFIER)
|
||||
);
|
||||
}
|
||||
@@ -5242,7 +5181,11 @@ mod tests {
|
||||
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
||||
panic!("Blend should be a network node")
|
||||
};
|
||||
let edited_subtract = network_template.nodes.get_mut(&NodeId(5)).expect("Blend should have an open-path denominator node");
|
||||
let (&edited_subtract_id, edited_subtract) = network_template
|
||||
.nodes
|
||||
.iter_mut()
|
||||
.find(|(_, node)| node.implementation == NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::subtract::IDENTIFIER))
|
||||
.expect("Blend should have an open-path denominator node");
|
||||
edited_subtract.inputs[1] = NodeInput::value(TaggedValue::Number(42.), false);
|
||||
document.network_interface.insert_node(node_id, node_template, &[]);
|
||||
|
||||
@@ -5252,7 +5195,7 @@ mod tests {
|
||||
let (DocumentNodeImplementation::Definition(definition), Some(inner)) = (implementation, document.network_interface.document_network().implementation_network(implementation)) else {
|
||||
panic!("Blend should stay a network node")
|
||||
};
|
||||
let edited_subtract = derived_node_id(*definition, NodeId(5));
|
||||
let edited_subtract = derived_node_id(*definition, edited_subtract_id);
|
||||
assert_eq!(inner.nodes[&edited_subtract].inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::Number(42.)));
|
||||
}
|
||||
|
||||
@@ -5334,8 +5277,15 @@ mod tests {
|
||||
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
||||
panic!("Regex Find should be a network node")
|
||||
};
|
||||
network_template.nodes.get_mut(&NodeId(0)).expect("Regex Find should have a find node").inputs[2] = NodeInput::import(item!(f64), 2);
|
||||
network_template.nodes.get_mut(&NodeId(1)).expect("Regex Find should have an item-at-index node").inputs[1] = NodeInput::value(TaggedValue::Number(0.), false);
|
||||
let inner_node_id = |identifier: graphene_std::ProtoNodeIdentifier| {
|
||||
let implementation = NodeTemplateImplementation::ProtoNode(identifier);
|
||||
network_template.nodes.iter().find(|(_, node)| node.implementation == implementation).map(|(&id, _)| id)
|
||||
};
|
||||
let find_id = inner_node_id(graphene_std::text_nodes::regex::regex_find::IDENTIFIER).expect("Regex Find should have a find node");
|
||||
let item_at_index_id = inner_node_id(graphene_std::graphic::item_at_index::IDENTIFIER).expect("Regex Find should have an item-at-index node");
|
||||
|
||||
network_template.nodes.get_mut(&find_id).expect("the find node should exist").inputs[2] = NodeInput::import(item!(f64), 2);
|
||||
network_template.nodes.get_mut(&item_at_index_id).expect("the item-at-index node should exist").inputs[1] = NodeInput::value(TaggedValue::Number(0.), false);
|
||||
document.network_interface.insert_node(node_id, node_template, &[]);
|
||||
|
||||
migrate(&mut document);
|
||||
@@ -5349,9 +5299,9 @@ mod tests {
|
||||
let Some(inner) = document.network_interface.document_network().implementation_network(&node.implementation) else {
|
||||
panic!("Regex Find should stay a network node")
|
||||
};
|
||||
assert_eq!(inner.nodes[&shipped_node_id("Regex Find", NodeId(0))].inputs.get(2), Some(&NodeInput::import(item!(i64), 2)));
|
||||
assert_eq!(inner.nodes[&shipped_node_id("Regex Find", find_id)].inputs.get(2), Some(&NodeInput::import(item!(i64), 2)));
|
||||
assert_eq!(
|
||||
inner.nodes[&shipped_node_id("Regex Find", NodeId(1))].inputs.get(1).and_then(|input| input.as_value()).cloned(),
|
||||
inner.nodes[&shipped_node_id("Regex Find", item_at_index_id)].inputs.get(1).and_then(|input| input.as_value()).cloned(),
|
||||
Some(TaggedValue::Integer(0))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@ pub use crate::messages::clipboard::{ClipboardMessage, ClipboardMessageContext,
|
||||
pub use crate::messages::color_picker::{ColorPickerMessage, ColorPickerMessageDiscriminant, ColorPickerMessageHandler};
|
||||
pub use crate::messages::debug::{DebugMessage, DebugMessageDiscriminant, DebugMessageHandler};
|
||||
pub use crate::messages::defer::{DeferMessage, DeferMessageDiscriminant, DeferMessageHandler};
|
||||
pub use crate::messages::dialog::document_setup_dialog::{DocumentSetupDialogMessage, DocumentSetupDialogMessageDiscriminant, DocumentSetupDialogMessageHandler};
|
||||
pub use crate::messages::dialog::export_dialog::{ExportDialogMessage, ExportDialogMessageContext, ExportDialogMessageDiscriminant, ExportDialogMessageHandler};
|
||||
pub use crate::messages::dialog::new_document_dialog::{NewDocumentDialogMessage, NewDocumentDialogMessageDiscriminant, NewDocumentDialogMessageHandler};
|
||||
pub use crate::messages::dialog::preferences_dialog::{PreferencesDialogMessage, PreferencesDialogMessageContext, PreferencesDialogMessageDiscriminant, PreferencesDialogMessageHandler};
|
||||
|
||||
+2
-8
@@ -194,15 +194,9 @@ impl RadiusHandle {
|
||||
// The size is snapped, which keeps whichever sign the radius has come to
|
||||
let snapped_radius = snap_session.snap_value(view, position_of, self.free_radius.abs(), on_screen_per_unit, equal_radii) * self.free_radius.signum();
|
||||
|
||||
// A radius typed in a unit like millimeters stays in it
|
||||
let input_connector = InputConnector::node(node_id, radius_parameter);
|
||||
let radius = match document.network_interface.input_from_connector(&input_connector, &[]).and_then(|input| input.as_value()) {
|
||||
Some(existing @ TaggedValue::Length(_)) => existing.length_in_same_unit(snapped_radius, document.network_interface.pixels_per_inch()),
|
||||
_ => TaggedValue::Number(snapped_radius),
|
||||
};
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector,
|
||||
input: NodeInput::value(radius, false),
|
||||
input_connector: InputConnector::node(node_id, radius_parameter),
|
||||
input: NodeInput::value(TaggedValue::Number(snapped_radius), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
@@ -12,7 +12,6 @@ use crate::messages::tool::tool_messages::shape_tool::ShapeToolData;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::*;
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::units::TypedLength;
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct CircleGizmoHandler {
|
||||
@@ -109,7 +108,7 @@ impl Circle {
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::circle::RadiusInput),
|
||||
input: NodeInput::value(TaggedValue::Length(TypedLength::pixels(radius)), false),
|
||||
input: NodeInput::value(TaggedValue::Number(radius), false),
|
||||
});
|
||||
|
||||
responses.add(window_aligned_transform_set(document, layer, start.midpoint(end), DVec2::ONE));
|
||||
|
||||
@@ -421,7 +421,11 @@ pub fn pointer_travel_per_radian(layer_to_viewport: DAffine2, pointer: DVec2) ->
|
||||
pub fn extract_circle_radius(layer: LayerNodeIdentifier, document: &DocumentMessageHandler) -> Option<f64> {
|
||||
let node_inputs = NodeGraphLayer::new(layer, &document.network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::circle::IDENTIFIER))?;
|
||||
|
||||
node_inputs.get(1)?.as_value()?.as_length_pixels(document.network_interface.pixels_per_inch())
|
||||
let Some(&TaggedValue::Number(radius)) = node_inputs.get(1)?.as_value() else {
|
||||
return None;
|
||||
};
|
||||
|
||||
Some(radius)
|
||||
}
|
||||
|
||||
/// Calculate the viewport position of as a star vertex given its index
|
||||
|
||||
@@ -271,7 +271,6 @@ impl NodeGraphExecutor {
|
||||
previewed: Vec::new(),
|
||||
layers: document.network_interface.layer_paths(),
|
||||
observations: self.observations(&document.network_interface),
|
||||
pixels_per_inch: document.network_interface.pixels_per_inch(),
|
||||
}))
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(instrumented)
|
||||
@@ -302,7 +301,6 @@ impl NodeGraphExecutor {
|
||||
previewed,
|
||||
layers,
|
||||
observations: self.observations(&document.network_interface),
|
||||
pixels_per_inch: document.network_interface.pixels_per_inch(),
|
||||
}))
|
||||
.map_err(|e| e.to_string())?;
|
||||
} else if inspected_node_changed {
|
||||
@@ -357,7 +355,6 @@ impl NodeGraphExecutor {
|
||||
render_mode: document.render_mode,
|
||||
for_export: false,
|
||||
for_eyedropper: false,
|
||||
pixels_per_inch: None,
|
||||
};
|
||||
|
||||
// Execute the node graph
|
||||
@@ -425,7 +422,6 @@ impl NodeGraphExecutor {
|
||||
render_mode,
|
||||
for_export: false,
|
||||
for_eyedropper: true,
|
||||
pixels_per_inch: None,
|
||||
};
|
||||
|
||||
// Execute the node graph
|
||||
@@ -486,8 +482,6 @@ impl NodeGraphExecutor {
|
||||
render_mode: graphene_std::vector::style::RenderMode::Normal,
|
||||
for_export: true,
|
||||
for_eyedropper: false,
|
||||
// A document at CSS's 96 pixels per inch exports as it always has, in unitless pixels
|
||||
pixels_per_inch: Some(document.network_interface.pixels_per_inch()).filter(|pixels_per_inch| *pixels_per_inch != graphene_std::units::DEFAULT_PIXELS_PER_INCH),
|
||||
};
|
||||
|
||||
// Execute the node graph
|
||||
@@ -498,7 +492,6 @@ impl NodeGraphExecutor {
|
||||
previewed,
|
||||
layers: document.network_interface.layer_paths(),
|
||||
observations: self.observations(&document.network_interface),
|
||||
pixels_per_inch: document.network_interface.pixels_per_inch(),
|
||||
}))
|
||||
.map_err(|e| e.to_string())?;
|
||||
let execution_id = self.queue_execution(render_config);
|
||||
@@ -898,7 +891,6 @@ impl NodeGraphExecutor {
|
||||
previewed: Vec::new(),
|
||||
layers: document.network_interface.layer_paths(),
|
||||
observations: HashMap::from([(ObservationKey::FillMeasurement, fill_measurement)]),
|
||||
pixels_per_inch: document.network_interface.pixels_per_inch(),
|
||||
}))
|
||||
.is_err()
|
||||
{
|
||||
@@ -924,7 +916,6 @@ impl NodeGraphExecutor {
|
||||
render_mode: document.render_mode,
|
||||
for_export: false,
|
||||
for_eyedropper: false,
|
||||
pixels_per_inch: None,
|
||||
};
|
||||
let execution_id = self.queue_execution(render_config);
|
||||
self.futures.push_back((
|
||||
|
||||
@@ -124,8 +124,6 @@ pub struct GraphUpdate {
|
||||
pub(super) layers: Vec<Vec<NodeId>>,
|
||||
/// The connectors whose values are sent back after each evaluation, replacing those observed before.
|
||||
pub(super) observations: HashMap<ObservationKey, Observation>,
|
||||
/// The document's pixels per inch, which sizes lengths typed in a physical unit.
|
||||
pub(super) pixels_per_inch: f64,
|
||||
}
|
||||
|
||||
/// Replaces each network's primary export with its previewed node.
|
||||
@@ -242,7 +240,6 @@ impl NodeRuntime {
|
||||
previewed,
|
||||
layers,
|
||||
observations,
|
||||
pixels_per_inch,
|
||||
}) = graph
|
||||
else {
|
||||
return;
|
||||
@@ -255,7 +252,7 @@ impl NodeRuntime {
|
||||
|
||||
self.node_graph_errors.clear();
|
||||
self.node_graph_warnings.clear();
|
||||
let result = self.update_network(network.clone(), pixels_per_inch);
|
||||
let result = self.update_network(network.clone());
|
||||
self.compile_failed = result.is_err();
|
||||
if result.is_ok() {
|
||||
self.thumbnails.update_sources(&layers, &network, &self.executor);
|
||||
@@ -524,8 +521,8 @@ impl NodeRuntime {
|
||||
Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await
|
||||
}
|
||||
|
||||
fn update_network(&mut self, graph: NodeNetwork, pixels_per_inch: f64) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
||||
let mut scoped_network = wrap_network_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle(), pixels_per_inch);
|
||||
fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
||||
let mut scoped_network = wrap_network_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle());
|
||||
|
||||
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) {
|
||||
return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string()));
|
||||
|
||||
@@ -398,7 +398,8 @@ fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, shipped_node_id};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, NodeTemplateImplementation, shipped_node_id};
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use glam::UVec2;
|
||||
use graph_craft::document::NodeId;
|
||||
@@ -429,8 +430,20 @@ mod tests {
|
||||
editor.draw_rect(0., 0., 10., 10.).await;
|
||||
let layer = editor.get_selected_layer().await.expect("The drawn rectangle should be selected").to_node();
|
||||
|
||||
// The node adding Merge's content to the stack
|
||||
let Some(NodeTemplateImplementation::Network(merge_network)) = resolve_network_node_type("Merge").map(|merge| &merge.node_template.implementation) else {
|
||||
panic!("Merge should be a network node")
|
||||
};
|
||||
let Some((&extend_id, _)) = merge_network
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|(_, node)| node.implementation == NodeTemplateImplementation::ProtoNode(graphene_std::graphic::extend::IDENTIFIER))
|
||||
else {
|
||||
panic!("Merge should extend the stack with its content")
|
||||
};
|
||||
|
||||
compile_and_run(&mut editor).await;
|
||||
let merge_content = compiled_id(&editor, &[layer, layer_path_writer_id(shipped_node_id("Merge", NodeId(2)))]);
|
||||
let merge_content = compiled_id(&editor, &[layer, layer_path_writer_id(shipped_node_id("Merge", extend_id))]);
|
||||
assert!(merge_content.is_some(), "The Merge layer's content should be compiled");
|
||||
assert_eq!(
|
||||
editor.runtime.thumbnails.sources.get(&layer).copied(),
|
||||
|
||||
@@ -423,6 +423,17 @@ impl EditorTestUtils {
|
||||
self.create_node(node_type, Some((x, y))).await
|
||||
}
|
||||
|
||||
/// Adds an empty subgraph at the grid position, as the graph's New Custom Node button does.
|
||||
pub async fn create_empty_subgraph_at(&mut self, x: i32, y: i32) -> NodeId {
|
||||
let node_id = NodeId::new();
|
||||
self.handle_message(NodeGraphMessage::CreateEmptySubgraph {
|
||||
node_id: Some(node_id),
|
||||
xy: Some((x, y)),
|
||||
})
|
||||
.await;
|
||||
node_id
|
||||
}
|
||||
|
||||
async fn create_node(&mut self, node_type: DefinitionIdentifier, xy: Option<(i32, i32)>) -> NodeId {
|
||||
let node_id = NodeId::new();
|
||||
self.handle_message(NodeGraphMessage::CreateNodeFromContextMenu {
|
||||
|
||||
@@ -1151,7 +1151,6 @@
|
||||
--math-basis-j: #66c14a;
|
||||
--math-basis-k: #76b6ff;
|
||||
--math-variable: #fff9a8;
|
||||
--math-unit: #eeeeee;
|
||||
--math-function: #c9c2ff;
|
||||
--math-operator: #ffffff;
|
||||
--math-bracket: #f2b532;
|
||||
@@ -1203,11 +1202,6 @@
|
||||
color: var(--math-function);
|
||||
}
|
||||
|
||||
// A unit is set upright beside its number, unlike the italic variables
|
||||
.unit {
|
||||
color: var(--math-unit);
|
||||
}
|
||||
|
||||
// A keyword is an operator spelled as a word
|
||||
.operator,
|
||||
.keyword {
|
||||
|
||||
@@ -75,9 +75,6 @@
|
||||
let inputRangeElement: HTMLInputElement | undefined;
|
||||
let text = exact ?? displayText(value, unit);
|
||||
let editing = false;
|
||||
|
||||
// While editing, the unit a number typed without one is read in shows faintly after the text
|
||||
$: ghostUnit = editing && exact === undefined && unit.trim() !== "" && !endsInUnit(text) ? unit : "";
|
||||
let isDragging = false;
|
||||
let pressingArrow = false;
|
||||
let repeatTimeout: ReturnType<typeof setTimeout> | undefined = undefined;
|
||||
@@ -121,7 +118,7 @@
|
||||
let sliderAbortTimeout1: ReturnType<typeof setTimeout> | undefined;
|
||||
let sliderAbortTimeout2: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
$: watchValue(value, unit, min, max);
|
||||
$: watchValue(value, unit);
|
||||
$: if (exact !== undefined && !editing) text = exact;
|
||||
$: present = exact !== undefined || value !== undefined;
|
||||
// A number of only one digit, like `0` or `-1`, has no other digit to move the underline to, so it isn't shown
|
||||
@@ -179,8 +176,8 @@
|
||||
// TRACKING AND UPDATING THE VALUE
|
||||
// ===============================
|
||||
|
||||
// Called only when `value`, its unit, or its bounds are changed from outside this component.
|
||||
function watchValue(value: number | undefined, unit: string, min: number | undefined, max: number | undefined) {
|
||||
// Called only when `value` is changed from outside this component.
|
||||
function watchValue(value: number | undefined, unit: string) {
|
||||
// Don't update if the slider is currently being dragged (we don't want the backend fighting with the user's drag)
|
||||
if (rangeSliderClickDragState === "Dragging") return;
|
||||
|
||||
@@ -384,11 +381,6 @@
|
||||
return `${number}`;
|
||||
}
|
||||
|
||||
// Whether typed text ends in a unit (or a name), so no unit is assumed after it
|
||||
function endsInUnit(typed: string): boolean {
|
||||
return /[\p{L}%°'"]\s*$/u.test(typed);
|
||||
}
|
||||
|
||||
// Removes the trailing "s" from a unit if the quantity is 1.
|
||||
function unPluralize(unit: string, quantity: number): string {
|
||||
if (quantity !== 1 || !unit.endsWith("s")) return unit;
|
||||
@@ -1010,9 +1002,6 @@
|
||||
>{text.slice(markedDigit + 1)}</span
|
||||
>
|
||||
{/if}
|
||||
{#if ghostUnit}
|
||||
<span class="ghost-unit">{text}<span class="unit">{ghostUnit}</span></span>
|
||||
{/if}
|
||||
{#if present}
|
||||
{#if mode === "Increment" && incrementBehavior !== "None"}
|
||||
<button
|
||||
@@ -1114,24 +1103,6 @@
|
||||
display: none;
|
||||
}
|
||||
|
||||
// Laid out like the field's text while it's edited, which it mirrors in transparent characters before the faint unit
|
||||
.ghost-unit {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
margin: 0 8px;
|
||||
padding: 3px 0;
|
||||
line-height: calc(var(--widget-height) - 6px);
|
||||
text-align: left;
|
||||
white-space: pre;
|
||||
overflow: hidden;
|
||||
color: transparent;
|
||||
pointer-events: none;
|
||||
|
||||
.unit {
|
||||
color: var(--color-8-uppergray);
|
||||
}
|
||||
}
|
||||
|
||||
// A disabled field's underline only marks the stepped digit, with no press target to hover or drag
|
||||
&.disabled .digit-mark .marked::after {
|
||||
pointer-events: none;
|
||||
|
||||
@@ -37,10 +37,6 @@ macro_rules! generate_benchmarks {
|
||||
}
|
||||
|
||||
generate_benchmarks! {
|
||||
"1 + 2 * 3 - 4 / 5",
|
||||
"pi + e - tau",
|
||||
"sin(1) + cos(2)",
|
||||
"(1.5 + 2.5) * 3.5",
|
||||
"(3 * (4 + sqrt(25)) - cos(pi/3) * (2^3)) + 5 * e", // Mixed nested functions, constants, and operations
|
||||
"((5 + 2 * (3 - sqrt(49)))^2) / (1 + sqrt(16)) + tau / 2", // Complex nested expression with constants
|
||||
"log(100, 10) + (5 * sin(pi/4) + sqrt(81)) / (2 * phi)", // Logarithmic and trigonometric functions
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
use crate::constants::{BuiltinFunction, MatrixToMatrix, MatrixToValue, ValueOfRegions, ValuesToMatrix};
|
||||
use crate::quantity::{BuilderUnits, MatrixValueUnit, RegionResult, UnitRule};
|
||||
use crate::units::UnitId;
|
||||
use crate::constants::{MatrixToMatrix, MatrixToValue, ValueOfRegions, ValuesToMatrix};
|
||||
use crate::value::Value;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
@@ -98,11 +96,6 @@ pub enum Syntax<'src> {
|
||||
first: Box<Syntax<'src>>,
|
||||
rest: Vec<(BinaryOp, Syntax<'src>)>,
|
||||
},
|
||||
/// A number juxtaposed with units after a `/`, like the `2mm` of `x / 2mm`, which only a dividend with a unit divides by whole.
|
||||
Measure {
|
||||
number: Box<Syntax<'src>>,
|
||||
units: Vec<Syntax<'src>>,
|
||||
},
|
||||
/// The cases of math's `cases` notation, `{a if cond, b otherwise}`: disjoint conditions in no meaningful order, with `otherwise` holding when none of them do.
|
||||
Piecewise {
|
||||
cases: Vec<Case<'src>>,
|
||||
@@ -164,17 +157,10 @@ pub enum Node {
|
||||
pub enum ValueNode {
|
||||
Lit(Literal),
|
||||
Var(String),
|
||||
/// A unit's spelling, resolved as the expression is read, which a host's binding of the name still shadows.
|
||||
Unit {
|
||||
name: String,
|
||||
unit: UnitId,
|
||||
},
|
||||
FnCall {
|
||||
name: String,
|
||||
expr: Vec<ValueNode>,
|
||||
},
|
||||
/// A call of a builtin taking values, found as the expression is read so evaluating it looks nothing up by name.
|
||||
BuiltinCall(Box<BuiltinCall>),
|
||||
BinOp {
|
||||
lhs: Box<ValueNode>,
|
||||
op: BinaryOp,
|
||||
@@ -197,24 +183,16 @@ pub enum ValueNode {
|
||||
matrix: Box<MatrixNode>,
|
||||
value: Box<ValueNode>,
|
||||
},
|
||||
/// A quotient by a measure, which is the whole divisor where the dividend has a unit. A plain dividend is divided by the
|
||||
/// measure's number alone and then takes its units, so `x / 2mm` is half of `x` in millimeters.
|
||||
MeasureQuotient {
|
||||
dividend: Box<ValueNode>,
|
||||
measure: Box<Measure>,
|
||||
},
|
||||
/// A function of a matrix with a value result, like `det(A)`.
|
||||
OfMatrix {
|
||||
function: MatrixToValue,
|
||||
unit: MatrixValueUnit,
|
||||
matrix: Box<MatrixNode>,
|
||||
},
|
||||
/// A function of a value and regions with a value result, like `within(p, R)`.
|
||||
OfValueAndRegions {
|
||||
function: ValueOfRegions,
|
||||
result: RegionResult,
|
||||
value: Box<ValueNode>,
|
||||
regions: Box<[MatrixNode]>,
|
||||
regions: Vec<MatrixNode>,
|
||||
/// The value after the regions, where the builtin takes one, like `smoothstep`'s continuity.
|
||||
trailing: Option<Box<ValueNode>>,
|
||||
},
|
||||
@@ -237,28 +215,6 @@ pub enum ValueNode {
|
||||
},
|
||||
}
|
||||
|
||||
/// A call of a builtin function of values with the rule for its units.
|
||||
#[derive(Debug)]
|
||||
pub struct BuiltinCall {
|
||||
/// The builtin's name, which a base-suffixed form like `log2` gives without its suffix.
|
||||
pub name: String,
|
||||
/// The spelling by which a host's function would shadow the builtin, or `None` behind the `\` prefix.
|
||||
pub host_name: Option<String>,
|
||||
pub function: BuiltinFunction,
|
||||
pub rule: UnitRule,
|
||||
pub arguments: Vec<ValueNode>,
|
||||
/// The second argument a base-suffixed form like `log2(x)` bakes into its name.
|
||||
pub suffix: Option<f64>,
|
||||
}
|
||||
|
||||
/// A number juxtaposed with units after a `/`, like the `2mm` of `x / 2mm`.
|
||||
#[derive(Debug)]
|
||||
pub struct Measure {
|
||||
pub number: ValueNode,
|
||||
/// The units as read, any of which a `where` definition or a host's binding of its spelling may shadow.
|
||||
pub units: Vec<ValueNode>,
|
||||
}
|
||||
|
||||
/// A subexpression evaluating to a matrix.
|
||||
#[derive(Debug)]
|
||||
pub enum MatrixNode {
|
||||
@@ -270,7 +226,6 @@ pub enum MatrixNode {
|
||||
/// A function building a matrix from values, like `rotation(angle)`.
|
||||
FromValues {
|
||||
function: ValuesToMatrix,
|
||||
units: BuilderUnits,
|
||||
arguments: Vec<ValueNode>,
|
||||
},
|
||||
/// The range `a..b`.
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
//! The names an editor offers to finish the one being typed.
|
||||
|
||||
use crate::constants::{BUILTIN_FUNCTION_ALIASES, SUFFIXED_FORMS};
|
||||
use crate::documentation::{BUILTIN_FUNCTIONS, Operator, Tooltip, constant_tooltip, function_tooltip, identity_tooltip, keyword_tooltip, unit_tooltip};
|
||||
use crate::documentation::{BUILTIN_FUNCTIONS, Operator, Tooltip, constant_tooltip, function_tooltip, identity_tooltip, keyword_tooltip};
|
||||
use crate::lexer::{CONSTANT_SPELLINGS, Constant, KEYWORDS, Lexer, Token, offset_in, operand_ended};
|
||||
use crate::parser::{keywords_accepted_after, parse_quietly};
|
||||
use crate::sort::names_in_scope;
|
||||
use crate::units::{UNITS, unit_named};
|
||||
use std::borrow::Cow;
|
||||
|
||||
/// What an offered name is, by which the offers are grouped.
|
||||
@@ -15,8 +14,6 @@ pub enum CompletionKind {
|
||||
Local,
|
||||
Function,
|
||||
Constant,
|
||||
/// A unit of measure, like `mm`.
|
||||
Unit,
|
||||
Keyword,
|
||||
/// The typeset alias of an operator typed in ASCII, like `≤` for `<=`.
|
||||
Operator,
|
||||
@@ -237,42 +234,6 @@ pub fn completions(source: &str, caret: usize, asked: bool) -> Completions<'_> {
|
||||
});
|
||||
let constants = identity.into_iter().chain(constants).collect::<Vec<_>>();
|
||||
|
||||
// A unit is offered right after a number, where units are written, by a spelling that begins with what's typed, with a symbol that
|
||||
// can't be typed, like `°` or `µm`, leading its words
|
||||
let after_number = Lexer::new(source.get(..start).unwrap_or_default())
|
||||
.last()
|
||||
.is_some_and(|token| matches!(token, Token::Integer(_) | Token::Float(_)));
|
||||
let units = UNITS.iter().filter(|_| after_number).filter_map(|definition| {
|
||||
let typeable = |spelling: &str| spelling.chars().all(|c| c.is_ascii_alphanumeric());
|
||||
let fitting = |spelling: &str| fit(typed, spelling).filter(|closeness| *closeness != Fit::Scattered);
|
||||
let best = definition.spellings.iter().filter(|spelling| typeable(spelling)).filter_map(|spelling| fitting(spelling)).min()?;
|
||||
|
||||
// Its symbol and singular name stand for every spelling, so plurals and abbreviations don't crowd the list
|
||||
let words: Vec<(&str, Fit)> = [definition.symbol, definition.name].into_iter().filter(|word| typeable(word)).fold(Vec::new(), |mut words, word| {
|
||||
if !words.iter().any(|(existing, _)| *existing == word) {
|
||||
words.push((word, fitting(word).unwrap_or(Fit::Scattered)));
|
||||
}
|
||||
words
|
||||
});
|
||||
let tooltip = unit_named(definition.symbol).map(unit_tooltip);
|
||||
let symbol = (!typeable(definition.symbol)).then(|| Candidate {
|
||||
name: definition.symbol,
|
||||
parameters: None,
|
||||
tooltip: tooltip.clone(),
|
||||
fit: best,
|
||||
prefixed: false,
|
||||
});
|
||||
let words = words.into_iter().map(move |(word, closeness)| Candidate {
|
||||
name: word,
|
||||
parameters: None,
|
||||
tooltip: tooltip.clone(),
|
||||
fit: closeness,
|
||||
prefixed: prefixed(word, false),
|
||||
});
|
||||
Some(symbol.into_iter().chain(words))
|
||||
});
|
||||
let units = units.flatten().collect::<Vec<_>>();
|
||||
|
||||
// A keyword is offered only where the grammar takes one, which is asked only once one is typed toward
|
||||
let keywords = KEYWORDS.into_iter().filter(|_| !builtins_only).filter_map(|(keyword, token)| {
|
||||
Some(Candidate {
|
||||
@@ -299,7 +260,6 @@ pub fn completions(source: &str, caret: usize, asked: bool) -> Completions<'_> {
|
||||
(locals, CompletionKind::Local),
|
||||
(functions, CompletionKind::Function),
|
||||
(constants, CompletionKind::Constant),
|
||||
(units, CompletionKind::Unit),
|
||||
(keywords, CompletionKind::Keyword),
|
||||
]
|
||||
.into_iter()
|
||||
@@ -556,12 +516,12 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn definitions_are_offered_where_they_can_be_read() {
|
||||
assert_eq!(names("2 rad‸ where radius = 2"), ["radius", "rad", "radian"]);
|
||||
assert_eq!(names("2 rad‸ where radius = 2"), ["radius"]);
|
||||
assert_eq!(names("ea‸(2) where ease(t) = t^2"), ["ease"]);
|
||||
assert_eq!(names("sig‸ where sigma = 1"), ["sigma", "sign"]);
|
||||
|
||||
// A parameter is read only in its function's body, and a clause's names only within its parentheses, which the called name is outside of
|
||||
assert_eq!(names("f(1) where f(radius) = 2 rad‸"), ["radius", "rad", "radian"]);
|
||||
assert_eq!(names("f(1) where f(radius) = 2 rad‸"), ["radius"]);
|
||||
assert!(names("(f(1) where f(radius) = 2 radius) + rad‸").is_empty());
|
||||
assert!(names("(2 where radius = 1) + rad‸").is_empty());
|
||||
assert!(!names("fo‸(2 where foo = 1)").contains(&"foo".to_string()));
|
||||
@@ -712,18 +672,4 @@ mod tests {
|
||||
assert_eq!(crate::evaluate(ascii).unwrap().unwrap(), crate::evaluate(typeset).unwrap().unwrap(), "`{typeset}`");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn units_are_offered_after_a_number() {
|
||||
for unit in ["m", "meter", "mm", "millimeter", "min", "minute"] {
|
||||
assert!(names("5m‸").contains(&unit.to_string()), "`{unit}` should be offered");
|
||||
}
|
||||
let degrees = names("5 de‸");
|
||||
let symbol = degrees.iter().position(|name| name == "°").unwrap();
|
||||
assert_eq!(degrees[symbol + 1], "degree", "the symbol leads its words");
|
||||
assert!(names("5 inc‸").contains(&"in".to_string()));
|
||||
// Elsewhere a unit's spelling stays a name like any other, so it doesn't crowd the builtins
|
||||
assert!(!names("m‸").contains(&"meter".to_string()));
|
||||
assert!(!names("x m‸").contains(&"meter".to_string()));
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,4 @@
|
||||
use crate::matrix::Matrix;
|
||||
use crate::quantity::{MatrixQuantity, Quantity};
|
||||
use crate::units::DEFAULT_PIXELS_PER_INCH;
|
||||
use crate::value::Value;
|
||||
use std::collections::HashMap;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
@@ -13,16 +11,6 @@ pub trait ValueProvider {
|
||||
fn get_matrix(&self, _name: &str) -> Option<Matrix> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The value bound to a name with the unit it is measured in, which is plain unless a host measures it.
|
||||
fn get_quantity(&self, name: &str) -> Option<Quantity> {
|
||||
self.get_value(name).map(Quantity::plain)
|
||||
}
|
||||
|
||||
/// The matrix bound to a name with the units of its linear part and translation, which are plain unless a host measures them.
|
||||
fn get_matrix_quantity(&self, name: &str) -> Option<MatrixQuantity> {
|
||||
self.get_matrix(name).map(MatrixQuantity::plain)
|
||||
}
|
||||
}
|
||||
|
||||
pub trait FunctionProvider {
|
||||
@@ -46,14 +34,6 @@ impl<V: ValueProvider> ValueProvider for &V {
|
||||
fn get_matrix(&self, name: &str) -> Option<Matrix> {
|
||||
(**self).get_matrix(name)
|
||||
}
|
||||
|
||||
fn get_quantity(&self, name: &str) -> Option<Quantity> {
|
||||
(**self).get_quantity(name)
|
||||
}
|
||||
|
||||
fn get_matrix_quantity(&self, name: &str) -> Option<MatrixQuantity> {
|
||||
(**self).get_matrix_quantity(name)
|
||||
}
|
||||
}
|
||||
|
||||
impl ValueProvider for NothingMap {
|
||||
@@ -93,47 +73,20 @@ impl FunctionProvider for NothingMap {
|
||||
pub struct EvalContext<V: ValueProvider, F: FunctionProvider> {
|
||||
values: V,
|
||||
functions: F,
|
||||
/// The size of the `px` unit, as the count of pixels in an inch.
|
||||
pixels_per_inch: f64,
|
||||
}
|
||||
|
||||
impl Default for EvalContext<NothingMap, NothingMap> {
|
||||
fn default() -> Self {
|
||||
Self::new(NothingMap, NothingMap)
|
||||
Self {
|
||||
values: NothingMap,
|
||||
functions: NothingMap,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: ValueProvider, F: FunctionProvider> EvalContext<V, F> {
|
||||
pub fn new(values: V, functions: F) -> Self {
|
||||
Self {
|
||||
values,
|
||||
functions,
|
||||
pixels_per_inch: DEFAULT_PIXELS_PER_INCH,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sizes the `px` unit as an inch over this count, where a count that isn't positive and finite keeps the default.
|
||||
pub fn with_pixels_per_inch(mut self, pixels_per_inch: f64) -> Self {
|
||||
if pixels_per_inch.is_finite() && pixels_per_inch > 0. {
|
||||
self.pixels_per_inch = pixels_per_inch;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
pub fn pixels_per_inch(&self) -> f64 {
|
||||
self.pixels_per_inch
|
||||
}
|
||||
|
||||
pub fn get_quantity(&self, name: &str) -> Option<Quantity> {
|
||||
self.values.get_quantity(name)
|
||||
}
|
||||
|
||||
pub fn get_matrix_quantity(&self, name: &str) -> Option<MatrixQuantity> {
|
||||
self.values.get_matrix_quantity(name)
|
||||
}
|
||||
|
||||
pub fn provides_function(&self, name: &str) -> bool {
|
||||
self.functions.provides(name)
|
||||
Self { values, functions }
|
||||
}
|
||||
|
||||
pub fn get_value(&self, name: &str) -> Option<Value> {
|
||||
|
||||
@@ -8,7 +8,6 @@ use crate::lexer::{Constant, Token};
|
||||
use crate::matrix::Matrix;
|
||||
use crate::quaternion::Quaternion;
|
||||
use crate::reducer::{Reducer, classify_reducer};
|
||||
use crate::units::UnitId;
|
||||
use crate::value::Value;
|
||||
|
||||
/// Hover text, as the tooltip Markdown subset: code spans, fenced code blocks, bold, and italic.
|
||||
@@ -190,7 +189,7 @@ pub static BUILTIN_FUNCTIONS: &[DocumentedFunction] = &[
|
||||
"[−π/2, π/2]",
|
||||
doc(
|
||||
"The angle whose sine is `x`. Outside its domain, the result climbs into the complex plane.",
|
||||
&[("asin(1)", "π/2 rad"), ("asin(2)", "(π/2 - 1.317i) rad")],
|
||||
&[("asin(1)", "π/2"), ("asin(2)", "π/2 - 1.317i")],
|
||||
),
|
||||
),
|
||||
function(
|
||||
@@ -201,7 +200,7 @@ pub static BUILTIN_FUNCTIONS: &[DocumentedFunction] = &[
|
||||
"[0, π]",
|
||||
doc(
|
||||
"The angle whose cosine is `x`. Outside its domain, the result climbs into the complex plane.",
|
||||
&[("acos(-1)", "π rad"), ("acos(2)", "1.317i rad")],
|
||||
&[("acos(-1)", "π"), ("acos(2)", "1.317i")],
|
||||
),
|
||||
),
|
||||
function(
|
||||
@@ -210,7 +209,7 @@ pub static BUILTIN_FUNCTIONS: &[DocumentedFunction] = &[
|
||||
Treatment::InPlane,
|
||||
&[parameter("x", "[−∞, ∞]", "the tangent")],
|
||||
"[−π/2, π/2]",
|
||||
doc("The angle whose tangent is `x`.", &[("atan(1)", "π/4 rad"), ("atan(∞)", "π/2 rad")]),
|
||||
doc("The angle whose tangent is `x`.", &[("atan(1)", "π/4"), ("atan(∞)", "π/2")]),
|
||||
),
|
||||
function(
|
||||
"atan2",
|
||||
@@ -218,7 +217,7 @@ pub static BUILTIN_FUNCTIONS: &[DocumentedFunction] = &[
|
||||
Treatment::RealOnly,
|
||||
&[parameter("y", "[−∞, ∞]", "the point's `y` coordinate"), parameter("x", "[−∞, ∞]", "the point's `x` coordinate")],
|
||||
"[−π, π]",
|
||||
doc("The angle from the positive `x` axis to the point `(x, y)`.", &[("atan2(1, 1)", "π/4 rad"), ("atan2(0, -1)", "π rad")]),
|
||||
doc("The angle from the positive `x` axis to the point `(x, y)`.", &[("atan2(1, 1)", "π/4"), ("atan2(0, -1)", "π")]),
|
||||
),
|
||||
function(
|
||||
"acsc",
|
||||
@@ -228,7 +227,7 @@ pub static BUILTIN_FUNCTIONS: &[DocumentedFunction] = &[
|
||||
"[−π/2, π/2]",
|
||||
doc(
|
||||
"The angle whose cosecant is `x`, `asin(1/x)`. Outside its domain, the result climbs into the complex plane, except that 0 is an error.",
|
||||
&[("acsc(2)", "π/6 rad")],
|
||||
&[("acsc(2)", "π/6")],
|
||||
),
|
||||
),
|
||||
function(
|
||||
@@ -239,7 +238,7 @@ pub static BUILTIN_FUNCTIONS: &[DocumentedFunction] = &[
|
||||
"[0, π]",
|
||||
doc(
|
||||
"The angle whose secant is `x`, `acos(1/x)`. Outside its domain, the result climbs into the complex plane, except that 0 is an error.",
|
||||
&[("asec(2)", "π/3 rad")],
|
||||
&[("asec(2)", "π/3")],
|
||||
),
|
||||
),
|
||||
function(
|
||||
@@ -248,7 +247,7 @@ pub static BUILTIN_FUNCTIONS: &[DocumentedFunction] = &[
|
||||
Treatment::InPlane,
|
||||
&[parameter("x", "[−∞, ∞]", "the cotangent")],
|
||||
"[−π/2, π/2]",
|
||||
doc("The angle whose cotangent is `x`, `atan(1/x)`.", &[("acot(1)", "π/4 rad")]),
|
||||
doc("The angle whose cotangent is `x`, `atan(1/x)`.", &[("acot(1)", "π/4")]),
|
||||
),
|
||||
// Hyperbolic functions
|
||||
function(
|
||||
@@ -737,7 +736,7 @@ pub static BUILTIN_FUNCTIONS: &[DocumentedFunction] = &[
|
||||
"[−π, π]",
|
||||
doc(
|
||||
"How far `a` must turn to face `b`, signed by the turn's direction seen from `+k`. `angle(i, v)` is the heading of `v`.",
|
||||
&[("angle(i, j)", "π/2 rad"), ("angle(j, i)", "-π/2 rad")],
|
||||
&[("angle(i, j)", "π/2"), ("angle(j, i)", "-π/2")],
|
||||
),
|
||||
),
|
||||
function(
|
||||
@@ -1091,28 +1090,6 @@ const IDENTITY: Doc = doc(
|
||||
&[("I (3i + 4j)", "3i + 4j")],
|
||||
);
|
||||
|
||||
/// The hover text for a unit, naming what it measures and its other spellings.
|
||||
pub fn unit_tooltip(unit: UnitId) -> Tooltip {
|
||||
let definition = unit.definition();
|
||||
let mut label = definition.name.to_string();
|
||||
if let Some(first) = label.get(..1) {
|
||||
label = first.to_uppercase() + &label[1..];
|
||||
}
|
||||
|
||||
let others: Vec<String> = definition.spellings.iter().skip(1).map(|spelling| format!("`{spelling}`")).collect();
|
||||
let spellings = match others.as_slice() {
|
||||
[] => String::new(),
|
||||
[only] => format!(" Also written {only}."),
|
||||
[rest @ .., last] => format!(" Also written {} or {last}.", rest.join(", ")),
|
||||
};
|
||||
Tooltip {
|
||||
label,
|
||||
form: Some(definition.symbol.to_string()),
|
||||
description: format!("A unit of {}.{spellings}", definition.dimension.noun()),
|
||||
signature: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The hover text for the identity matrix `I`.
|
||||
pub fn identity_tooltip() -> Tooltip {
|
||||
documented("Identity Matrix", "I".to_string(), &IDENTITY, Treatment::Whole, "")
|
||||
@@ -1735,17 +1712,11 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::object::Object;
|
||||
|
||||
/// Whether two results agree to the few digits the documentation rounds them to, matrices entry by entry, and values in their units.
|
||||
/// Whether two results agree to the few digits the documentation rounds them to, matrices entry by entry.
|
||||
fn agree(actual: &Object, expected: &Object) -> bool {
|
||||
if let (Object::Value(actual), Object::Value(expected)) = (actual, expected)
|
||||
&& actual.unit != expected.unit
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
let parts = |object: &Object| match object {
|
||||
Object::Value(quantity) => quantity.number().to_quaternion().parts().to_vec(),
|
||||
Object::Matrix(matrix) => matrix.matrix.rows.iter().chain([&matrix.matrix.translation]).flat_map(|row| row.parts()).collect(),
|
||||
Object::Value(Value::Number(number)) => number.to_quaternion().parts().to_vec(),
|
||||
Object::Matrix(matrix) => matrix.rows.iter().chain([&matrix.translation]).flat_map(|row| row.parts()).collect(),
|
||||
};
|
||||
let close = |actual: f64, expected: f64| {
|
||||
if expected.is_infinite() {
|
||||
@@ -1781,7 +1752,7 @@ mod tests {
|
||||
fn every_treatment_matches_how_the_function_evaluates() {
|
||||
let evaluate = |expression: &str| crate::evaluate(expression).ok()?.ok();
|
||||
let number = |expression: &str| match evaluate(expression) {
|
||||
Some(Object::Value(quantity)) => quantity.number().to_quaternion(),
|
||||
Some(Object::Value(Value::Number(number))) => number.to_quaternion(),
|
||||
result => panic!("`{expression}` should be a number, not {result:?}"),
|
||||
};
|
||||
let close = |actual: Quaternion, expected: Quaternion| actual.parts().iter().zip(expected.parts()).all(|(actual, expected)| (actual - expected).abs() <= 1e-9);
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
use crate::ast::{BinaryOp, BuiltinCall, Clause, Literal, Local, MatrixNode, Measure, Node, SortedCase, UnaryOp, ValueNode};
|
||||
use crate::ast::{BinaryOp, Clause, Literal, Local, MatrixNode, Node, SortedCase, UnaryOp, ValueNode};
|
||||
use crate::constants::{Builtin, MatrixToValue, SuffixedFunction, ValueOfRegions, builtin_function, suffixed_function};
|
||||
use crate::context::{EvalContext, FunctionProvider, ValueProvider};
|
||||
use crate::lexer::Constant;
|
||||
use crate::matrix::{Matrix, Region};
|
||||
use crate::object::Object;
|
||||
use crate::quantity::{self, MatrixQuantity, MatrixValueUnit, Quantity, RegionResult, UnitRule, unit_rule};
|
||||
use crate::quaternion::Quaternion;
|
||||
use crate::units::{Unit, unit_named};
|
||||
use crate::value::{Number, Value};
|
||||
use std::cell::OnceCell;
|
||||
use thiserror::Error;
|
||||
@@ -60,58 +58,18 @@ pub enum EvalError {
|
||||
|
||||
#[error("Value of {0} is not a number")]
|
||||
NotANumber(String),
|
||||
|
||||
#[error(transparent)]
|
||||
Units(Box<UnitMismatch>),
|
||||
|
||||
#[error("An exponent in an angle unit rotates, so it can't also have a plain part")]
|
||||
AngleExponentWithPlainPart,
|
||||
|
||||
#[error("The units are too far apart in size to combine")]
|
||||
UnitOverflow,
|
||||
}
|
||||
|
||||
/// Why units don't fit an operation, boxed within [`EvalError`] so the error every evaluation step returns stays small.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum UnitMismatch {
|
||||
#[error("A value in `{left}` can't be {verb} one in `{right}`, since they measure different things")]
|
||||
IncompatibleUnits { verb: &'static str, left: String, right: String },
|
||||
|
||||
#[error("A plain number can't be {verb} a value in `{unit}`, so give it a unit too, like `1 {unit}`")]
|
||||
PlainWithUnit { verb: &'static str, unit: String },
|
||||
|
||||
#[error("`{function}` takes plain numbers, not a value in `{unit}`")]
|
||||
UnitsNotAccepted { function: String, unit: String },
|
||||
|
||||
#[error("`{function}` takes a plain number, since its result would depend on the unit, so round a value in `{unit}` with `snap(x, 1 {unit})`")]
|
||||
RoundingWithUnits { function: String, unit: String },
|
||||
|
||||
#[error("`{function}` takes an angle or a plain number, not a value in `{unit}`")]
|
||||
AngleExpected { function: String, unit: String },
|
||||
|
||||
#[error("The power leaves `{0}` with a fractional exponent")]
|
||||
FractionalUnitPower(String),
|
||||
|
||||
#[error("An exponent can't be in `{0}`")]
|
||||
ExponentWithUnits(String),
|
||||
}
|
||||
|
||||
impl From<UnitMismatch> for EvalError {
|
||||
fn from(mismatch: UnitMismatch) -> Self {
|
||||
Self::Units(Box::new(mismatch))
|
||||
}
|
||||
}
|
||||
|
||||
/// Settles an operation's result: no operation may produce NaN, so an indeterminate form is an error, and the value takes
|
||||
/// its canonical form so that a zero imaginary part or a signed zero never changes a later result.
|
||||
// Inlined with the canonical form it calls, since these run after every operation where a call would cost as much as the work
|
||||
#[inline(always)]
|
||||
fn settle(quantity: Quantity) -> Result<Quantity, EvalError> {
|
||||
let number = quantity.number();
|
||||
fn settle(value: Value) -> Result<Value, EvalError> {
|
||||
let Value::Number(number) = value;
|
||||
if number.is_nan() {
|
||||
return Err(EvalError::Indeterminate);
|
||||
}
|
||||
Ok(Quantity::new(Value::Number(number.canonical()), quantity.unit))
|
||||
Ok(Value::Number(number.canonical()))
|
||||
}
|
||||
|
||||
/// Settles a matrix result like [`settle`] does a value, with signed zeros made plain zero.
|
||||
@@ -122,90 +80,35 @@ pub(crate) fn settle_matrix(matrix: Matrix) -> Result<Matrix, EvalError> {
|
||||
Ok(matrix.map(|entry| if entry == 0. { 0. } else { entry }))
|
||||
}
|
||||
|
||||
fn settle_matrix_quantity(matrix: MatrixQuantity) -> Result<MatrixQuantity, EvalError> {
|
||||
Ok(MatrixQuantity {
|
||||
matrix: settle_matrix(matrix.matrix)?,
|
||||
..matrix
|
||||
})
|
||||
}
|
||||
|
||||
/// The binary operation on two evaluated values, settled.
|
||||
#[inline(always)]
|
||||
fn binary(lhs: Quantity, op: BinaryOp, rhs: Quantity, pixels_per_inch: f64) -> Result<Quantity, EvalError> {
|
||||
if !lhs.is_plain() || !rhs.is_plain() {
|
||||
return settle(quantity::unit_binary_op(lhs, op, rhs, pixels_per_inch)?);
|
||||
}
|
||||
|
||||
// Plain numbers, the common case, take the arithmetic directly
|
||||
let rejected = if matches!(op, BinaryOp::And | BinaryOp::Or) {
|
||||
EvalError::NotATruthValue
|
||||
} else {
|
||||
EvalError::OperatorTypeError
|
||||
};
|
||||
let number = lhs.number().binary_op(op, rhs.number()).ok_or(rejected)?;
|
||||
settle(Quantity::of_number(number, Unit::NONE))
|
||||
}
|
||||
|
||||
/// A quotient by a measure, which is the whole divisor where the dividend has a unit, and otherwise divides by the measure's
|
||||
/// number before its units multiply in. Kept out of the evaluator's frame, which nesting multiplies.
|
||||
#[inline(never)]
|
||||
fn measure_quotient<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, dividend: &ValueNode, measure: &Measure) -> Result<Quantity, EvalError> {
|
||||
let pixels_per_inch = scope.pixels_per_inch();
|
||||
let dividend = dividend.eval_in(scope)?;
|
||||
let number = measure.number.eval_in(scope)?;
|
||||
let units = measure
|
||||
.units
|
||||
.iter()
|
||||
.try_fold(Quantity::plain(Value::from_i64(1)), |units, unit| binary(units, BinaryOp::Mul, unit.eval_in(scope)?, pixels_per_inch))?;
|
||||
|
||||
// A name the host or a `where` definition binds is no unit, so the measure then reads left to right as written
|
||||
fn is_unit<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, node: &ValueNode) -> bool {
|
||||
match node {
|
||||
ValueNode::Unit { name, .. } => name.starts_with('\\') || scope.context.get_quantity(name).is_none(),
|
||||
ValueNode::BinOp { lhs, op: BinaryOp::Pow, .. } => is_unit(scope, lhs),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
if measure.units.iter().all(|unit| is_unit(scope, unit)) && !dividend.unit.dimension().is_none() {
|
||||
binary(dividend, BinaryOp::Div, binary(number, BinaryOp::Mul, units, pixels_per_inch)?, pixels_per_inch)
|
||||
} else {
|
||||
binary(binary(dividend, BinaryOp::Div, number, pixels_per_inch)?, BinaryOp::Mul, units, pixels_per_inch)
|
||||
}
|
||||
}
|
||||
|
||||
/// The canonical form of a value the host supplied for `name`, like [`settle`], except that NaN (which only a host can
|
||||
/// supply) is an error naming its source.
|
||||
#[inline(always)]
|
||||
fn canonical_host_value(name: &str, quantity: Quantity) -> Result<Quantity, EvalError> {
|
||||
let number = quantity.number();
|
||||
fn canonical_host_value(name: &str, value: Value) -> Result<Value, EvalError> {
|
||||
let Value::Number(number) = value;
|
||||
if number.is_nan() {
|
||||
return Err(EvalError::NotANumber(name.to_string()));
|
||||
}
|
||||
Ok(Quantity::new(Value::Number(number.canonical()), quantity.unit))
|
||||
Ok(Value::Number(number.canonical()))
|
||||
}
|
||||
|
||||
/// Resolves a name against the environment before the builtin constants and units, so a binding of exactly that spelling shadows
|
||||
/// the builtin. The `\` prefix skips the environment.
|
||||
fn resolve_value<V: ValueProvider, F: FunctionProvider>(context: &EvalContext<V, F>, name: &str) -> Option<Quantity> {
|
||||
let builtin = |name: &str| {
|
||||
Constant::from_name(name)
|
||||
.map(|constant| Quantity::plain(Value::Number(constant.value())))
|
||||
.or_else(|| unit_named(name).map(|unit| Quantity::new(Value::from_i64(1), Unit::of(unit))))
|
||||
};
|
||||
/// Resolves a name against the environment before the builtin constants, so a binding of exactly that spelling shadows the builtin.
|
||||
/// The `\` prefix skips the environment.
|
||||
fn resolve_value<V: ValueProvider, F: FunctionProvider>(context: &EvalContext<V, F>, name: &str) -> Option<Value> {
|
||||
let constant = |name: &str| Constant::from_name(name).map(|constant| Value::Number(constant.value()));
|
||||
|
||||
match name.strip_prefix('\\') {
|
||||
Some(builtin_name) => builtin(builtin_name),
|
||||
None => context.get_quantity(name).or_else(|| builtin(name)),
|
||||
Some(builtin_name) => constant(builtin_name),
|
||||
None => context.get_value(name).or_else(|| constant(name)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves a matrix's name like [`resolve_value`], with `I` the one builtin.
|
||||
fn resolve_matrix<V: ValueProvider, F: FunctionProvider>(context: &EvalContext<V, F>, name: &str) -> Option<MatrixQuantity> {
|
||||
let constant = |name: &str| (name == "I").then_some(MatrixQuantity::plain(Matrix::IDENTITY));
|
||||
fn resolve_matrix<V: ValueProvider, F: FunctionProvider>(context: &EvalContext<V, F>, name: &str) -> Option<Matrix> {
|
||||
let constant = |name: &str| (name == "I").then_some(Matrix::IDENTITY);
|
||||
|
||||
match name.strip_prefix('\\') {
|
||||
Some(builtin_name) => constant(builtin_name),
|
||||
None => context.get_matrix_quantity(name).or_else(|| constant(name)),
|
||||
None => context.get_matrix(name).or_else(|| constant(name)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -228,10 +131,6 @@ impl<'a, V: ValueProvider, F: FunctionProvider> Scope<'a, V, F> {
|
||||
}
|
||||
frame.ok_or(EvalError::OperatorTypeError)
|
||||
}
|
||||
|
||||
fn pixels_per_inch(&self) -> f64 {
|
||||
self.context.pixels_per_inch()
|
||||
}
|
||||
}
|
||||
|
||||
/// The definitions of one `where` clause, or the arguments of one call, each evaluated on its first read and at most once.
|
||||
@@ -260,9 +159,9 @@ enum Bound<'a, T> {
|
||||
// Each sort reads through `where` definitions by an outlined function, keeping its frames out of the recursive evaluator's, and
|
||||
// called from several sites since wasm-opt inlines a function with one call site
|
||||
#[inline(never)]
|
||||
fn bound_value<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, bound: Bound<ValueNode>) -> Result<Quantity, EvalError> {
|
||||
fn bound_value<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, bound: Bound<ValueNode>) -> Result<Value, EvalError> {
|
||||
match bound {
|
||||
Bound::Local(local) => read(scope, local)?.as_quantity().copied().ok_or(EvalError::OperatorTypeError),
|
||||
Bound::Local(local) => read(scope, local)?.as_value().copied().ok_or(EvalError::OperatorTypeError),
|
||||
Bound::Call(function, arguments) => call(scope, function, arguments, |body, scope| match body {
|
||||
Node::Value(body) => body.eval_in(scope),
|
||||
Node::Matrix(_) => Err(EvalError::OperatorTypeError),
|
||||
@@ -272,9 +171,9 @@ fn bound_value<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, b
|
||||
}
|
||||
|
||||
#[inline(never)]
|
||||
fn bound_matrix<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, bound: Bound<MatrixNode>) -> Result<MatrixQuantity, EvalError> {
|
||||
fn bound_matrix<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, bound: Bound<MatrixNode>) -> Result<Matrix, EvalError> {
|
||||
match bound {
|
||||
Bound::Local(local) => read(scope, local)?.as_matrix_quantity().copied().ok_or(EvalError::OperatorTypeError),
|
||||
Bound::Local(local) => read(scope, local)?.as_matrix().copied().ok_or(EvalError::OperatorTypeError),
|
||||
Bound::Call(function, arguments) => call(scope, function, arguments, |body, scope| match body {
|
||||
Node::Matrix(body) => body.eval_in(scope),
|
||||
Node::Value(_) => Err(EvalError::OperatorTypeError),
|
||||
@@ -353,11 +252,8 @@ fn holding_case<'a, T, V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_,
|
||||
let mut holding = None;
|
||||
let mut overlapping = false;
|
||||
for case in cases {
|
||||
let condition = case.condition.eval_in(scope)?;
|
||||
if !condition.is_plain() {
|
||||
return Err(EvalError::NotATruthValue);
|
||||
}
|
||||
match condition.number().as_bool() {
|
||||
let Value::Number(condition) = case.condition.eval_in(scope)?;
|
||||
match condition.as_bool() {
|
||||
Some(false) => {}
|
||||
Some(true) if holding.is_none() => holding = Some(&case.value),
|
||||
Some(true) => overlapping = true,
|
||||
@@ -372,8 +268,8 @@ fn holding_case<'a, T, V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_,
|
||||
|
||||
/// An operand of a matrix operation, holding a matrix on the stack since the operation consumes it at once.
|
||||
enum Operand {
|
||||
Value(Quantity),
|
||||
Matrix(MatrixQuantity),
|
||||
Value(Value),
|
||||
Matrix(Matrix),
|
||||
}
|
||||
|
||||
impl Node {
|
||||
@@ -387,40 +283,30 @@ impl Node {
|
||||
|
||||
/// An operation with a matrix result: a value on the left acts as `L_q`, matrices compose, sums are pointwise or attach a
|
||||
/// value as translation, division is times-inverse, and powers are whole.
|
||||
fn matrix_binary_op(lhs: Operand, op: BinaryOp, rhs: Operand, pixels_per_inch: f64) -> Result<MatrixQuantity, EvalError> {
|
||||
fn matrix_binary_op(lhs: Operand, op: BinaryOp, rhs: Operand) -> Result<Matrix, EvalError> {
|
||||
use BinaryOp as Op;
|
||||
let result = match (lhs, op, rhs) {
|
||||
(Operand::Value(q), Op::Mul, Operand::Matrix(b)) => {
|
||||
let left_multiplication = MatrixQuantity {
|
||||
matrix: Matrix::left_multiplication(q.number().to_quaternion()),
|
||||
linear: q.unit,
|
||||
translation: Unit::NONE,
|
||||
};
|
||||
left_multiplication.compose(&b, pixels_per_inch)?
|
||||
}
|
||||
(Operand::Matrix(a), Op::Mul, Operand::Matrix(b)) => a.compose(&b, pixels_per_inch)?,
|
||||
(lhs, Op::Div, Operand::Matrix(b)) => return matrix_binary_op(lhs, Op::Mul, Operand::Matrix(b.inverse(pixels_per_inch)?), pixels_per_inch),
|
||||
(Operand::Matrix(a), Op::Add | Op::Sub, Operand::Matrix(b)) => a.sum(op, &b, pixels_per_inch)?,
|
||||
(Operand::Matrix(a), Op::Add | Op::Sub, Operand::Value(t)) => a.translated(op, t, pixels_per_inch)?,
|
||||
(Operand::Value(t), Op::Add, Operand::Matrix(a)) => a.translated(Op::Add, t, pixels_per_inch)?,
|
||||
(Operand::Value(t), Op::Sub, Operand::Matrix(a)) => a.negated().translated(Op::Add, t, pixels_per_inch)?,
|
||||
(Operand::Matrix(a), Op::Pow, Operand::Value(exponent)) => {
|
||||
if !exponent.is_plain() {
|
||||
return Err(EvalError::from(UnitMismatch::ExponentWithUnits(exponent.unit.to_string())));
|
||||
}
|
||||
match (lhs, op, rhs) {
|
||||
(Operand::Value(Value::Number(q)), Op::Mul, Operand::Matrix(b)) => settle_matrix(Matrix::left_multiplication(q.to_quaternion()).compose(b)),
|
||||
(Operand::Matrix(a), Op::Mul, Operand::Matrix(b)) => settle_matrix(a.compose(b)),
|
||||
(lhs, Op::Div, Operand::Matrix(b)) => matrix_binary_op(lhs, Op::Mul, Operand::Matrix(b.inverse().ok_or(EvalError::SingularMatrix)?)),
|
||||
(Operand::Matrix(a), Op::Add, Operand::Matrix(b)) => settle_matrix(a + b),
|
||||
(Operand::Matrix(a), Op::Sub, Operand::Matrix(b)) => settle_matrix(a - b),
|
||||
(Operand::Matrix(a), Op::Add, Operand::Value(Value::Number(t))) | (Operand::Value(Value::Number(t)), Op::Add, Operand::Matrix(a)) => settle_matrix(a.translated(t.to_quaternion())),
|
||||
(Operand::Matrix(a), Op::Sub, Operand::Value(Value::Number(t))) => settle_matrix(a.translated(-t.to_quaternion())),
|
||||
(Operand::Value(Value::Number(t)), Op::Sub, Operand::Matrix(a)) => settle_matrix((-a).translated(t.to_quaternion())),
|
||||
(Operand::Matrix(a), Op::Pow, Operand::Value(Value::Number(exponent))) => {
|
||||
// A whole exponent is a composition power, a negative one of the inverse, with an integer read exactly past 2^53
|
||||
let whole = match exponent.number() {
|
||||
let whole = match exponent {
|
||||
Number::Integer(integer) => integer,
|
||||
real => real
|
||||
.as_real()
|
||||
.filter(|real| real.fract() == 0. && real.abs() < i64::MAX as f64)
|
||||
.ok_or(EvalError::FractionalMatrixPower)? as i64,
|
||||
};
|
||||
a.power(whole, pixels_per_inch)?
|
||||
settle_matrix(a.power(whole).ok_or(EvalError::SingularMatrix)?)
|
||||
}
|
||||
_ => return Err(EvalError::OperatorTypeError),
|
||||
};
|
||||
settle_matrix_quantity(result)
|
||||
_ => Err(EvalError::OperatorTypeError),
|
||||
}
|
||||
}
|
||||
|
||||
impl Node {
|
||||
@@ -441,43 +327,98 @@ impl Node {
|
||||
}
|
||||
|
||||
impl ValueNode {
|
||||
pub fn eval<V: ValueProvider, F: FunctionProvider>(&self, context: &EvalContext<V, F>) -> Result<Quantity, EvalError> {
|
||||
pub fn eval<V: ValueProvider, F: FunctionProvider>(&self, context: &EvalContext<V, F>) -> Result<Value, EvalError> {
|
||||
self.eval_in(&Scope::root(context))
|
||||
}
|
||||
|
||||
fn eval_in<V: ValueProvider, F: FunctionProvider>(&self, scope: &Scope<'_, V, F>) -> Result<Quantity, EvalError> {
|
||||
fn eval_in<V: ValueProvider, F: FunctionProvider>(&self, scope: &Scope<'_, V, F>) -> Result<Value, EvalError> {
|
||||
match self {
|
||||
ValueNode::Lit(lit) => match lit {
|
||||
Literal::Integer(integer) => Ok(Quantity::plain(Value::from_i64(*integer))),
|
||||
Literal::Float(float) => Ok(Quantity::plain(Value::from_f64(*float))),
|
||||
Literal::Integer(integer) => Ok(Value::from_i64(*integer)),
|
||||
Literal::Float(float) => Ok(Value::from_f64(*float)),
|
||||
},
|
||||
|
||||
ValueNode::BinOp { lhs, op, rhs } => binary(lhs.eval_in(scope)?, *op, rhs.eval_in(scope)?, scope.pixels_per_inch()),
|
||||
ValueNode::MeasureQuotient { dividend, measure } => measure_quotient(scope, dividend, measure),
|
||||
ValueNode::UnaryOp { expr, op } => {
|
||||
let operand = expr.eval_in(scope)?;
|
||||
if !operand.is_plain() {
|
||||
return settle(quantity::unary_op(operand, *op)?);
|
||||
ValueNode::BinOp { lhs, op, rhs } => match (lhs.eval_in(scope)?, rhs.eval_in(scope)?) {
|
||||
(Value::Number(lhs), Value::Number(rhs)) => {
|
||||
// Logic rejects operands that aren't truth values, while the other operators reject operand types they don't support
|
||||
let rejected = if matches!(op, BinaryOp::And | BinaryOp::Or) {
|
||||
EvalError::NotATruthValue
|
||||
} else {
|
||||
EvalError::OperatorTypeError
|
||||
};
|
||||
settle(Value::Number(lhs.binary_op(*op, rhs).ok_or(rejected)?))
|
||||
}
|
||||
},
|
||||
ValueNode::UnaryOp { expr, op } => match expr.eval_in(scope)? {
|
||||
Value::Number(num) => {
|
||||
let rejected = if *op == UnaryOp::Not { EvalError::NotATruthValue } else { EvalError::OperatorTypeError };
|
||||
settle(Value::Number(num.unary_op(*op).ok_or(rejected)?))
|
||||
}
|
||||
},
|
||||
ValueNode::Comparison { first, rest } => {
|
||||
let Value::Number(first) = first.eval_in(scope)?;
|
||||
let rest = rest
|
||||
.iter()
|
||||
.map(|(op, operand)| operand.eval_in(scope).map(|Value::Number(number)| (*op, number)))
|
||||
.collect::<Result<Vec<(BinaryOp, Number)>, EvalError>>()?;
|
||||
|
||||
let rejected = if *op == UnaryOp::Not { EvalError::NotATruthValue } else { EvalError::OperatorTypeError };
|
||||
settle(Quantity::of_number(operand.number().unary_op(*op).ok_or(rejected)?, Unit::NONE))
|
||||
// A `!=` chain asserts every pair distinct, while the ordered chains assert each adjacent pair's relation; every pair is checked so an unsupported comparison errors regardless of the others
|
||||
let holds = if rest.iter().all(|(op, _)| *op == BinaryOp::Neq) {
|
||||
let numbers: Vec<Number> = std::iter::once(first).chain(rest.iter().map(|(_, number)| *number)).collect();
|
||||
numbers.iter().enumerate().all(|(index, a)| numbers[index + 1..].iter().all(|b| a != b))
|
||||
} else {
|
||||
let mut holds = true;
|
||||
let mut previous = first;
|
||||
for (op, number) in rest {
|
||||
holds &= previous.binary_op(op, number).ok_or(EvalError::OperatorTypeError)?.as_bool() == Some(true);
|
||||
previous = number;
|
||||
}
|
||||
holds
|
||||
};
|
||||
Ok(Value::from_bool(holds))
|
||||
}
|
||||
ValueNode::Comparison { first, rest } => comparison_chain(scope, first, rest),
|
||||
ValueNode::Var(name) => {
|
||||
let value = resolve_value(scope.context, name).ok_or_else(|| EvalError::MissingValue(name.clone()))?;
|
||||
canonical_host_value(name, value)
|
||||
}
|
||||
ValueNode::Unit { name, unit } => {
|
||||
// A host's binding of the spelling shadows the unit, unless the `\` prefix asks for the unit
|
||||
let bound = (!name.starts_with('\\')).then(|| scope.context.get_quantity(name)).flatten();
|
||||
match bound {
|
||||
Some(value) => canonical_host_value(name, value),
|
||||
None => Ok(Quantity::new(Value::from_i64(1), Unit::of(*unit))),
|
||||
ValueNode::FnCall { name, expr } => {
|
||||
// Arguments land in a stack buffer when they fit (builtins take at most 5), avoiding a heap allocation per call
|
||||
let mut stack_values = [Value::from_i64(0); 5];
|
||||
let heap_values: Vec<Value>;
|
||||
let values: &[Value] = if expr.len() <= stack_values.len() {
|
||||
for (slot, argument) in stack_values.iter_mut().zip(expr) {
|
||||
*slot = argument.eval_in(scope)?;
|
||||
}
|
||||
&stack_values[..expr.len()]
|
||||
} else {
|
||||
heap_values = expr.iter().map(|argument| argument.eval_in(scope)).collect::<Result<Vec<Value>, EvalError>>()?;
|
||||
&heap_values
|
||||
};
|
||||
|
||||
// A host-supplied function shadows the builtin of the same name, unless the `\` prefix asks for the language's own
|
||||
let (prefixed, bare_name) = match name.strip_prefix('\\') {
|
||||
Some(bare_name) => (true, bare_name),
|
||||
None => (false, name.as_str()),
|
||||
};
|
||||
|
||||
if !prefixed && let Some(value) = scope.context.run_function(bare_name, values) {
|
||||
settle(canonical_host_value(bare_name, value)?)
|
||||
} else if let Some(Builtin::Values { function, .. }) = builtin_function(bare_name) {
|
||||
settle(function(values).ok_or(EvalError::TypeError)?)
|
||||
} else if let Some(SuffixedFunction { function, argument, .. }) = suffixed_function(bare_name) {
|
||||
// A base-suffixed call like `log10(x)` runs the two-argument form with the suffix baked in as its second argument
|
||||
let [value] = values else { return Err(EvalError::TypeError) };
|
||||
settle(function(&[*value, Value::from_f64(argument)]).ok_or(EvalError::TypeError)?)
|
||||
} else if let Some(value) = resolve_value(scope.context, name)
|
||||
&& let [Value::Number(argument)] = values
|
||||
{
|
||||
// A known value applied to one argument is implicit multiplication, so `x(2)` matches `2(3)` and `i(16)`
|
||||
let Value::Number(value) = canonical_host_value(name, value)?;
|
||||
settle(Value::Number(value.binary_op(BinaryOp::Mul, *argument).ok_or(EvalError::OperatorTypeError)?))
|
||||
} else {
|
||||
Err(EvalError::MissingFunction(name.to_string()))
|
||||
}
|
||||
}
|
||||
ValueNode::FnCall { name, expr } => function_call(scope, name, expr),
|
||||
ValueNode::BuiltinCall(call) => builtin_call(scope, call),
|
||||
// Only the chosen value is evaluated, so an error in any other case's value is never raised
|
||||
ValueNode::Piecewise { cases, otherwise } => match (holding_case(scope, cases)?, otherwise) {
|
||||
(Some(value), _) => value.eval_in(scope),
|
||||
@@ -485,14 +426,8 @@ impl ValueNode {
|
||||
(None, None) => Err(EvalError::NoCaseHolds),
|
||||
},
|
||||
ValueNode::Apply { matrix, value } => value_of_matrix(scope, MatrixValueCase::Apply(matrix, value)),
|
||||
ValueNode::OfMatrix { function, unit, matrix } => value_of_matrix(scope, MatrixValueCase::OfMatrix(*function, *unit, matrix)),
|
||||
ValueNode::OfValueAndRegions {
|
||||
function,
|
||||
result,
|
||||
value,
|
||||
regions,
|
||||
trailing,
|
||||
} => value_of_matrix(scope, MatrixValueCase::OfValueAndRegions(*function, *result, value, regions, trailing.as_deref())),
|
||||
ValueNode::OfMatrix { function, matrix } => value_of_matrix(scope, MatrixValueCase::OfMatrix(*function, matrix)),
|
||||
ValueNode::OfValueAndRegions { function, value, regions, trailing } => value_of_matrix(scope, MatrixValueCase::OfValueAndRegions(*function, value, regions, trailing.as_deref())),
|
||||
ValueNode::MatrixComparison { matrices, distinct } => value_of_matrix(scope, MatrixValueCase::Comparison(matrices, *distinct)),
|
||||
ValueNode::Local(local) => bound_value(scope, Bound::Local(*local)),
|
||||
ValueNode::Call { function, arguments } => bound_value(scope, Bound::Call(*function, arguments)),
|
||||
@@ -501,349 +436,134 @@ impl ValueNode {
|
||||
}
|
||||
}
|
||||
|
||||
/// A chain of comparisons, outlined to keep its buffers out of the recursive evaluator's frame.
|
||||
#[inline(never)]
|
||||
fn comparison_chain<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, first: &ValueNode, rest: &[(BinaryOp, ValueNode)]) -> Result<Quantity, EvalError> {
|
||||
let first = first.eval_in(scope)?;
|
||||
let rest = rest
|
||||
.iter()
|
||||
.map(|(op, operand)| operand.eval_in(scope).map(|quantity| (*op, quantity)))
|
||||
.collect::<Result<Vec<(BinaryOp, Quantity)>, EvalError>>()?;
|
||||
let (first, rest) = quantity::comparison_operands(first, &rest, scope.pixels_per_inch())?;
|
||||
|
||||
// A `!=` chain asserts every pair distinct, while the ordered chains assert each adjacent pair's relation; every pair is checked so an unsupported comparison errors regardless of the others
|
||||
let holds = if rest.iter().all(|(op, _)| *op == BinaryOp::Neq) {
|
||||
let numbers: Vec<Number> = std::iter::once(first).chain(rest.iter().map(|(_, number)| *number)).collect();
|
||||
numbers.iter().enumerate().all(|(index, a)| numbers[index + 1..].iter().all(|b| a != b))
|
||||
} else {
|
||||
let mut holds = true;
|
||||
let mut previous = first;
|
||||
for (op, number) in rest {
|
||||
holds &= previous.binary_op(op, number).ok_or(EvalError::OperatorTypeError)?.as_bool() == Some(true);
|
||||
previous = number;
|
||||
}
|
||||
holds
|
||||
};
|
||||
Ok(Quantity::plain(Value::from_bool(holds)))
|
||||
}
|
||||
|
||||
/// A call of a builtin found as the expression was read, kept apart from the recursive evaluator so its argument buffers stay out of the evaluator's frame in unoptimized builds.
|
||||
fn builtin_call<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, call: &BuiltinCall) -> Result<Quantity, EvalError> {
|
||||
if call.suffix.is_some() && call.arguments.len() != 1 {
|
||||
return Err(EvalError::TypeError);
|
||||
}
|
||||
|
||||
// Arguments land in stack buffers when they fit (builtins take at most 5), each value beside its unit
|
||||
let count = call.arguments.len() + usize::from(call.suffix.is_some());
|
||||
let mut stack_values = [Value::from_i64(0); 5];
|
||||
let mut stack_units = [Unit::NONE; 5];
|
||||
let (mut heap_values, mut heap_units): (Vec<Value>, Vec<Unit>);
|
||||
let (values, units): (&mut [Value], &mut [Unit]) = if count <= stack_values.len() {
|
||||
(&mut stack_values[..count], &mut stack_units[..count])
|
||||
} else {
|
||||
heap_values = vec![Value::from_i64(0); count];
|
||||
heap_units = vec![Unit::NONE; count];
|
||||
(&mut heap_values, &mut heap_units)
|
||||
};
|
||||
|
||||
for ((value, unit), argument) in values.iter_mut().zip(units.iter_mut()).zip(&call.arguments) {
|
||||
let Quantity {
|
||||
value: argument_value,
|
||||
unit: argument_unit,
|
||||
} = argument.eval_in(scope)?;
|
||||
*value = argument_value;
|
||||
*unit = argument_unit;
|
||||
}
|
||||
|
||||
// A host may supply a function the expression wasn't read with, which shadows the builtin as it would have then
|
||||
if let Some(host_name) = &call.host_name
|
||||
&& scope.context.provides_function(host_name)
|
||||
{
|
||||
let arguments: Vec<Quantity> = values.iter().zip(units.iter()).take(call.arguments.len()).map(|(value, unit)| Quantity::new(*value, *unit)).collect();
|
||||
if let Some(value) = host_function(scope, host_name, &arguments)? {
|
||||
return settle(canonical_host_value(host_name, Quantity::plain(value))?);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(suffix) = call.suffix {
|
||||
values[count - 1] = Value::from_f64(suffix);
|
||||
}
|
||||
|
||||
settle(quantity::run_builtin_on_parts(&call.name, call.rule, call.function, values, units, scope.pixels_per_inch())?)
|
||||
}
|
||||
|
||||
/// A call of a host function or a builtin, outlined to keep its argument buffer out of the recursive evaluator's frame.
|
||||
#[inline(never)]
|
||||
fn function_call<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, name: &str, expr: &[ValueNode]) -> Result<Quantity, EvalError> {
|
||||
// Arguments land in a stack buffer when they fit (builtins take at most 5), avoiding a heap allocation per call
|
||||
let mut stack_values = [Quantity::plain(Value::from_i64(0)); 5];
|
||||
let heap_values: Vec<Quantity>;
|
||||
let arguments: &[Quantity] = if expr.len() <= stack_values.len() {
|
||||
for (slot, argument) in stack_values.iter_mut().zip(expr) {
|
||||
*slot = argument.eval_in(scope)?;
|
||||
}
|
||||
&stack_values[..expr.len()]
|
||||
} else {
|
||||
heap_values = expr.iter().map(|argument| argument.eval_in(scope)).collect::<Result<Vec<Quantity>, EvalError>>()?;
|
||||
&heap_values
|
||||
};
|
||||
|
||||
// A host-supplied function shadows the builtin of the same name, unless the `\` prefix asks for the language's own
|
||||
let (prefixed, bare_name) = match name.strip_prefix('\\') {
|
||||
Some(bare_name) => (true, bare_name),
|
||||
None => (false, name),
|
||||
};
|
||||
|
||||
if !prefixed && let Some(value) = host_function(scope, bare_name, arguments)? {
|
||||
settle(canonical_host_value(bare_name, Quantity::plain(value))?)
|
||||
} else if let Some(Builtin::Values { function, .. }) = builtin_function(bare_name) {
|
||||
let rule = unit_rule(bare_name).unwrap_or(UnitRule::Plain);
|
||||
settle(quantity::run_builtin(bare_name, rule, function, arguments, scope.pixels_per_inch())?)
|
||||
} else if let Some(SuffixedFunction { name: base_name, function, argument }) = suffixed_function(bare_name) {
|
||||
// A base-suffixed call like `log10(x)` runs the two-argument form with the suffix baked in as its second argument
|
||||
let [value] = arguments else { return Err(EvalError::TypeError) };
|
||||
let rule = unit_rule(base_name).unwrap_or(UnitRule::Plain);
|
||||
let arguments = [*value, Quantity::plain(Value::from_f64(argument))];
|
||||
settle(quantity::run_builtin(base_name, rule, function, &arguments, scope.pixels_per_inch())?)
|
||||
} else if let Some(value) = resolve_value(scope.context, name)
|
||||
&& let [argument] = arguments
|
||||
{
|
||||
// A known value applied to one argument is implicit multiplication, so `x(2)` matches `2(3)` and `i(16)`
|
||||
let value = canonical_host_value(name, value)?;
|
||||
settle(quantity::binary_op(value, BinaryOp::Mul, *argument, scope.pixels_per_inch())?)
|
||||
} else {
|
||||
Err(EvalError::MissingFunction(name.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the host's function of the name, which takes plain numbers, or gives `None` where the host has none.
|
||||
fn host_function<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, name: &str, arguments: &[Quantity]) -> Result<Option<Value>, EvalError> {
|
||||
if !scope.context.provides_function(name) {
|
||||
return Ok(None);
|
||||
}
|
||||
let arguments: Vec<Quantity> = arguments.iter().map(|argument| argument.plain_if_dimensionless()).collect();
|
||||
if let Some(argument) = arguments.iter().find(|argument| !argument.is_plain()) {
|
||||
return Err(EvalError::from(UnitMismatch::UnitsNotAccepted {
|
||||
function: name.to_string(),
|
||||
unit: argument.unit.to_string(),
|
||||
}));
|
||||
}
|
||||
|
||||
let values: Vec<Value> = arguments.iter().map(|argument| argument.value).collect();
|
||||
Ok(scope.context.run_function(name, &values))
|
||||
}
|
||||
|
||||
/// A value computed from matrices.
|
||||
enum MatrixValueCase<'a> {
|
||||
Apply(&'a MatrixNode, &'a ValueNode),
|
||||
OfMatrix(MatrixToValue, MatrixValueUnit, &'a MatrixNode),
|
||||
OfValueAndRegions(ValueOfRegions, RegionResult, &'a ValueNode, &'a [MatrixNode], Option<&'a ValueNode>),
|
||||
OfMatrix(MatrixToValue, &'a MatrixNode),
|
||||
OfValueAndRegions(ValueOfRegions, &'a ValueNode, &'a [MatrixNode], Option<&'a ValueNode>),
|
||||
Comparison(&'a [MatrixNode], bool),
|
||||
}
|
||||
|
||||
/// A region with the unit of the values it holds.
|
||||
#[derive(Clone, Copy)]
|
||||
struct UnitRegion {
|
||||
region: Region,
|
||||
unit: Unit,
|
||||
}
|
||||
|
||||
// One function for every value taken from a matrix, called from several sites, since wasm-opt inlines a function with one call site back into the evaluator whatever its attributes say
|
||||
#[cold]
|
||||
#[inline(never)]
|
||||
fn value_of_matrix<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, case: MatrixValueCase) -> Result<Quantity, EvalError> {
|
||||
let pixels_per_inch = scope.pixels_per_inch();
|
||||
fn value_of_matrix<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, case: MatrixValueCase) -> Result<Value, EvalError> {
|
||||
match case {
|
||||
MatrixValueCase::Apply(matrix, value) => {
|
||||
let matrix = matrix.eval_in(scope)?;
|
||||
let value = value.eval_in(scope)?;
|
||||
settle(matrix.apply(value, pixels_per_inch)?)
|
||||
let Value::Number(value) = value.eval_in(scope)?;
|
||||
settle(Value::from(matrix.apply(value.to_quaternion())))
|
||||
}
|
||||
MatrixValueCase::OfMatrix(function, unit, matrix) => {
|
||||
let matrix = matrix.eval_in(scope)?;
|
||||
let unit = quantity::matrix_value_result_unit(unit, &matrix)?;
|
||||
settle(Quantity::new(function(matrix.matrix), unit))
|
||||
}
|
||||
MatrixValueCase::OfValueAndRegions(function, result_unit, value, regions, trailing) => {
|
||||
MatrixValueCase::OfMatrix(function, matrix) => settle(function(matrix.eval_in(scope)?)),
|
||||
MatrixValueCase::OfValueAndRegions(function, value, regions, trailing) => {
|
||||
let value = value.eval_in(scope)?;
|
||||
|
||||
// A range literal is kept by its corners, which may be infinite where no matrix can hold them
|
||||
let region_of = |region: &MatrixNode| -> Result<UnitRegion, EvalError> {
|
||||
let region_of = |region: &MatrixNode| -> Result<Region, EvalError> {
|
||||
match region {
|
||||
MatrixNode::Range { from, to } => {
|
||||
let (from, to, unit) = quantity::range_corners(from.eval_in(scope)?, to.eval_in(scope)?, pixels_per_inch)?;
|
||||
Ok(UnitRegion {
|
||||
region: Region::Range(from, to),
|
||||
unit,
|
||||
})
|
||||
}
|
||||
region => {
|
||||
let matrix = region.eval_in(scope)?;
|
||||
let unit = matrix.region_unit();
|
||||
Ok(UnitRegion {
|
||||
region: Region::Map(matrix.as_region_in(unit, pixels_per_inch)?),
|
||||
unit,
|
||||
})
|
||||
let (Value::Number(from), Value::Number(to)) = (from.eval_in(scope)?, to.eval_in(scope)?);
|
||||
Ok(Region::Range(from, to))
|
||||
}
|
||||
region => region.eval_in(scope).map(Region::Map),
|
||||
}
|
||||
};
|
||||
|
||||
// The range functions take at most two regions as parsed, which land in a stack buffer, while a longer list a host built goes to the heap
|
||||
let placeholder = UnitRegion {
|
||||
region: Region::Range(Number::Integer(0), Number::Integer(0)),
|
||||
unit: Unit::NONE,
|
||||
};
|
||||
let mut stack_regions = [placeholder; 2];
|
||||
let heap_regions: Vec<UnitRegion>;
|
||||
let unit_regions: &[UnitRegion] = if regions.len() <= stack_regions.len() {
|
||||
let mut stack_regions = [Region::Range(Number::Integer(0), Number::Integer(0)); 2];
|
||||
let heap_regions: Vec<Region>;
|
||||
let regions: &[Region] = if regions.len() <= stack_regions.len() {
|
||||
for (slot, region) in stack_regions.iter_mut().zip(regions) {
|
||||
*slot = region_of(region)?;
|
||||
}
|
||||
&stack_regions[..regions.len()]
|
||||
} else {
|
||||
heap_regions = regions.iter().map(region_of).collect::<Result<Vec<UnitRegion>, EvalError>>()?;
|
||||
heap_regions = regions.iter().map(region_of).collect::<Result<Vec<Region>, EvalError>>()?;
|
||||
&heap_regions
|
||||
};
|
||||
|
||||
// The value is measured in the first region's unit, and a remap's result in the last's
|
||||
let Some(first) = unit_regions.first() else { return Err(EvalError::TypeError) };
|
||||
let value = Quantity::of_number(quantity::into_region_unit(value, first.unit, pixels_per_inch)?, Unit::NONE);
|
||||
let mut stack_plain_regions = [placeholder.region; 2];
|
||||
let heap_plain_regions: Vec<Region>;
|
||||
let plain_regions: &[Region] = if unit_regions.len() <= stack_plain_regions.len() {
|
||||
for (slot, unit_region) in stack_plain_regions.iter_mut().zip(unit_regions) {
|
||||
*slot = unit_region.region;
|
||||
}
|
||||
&stack_plain_regions[..unit_regions.len()]
|
||||
} else {
|
||||
heap_plain_regions = unit_regions.iter().map(|unit_region| unit_region.region).collect();
|
||||
&heap_plain_regions
|
||||
};
|
||||
|
||||
let trailing = match trailing.map(|trailing| trailing.eval_in(scope)).transpose()? {
|
||||
Some(trailing) if !trailing.is_plain() => return Err(EvalError::SmoothstepContinuity),
|
||||
trailing => trailing.map(|trailing| trailing.value),
|
||||
};
|
||||
let result = function(value.value, plain_regions, trailing)?;
|
||||
|
||||
let unit = match result_unit {
|
||||
RegionResult::FirstRegion => first.unit,
|
||||
RegionResult::LastRegion => unit_regions.last().map_or(Unit::NONE, |region| region.unit),
|
||||
RegionResult::Plain => Unit::NONE,
|
||||
};
|
||||
settle(Quantity::new(result, unit))
|
||||
let trailing = trailing.map(|trailing| trailing.eval_in(scope)).transpose()?;
|
||||
settle(function(value, regions, trailing)?)
|
||||
}
|
||||
MatrixValueCase::Comparison(matrices, distinct) => {
|
||||
// A chain lands in a stack buffer when it fits, the usual case
|
||||
let mut stack_matrices = [MatrixQuantity::plain(Matrix::ZERO); 4];
|
||||
let heap_matrices: Vec<MatrixQuantity>;
|
||||
let matrices: &[MatrixQuantity] = if matrices.len() <= stack_matrices.len() {
|
||||
let mut stack_matrices = [Matrix::ZERO; 4];
|
||||
let heap_matrices: Vec<Matrix>;
|
||||
let matrices: &[Matrix] = if matrices.len() <= stack_matrices.len() {
|
||||
for (slot, matrix) in stack_matrices.iter_mut().zip(matrices) {
|
||||
*slot = matrix.eval_in(scope)?;
|
||||
}
|
||||
&stack_matrices[..matrices.len()]
|
||||
} else {
|
||||
heap_matrices = matrices.iter().map(|matrix| matrix.eval_in(scope)).collect::<Result<Vec<MatrixQuantity>, EvalError>>()?;
|
||||
heap_matrices = matrices.iter().map(|matrix| matrix.eval_in(scope)).collect::<Result<Vec<Matrix>, EvalError>>()?;
|
||||
&heap_matrices
|
||||
};
|
||||
|
||||
// Matrices compare in the first one's units, which every other must share in dimension
|
||||
let Some(first) = matrices.first() else { return Err(EvalError::TypeError) };
|
||||
let translation_unit = matrices.iter().map(|matrix| matrix.translation).find(|unit| !unit.is_none()).unwrap_or(Unit::NONE);
|
||||
let in_first_units = |matrix: &MatrixQuantity| -> Result<Matrix, EvalError> {
|
||||
if matrix.linear == first.linear && matrix.translation == translation_unit {
|
||||
return Ok(matrix.matrix);
|
||||
}
|
||||
matrix.in_units(first.linear, translation_unit, pixels_per_inch)
|
||||
};
|
||||
let plain = matrices.iter().map(in_first_units).collect::<Result<Vec<Matrix>, EvalError>>()?;
|
||||
|
||||
let holds = if distinct {
|
||||
plain.iter().enumerate().all(|(index, a)| plain[index + 1..].iter().all(|b| !a.same_entries(*b)))
|
||||
matrices.iter().enumerate().all(|(index, a)| matrices[index + 1..].iter().all(|b| !a.same_entries(*b)))
|
||||
} else {
|
||||
plain.windows(2).all(|pair| pair[0].same_entries(pair[1]))
|
||||
matrices.windows(2).all(|pair| pair[0].same_entries(pair[1]))
|
||||
};
|
||||
Ok(Quantity::plain(Value::from_bool(holds)))
|
||||
Ok(Value::from_bool(holds))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MatrixNode {
|
||||
pub fn eval<V: ValueProvider, F: FunctionProvider>(&self, context: &EvalContext<V, F>) -> Result<MatrixQuantity, EvalError> {
|
||||
pub fn eval<V: ValueProvider, F: FunctionProvider>(&self, context: &EvalContext<V, F>) -> Result<Matrix, EvalError> {
|
||||
self.eval_in(&Scope::root(context))
|
||||
}
|
||||
|
||||
fn eval_in<V: ValueProvider, F: FunctionProvider>(&self, scope: &Scope<'_, V, F>) -> Result<MatrixQuantity, EvalError> {
|
||||
let pixels_per_inch = scope.pixels_per_inch();
|
||||
fn eval_in<V: ValueProvider, F: FunctionProvider>(&self, scope: &Scope<'_, V, F>) -> Result<Matrix, EvalError> {
|
||||
match self {
|
||||
MatrixNode::Var(name) => {
|
||||
let matrix = resolve_matrix(scope.context, name).ok_or_else(|| EvalError::MissingValue(name.clone()))?;
|
||||
if matrix.matrix.is_nan() {
|
||||
if matrix.is_nan() {
|
||||
return Err(EvalError::NotANumber(name.clone()));
|
||||
}
|
||||
settle_matrix_quantity(matrix)
|
||||
settle_matrix(matrix)
|
||||
}
|
||||
MatrixNode::Literal { entries, by_rows } => {
|
||||
if entries.len() > 4 {
|
||||
let mut quaternions = [Quaternion::ZERO; 4];
|
||||
if entries.len() > quaternions.len() {
|
||||
return Err(EvalError::TypeError);
|
||||
}
|
||||
let quantities = entries.iter().map(|entry| entry.eval_in(scope)).collect::<Result<Vec<Quantity>, EvalError>>()?;
|
||||
let (quaternions, unit) = quantity::literal_entries(&quantities, pixels_per_inch)?;
|
||||
for (slot, entry) in quaternions.iter_mut().zip(entries) {
|
||||
let Value::Number(number) = entry.eval_in(scope)?;
|
||||
*slot = number.to_quaternion();
|
||||
}
|
||||
|
||||
let matrix = if *by_rows { Matrix::from_rows(&quaternions) } else { Matrix::from_columns(&quaternions) };
|
||||
settle_matrix_quantity(MatrixQuantity {
|
||||
matrix: matrix.ok_or(EvalError::TypeError)?,
|
||||
linear: unit,
|
||||
translation: Unit::NONE,
|
||||
})
|
||||
let entries = &quaternions[..entries.len()];
|
||||
let matrix = if *by_rows { Matrix::from_rows(entries) } else { Matrix::from_columns(entries) };
|
||||
settle_matrix(matrix.ok_or(EvalError::TypeError)?)
|
||||
}
|
||||
MatrixNode::FromValues { function, units, arguments } => {
|
||||
MatrixNode::FromValues { function, arguments } => {
|
||||
// The builders take at most three arguments as parsed, which land in a stack buffer, while a longer list a host built goes to the heap
|
||||
let mut stack_values = [Quantity::plain(Value::from_i64(0)); 3];
|
||||
let heap_values: Vec<Quantity>;
|
||||
let quantities: &[Quantity] = if arguments.len() <= stack_values.len() {
|
||||
let mut stack_values = [Value::from_i64(0); 3];
|
||||
let heap_values: Vec<Value>;
|
||||
let values: &[Value] = if arguments.len() <= stack_values.len() {
|
||||
for (slot, argument) in stack_values.iter_mut().zip(arguments) {
|
||||
*slot = argument.eval_in(scope)?;
|
||||
}
|
||||
&stack_values[..arguments.len()]
|
||||
} else {
|
||||
heap_values = arguments.iter().map(|argument| argument.eval_in(scope)).collect::<Result<Vec<Quantity>, EvalError>>()?;
|
||||
heap_values = arguments.iter().map(|argument| argument.eval_in(scope)).collect::<Result<Vec<Value>, EvalError>>()?;
|
||||
&heap_values
|
||||
};
|
||||
|
||||
let (values, linear) = quantity::builder_arguments(*units, quantities)?;
|
||||
settle_matrix_quantity(MatrixQuantity {
|
||||
matrix: function(&values).ok_or(EvalError::TypeError)?,
|
||||
linear,
|
||||
translation: Unit::NONE,
|
||||
})
|
||||
settle_matrix(function(values).ok_or(EvalError::TypeError)?)
|
||||
}
|
||||
MatrixNode::Range { from, to } => {
|
||||
let (from, to, unit) = quantity::range_corners(from.eval_in(scope)?, to.eval_in(scope)?, pixels_per_inch)?;
|
||||
let matrix = Matrix::range(from.to_quaternion(), to.to_quaternion());
|
||||
let translation = if matrix.translation == Quaternion::ZERO { Unit::NONE } else { unit };
|
||||
settle_matrix_quantity(MatrixQuantity { matrix, linear: unit, translation })
|
||||
let (Value::Number(from), Value::Number(to)) = (from.eval_in(scope)?, to.eval_in(scope)?);
|
||||
settle_matrix(Matrix::range(from.to_quaternion(), to.to_quaternion()))
|
||||
}
|
||||
MatrixNode::OfMatrix { function, matrix } => {
|
||||
let matrix = matrix.eval_in(scope)?;
|
||||
let result = function(matrix.matrix);
|
||||
let translation = if result.translation == Quaternion::ZERO { Unit::NONE } else { matrix.translation };
|
||||
settle_matrix_quantity(MatrixQuantity {
|
||||
matrix: result,
|
||||
linear: matrix.linear,
|
||||
translation,
|
||||
})
|
||||
}
|
||||
MatrixNode::BinOp { lhs, op, rhs } => matrix_binary_op(lhs.operand(scope)?, *op, rhs.operand(scope)?, pixels_per_inch),
|
||||
MatrixNode::OfMatrix { function, matrix } => settle_matrix(function(matrix.eval_in(scope)?)),
|
||||
MatrixNode::BinOp { lhs, op, rhs } => matrix_binary_op(lhs.operand(scope)?, *op, rhs.operand(scope)?),
|
||||
MatrixNode::UnaryOp { expr, op } => {
|
||||
let matrix = expr.eval_in(scope)?;
|
||||
match op {
|
||||
UnaryOp::Pos => Ok(matrix),
|
||||
UnaryOp::Neg => settle_matrix_quantity(matrix.negated()),
|
||||
UnaryOp::Transpose if matrix.matrix.is_linear() => settle_matrix_quantity(MatrixQuantity {
|
||||
matrix: matrix.matrix.transposed(),
|
||||
..matrix
|
||||
}),
|
||||
UnaryOp::Neg => settle_matrix(-matrix),
|
||||
UnaryOp::Transpose if matrix.is_linear() => settle_matrix(matrix.transposed()),
|
||||
UnaryOp::Transpose => Err(EvalError::AffineTranspose),
|
||||
UnaryOp::Not | UnaryOp::Fac | UnaryOp::Magnitude => Err(EvalError::OperatorTypeError),
|
||||
}
|
||||
@@ -881,7 +601,7 @@ mod tests {
|
||||
expr: vec![ValueNode::Lit(Literal::Float(2.))],
|
||||
};
|
||||
let result = call.eval(&EvalContext::new(SingleValue(5.), NothingMap)).unwrap();
|
||||
assert_eq!(result.value, Value::from_f64(10.));
|
||||
assert_eq!(result, Value::from_f64(10.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -899,7 +619,7 @@ mod tests {
|
||||
#[test]
|
||||
fn $name() {
|
||||
let result = $expr.eval(&EvalContext::default()).unwrap();
|
||||
assert_eq!(result.value, $expected);
|
||||
assert_eq!(result, $expected);
|
||||
}
|
||||
)*
|
||||
};
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
//! The roles the lexer and grammar give each stretch of source, for an editor to color and typeset an expression as it is typed.
|
||||
|
||||
use crate::constants::{builtin_function, suffixed_function};
|
||||
use crate::documentation::{Operator, Tooltip, constant_tooltip, function_tooltip, identity_tooltip, keyword_tooltip, matrix_literal_tooltip, range_tooltip, reducer_tooltip, unit_tooltip};
|
||||
use crate::documentation::{Operator, Tooltip, constant_tooltip, function_tooltip, identity_tooltip, keyword_tooltip, matrix_literal_tooltip, range_tooltip, reducer_tooltip};
|
||||
use crate::lexer::{Constant, Lexer, Token, names_matrix, operand_ended};
|
||||
use crate::parser::parse_quietly;
|
||||
use crate::sort::{NameUse, name_uses};
|
||||
use crate::units::unit_named;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// What a stretch of source is, as far as its spelling and its neighbors say.
|
||||
@@ -21,8 +20,6 @@ pub enum Role {
|
||||
Function,
|
||||
Keyword,
|
||||
Operator,
|
||||
/// A unit of measure, like `mm` or `%`, which a name binding no local reaches.
|
||||
Unit,
|
||||
/// A grouping delimiter: a parenthesis, a brace, or a magnitude bar.
|
||||
Bracket,
|
||||
/// A matrix literal's brackets and separators, and a range's `..`.
|
||||
@@ -137,8 +134,6 @@ pub fn highlight(source: &str, accepts_reducers: bool) -> Vec<Highlight> {
|
||||
Role::Function
|
||||
} else if matches!(bare, "i" | "j" | "k") {
|
||||
Role::Basis
|
||||
} else if unit_named(bare).is_some() && !called {
|
||||
Role::Unit
|
||||
} else {
|
||||
Role::Variable
|
||||
}
|
||||
@@ -150,7 +145,6 @@ pub fn highlight(source: &str, accepts_reducers: bool) -> Vec<Highlight> {
|
||||
(Some(NameUse::Local | NameUse::LocalFunction), _) => None,
|
||||
(_, Role::Function) => function_tooltip(bare),
|
||||
(_, Role::Matrix) => (bare == "I").then(identity_tooltip),
|
||||
(_, Role::Unit) => unit_named(bare).map(unit_tooltip),
|
||||
_ => Constant::from_name(bare).map(constant_tooltip),
|
||||
};
|
||||
highlights.push(Highlight {
|
||||
@@ -211,10 +205,6 @@ pub fn highlight(source: &str, accepts_reducers: bool) -> Vec<Highlight> {
|
||||
});
|
||||
}
|
||||
Token::DotDot => highlights.push(plain(start, end, Role::MatrixLiteral)),
|
||||
Token::Percent => highlights.push(Highlight {
|
||||
tooltip: unit_named("%").map(unit_tooltip),
|
||||
..plain(start, end, Role::Unit)
|
||||
}),
|
||||
Token::Error(_) => highlights.push(plain(start, end, Role::Error)),
|
||||
_ => highlights.push(Highlight {
|
||||
tooltip: operator,
|
||||
@@ -438,7 +428,7 @@ mod tests {
|
||||
|
||||
// A matrix's name applied to an argument is its product, and a matrix literal's separators are told from a call's
|
||||
assert_eq!(
|
||||
read("[a, b; c] max(a, b) M(v) 1..5 \\pi θ Δx q@"),
|
||||
read("[a, b; c] max(a, b) M(v) 1..5 \\pi θ Δx m@"),
|
||||
[
|
||||
("[", MatrixLiteral, 0, None),
|
||||
("a", Variable, 0, None),
|
||||
@@ -463,7 +453,7 @@ mod tests {
|
||||
("\\pi", Variable, 0, None),
|
||||
("θ", Variable, 0, None),
|
||||
("Δx", Matrix, 0, None),
|
||||
("q", Variable, 0, None),
|
||||
("m", Variable, 0, None),
|
||||
("@", Error, 0, None),
|
||||
]
|
||||
);
|
||||
@@ -740,38 +730,4 @@ mod tests {
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn units_are_upright_and_documented() {
|
||||
let roles = |source: &str| {
|
||||
highlight(source, false)
|
||||
.into_iter()
|
||||
.map(|highlight| (source[highlight.start..highlight.end].to_string(), highlight.role))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(
|
||||
roles("5mm + 50% + 45° + 5'6\""),
|
||||
[
|
||||
("5".to_string(), Role::Number),
|
||||
("mm".to_string(), Role::Unit),
|
||||
("+".to_string(), Role::Operator),
|
||||
("50".to_string(), Role::Number),
|
||||
("%".to_string(), Role::Unit),
|
||||
("+".to_string(), Role::Operator),
|
||||
("45".to_string(), Role::Number),
|
||||
("°".to_string(), Role::Unit),
|
||||
("+".to_string(), Role::Operator),
|
||||
("5".to_string(), Role::Number),
|
||||
("'".to_string(), Role::Unit),
|
||||
("6".to_string(), Role::Number),
|
||||
("\"".to_string(), Role::Unit),
|
||||
]
|
||||
);
|
||||
// A definition of a unit's spelling makes it a variable
|
||||
assert_eq!(roles("2m where m = 3")[1].1, Role::Variable);
|
||||
|
||||
let tooltip = highlight("5mm", false)[1].tooltip.clone().unwrap();
|
||||
assert_eq!(tooltip.label, "Millimeter");
|
||||
assert_eq!(tooltip.description, "A unit of length. Also written `millimeter` or `millimeters`.");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
use crate::quaternion::Quaternion;
|
||||
use crate::units::unit_named;
|
||||
use crate::value::{Complex, Number};
|
||||
use chumsky::input::{Input, ValueInput};
|
||||
use chumsky::span::SimpleSpan;
|
||||
@@ -34,7 +33,7 @@ pub enum Token<'src> {
|
||||
DotDot,
|
||||
Plus,
|
||||
Minus,
|
||||
/// The percent unit, which only follows the number it is a percentage of.
|
||||
/// Reserved for percentages, so the parser never matches it and its error points a C-style remainder to `mod(a, b)`.
|
||||
Percent,
|
||||
Star,
|
||||
Slash,
|
||||
@@ -222,16 +221,14 @@ fn keyword(word: &str) -> Option<Token<'static>> {
|
||||
KEYWORDS.into_iter().find_map(|(spelling, token)| (word == spelling).then_some(token))
|
||||
}
|
||||
|
||||
/// Whether a name is a matrix's by the case rule: an uppercase-initial identifier, read after the `\` prefix, other than the
|
||||
/// spelling of a unit like `Hz`.
|
||||
/// Whether a name is a matrix's by the case rule: an uppercase-initial identifier, read after the `\` prefix.
|
||||
#[inline]
|
||||
pub fn names_matrix(name: &str) -> bool {
|
||||
let name = name.strip_prefix('\\').unwrap_or(name);
|
||||
let uppercase = match name.as_bytes().first() {
|
||||
match name.as_bytes().first() {
|
||||
Some(byte) if byte.is_ascii() => byte.is_ascii_uppercase(),
|
||||
_ => name.starts_with(char::is_uppercase),
|
||||
};
|
||||
uppercase && unit_named(name).is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an operand has just ended after the token, given whether one had before it. A `!` leaves that as it was, since a factorial
|
||||
@@ -245,15 +242,9 @@ pub(crate) fn operand_ended(token: &Token, after_operand: bool) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a character ends an operand: a name, a number, a closing parenthesis, brace, or bracket, the `∞` literal, or a
|
||||
/// unit symbol that isn't a letter.
|
||||
/// Whether a character ends an operand: a name, a number, a closing parenthesis, brace, or bracket, or the `∞` literal.
|
||||
fn ends_operand(c: char) -> bool {
|
||||
c.is_alphanumeric() || unicode_ident::is_xid_continue(c) || matches!(c, '.' | ')' | '}' | ']' | '∞') || is_unit_symbol(c)
|
||||
}
|
||||
|
||||
/// Whether a character is a whole unit spelled by a symbol rather than letters: degrees, feet, inches, or percent.
|
||||
pub(crate) fn is_unit_symbol(c: char) -> bool {
|
||||
matches!(c, '°' | '\'' | '"' | '%')
|
||||
c.is_alphanumeric() || unicode_ident::is_xid_continue(c) || matches!(c, '.' | ')' | '}' | ']' | '∞')
|
||||
}
|
||||
|
||||
/// Reads every `|` in the source up front, since each depends on what precedes it: a bar opens a magnitude where an operand
|
||||
@@ -548,9 +539,6 @@ impl<'a> Lexer<'a> {
|
||||
// A symbol can't be a name, so unlike `inf`, no binding can shadow `∞`
|
||||
'∞' => Float(f64::INFINITY),
|
||||
|
||||
// The units spelled by a symbol rather than letters read as names, like `deg`, `ft`, and `in`
|
||||
'°' | '\'' | '"' => Ident(&self.input[start..self.pos]),
|
||||
|
||||
// Typeset math symbol aliases
|
||||
'∧' => AndAnd,
|
||||
'∨' => OrOr,
|
||||
|
||||
@@ -9,16 +9,11 @@ pub mod lexer;
|
||||
pub mod matrix;
|
||||
pub mod object;
|
||||
pub mod parser;
|
||||
pub mod quantity;
|
||||
pub mod quaternion;
|
||||
pub mod reducer;
|
||||
pub mod sort;
|
||||
pub mod units;
|
||||
pub mod value;
|
||||
|
||||
#[cfg(test)]
|
||||
mod units_tests;
|
||||
|
||||
use context::EvalContext;
|
||||
use executer::EvalError;
|
||||
use object::Object;
|
||||
@@ -73,7 +68,7 @@ mod tests {
|
||||
#[test]
|
||||
fn percent_is_not_the_remainder() {
|
||||
// `%` is reserved for percentages, so a C-style remainder is a parse error naming the function that computes it
|
||||
for input in ["5 % 3", "x % 2", "%", "50% 2", "5 + %"] {
|
||||
for input in ["5 % 3", "x % 2", "%", "50%"] {
|
||||
let error = evaluate(input).unwrap_err().to_string();
|
||||
assert!(error.contains("`mod(a, b)`"), "`{input}` gave the error `{error}`");
|
||||
}
|
||||
@@ -95,7 +90,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn error_spans_begin_at_the_token() {
|
||||
for (input, expected) in [("7 % 3", "at 2..3"), ("x if 1", "at 3..5")] {
|
||||
for (input, expected) in [("2 %", "at 2..3"), ("x if 1", "at 3..5")] {
|
||||
let error = evaluate(input).unwrap_err().to_string();
|
||||
assert!(error.ends_with(expected), "`{input}` gave the error `{error}`");
|
||||
}
|
||||
@@ -125,11 +120,7 @@ mod tests {
|
||||
assert_eq!(message("`abc").span(), Some(0..4));
|
||||
assert_eq!(
|
||||
message("7 % 3").parts(),
|
||||
[
|
||||
Code("%".into()),
|
||||
Text(" makes the number before it a percentage, so the remainder is written ".into()),
|
||||
Code("mod(a, b)".into()),
|
||||
]
|
||||
[Code("%".into()), Text(" is reserved for percentages, so the remainder is written ".into()), Code("mod(a, b)".into()),]
|
||||
);
|
||||
assert_eq!(message("7 % 3").span(), Some(2..3));
|
||||
assert_eq!(message("sin(I)").parts(), [Text("A matrix stands where a value is needed".into())]);
|
||||
@@ -177,11 +168,10 @@ mod tests {
|
||||
let negations = format!("{}1", "-".repeat(127));
|
||||
// Each matrix in a product is evaluated a level deeper than the last, with the largest frames of any chain
|
||||
let product = format!("{}1", "I ".repeat(127));
|
||||
let measures = format!("1mm{}", " / 2mm".repeat(42));
|
||||
let nested = format!("{}1{}", "(".repeat(32), ")".repeat(32));
|
||||
let bindings = (0..99).map(|n| format!("a{n} = I a{}", n + 1)).collect::<Vec<_>>().join(", ");
|
||||
let bindings = format!("a0 where {bindings}, a99 = 1");
|
||||
for source in [&sum, &negations, &product, &measures, &nested, &bindings] {
|
||||
for source in [&sum, &negations, &product, &nested, &bindings] {
|
||||
assert!(evaluate(source).is_ok(), "`{source}` should be read");
|
||||
highlight::highlight(source, false);
|
||||
completion::completions(source, source.len(), true);
|
||||
@@ -999,8 +989,8 @@ mod tests {
|
||||
|
||||
// Storage is never observable, so a value compares by its four parts and a matrix by its twenty entries, with infinities matched exactly
|
||||
let entries = |object: &Object| match object {
|
||||
Object::Value(quantity) => quantity.number().to_quaternion().parts().to_vec(),
|
||||
Object::Matrix(matrix) => matrix.matrix.rows.iter().chain([&matrix.matrix.translation]).flat_map(|row| row.parts()).collect::<Vec<f64>>(),
|
||||
Object::Value(Value::Number(number)) => number.to_quaternion().parts().to_vec(),
|
||||
Object::Matrix(matrix) => matrix.rows.iter().chain([&matrix.translation]).flat_map(|row| row.parts()).collect::<Vec<f64>>(),
|
||||
};
|
||||
assert!(actual.as_matrix().is_some() == expected.as_matrix().is_some(), "`{input}`: expected {expected}, got {actual}");
|
||||
if let (Some(actual), Some(expected)) = (actual.as_matrix(), expected.as_matrix()) {
|
||||
@@ -1840,7 +1830,7 @@ mod tests {
|
||||
#[test]
|
||||
fn smoothstep_eases_along_a_rotated_box() {
|
||||
// The parameter is read in the box's own frame, so the ease follows a rotated box's axes and lands on the parameter's
|
||||
let Value::Number(number) = evaluate("smoothstep(-0.5i + 0.25j, rotation(pi/2) (0..(i + j)))").unwrap().unwrap().as_value().unwrap();
|
||||
let Value::Number(number) = *evaluate("smoothstep(-0.5i + 0.25j, rotation(pi/2) (0..(i + j)))").unwrap().unwrap().as_value().unwrap();
|
||||
for (part, expected) in number.to_quaternion().parts().into_iter().zip([0., 0.15625, 0.5, 0.]) {
|
||||
assert!((part - expected).abs() < 1e-12, "{part} against {expected}");
|
||||
}
|
||||
|
||||
@@ -1,21 +1,20 @@
|
||||
use crate::matrix::Matrix;
|
||||
use crate::quantity::{MatrixQuantity, Quantity};
|
||||
use crate::value::Value;
|
||||
use std::fmt;
|
||||
|
||||
/// What an expression evaluates to, one of the language's two sorts: a value or a matrix, each with the units it is measured in.
|
||||
/// The matrix is boxed so that a value, the common case, stays small.
|
||||
/// What an expression evaluates to, one of the language's two sorts: a value or a matrix. The matrix is boxed so that a
|
||||
/// value, the common case, stays small.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Object {
|
||||
Value(Quantity),
|
||||
Matrix(Box<MatrixQuantity>),
|
||||
Value(Value),
|
||||
Matrix(Box<Matrix>),
|
||||
}
|
||||
|
||||
/// Generates readers that see a value's parts read as a plain number and nothing of a matrix.
|
||||
/// Generates readers that see a value's parts and nothing of a matrix.
|
||||
macro_rules! value_readers {
|
||||
($($fn_name:ident: $type:ty),* $(,)?) => {
|
||||
$(
|
||||
#[doc = concat!("Reads the object as [`Value::", stringify!($fn_name), "`] does once read as a plain number, or `None` for a matrix or a value with a dimension other than an angle.")]
|
||||
#[doc = concat!("Reads the object as [`Value::", stringify!($fn_name), "`] does, or `None` for a matrix.")]
|
||||
pub fn $fn_name(&self) -> Option<$type> {
|
||||
self.as_value()?.$fn_name()
|
||||
}
|
||||
@@ -24,44 +23,36 @@ macro_rules! value_readers {
|
||||
}
|
||||
|
||||
impl Object {
|
||||
/// The value with its unit, or `None` for a matrix.
|
||||
#[inline]
|
||||
pub fn as_quantity(&self) -> Option<&Quantity> {
|
||||
pub fn as_value(&self) -> Option<&Value> {
|
||||
match self {
|
||||
Self::Value(quantity) => Some(quantity),
|
||||
Self::Value(value) => Some(value),
|
||||
Self::Matrix(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The value read as a plain number, as [`Quantity::as_plain`] reads it, or `None` for a matrix.
|
||||
#[inline]
|
||||
pub fn as_value(&self) -> Option<Value> {
|
||||
self.as_quantity()?.as_plain()
|
||||
}
|
||||
|
||||
/// The matrix with its units, or `None` for a value.
|
||||
#[inline]
|
||||
pub fn as_matrix_quantity(&self) -> Option<&MatrixQuantity> {
|
||||
pub fn as_matrix(&self) -> Option<&Matrix> {
|
||||
match self {
|
||||
Self::Value(_) => None,
|
||||
Self::Matrix(matrix) => Some(matrix),
|
||||
}
|
||||
}
|
||||
|
||||
/// The matrix, or `None` for a value or a matrix with units.
|
||||
#[inline]
|
||||
pub fn as_matrix(&self) -> Option<Matrix> {
|
||||
self.as_matrix_quantity().filter(|matrix| matrix.is_plain()).map(|matrix| matrix.matrix)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn into_value(self) -> Option<Value> {
|
||||
self.as_value()
|
||||
match self {
|
||||
Self::Value(value) => Some(value),
|
||||
Self::Matrix(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn into_matrix(self) -> Option<Matrix> {
|
||||
self.as_matrix()
|
||||
match self {
|
||||
Self::Value(_) => None,
|
||||
Self::Matrix(matrix) => Some(*matrix),
|
||||
}
|
||||
}
|
||||
|
||||
value_readers! {
|
||||
@@ -83,24 +74,12 @@ impl Object {
|
||||
|
||||
impl<T: Into<Value>> From<T> for Object {
|
||||
fn from(value: T) -> Self {
|
||||
Self::Value(Quantity::plain(value.into()))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Quantity> for Object {
|
||||
fn from(quantity: Quantity) -> Self {
|
||||
Self::Value(quantity)
|
||||
Self::Value(value.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Matrix> for Object {
|
||||
fn from(matrix: Matrix) -> Self {
|
||||
Self::Matrix(Box::new(MatrixQuantity::plain(matrix)))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<MatrixQuantity> for Object {
|
||||
fn from(matrix: MatrixQuantity) -> Self {
|
||||
Self::Matrix(Box::new(matrix))
|
||||
}
|
||||
}
|
||||
@@ -108,7 +87,7 @@ impl From<MatrixQuantity> for Object {
|
||||
impl fmt::Display for Object {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Value(quantity) => quantity.fmt(f),
|
||||
Self::Value(value) => value.fmt(f),
|
||||
Self::Matrix(matrix) => matrix.fmt(f),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ use crate::ast::{BinaryOp, Binding, CallWhere, Case, Literal, Node, Syntax, Unar
|
||||
use crate::context::{FunctionProvider, NothingMap};
|
||||
use crate::lexer::{LexError, Lexer, Span, Token};
|
||||
use crate::sort::sorted;
|
||||
use crate::units::unit_named;
|
||||
use chumsky::cache::{Cache, Cached};
|
||||
use chumsky::error::{EmptyErr, LabelError, RichPattern, RichReason};
|
||||
use chumsky::input::ValueInput;
|
||||
@@ -298,7 +297,7 @@ fn parse(src: &str) -> Result<Syntax<'_>, ParseError> {
|
||||
let after_operand = e.expected().any(|pattern| matches!(pattern, RichPattern::Token(token) if **token == Token::EqEq));
|
||||
|
||||
match e.found() {
|
||||
Some(Token::Percent) => ErrorMessage::from_prose("`%` follows the number it makes a percentage, like `50%`, so the remainder is written `mod(a, b)`").at(e.span()),
|
||||
Some(Token::Percent) => ErrorMessage::from_prose("`%` is reserved for percentages, so the remainder is written `mod(a, b)`").at(e.span()),
|
||||
Some(Token::If) => ErrorMessage::from_prose("`if` joins a case's value to its condition, like `{a if x > 0, b otherwise}`").at(e.span()),
|
||||
Some(Token::Otherwise) => ErrorMessage::from_prose("`otherwise` ends the one case with no condition, like `{a if x > 0, b otherwise}`").at(e.span()),
|
||||
Some(Token::Equals) if after_operand => ErrorMessage::from_prose("`=` names a value in a `where` clause, so equality is written `==`").at(e.span()),
|
||||
@@ -369,128 +368,6 @@ where
|
||||
}
|
||||
|
||||
/// The expression, within the names its `where` clause defines if it has one.
|
||||
/// A factor of a product chain after the first, with the operator before it, whether that operator is juxtaposition, and where
|
||||
/// the factor stands.
|
||||
#[derive(Clone)]
|
||||
struct ProductLink<'src> {
|
||||
op: BinaryOp,
|
||||
factor: Syntax<'src>,
|
||||
implicit: bool,
|
||||
span: Span,
|
||||
}
|
||||
|
||||
/// Whether a factor is a unit by its spelling, or a power of one like `mm^2`.
|
||||
fn is_unit(syntax: &Syntax) -> bool {
|
||||
match syntax {
|
||||
Syntax::Var(name) => unit_named(name).is_some(),
|
||||
Syntax::BinOp { lhs, op: BinaryOp::Pow, .. } => is_unit(lhs),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a factor spells a unit anywhere in its arithmetic, like `10mm` or `(1mm + 2mm)`, though not within a call.
|
||||
fn spells_unit(syntax: &Syntax) -> bool {
|
||||
match syntax {
|
||||
Syntax::BinOp { lhs, rhs, .. } => is_unit(syntax) || spells_unit(lhs) || spells_unit(rhs),
|
||||
Syntax::UnaryOp { expr, .. } => spells_unit(expr),
|
||||
Syntax::Product { first, rest } => spells_unit(first) || rest.iter().any(|(_, factor)| spells_unit(factor)),
|
||||
Syntax::Measure { .. } => true,
|
||||
_ => is_unit(syntax),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a factor is a number literal, signed or not.
|
||||
fn is_number(syntax: &Syntax) -> bool {
|
||||
match syntax {
|
||||
Syntax::Lit(_) => true,
|
||||
Syntax::UnaryOp {
|
||||
op: UnaryOp::Neg | UnaryOp::Pos,
|
||||
expr,
|
||||
} => is_number(expr),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn juxtaposed<'src>(lhs: Syntax<'src>, rhs: Syntax<'src>) -> Syntax<'src> {
|
||||
Syntax::BinOp {
|
||||
lhs: Box::new(lhs),
|
||||
op: BinaryOp::Mul,
|
||||
rhs: Box::new(rhs),
|
||||
}
|
||||
}
|
||||
|
||||
/// Groups the units of a product chain as they read. After a `/`, a number juxtaposed with units is a [`Syntax::Measure`], which
|
||||
/// evaluation divides by as the dividend's units decide, though a percentage like `50%` is always one divisor. Feet then inches
|
||||
/// like `5'6"` sum, and a factor juxtaposed after a percentage's `%` is reported, since `7 % 3` is likely a remainder.
|
||||
fn group_units<'src>(first: Syntax<'src>, links: Vec<ProductLink<'src>>, mut report: impl FnMut(Span, &'static str)) -> (Syntax<'src>, Vec<(BinaryOp, Syntax<'src>)>) {
|
||||
// A chain spelling no unit, the common case, has nothing to group
|
||||
if !links.iter().any(|link| spells_unit(&link.factor)) {
|
||||
return (first, links.into_iter().map(|link| (link.op, link.factor)).collect());
|
||||
}
|
||||
|
||||
for pair in links.windows(2) {
|
||||
if matches!(pair[0].factor, Syntax::Var("%")) && pair[1].implicit {
|
||||
report(pair[0].span, "`%` makes the number before it a percentage, so the remainder is written `mod(a, b)`");
|
||||
}
|
||||
}
|
||||
|
||||
let mut factors: Vec<(BinaryOp, Syntax<'src>, bool)> = std::iter::once((BinaryOp::Mul, first, false))
|
||||
.chain(links.into_iter().map(|link| (link.op, link.factor, link.implicit)))
|
||||
.collect();
|
||||
|
||||
// Feet then inches written together are their sum
|
||||
let mut index = 0;
|
||||
while index + 3 < factors.len() {
|
||||
if let [(op, feet, implicit), (_, Syntax::Var("'"), true), (_, inches @ Syntax::Lit(_), true), (_, Syntax::Var("\""), true)] = &factors[index..index + 4]
|
||||
&& is_number(feet)
|
||||
{
|
||||
// A sign before the feet applies to the whole measurement, so `-5'6"` is `-66in`
|
||||
let (sign, feet) = match feet {
|
||||
Syntax::UnaryOp {
|
||||
op: op @ (UnaryOp::Neg | UnaryOp::Pos),
|
||||
expr,
|
||||
} => (Some(*op), (**expr).clone()),
|
||||
feet => (None, feet.clone()),
|
||||
};
|
||||
let mut sum = Syntax::BinOp {
|
||||
lhs: Box::new(juxtaposed(feet, Syntax::Var("'"))),
|
||||
op: BinaryOp::Add,
|
||||
rhs: Box::new(juxtaposed(inches.clone(), Syntax::Var("\""))),
|
||||
};
|
||||
if let Some(op) = sign {
|
||||
sum = Syntax::UnaryOp { op, expr: Box::new(sum) };
|
||||
}
|
||||
let (op, implicit) = (*op, *implicit);
|
||||
factors.splice(index..index + 4, [(op, sum, implicit)]);
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
|
||||
// A number after a `/` and the units juxtaposed after it form a measure
|
||||
let mut index = 1;
|
||||
while index + 1 < factors.len() {
|
||||
let numbered_divisor = factors[index].0 == BinaryOp::Div && is_number(&factors[index].1);
|
||||
if numbered_divisor && factors[index + 1].2 && is_unit(&factors[index + 1].1) {
|
||||
let end = (index + 1..factors.len()).find(|&end| !(factors[end].2 && is_unit(&factors[end].1))).unwrap_or(factors.len());
|
||||
let mut measure = factors.drain(index..end).map(|(_, factor, _)| factor);
|
||||
let number = measure.next().unwrap_or(Syntax::Lit(Literal::Integer(1)));
|
||||
let units: Vec<Syntax<'src>> = measure.collect();
|
||||
|
||||
let divisor = if matches!(units.first(), Some(Syntax::Var("%"))) {
|
||||
units.into_iter().fold(number, juxtaposed)
|
||||
} else {
|
||||
Syntax::Measure { number: Box::new(number), units }
|
||||
};
|
||||
factors.insert(index, (BinaryOp::Div, divisor, false));
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
|
||||
let mut factors = factors.into_iter().map(|(op, factor, _)| (op, factor));
|
||||
let first = factors.next().map_or(Syntax::Lit(Literal::Integer(1)), |(_, first)| first);
|
||||
(first, factors.collect())
|
||||
}
|
||||
|
||||
fn with_bindings<'src>((body, bindings): (Syntax<'src>, Option<Vec<Binding<'src>>>)) -> Syntax<'src> {
|
||||
match bindings {
|
||||
Some(bindings) => Syntax::Where { body: Box::new(body), bindings },
|
||||
@@ -618,21 +495,11 @@ where
|
||||
|
||||
// Juxtaposed factors like `2pi` or `2sqrt(4)` multiply implicitly at the same precedence as `*` and `/`.
|
||||
// The implicit operand is a `pow`, not a full unary, so `2 -3` stays a subtraction; the lexer rejects a number right after another number (`10 000` is not `10*000`).
|
||||
let implicit_mul = pow.map(|rhs| (BinaryOp::Mul, rhs, true));
|
||||
// A `%` after a factor makes it a percentage, the factor times the percent unit
|
||||
let percent = just(Token::Percent).to((BinaryOp::Mul, Syntax::Var("%"), true));
|
||||
let link = choice((mul_op.then(unary.clone()).map(|(op, factor)| (op, factor, false)), percent, implicit_mul)).map_with(|(op, factor, implicit), extra| ProductLink {
|
||||
op,
|
||||
factor,
|
||||
implicit,
|
||||
span: extra.span(),
|
||||
});
|
||||
let implicit_mul = pow.map(|rhs| (BinaryOp::Mul, rhs));
|
||||
let product = unary
|
||||
.clone()
|
||||
.then(link.repeated().collect::<Vec<_>>())
|
||||
.validate(|(first, links): (Syntax<'src>, Vec<ProductLink<'src>>), _, emitter| {
|
||||
let (first, mut rest) = group_units(first, links, |span, message| emitter.emit(CustomError::custom(span, message)));
|
||||
|
||||
.then(choice((mul_op.then(unary), implicit_mul)).repeated().collect::<Vec<_>>())
|
||||
.map(|(first, mut rest): (Syntax<'src>, Vec<(BinaryOp, Syntax<'src>)>)| {
|
||||
// Two factors group only one way, while a longer chain is grouped by the sort pass, which knows the matrices
|
||||
if rest.len() <= 1 {
|
||||
return match rest.pop() {
|
||||
|
||||
@@ -1,913 +0,0 @@
|
||||
//! Values and matrices with the units they are measured in, and the arithmetic that carries units through every operation and
|
||||
//! builtin, so the builtins themselves only ever see plain numbers.
|
||||
|
||||
use crate::ast::{BinaryOp, UnaryOp};
|
||||
use crate::constants::BuiltinFunction;
|
||||
use crate::executer::{EvalError, UnitMismatch};
|
||||
use crate::matrix::Matrix;
|
||||
use crate::quaternion::Quaternion;
|
||||
use crate::units::{Dimension, Size, Unit, UnitError, UnitId, common_unit};
|
||||
use crate::value::{Number, Value};
|
||||
use std::fmt;
|
||||
|
||||
/// A value with the unit it is measured in, which is [`Unit::NONE`] for a plain number.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Quantity {
|
||||
pub value: Value,
|
||||
pub unit: Unit,
|
||||
}
|
||||
|
||||
impl Quantity {
|
||||
#[inline(always)]
|
||||
pub const fn plain(value: Value) -> Self {
|
||||
Self { value, unit: Unit::NONE }
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub const fn new(value: Value, unit: Unit) -> Self {
|
||||
Self { value, unit }
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn of_number(number: Number, unit: Unit) -> Self {
|
||||
Self::new(Value::Number(number), unit)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn number(self) -> Number {
|
||||
let Value::Number(number) = self.value;
|
||||
number
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn is_plain(self) -> bool {
|
||||
self.unit.is_none()
|
||||
}
|
||||
|
||||
pub fn dimension(self) -> Dimension {
|
||||
self.unit.dimension()
|
||||
}
|
||||
|
||||
/// Converts the value into `unit`, which must measure the same dimension, or is an error. A plain value converts only into no unit.
|
||||
pub fn convert(self, unit: Unit, pixels_per_inch: f64) -> Result<Value, UnitError> {
|
||||
let factor = self.unit.conversion(unit)?;
|
||||
factor.apply(self.number(), pixels_per_inch).map(Value::Number).ok_or(UnitError::Overflow)
|
||||
}
|
||||
|
||||
/// Reads the value in `unit` as a host field reads what was typed into it: a plain value is taken as already in `unit`, and
|
||||
/// one with a unit converts from it.
|
||||
pub fn read_in(self, unit: Unit, pixels_per_inch: f64) -> Result<Value, UnitError> {
|
||||
if self.is_plain() {
|
||||
return Ok(self.value);
|
||||
}
|
||||
self.convert(unit, pixels_per_inch)
|
||||
}
|
||||
|
||||
/// Reads the value as a plain number: a dimensionless unit like `%` converts out, and an angle reads in radians, or `None` for
|
||||
/// any other dimension.
|
||||
pub fn as_plain(self) -> Option<Value> {
|
||||
match self.dimension() {
|
||||
Dimension::NONE => self.convert(Unit::NONE, 0.).ok(),
|
||||
Dimension::ANGLE => self.convert(radians(), 0.).ok(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The value with any dimensionless unit like `%` converted out, so it can stand where a plain number is needed.
|
||||
pub(crate) fn plain_if_dimensionless(self) -> Self {
|
||||
if self.unit.is_dimensionless() {
|
||||
return self.convert(Unit::NONE, 0.).map(Self::plain).unwrap_or(self);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
fn is_zero(self) -> bool {
|
||||
self.number() == Number::Integer(0)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Quantity {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
if self.unit.is_none() {
|
||||
return self.value.fmt(f);
|
||||
}
|
||||
|
||||
// A unit with only a denominator reads after the number's own `/`, like `5/s`
|
||||
let unit = self.unit.to_string();
|
||||
let unit = unit.strip_prefix("1/").map(|denominator| format!("/{denominator}")).unwrap_or(unit);
|
||||
let separator = if self.unit.attaches_without_space() || unit.starts_with('/') { "" } else { " " };
|
||||
|
||||
// A value with several parts is grouped, so the unit applies to the whole of it
|
||||
match self.number() {
|
||||
Number::Complex(_) | Number::Quaternion(_) => write!(f, "({}){separator}{unit}", self.value),
|
||||
_ => write!(f, "{}{separator}{unit}", self.value),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) const fn radians() -> Unit {
|
||||
Unit::of(UnitId::RADIAN)
|
||||
}
|
||||
|
||||
/// Converts a number by a unit conversion factor.
|
||||
fn scaled(number: Number, size: Size, pixels_per_inch: f64) -> Result<Number, EvalError> {
|
||||
if size.is_one() {
|
||||
return Ok(number);
|
||||
}
|
||||
size.apply(number, pixels_per_inch).ok_or(EvalError::UnitOverflow)
|
||||
}
|
||||
|
||||
fn unit_error(error: UnitError, left: Unit, right: Unit, verb: &'static str) -> EvalError {
|
||||
match error {
|
||||
UnitError::Overflow => EvalError::UnitOverflow,
|
||||
UnitError::FractionalPower => EvalError::from(UnitMismatch::FractionalUnitPower(left.to_string())),
|
||||
UnitError::Incompatible if left.is_none() || right.is_none() => EvalError::from(UnitMismatch::PlainWithUnit {
|
||||
verb,
|
||||
unit: if left.is_none() { right } else { left }.to_string(),
|
||||
}),
|
||||
UnitError::Incompatible => EvalError::from(UnitMismatch::IncompatibleUnits {
|
||||
verb,
|
||||
left: left.to_string(),
|
||||
right: right.to_string(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Two operands in one unit, for a sum or a comparison: the unit a sum of theirs is measured in, where a plain zero takes the
|
||||
/// other's unit, as zero is the same in every unit, while any other plain number can't mix with a unit.
|
||||
fn in_common_unit(lhs: Quantity, rhs: Quantity, verb: &'static str, pixels_per_inch: f64) -> Result<(Number, Number, Unit), EvalError> {
|
||||
if lhs.unit == rhs.unit {
|
||||
return Ok((lhs.number(), rhs.number(), lhs.unit));
|
||||
}
|
||||
if lhs.is_plain() && lhs.is_zero() {
|
||||
return Ok((lhs.number(), rhs.number(), rhs.unit));
|
||||
}
|
||||
if rhs.is_plain() && rhs.is_zero() {
|
||||
return Ok((lhs.number(), rhs.number(), lhs.unit));
|
||||
}
|
||||
if lhs.is_plain() || rhs.is_plain() {
|
||||
let unit = if lhs.is_plain() { rhs.unit } else { lhs.unit };
|
||||
return Err(EvalError::from(UnitMismatch::PlainWithUnit { verb, unit: unit.to_string() }));
|
||||
}
|
||||
if lhs.dimension() != rhs.dimension() {
|
||||
return Err(unit_error(UnitError::Incompatible, lhs.unit, rhs.unit, verb));
|
||||
}
|
||||
|
||||
let unit = common_unit(lhs.unit, rhs.unit, pixels_per_inch);
|
||||
let convert = |operand: Quantity| -> Result<Number, EvalError> {
|
||||
let factor = operand.unit.conversion(unit).map_err(|error| unit_error(error, operand.unit, unit, verb))?;
|
||||
scaled(operand.number(), factor, pixels_per_inch)
|
||||
};
|
||||
Ok((convert(lhs)?, convert(rhs)?, unit))
|
||||
}
|
||||
|
||||
/// Brings any count of operands into the unit a sum of them would be measured in, as `min`, `max`, and the statistics take them.
|
||||
pub(crate) fn all_in_common_unit(operands: &[Quantity], verb: &'static str, pixels_per_inch: f64) -> Result<(Vec<Value>, Unit), EvalError> {
|
||||
if operands.iter().all(|operand| operand.is_plain()) {
|
||||
return Ok((operands.iter().map(|operand| operand.value).collect(), Unit::NONE));
|
||||
}
|
||||
|
||||
// A plain zero takes whatever unit the others share
|
||||
let mut common: Option<Unit> = None;
|
||||
for operand in operands.iter().filter(|operand| !(operand.is_plain() && operand.is_zero())) {
|
||||
common = Some(match common {
|
||||
None => operand.unit,
|
||||
Some(unit) if unit.is_none() != operand.is_plain() => {
|
||||
let unit = if operand.is_plain() { unit } else { operand.unit };
|
||||
return Err(EvalError::from(UnitMismatch::PlainWithUnit { verb, unit: unit.to_string() }));
|
||||
}
|
||||
Some(unit) if unit.dimension() != operand.dimension() => return Err(unit_error(UnitError::Incompatible, unit, operand.unit, verb)),
|
||||
Some(unit) => common_unit(unit, operand.unit, pixels_per_inch),
|
||||
});
|
||||
}
|
||||
let unit = common.unwrap_or(Unit::NONE);
|
||||
|
||||
let values = operands
|
||||
.iter()
|
||||
.map(|operand| into_region_unit(*operand, unit, pixels_per_inch).map(Value::Number))
|
||||
.collect::<Result<Vec<Value>, EvalError>>()?;
|
||||
Ok((values, unit))
|
||||
}
|
||||
|
||||
/// A binary operation over quantities. Sums and comparisons bring both into one unit, products multiply their units, and a
|
||||
/// power raises its base's unit, while logic takes only plain truth values.
|
||||
#[inline]
|
||||
pub(crate) fn binary_op(lhs: Quantity, op: BinaryOp, rhs: Quantity, pixels_per_inch: f64) -> Result<Quantity, EvalError> {
|
||||
// Plain numbers skip the unit arithmetic, the common case
|
||||
if lhs.is_plain() && rhs.is_plain() {
|
||||
return plain_binary_op(lhs.number(), op, rhs.number()).map(|number| Quantity::of_number(number, Unit::NONE));
|
||||
}
|
||||
unit_binary_op(lhs, op, rhs, pixels_per_inch)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn plain_binary_op(lhs: Number, op: BinaryOp, rhs: Number) -> Result<Number, EvalError> {
|
||||
// Logic rejects operands that aren't truth values, while the other operators reject operand types they don't support
|
||||
let rejected = if matches!(op, BinaryOp::And | BinaryOp::Or) {
|
||||
EvalError::NotATruthValue
|
||||
} else {
|
||||
EvalError::OperatorTypeError
|
||||
};
|
||||
lhs.binary_op(op, rhs).ok_or(rejected)
|
||||
}
|
||||
|
||||
// Out of line, keeping the plain arithmetic that dominates compact
|
||||
#[inline(never)]
|
||||
pub(crate) fn unit_binary_op(lhs: Quantity, op: BinaryOp, rhs: Quantity, pixels_per_inch: f64) -> Result<Quantity, EvalError> {
|
||||
use BinaryOp as Op;
|
||||
match op {
|
||||
Op::Add | Op::Sub => {
|
||||
let verb = if op == Op::Add { "added to" } else { "subtracted from" };
|
||||
let (lhs, rhs, unit) = in_common_unit(lhs, rhs, verb, pixels_per_inch)?;
|
||||
Ok(Quantity::of_number(plain_binary_op(lhs, op, rhs)?, unit))
|
||||
}
|
||||
Op::Lt | Op::Leq | Op::Gt | Op::Geq | Op::Eq | Op::Neq => {
|
||||
let (lhs, rhs, _) = in_common_unit(lhs, rhs, "compared with", pixels_per_inch)?;
|
||||
Ok(Quantity::of_number(plain_binary_op(lhs, op, rhs)?, Unit::NONE))
|
||||
}
|
||||
Op::Mul | Op::Div => {
|
||||
let rhs_unit = if op == Op::Div { rhs.unit.inverse() } else { rhs.unit };
|
||||
let (unit, scale) = lhs.unit.product(rhs_unit, pixels_per_inch).map_err(|error| unit_error(error, lhs.unit, rhs.unit, "multiplied by"))?;
|
||||
|
||||
// The left operand takes the conversion's numerator and a divisor its denominator, so `1in / 2.54cm` is exactly 1
|
||||
let (numerator, denominator) = scale.split();
|
||||
let (lhs, rhs) = (lhs.number(), rhs.number());
|
||||
if let Some(exact) = exact_integer_product(lhs, op, rhs, scale) {
|
||||
return Ok(Quantity::of_number(exact, unit));
|
||||
}
|
||||
let split = || -> Result<Number, EvalError> {
|
||||
let lhs = scaled(lhs, numerator, pixels_per_inch)?;
|
||||
if op == Op::Div {
|
||||
plain_binary_op(lhs, op, scaled(rhs, denominator, pixels_per_inch)?)
|
||||
} else {
|
||||
scaled(plain_binary_op(lhs, op, rhs)?, denominator.inverse_exact(), pixels_per_inch)
|
||||
}
|
||||
};
|
||||
let number = split()?;
|
||||
|
||||
// Near the limits of f64, scaling first or last may keep a finite result that scaling one operand overflowed
|
||||
if !all_finite(number) && all_finite(lhs) && all_finite(rhs) {
|
||||
let first = plain_binary_op(scaled(lhs, scale, pixels_per_inch)?, op, rhs)?;
|
||||
let last = scaled(plain_binary_op(lhs, op, rhs)?, scale, pixels_per_inch)?;
|
||||
let number = [first, last].into_iter().find(|number| all_finite(*number)).unwrap_or(number);
|
||||
return Ok(Quantity::of_number(number, unit));
|
||||
}
|
||||
Ok(Quantity::of_number(number, unit))
|
||||
}
|
||||
Op::Pow => power(lhs, rhs),
|
||||
Op::And | Op::Or => Err(EvalError::NotATruthValue),
|
||||
}
|
||||
}
|
||||
|
||||
/// A product or quotient of integers times a conversion's ratio, computed in 128 bits where it lands on an integer that fits.
|
||||
fn exact_integer_product(lhs: Number, op: BinaryOp, rhs: Number, scale: Size) -> Option<Number> {
|
||||
let (Number::Integer(lhs), Number::Integer(rhs)) = (lhs, rhs) else { return None };
|
||||
let (numerator, denominator) = scale.rational(0.)?;
|
||||
|
||||
let (dividend, divisor) = match op {
|
||||
BinaryOp::Mul => ((lhs as i128).checked_mul(rhs as i128)?.checked_mul(numerator)?, denominator),
|
||||
_ => ((lhs as i128).checked_mul(numerator)?, (rhs as i128).checked_mul(denominator)?),
|
||||
};
|
||||
if divisor == 0 || dividend % divisor != 0 {
|
||||
return None;
|
||||
}
|
||||
i64::try_from(dividend / divisor).ok().map(Number::Integer)
|
||||
}
|
||||
|
||||
fn all_finite(number: Number) -> bool {
|
||||
number.to_quaternion().parts().iter().all(|part| part.is_finite())
|
||||
}
|
||||
|
||||
/// A power: a plain exponent raises the base's unit, which must land every unit on an integer power, while an exponent in an
|
||||
/// angle unit with no plain part is the rotation `e^(i θ)`, read in radians.
|
||||
fn power(base: Quantity, exponent: Quantity) -> Result<Quantity, EvalError> {
|
||||
let (base, exponent) = (base.plain_if_dimensionless(), exponent.plain_if_dimensionless());
|
||||
|
||||
if !exponent.is_plain() {
|
||||
let in_radians = exponent.convert(radians(), 0.).ok().map(|value| Quantity::plain(value).number());
|
||||
return match in_radians {
|
||||
Some(angle) if base.is_plain() && angle.to_quaternion().w == 0. => plain_binary_op(base.number(), BinaryOp::Pow, angle).map(|number| Quantity::of_number(number, Unit::NONE)),
|
||||
Some(_) => Err(EvalError::AngleExponentWithPlainPart),
|
||||
None => Err(EvalError::from(UnitMismatch::ExponentWithUnits(exponent.unit.to_string()))),
|
||||
};
|
||||
}
|
||||
|
||||
let number = plain_binary_op(base.number(), BinaryOp::Pow, exponent.number())?;
|
||||
if base.is_plain() {
|
||||
return Ok(Quantity::of_number(number, Unit::NONE));
|
||||
}
|
||||
|
||||
// The exponent of a value with units must be real, and raises each unit's power
|
||||
let real_exponent = exponent.number().as_real().ok_or_else(|| EvalError::from(UnitMismatch::FractionalUnitPower(base.unit.to_string())))?;
|
||||
let unit = base.unit.power(real_exponent).map_err(|error| unit_error(error, base.unit, base.unit, "raised to"))?;
|
||||
Ok(Quantity::of_number(number, unit))
|
||||
}
|
||||
|
||||
/// A unary operation over a quantity: signs and the magnitude keep the unit, while the factorial and logic take plain numbers.
|
||||
pub(crate) fn unary_op(operand: Quantity, op: UnaryOp) -> Result<Quantity, EvalError> {
|
||||
let operand = if matches!(op, UnaryOp::Not | UnaryOp::Fac) { operand.plain_if_dimensionless() } else { operand };
|
||||
let rejected = if op == UnaryOp::Not { EvalError::NotATruthValue } else { EvalError::OperatorTypeError };
|
||||
|
||||
match op {
|
||||
UnaryOp::Not if !operand.is_plain() => Err(EvalError::NotATruthValue),
|
||||
UnaryOp::Fac if !operand.is_plain() => Err(EvalError::from(UnitMismatch::UnitsNotAccepted {
|
||||
function: "!".to_string(),
|
||||
unit: operand.unit.to_string(),
|
||||
})),
|
||||
_ => Ok(Quantity::of_number(operand.number().unary_op(op).ok_or(rejected)?, operand.unit)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Compares a chain of quantities, all brought into one unit first.
|
||||
pub(crate) fn comparison_operands(first: Quantity, rest: &[(BinaryOp, Quantity)], pixels_per_inch: f64) -> Result<(Number, Vec<(BinaryOp, Number)>), EvalError> {
|
||||
if first.is_plain() && rest.iter().all(|(_, operand)| operand.is_plain()) {
|
||||
return Ok((first.number(), rest.iter().map(|(op, operand)| (*op, operand.number())).collect()));
|
||||
}
|
||||
|
||||
let operands: Vec<Quantity> = std::iter::once(first).chain(rest.iter().map(|(_, operand)| *operand)).collect();
|
||||
let (values, _) = all_in_common_unit(&operands, "compared with", pixels_per_inch)?;
|
||||
let numbers: Vec<Number> = values.into_iter().map(|Value::Number(number)| number).collect();
|
||||
Ok((numbers[0], rest.iter().map(|(op, _)| *op).zip(numbers[1..].iter().copied()).collect()))
|
||||
}
|
||||
|
||||
/// How a builtin taking values treats their units.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum UnitRule {
|
||||
/// Plain values only, like `ln` or `choose`.
|
||||
Plain,
|
||||
/// Plain values only, since the result would depend on the unit: `floor`, `ceil`, `round`, `trunc`, and `fract`.
|
||||
Rounding,
|
||||
/// Values of one dimension brought into one unit, with the result in it, like `min`, `abs`, `snap`, and `mean`.
|
||||
Preserving,
|
||||
/// Values of one dimension, with a plain result, like `sign`.
|
||||
PreservingToPlain,
|
||||
/// Values of one dimension, with the result in its square: `variance`.
|
||||
Squared,
|
||||
/// Anything, with a plain result: `count`.
|
||||
Count,
|
||||
/// An angle, or a plain value read as radians, with a plain result: the circular functions.
|
||||
Circular,
|
||||
/// Plain values with a result in radians: the inverse circular functions.
|
||||
InverseCircular,
|
||||
/// Coordinates of one dimension with a result in radians: `atan2`.
|
||||
TwoArgumentArctangent,
|
||||
/// A plain value, or an angle with no plain part read as radians: `exp`, the function of the rotation `e^(i θ)`.
|
||||
Exponential,
|
||||
/// The root of the given degree, which must land every unit on an integer power: `sqrt` and `cbrt`.
|
||||
Root(u8),
|
||||
/// A root whose degree is the plain second argument: `root`.
|
||||
RootOfDegree,
|
||||
/// The product of the two arguments' units: `dot` and `cross`.
|
||||
Product,
|
||||
/// Directions, whose units drop: `normalize` and `axis`.
|
||||
Direction,
|
||||
/// The angle between two directions of any units, in radians.
|
||||
AngleBetween,
|
||||
/// A value of any unit, which the result keeps, turned by an angle about a direction: `rotate`.
|
||||
Rotate,
|
||||
/// An angle about a direction, with a plain result: `rotor`.
|
||||
Rotor,
|
||||
/// Two endpoints of one dimension and a plain fraction between them: `lerp`.
|
||||
Interpolate,
|
||||
/// A value of any unit, which the result keeps, against a direction: `project`, `reject`, and `reflect`.
|
||||
FirstArgument,
|
||||
}
|
||||
|
||||
impl UnitRule {
|
||||
/// The unit of the result for plain arguments, which is radians for a function giving an angle.
|
||||
const fn plain_result_unit(self) -> Unit {
|
||||
match self {
|
||||
Self::InverseCircular | Self::TwoArgumentArctangent | Self::AngleBetween => radians(),
|
||||
_ => Unit::NONE,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How a builtin taking values treats their units, or `None` for a name that is no builtin of values.
|
||||
pub fn unit_rule(name: &str) -> Option<UnitRule> {
|
||||
use UnitRule::*;
|
||||
Some(match name {
|
||||
"sin" | "cos" | "tan" | "csc" | "sec" | "cot" => Circular,
|
||||
"asin" | "acos" | "atan" | "acsc" | "asec" | "acot" => InverseCircular,
|
||||
"atan2" => TwoArgumentArctangent,
|
||||
"sinh" | "cosh" | "tanh" | "csch" | "sech" | "coth" | "asinh" | "acosh" | "atanh" | "acsch" | "asech" | "acoth" => Plain,
|
||||
"ln" | "log" | "xor" | "slerp" | "gcd" | "lcm" | "choose" | "pick" => Plain,
|
||||
"exp" => Exponential,
|
||||
"sqrt" => Root(2),
|
||||
"cbrt" => Root(3),
|
||||
"root" => RootOfDegree,
|
||||
"floor" | "ceil" | "round" | "trunc" | "fract" => Rounding,
|
||||
"hypot" | "abs" | "snap" | "mod" | "min" | "max" | "mean" | "median" | "mode" | "geomean" | "harmmean" | "rms" | "stdev" | "stdevpop" | "distance" | "conj" | "perp" => Preserving,
|
||||
"sign" => PreservingToPlain,
|
||||
"variance" | "variancepop" => Squared,
|
||||
"count" => Count,
|
||||
"lerp" => Interpolate,
|
||||
"dot" | "cross" => Product,
|
||||
"normalize" | "axis" => Direction,
|
||||
"angle" => AngleBetween,
|
||||
"rotate" => Rotate,
|
||||
"rotor" => Rotor,
|
||||
"project" | "reject" | "reflect" => FirstArgument,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads an angle argument in radians, taking a plain value as radians already.
|
||||
fn angle_in_radians(function: &str, argument: Quantity) -> Result<Value, EvalError> {
|
||||
let argument = argument.plain_if_dimensionless();
|
||||
if argument.is_plain() {
|
||||
return Ok(argument.value);
|
||||
}
|
||||
argument.convert(radians(), 0.).map_err(|_| {
|
||||
EvalError::from(UnitMismatch::AngleExpected {
|
||||
function: function.to_string(),
|
||||
unit: argument.unit.to_string(),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads an argument that must be plain, converting a dimensionless unit like `%` out.
|
||||
fn plain_argument(function: &str, argument: Quantity, rule: UnitRule) -> Result<Value, EvalError> {
|
||||
let argument = argument.plain_if_dimensionless();
|
||||
if argument.is_plain() {
|
||||
return Ok(argument.value);
|
||||
}
|
||||
|
||||
let (function, unit) = (function.to_string(), argument.unit.to_string());
|
||||
Err(if rule == UnitRule::Rounding {
|
||||
EvalError::from(UnitMismatch::RoundingWithUnits { function, unit })
|
||||
} else {
|
||||
EvalError::from(UnitMismatch::UnitsNotAccepted { function, unit })
|
||||
})
|
||||
}
|
||||
|
||||
/// Runs a builtin taking values by its rule for units: the arguments are converted into the units it computes in and stripped,
|
||||
/// so it sees plain numbers, and its result takes the unit that follows from theirs.
|
||||
#[inline]
|
||||
pub(crate) fn run_builtin(name: &str, rule: UnitRule, function: BuiltinFunction, arguments: &[Quantity], pixels_per_inch: f64) -> Result<Quantity, EvalError> {
|
||||
// Plain arguments skip the unit rules, the common case, passing through a stack buffer when they fit
|
||||
if arguments.iter().all(|argument| argument.is_plain()) {
|
||||
let mut stack_values = [Value::from_i64(0); 5];
|
||||
let heap_values: Vec<Value>;
|
||||
let values: &[Value] = if arguments.len() <= stack_values.len() {
|
||||
for (slot, argument) in stack_values.iter_mut().zip(arguments) {
|
||||
*slot = argument.value;
|
||||
}
|
||||
&stack_values[..arguments.len()]
|
||||
} else {
|
||||
heap_values = arguments.iter().map(|argument| argument.value).collect();
|
||||
&heap_values
|
||||
};
|
||||
|
||||
let value = function(values).ok_or(EvalError::TypeError)?;
|
||||
return Ok(Quantity::new(value, rule.plain_result_unit()));
|
||||
}
|
||||
run_builtin_with_units(name, rule, function, arguments, pixels_per_inch)
|
||||
}
|
||||
|
||||
/// Runs a builtin over arguments gathered as values beside their units, which the evaluator keeps apart so plain ones need no copy.
|
||||
#[inline]
|
||||
pub(crate) fn run_builtin_on_parts(name: &str, rule: UnitRule, function: BuiltinFunction, values: &[Value], units: &[Unit], pixels_per_inch: f64) -> Result<Quantity, EvalError> {
|
||||
if units.iter().all(|unit| unit.is_none()) {
|
||||
let value = function(values).ok_or(EvalError::TypeError)?;
|
||||
return Ok(Quantity::new(value, rule.plain_result_unit()));
|
||||
}
|
||||
|
||||
let arguments: Vec<Quantity> = values.iter().zip(units).map(|(value, unit)| Quantity::new(*value, *unit)).collect();
|
||||
run_builtin_with_units(name, rule, function, &arguments, pixels_per_inch)
|
||||
}
|
||||
|
||||
#[inline(never)]
|
||||
fn run_builtin_with_units(name: &str, rule: UnitRule, function: BuiltinFunction, arguments: &[Quantity], pixels_per_inch: f64) -> Result<Quantity, EvalError> {
|
||||
use UnitRule::*;
|
||||
|
||||
let call = |values: &[Value]| function(values).ok_or(EvalError::TypeError);
|
||||
let result_in = |value: Value, unit: Unit| Ok(Quantity::new(value, unit));
|
||||
let plain_arguments = || arguments.iter().map(|argument| plain_argument(name, *argument, rule)).collect::<Result<Vec<Value>, EvalError>>();
|
||||
|
||||
match rule {
|
||||
Plain | Rounding => result_in(call(&plain_arguments()?)?, Unit::NONE),
|
||||
Preserving | PreservingToPlain | Squared => {
|
||||
let (values, unit) = all_in_common_unit(arguments, "mixed with", pixels_per_inch)?;
|
||||
let value = call(&values)?;
|
||||
match rule {
|
||||
Preserving => result_in(value, unit),
|
||||
Squared => result_in(value, unit.power(2.).map_err(|error| unit_error(error, unit, unit, "squared"))?),
|
||||
_ => result_in(value, Unit::NONE),
|
||||
}
|
||||
}
|
||||
Count => result_in(call(&arguments.iter().map(|argument| argument.value).collect::<Vec<Value>>())?, Unit::NONE),
|
||||
Circular => {
|
||||
let angles = arguments.iter().map(|argument| angle_in_radians(name, *argument)).collect::<Result<Vec<Value>, EvalError>>()?;
|
||||
result_in(call(&angles)?, Unit::NONE)
|
||||
}
|
||||
InverseCircular => result_in(call(&plain_arguments()?)?, radians()),
|
||||
TwoArgumentArctangent => {
|
||||
let (values, _) = all_in_common_unit(arguments, "mixed with", pixels_per_inch)?;
|
||||
result_in(call(&values)?, radians())
|
||||
}
|
||||
Exponential => {
|
||||
let [argument] = arguments else { return Err(EvalError::TypeError) };
|
||||
let argument = argument.plain_if_dimensionless();
|
||||
if argument.is_plain() {
|
||||
return result_in(call(&[argument.value])?, Unit::NONE);
|
||||
}
|
||||
let angle = angle_in_radians(name, argument)?;
|
||||
let Value::Number(number) = angle;
|
||||
if number.to_quaternion().w != 0. {
|
||||
return Err(EvalError::AngleExponentWithPlainPart);
|
||||
}
|
||||
result_in(call(&[angle])?, Unit::NONE)
|
||||
}
|
||||
Root(degree) => {
|
||||
let [argument] = arguments else { return Err(EvalError::TypeError) };
|
||||
let argument = argument.plain_if_dimensionless();
|
||||
let unit = argument.unit.power(1. / degree as f64).map_err(|error| unit_error(error, argument.unit, argument.unit, "rooted"))?;
|
||||
result_in(call(&[argument.value])?, unit)
|
||||
}
|
||||
RootOfDegree => {
|
||||
let [argument, degree] = arguments else { return Err(EvalError::TypeError) };
|
||||
let argument = argument.plain_if_dimensionless();
|
||||
let degree = plain_argument(name, *degree, rule)?;
|
||||
let unit = match degree.as_real() {
|
||||
Some(degree) => argument.unit.power(1. / degree).map_err(|error| unit_error(error, argument.unit, argument.unit, "rooted"))?,
|
||||
None if argument.is_plain() => Unit::NONE,
|
||||
None => return Err(EvalError::from(UnitMismatch::FractionalUnitPower(argument.unit.to_string()))),
|
||||
};
|
||||
result_in(call(&[argument.value, degree])?, unit)
|
||||
}
|
||||
Product => {
|
||||
let [a, b] = arguments else { return Err(EvalError::TypeError) };
|
||||
let (unit, scale) = a.unit.product(b.unit, pixels_per_inch).map_err(|error| unit_error(error, a.unit, b.unit, "multiplied by"))?;
|
||||
let Value::Number(number) = call(&[a.value, b.value])?;
|
||||
Ok(Quantity::of_number(scaled(number, scale, pixels_per_inch)?, unit))
|
||||
}
|
||||
Direction => result_in(call(&arguments.iter().map(|argument| argument.value).collect::<Vec<Value>>())?, Unit::NONE),
|
||||
AngleBetween => result_in(call(&arguments.iter().map(|argument| argument.value).collect::<Vec<Value>>())?, radians()),
|
||||
Rotate => {
|
||||
let [value, angle, axis @ ..] = arguments else { return Err(EvalError::TypeError) };
|
||||
let mut values = vec![value.value, angle_in_radians(name, *angle)?];
|
||||
values.extend(axis.iter().map(|axis| axis.value));
|
||||
result_in(call(&values)?, value.unit)
|
||||
}
|
||||
Rotor => {
|
||||
let [angle, axis @ ..] = arguments else { return Err(EvalError::TypeError) };
|
||||
let mut values = vec![angle_in_radians(name, *angle)?];
|
||||
values.extend(axis.iter().map(|axis| axis.value));
|
||||
result_in(call(&values)?, Unit::NONE)
|
||||
}
|
||||
Interpolate => {
|
||||
let [a, b, t] = arguments else { return Err(EvalError::TypeError) };
|
||||
let (endpoints, unit) = all_in_common_unit(&[*a, *b], "mixed with", pixels_per_inch)?;
|
||||
let t = plain_argument(name, *t, rule)?;
|
||||
result_in(call(&[endpoints[0], endpoints[1], t])?, unit)
|
||||
}
|
||||
FirstArgument => {
|
||||
let [value, direction] = arguments else { return Err(EvalError::TypeError) };
|
||||
result_in(call(&[value.value, direction.value])?, value.unit)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A matrix with the units of its linear part and of its translation, so it maps a value in some unit to one in that unit times
|
||||
/// the linear unit, plus the translation. A range from `0` to `10 mm` has both in `mm`, mapping a plain parameter to a length,
|
||||
/// while a rotation is plain and leaves any unit as it was. A zero translation has no unit.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct MatrixQuantity {
|
||||
pub matrix: Matrix,
|
||||
pub linear: Unit,
|
||||
pub translation: Unit,
|
||||
}
|
||||
|
||||
impl MatrixQuantity {
|
||||
pub const fn plain(matrix: Matrix) -> Self {
|
||||
Self {
|
||||
matrix,
|
||||
linear: Unit::NONE,
|
||||
translation: Unit::NONE,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_plain(&self) -> bool {
|
||||
self.linear.is_none() && self.translation.is_none()
|
||||
}
|
||||
|
||||
/// Builds the matrix from its linear part and its translation, dropping the unit of a zero translation.
|
||||
fn from_parts(linear: Matrix, linear_unit: Unit, translation: Quantity) -> Self {
|
||||
let translation_quaternion = translation.number().to_quaternion();
|
||||
Self {
|
||||
matrix: Matrix {
|
||||
translation: translation_quaternion,
|
||||
..linear
|
||||
},
|
||||
linear: linear_unit,
|
||||
translation: if translation_quaternion == Quaternion::ZERO { Unit::NONE } else { translation.unit },
|
||||
}
|
||||
}
|
||||
|
||||
fn linear_part(&self) -> Matrix {
|
||||
Matrix {
|
||||
translation: Quaternion::ZERO,
|
||||
..self.matrix
|
||||
}
|
||||
}
|
||||
|
||||
fn translation_part(&self) -> Quantity {
|
||||
Quantity::of_number(Number::Quaternion(self.matrix.translation).canonical(), self.translation)
|
||||
}
|
||||
|
||||
/// Multiplies the linear part's entries by a factor, as converting its unit does.
|
||||
fn scaled_linear(linear: Matrix, size: Size, pixels_per_inch: f64) -> Result<Matrix, EvalError> {
|
||||
if size.is_one() {
|
||||
return Ok(linear);
|
||||
}
|
||||
let mut rows = linear.rows;
|
||||
for (row, spanned) in rows.iter_mut().zip(linear.axes) {
|
||||
if spanned {
|
||||
*row = scaled(Number::Quaternion(*row), size, pixels_per_inch)?.to_quaternion();
|
||||
}
|
||||
}
|
||||
Ok(Matrix { rows, ..linear })
|
||||
}
|
||||
|
||||
/// The image of a value, `M v + c`, whose linear part is in the value's unit times the linear unit, and which the translation's unit must match.
|
||||
pub(crate) fn apply(&self, value: Quantity, pixels_per_inch: f64) -> Result<Quantity, EvalError> {
|
||||
if self.is_plain() && value.is_plain() {
|
||||
return Ok(Quantity::of_number(Number::Quaternion(self.matrix.apply(value.number().to_quaternion())).canonical(), Unit::NONE));
|
||||
}
|
||||
// A plain zero is the same in every unit, so its image is the translation alone
|
||||
if value.is_plain() && value.is_zero() {
|
||||
return Ok(self.translation_part());
|
||||
}
|
||||
|
||||
let linear = self.linear_part().apply(value.number().to_quaternion());
|
||||
let (unit, scale) = value
|
||||
.unit
|
||||
.product(self.linear, pixels_per_inch)
|
||||
.map_err(|error| unit_error(error, value.unit, self.linear, "multiplied by"))?;
|
||||
let image = Quantity::of_number(scaled(Number::Quaternion(linear).canonical(), scale, pixels_per_inch)?, unit);
|
||||
if self.matrix.translation == Quaternion::ZERO {
|
||||
return Ok(image);
|
||||
}
|
||||
binary_op(image, BinaryOp::Add, self.translation_part(), pixels_per_inch)
|
||||
}
|
||||
|
||||
/// The composition `A B`, applying `B` first.
|
||||
pub(crate) fn compose(&self, inner: &Self, pixels_per_inch: f64) -> Result<Self, EvalError> {
|
||||
if self.is_plain() && inner.is_plain() {
|
||||
return Ok(Self::plain(self.matrix.compose(inner.matrix)));
|
||||
}
|
||||
|
||||
let (linear_unit, scale) = self
|
||||
.linear
|
||||
.product(inner.linear, pixels_per_inch)
|
||||
.map_err(|error| unit_error(error, self.linear, inner.linear, "composed with"))?;
|
||||
let linear = Self::scaled_linear(self.linear_part().compose(inner.linear_part()), scale, pixels_per_inch)?;
|
||||
let translation = self.apply(inner.translation_part(), pixels_per_inch)?;
|
||||
Ok(Self::from_parts(linear, linear_unit, translation))
|
||||
}
|
||||
|
||||
/// The inverse map, whose linear unit is the reciprocal and whose translation is in the translation's unit over the linear one.
|
||||
pub(crate) fn inverse(&self, pixels_per_inch: f64) -> Result<Self, EvalError> {
|
||||
let inverse = self.matrix.inverse().ok_or(EvalError::SingularMatrix)?;
|
||||
if self.is_plain() {
|
||||
return Ok(Self::plain(inverse));
|
||||
}
|
||||
|
||||
let linear_unit = self.linear.inverse();
|
||||
let translation_part = Quantity::of_number(Number::Quaternion(inverse.translation).canonical(), self.translation);
|
||||
let (translation_unit, scale) = translation_part
|
||||
.unit
|
||||
.product(linear_unit, pixels_per_inch)
|
||||
.map_err(|error| unit_error(error, self.translation, linear_unit, "divided by"))?;
|
||||
let translation = Quantity::of_number(scaled(translation_part.number(), scale, pixels_per_inch)?, translation_unit);
|
||||
let linear = Matrix {
|
||||
translation: Quaternion::ZERO,
|
||||
..inverse
|
||||
};
|
||||
Ok(Self::from_parts(linear, linear_unit, translation))
|
||||
}
|
||||
|
||||
/// A whole power by repeated composition, where a negative one is of the inverse.
|
||||
pub(crate) fn power(&self, exponent: i64, pixels_per_inch: f64) -> Result<Self, EvalError> {
|
||||
if self.is_plain() {
|
||||
return self.matrix.power(exponent).map(Self::plain).ok_or(EvalError::SingularMatrix);
|
||||
}
|
||||
|
||||
// The zeroth power is the identity over the axes the matrix spans, as for a plain matrix
|
||||
let identity = self.matrix.power(0).ok_or(EvalError::SingularMatrix)?;
|
||||
let mut result = Self::plain(identity);
|
||||
|
||||
// By squaring, in O(log n) compositions, squaring only while bits remain
|
||||
let (mut base, mut remaining) = (if exponent < 0 { self.inverse(pixels_per_inch)? } else { *self }, exponent.unsigned_abs());
|
||||
while remaining > 0 {
|
||||
if remaining & 1 == 1 {
|
||||
result = result.compose(&base, pixels_per_inch)?;
|
||||
}
|
||||
remaining >>= 1;
|
||||
if remaining > 0 {
|
||||
base = base.compose(&base, pixels_per_inch)?;
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// The pointwise sum or difference of two matrices, whose linear parts and translations must each match in dimension.
|
||||
pub(crate) fn sum(&self, op: BinaryOp, other: &Self, pixels_per_inch: f64) -> Result<Self, EvalError> {
|
||||
if self.is_plain() && other.is_plain() {
|
||||
let matrix = if op == BinaryOp::Sub { self.matrix - other.matrix } else { self.matrix + other.matrix };
|
||||
return Ok(Self::plain(matrix));
|
||||
}
|
||||
|
||||
let verb = if op == BinaryOp::Sub { "subtracted from" } else { "added to" };
|
||||
let linear_unit = if self.linear == other.linear {
|
||||
self.linear
|
||||
} else {
|
||||
common_unit(self.linear, other.linear, pixels_per_inch)
|
||||
};
|
||||
let convert = |matrix: &Self| -> Result<Matrix, EvalError> {
|
||||
let factor = matrix.linear.conversion(linear_unit).map_err(|error| unit_error(error, matrix.linear, linear_unit, verb))?;
|
||||
Self::scaled_linear(matrix.linear_part(), factor, pixels_per_inch)
|
||||
};
|
||||
let (left, right) = (convert(self)?, convert(other)?);
|
||||
let linear = if op == BinaryOp::Sub { left - right } else { left + right };
|
||||
let translation = binary_op(self.translation_part(), op, other.translation_part(), pixels_per_inch)?;
|
||||
Ok(Self::from_parts(linear, linear_unit, translation))
|
||||
}
|
||||
|
||||
/// The matrix with a value attached as translation, or subtracted from it.
|
||||
pub(crate) fn translated(&self, op: BinaryOp, by: Quantity, pixels_per_inch: f64) -> Result<Self, EvalError> {
|
||||
let translation = binary_op(self.translation_part(), op, by, pixels_per_inch)?;
|
||||
Ok(Self::from_parts(self.linear_part(), self.linear, translation))
|
||||
}
|
||||
|
||||
pub(crate) fn negated(&self) -> Self {
|
||||
Self { matrix: -self.matrix, ..*self }
|
||||
}
|
||||
|
||||
/// The matrix's entries converted into the given linear and translation units, which must measure the same dimensions as its own.
|
||||
pub(crate) fn in_units(&self, linear: Unit, translation: Unit, pixels_per_inch: f64) -> Result<Matrix, EvalError> {
|
||||
let linear_factor = self.linear.conversion(linear).map_err(|error| unit_error(error, self.linear, linear, "compared with"))?;
|
||||
let linear_part = Self::scaled_linear(self.linear_part(), linear_factor, pixels_per_inch)?;
|
||||
let translation = into_region_unit(self.translation_part(), translation, pixels_per_inch)?.to_quaternion();
|
||||
Ok(Matrix { translation, ..linear_part })
|
||||
}
|
||||
|
||||
/// The matrix in plain numbers measured in `unit`, as a region of values in that unit: its linear part maps a plain parameter
|
||||
/// to that unit, and its translation must match it.
|
||||
pub(crate) fn as_region_in(&self, unit: Unit, pixels_per_inch: f64) -> Result<Matrix, EvalError> {
|
||||
let linear_factor = self.linear.conversion(unit).map_err(|error| unit_error(error, self.linear, unit, "mixed with"))?;
|
||||
let linear = Self::scaled_linear(self.linear_part(), linear_factor, pixels_per_inch)?;
|
||||
let translation = self.translation_part();
|
||||
let translation = if translation.is_zero() && translation.is_plain() {
|
||||
Quaternion::ZERO
|
||||
} else {
|
||||
let factor = translation.unit.conversion(unit).map_err(|error| unit_error(error, translation.unit, unit, "mixed with"))?;
|
||||
scaled(translation.number(), factor, pixels_per_inch)?.to_quaternion()
|
||||
};
|
||||
Ok(Matrix { translation, ..linear })
|
||||
}
|
||||
|
||||
/// The unit of the values a region holds: its linear unit, or its translation's when the linear part is plain.
|
||||
pub(crate) fn region_unit(&self) -> Unit {
|
||||
if self.linear.is_none() { self.translation } else { self.linear }
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for MatrixQuantity {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
self.matrix.fmt(f)?;
|
||||
if !self.linear.is_none() {
|
||||
write!(f, " in {}", self.linear)?;
|
||||
}
|
||||
if !self.translation.is_none() && self.translation != self.linear {
|
||||
write!(f, " translated in {}", self.translation)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The values of a matrix literal's entries brought into one unit, which becomes the matrix's linear unit.
|
||||
pub(crate) fn literal_entries(entries: &[Quantity], pixels_per_inch: f64) -> Result<(Vec<Quaternion>, Unit), EvalError> {
|
||||
let (values, unit) = all_in_common_unit(entries, "mixed with", pixels_per_inch)?;
|
||||
Ok((values.into_iter().map(|Value::Number(number)| number.to_quaternion()).collect(), unit))
|
||||
}
|
||||
|
||||
/// The corners of a range brought into one unit, with that unit.
|
||||
pub(crate) fn range_corners(from: Quantity, to: Quantity, pixels_per_inch: f64) -> Result<(Number, Number, Unit), EvalError> {
|
||||
in_common_unit(from, to, "mixed with", pixels_per_inch)
|
||||
}
|
||||
|
||||
/// Converts a value into the unit it's measured against, where a plain zero matches any unit.
|
||||
pub(crate) fn into_region_unit(value: Quantity, unit: Unit, pixels_per_inch: f64) -> Result<Number, EvalError> {
|
||||
let value = if unit.is_none() { value.plain_if_dimensionless() } else { value };
|
||||
if value.unit == unit || (value.is_plain() && value.is_zero()) {
|
||||
return Ok(value.number());
|
||||
}
|
||||
if value.is_plain() || unit.is_none() {
|
||||
let unit = if value.is_plain() { unit } else { value.unit };
|
||||
return Err(EvalError::from(UnitMismatch::PlainWithUnit {
|
||||
verb: "mixed with",
|
||||
unit: unit.to_string(),
|
||||
}));
|
||||
}
|
||||
|
||||
let factor = value.unit.conversion(unit).map_err(|error| unit_error(error, value.unit, unit, "mixed with"))?;
|
||||
scaled(value.number(), factor, pixels_per_inch)
|
||||
}
|
||||
|
||||
/// The unit of a range function's result.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum RegionResult {
|
||||
/// The unit of the region the value is measured against: `clamp`.
|
||||
FirstRegion,
|
||||
/// The unit of the region the value is mapped into: `remap`.
|
||||
LastRegion,
|
||||
/// No unit: `within` and `smoothstep`.
|
||||
Plain,
|
||||
}
|
||||
|
||||
pub fn region_result(name: &str) -> RegionResult {
|
||||
match name {
|
||||
"clamp" => RegionResult::FirstRegion,
|
||||
"remap" => RegionResult::LastRegion,
|
||||
_ => RegionResult::Plain,
|
||||
}
|
||||
}
|
||||
|
||||
/// The unit of a value taken from a matrix.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum MatrixValueUnit {
|
||||
/// The translation's unit: `translation`.
|
||||
Translation,
|
||||
/// The linear unit to the power of the axes the matrix spans: `det`.
|
||||
Determinant,
|
||||
}
|
||||
|
||||
pub fn matrix_value_unit(name: &str) -> MatrixValueUnit {
|
||||
match name {
|
||||
"translation" => MatrixValueUnit::Translation,
|
||||
_ => MatrixValueUnit::Determinant,
|
||||
}
|
||||
}
|
||||
|
||||
/// How a matrix builder reads its arguments' units.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum BuilderUnits {
|
||||
/// The value's unit becomes the linear unit: `matrix` and `scale`.
|
||||
Scaling,
|
||||
/// An angle read in radians, about a direction of any unit: `rotation`.
|
||||
Rotation,
|
||||
/// Directions of any unit and a plain factor: `shear`.
|
||||
Shear,
|
||||
}
|
||||
|
||||
pub fn builder_units(name: &str) -> BuilderUnits {
|
||||
match name {
|
||||
"rotation" => BuilderUnits::Rotation,
|
||||
"shear" => BuilderUnits::Shear,
|
||||
_ => BuilderUnits::Scaling,
|
||||
}
|
||||
}
|
||||
|
||||
/// The plain arguments of a matrix builder with the linear unit of the matrix it builds.
|
||||
pub(crate) fn builder_arguments(units: BuilderUnits, arguments: &[Quantity]) -> Result<(Vec<Value>, Unit), EvalError> {
|
||||
match units {
|
||||
BuilderUnits::Scaling => {
|
||||
let [value] = arguments else { return Err(EvalError::TypeError) };
|
||||
let value = value.plain_if_dimensionless();
|
||||
Ok((vec![value.value], value.unit))
|
||||
}
|
||||
BuilderUnits::Rotation => {
|
||||
let [angle, axis @ ..] = arguments else { return Err(EvalError::TypeError) };
|
||||
let mut values = vec![angle_in_radians("rotation", *angle)?];
|
||||
values.extend(axis.iter().map(|axis| axis.value));
|
||||
Ok((values, Unit::NONE))
|
||||
}
|
||||
BuilderUnits::Shear => {
|
||||
let [along, by, factor] = arguments else { return Err(EvalError::TypeError) };
|
||||
let factor = plain_argument("shear", *factor, UnitRule::Plain)?;
|
||||
Ok((vec![direction(*along)?, direction(*by)?, factor], Unit::NONE))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A direction given as a value: a plain one as it is, and one with a unit as its unit vector, since its size in that unit means nothing.
|
||||
fn direction(value: Quantity) -> Result<Value, EvalError> {
|
||||
let value = value.plain_if_dimensionless();
|
||||
if value.is_plain() {
|
||||
return Ok(value.value);
|
||||
}
|
||||
value.number().to_quaternion().normalized().map(Value::from).ok_or(EvalError::Indeterminate)
|
||||
}
|
||||
|
||||
/// The unit of a value taken from a matrix by a function.
|
||||
pub(crate) fn matrix_value_result_unit(unit: MatrixValueUnit, matrix: &MatrixQuantity) -> Result<Unit, EvalError> {
|
||||
match unit {
|
||||
MatrixValueUnit::Translation => Ok(matrix.translation),
|
||||
MatrixValueUnit::Determinant => {
|
||||
let spanned = matrix.matrix.axes.iter().filter(|spanned| **spanned).count();
|
||||
matrix.linear.power(spanned as f64).map_err(|_| EvalError::UnitOverflow)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,11 @@
|
||||
use crate::ast::BinaryOp;
|
||||
use crate::constants::{Builtin, BuiltinFunction, builtin_function};
|
||||
use crate::context::{NothingMap, ValueProvider};
|
||||
use crate::documentation::BUILTIN_FUNCTIONS;
|
||||
use crate::executer::{EvalError, settle_matrix};
|
||||
use crate::executer::settle_matrix;
|
||||
use crate::lexer::{Lexer, Token};
|
||||
use crate::matrix::Matrix;
|
||||
use crate::object::Object;
|
||||
use crate::parser::ParseError;
|
||||
use crate::quantity::{self, Quantity, UnitRule, unit_rule};
|
||||
use crate::value::{Number, Value};
|
||||
use std::cmp::Ordering;
|
||||
use std::collections::HashSet;
|
||||
@@ -28,12 +26,7 @@ pub enum Reducer {
|
||||
/// A single n-ary predicate asserting that every pair of items is distinct, like `a != b != c`.
|
||||
ChainDistinct,
|
||||
/// A single call of a variadic function over all items, like `min(a, b, c)`.
|
||||
Function {
|
||||
function: BuiltinFunction,
|
||||
/// The function's name, which decides how it treats the units of its items.
|
||||
name: &'static str,
|
||||
over_matrices: Option<MatrixFunction>,
|
||||
},
|
||||
Function { function: BuiltinFunction, over_matrices: Option<MatrixFunction> },
|
||||
}
|
||||
|
||||
/// The action of a variadic function across matrices: the mean is pointwise and the count counts, while the others need an
|
||||
@@ -79,7 +72,6 @@ pub fn classify_reducer(source: &str, bindings: impl ValueProvider) -> Option<Re
|
||||
match builtin_function(bare_name)? {
|
||||
Builtin::Values { function, variadic: true } => Reducer::Function {
|
||||
function,
|
||||
name: BUILTIN_FUNCTIONS.iter().find(|documented| documented.name == bare_name)?.name,
|
||||
over_matrices: matrix_function(bare_name),
|
||||
},
|
||||
_ => return None,
|
||||
@@ -273,107 +265,6 @@ impl Reducer {
|
||||
results.resize(items.len(), None);
|
||||
results
|
||||
}
|
||||
|
||||
/// Evaluates this reducer across items measured in units, carrying them as the written-out expression would, so `+` across lengths
|
||||
/// gives a length. Gives `None` where [`Self::evaluate`] would, and an error where the units don't fit, like `gcd` across lengths.
|
||||
pub fn evaluate_quantities(&self, items: &[Quantity], pixels_per_inch: f64) -> Result<Option<Quantity>, EvalError> {
|
||||
// Plain items skip the unit arithmetic, the common case
|
||||
if items.iter().all(|item| item.is_plain()) {
|
||||
let values: Vec<Value> = items.iter().map(|item| item.value).collect();
|
||||
return Ok(self.evaluate(&values).map(Quantity::plain));
|
||||
}
|
||||
if items.iter().any(|item| item.number().is_nan()) {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// Items take canonical form first, as in `evaluate_unsettled`
|
||||
let items: Vec<Quantity> = items.iter().map(|item| Quantity::new(Value::Number(item.number().canonical()), item.unit)).collect();
|
||||
let result = match self {
|
||||
Reducer::FoldLeft(op) => {
|
||||
let Some((first, rest)) = items.split_first() else {
|
||||
return Ok(op.identity_element().map(Quantity::plain));
|
||||
};
|
||||
|
||||
// A lone item meets no operator, so logic checks it is a truth value here, as `100%` is but `50%` isn't
|
||||
let first = match op {
|
||||
BinaryOp::And | BinaryOp::Or => {
|
||||
let truth = first.plain_if_dimensionless();
|
||||
if !truth.is_plain() || truth.number().as_bool().is_none() {
|
||||
return Err(EvalError::NotATruthValue);
|
||||
}
|
||||
truth
|
||||
}
|
||||
_ => *first,
|
||||
};
|
||||
rest.iter().try_fold(first, |accumulated, item| quantity::binary_op(accumulated, *op, *item, pixels_per_inch))?
|
||||
}
|
||||
|
||||
Reducer::FoldRight(op) => {
|
||||
let Some((last, rest)) = items.split_last() else { return Ok(None) };
|
||||
rest.iter().rev().try_fold(*last, |accumulated, item| quantity::binary_op(*item, *op, accumulated, pixels_per_inch))?
|
||||
}
|
||||
|
||||
// A relation holds alike in every unit the items convert into, so they are compared as plain numbers in one
|
||||
Reducer::ChainAdjacent(_) | Reducer::ChainDistinct => {
|
||||
let (values, _) = quantity::all_in_common_unit(&items, "compared with", pixels_per_inch)?;
|
||||
return Ok(self.evaluate(&values).map(Quantity::plain));
|
||||
}
|
||||
|
||||
Reducer::Function { function, name, .. } => quantity::run_builtin(name, unit_rule(name).unwrap_or(UnitRule::Plain), *function, &items, pixels_per_inch)?,
|
||||
};
|
||||
|
||||
Ok(settle_quantity(result))
|
||||
}
|
||||
|
||||
/// Evaluates this reducer across each leading run of the items, as [`Self::evaluate_quantities`] does for each run, though a comparison
|
||||
/// brings the whole list into one unit first. Once a fold step fails, every longer run gives `None` after that first error.
|
||||
pub fn evaluate_running_quantities(&self, items: &[Quantity], pixels_per_inch: f64) -> Vec<Result<Option<Quantity>, EvalError>> {
|
||||
if items.iter().all(|item| item.is_plain()) {
|
||||
let values: Vec<Value> = items.iter().map(|item| item.value).collect();
|
||||
return self.evaluate_running(&values).into_iter().map(|result| Ok(result.map(Quantity::plain))).collect();
|
||||
}
|
||||
|
||||
match self {
|
||||
// O(n) by folding each item into the previous run's result
|
||||
Reducer::FoldLeft(op) => {
|
||||
let mut accumulated: Option<Quantity> = None;
|
||||
let mut failed = false;
|
||||
items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, item)| {
|
||||
if failed {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let item = Quantity::new(Value::Number(item.number().canonical()), item.unit);
|
||||
let step = match (index, accumulated) {
|
||||
(0, _) => self.evaluate_quantities(&[item], pixels_per_inch),
|
||||
(_, Some(previous)) if !item.number().is_nan() => quantity::binary_op(previous, *op, item, pixels_per_inch).map(settle_quantity),
|
||||
_ => Ok(None),
|
||||
};
|
||||
accumulated = step.as_ref().ok().copied().flatten();
|
||||
failed = accumulated.is_none();
|
||||
step
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
// O(n) by comparing the items as plain numbers in one unit
|
||||
Reducer::ChainAdjacent(_) | Reducer::ChainDistinct => match quantity::all_in_common_unit(items, "compared with", pixels_per_inch) {
|
||||
Ok((values, _)) => self.evaluate_running(&values).into_iter().map(|result| Ok(result.map(Quantity::plain))).collect(),
|
||||
Err(error) => std::iter::once(Err(error)).chain(std::iter::repeat_with(|| Ok(None))).take(items.len()).collect(),
|
||||
},
|
||||
|
||||
// O(n²) since `^` groups from the right and a variadic builtin reads its whole list, so no run builds on a shorter one's result
|
||||
Reducer::FoldRight(_) | Reducer::Function { .. } => (1..=items.len()).map(|count| self.evaluate_quantities(&items[..count], pixels_per_inch)).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A reduction's result in canonical form, or `None` for an indeterminate result, as [`settle`] gives for plain values.
|
||||
fn settle_quantity(result: Quantity) -> Option<Quantity> {
|
||||
settle(result.value).map(|value| Quantity::new(value, result.unit))
|
||||
}
|
||||
|
||||
/// A reducer's result in canonical form, or `None` for an indeterminate result, since no operation produces NaN.
|
||||
@@ -469,7 +360,6 @@ mod tests {
|
||||
use crate::ast;
|
||||
use crate::context::{EvalContext, NothingMap, ValueMap};
|
||||
use crate::quaternion::Quaternion;
|
||||
use crate::units::Unit;
|
||||
use crate::value::Complex;
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -692,53 +582,4 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn in_unit(unit: &str, values: &[f64]) -> Vec<Quantity> {
|
||||
let unit = Unit::named(unit).unwrap();
|
||||
values.iter().map(|&value| Quantity::new(Value::from_f64(value), unit)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn measured_items_carry_their_units() {
|
||||
let reduce = |source: &str, items: &[Quantity]| classify_reducer(source, NothingMap).unwrap().evaluate_quantities(items, 96.);
|
||||
let pixels = Unit::named("px").unwrap();
|
||||
|
||||
let total = reduce("+", &in_unit("px", &[1., 2., 3.])).unwrap().unwrap();
|
||||
assert_eq!(total, Quantity::new(Value::from_i64(6), pixels));
|
||||
assert_eq!(reduce("max", &in_unit("px", &[4., 9., 2.])).unwrap().unwrap(), Quantity::new(Value::from_i64(9), pixels));
|
||||
assert_eq!(reduce("*", &in_unit("px", &[2., 3.])).unwrap().unwrap().unit, pixels.power(2.).unwrap());
|
||||
assert_eq!(reduce("/", &in_unit("px", &[6., 3.])).unwrap().unwrap(), Quantity::plain(Value::from_i64(2)));
|
||||
|
||||
// Counts and relations are plain, whatever the items measure
|
||||
assert_eq!(reduce("count", &in_unit("px", &[1., 2.])).unwrap().unwrap(), Quantity::plain(Value::from_i64(2)));
|
||||
assert_eq!(reduce("<", &in_unit("rad", &[1., 2., 3.])).unwrap().unwrap(), Quantity::plain(Value::from_bool(true)));
|
||||
assert_eq!(reduce("!=", &in_unit("rad", &[1., 2., 1.])).unwrap().unwrap(), Quantity::plain(Value::from_bool(false)));
|
||||
|
||||
// Items in different units of one dimension meet in a common unit, as `1in + 1px` does
|
||||
let mixed = [in_unit("in", &[1.]), in_unit("px", &[1.])].concat();
|
||||
assert_eq!(reduce("+", &mixed).unwrap().unwrap(), Quantity::new(Value::from_i64(97), pixels));
|
||||
|
||||
// A reduction that takes only plain numbers refuses measured items
|
||||
assert!(reduce("gcd", &in_unit("px", &[2., 4.])).is_err());
|
||||
assert!(reduce("&&", &in_unit("px", &[1.])).is_err());
|
||||
assert!(reduce("^", &in_unit("px", &[2., 3.])).is_err());
|
||||
assert_eq!(reduce("-", &[]).unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn running_measured_results_match_each_leading_run() {
|
||||
let lists = [
|
||||
in_unit("px", &[3., 1., 4., 1., 5.]),
|
||||
in_unit("rad", &[0.5, 2., 0., 2.]),
|
||||
[in_unit("in", &[1.]), in_unit("px", &[2., 3.])].concat(),
|
||||
];
|
||||
for source in ["+", "-", "*", "/", "<", "==", "!=", "min", "max", "mean", "count", "gcd", "&&", "^"] {
|
||||
let reducer = classify_reducer(source, NothingMap).unwrap();
|
||||
for list in &lists {
|
||||
let expected: Vec<Option<Quantity>> = (1..=list.len()).map(|count| reducer.evaluate_quantities(&list[..count], 96.).ok().flatten()).collect();
|
||||
let running: Vec<Option<Quantity>> = reducer.evaluate_running_quantities(list, 96.).into_iter().map(|result| result.ok().flatten()).collect();
|
||||
assert_eq!(running, expected, "`{source}` over {list:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,7 @@
|
||||
use crate::ast::{BinaryOp, Binding, BuiltinCall, CallWhere, Case, Clause, Literal, Local, MatrixNode, Measure, Node, SortedCase, Syntax, UnaryOp, ValueNode};
|
||||
use crate::constants::{Builtin, SuffixedFunction, builtin_function, suffixed_function};
|
||||
use crate::ast::{BinaryOp, Binding, CallWhere, Case, Clause, Literal, Local, MatrixNode, Node, SortedCase, Syntax, UnaryOp, ValueNode};
|
||||
use crate::constants::{Builtin, builtin_function, suffixed_function};
|
||||
use crate::context::{FunctionProvider, NothingMap};
|
||||
use crate::lexer::{names_matrix, offset_in};
|
||||
use crate::parser::juxtaposed;
|
||||
use crate::quantity::{UnitRule, builder_units, matrix_value_unit, region_result, unit_rule};
|
||||
use crate::units::unit_named;
|
||||
use std::borrow::Cow;
|
||||
use std::fmt;
|
||||
use std::ops::Range;
|
||||
@@ -305,10 +302,6 @@ impl<'src> Sorter<'_, 'src> {
|
||||
Syntax::Lit(literal) => Node::Value(ValueNode::Lit(literal)),
|
||||
Syntax::Var(name) => self.name(name, 0),
|
||||
Syntax::FnCall { name, expr } => self.call(name, expr, 0)?,
|
||||
// A quotient by a measure is a product, which reads the measure by its dividend
|
||||
Syntax::BinOp { lhs, op, rhs } if matches!(*rhs, Syntax::Measure { .. }) => self.sort(Syntax::Product { first: lhs, rest: vec![(op, *rhs)] })?,
|
||||
// Standing alone, where only a failed product leaves one, a measure is its number times its units
|
||||
Syntax::Measure { number, units } => self.sort(units.into_iter().fold(*number, juxtaposed))?,
|
||||
Syntax::BinOp { lhs, op, rhs } => {
|
||||
let lhs = self.sort(*lhs);
|
||||
let rhs = self.sort(*rhs);
|
||||
@@ -401,10 +394,7 @@ impl<'src> Sorter<'_, 'src> {
|
||||
match local {
|
||||
Some(local) => local,
|
||||
None if names_matrix(name) => Node::Matrix(MatrixNode::Var(name.to_string())),
|
||||
None => match unit_named(name) {
|
||||
Some(unit) => Node::Value(ValueNode::Unit { name: name.to_string(), unit }),
|
||||
None => Node::Value(ValueNode::Var(name.to_string())),
|
||||
},
|
||||
None => Node::Value(ValueNode::Var(name.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -518,7 +508,6 @@ impl<'src> Sorter<'_, 'src> {
|
||||
Ok(match builtin {
|
||||
Some(Builtin::OfMatrix(function)) => Node::Value(ValueNode::OfMatrix {
|
||||
function,
|
||||
unit: matrix_value_unit(bare_name),
|
||||
matrix: Box::new(self.matrix(one(arguments).ok_or(invalid_arguments)?, VALUE_AS_MATRIX)?),
|
||||
}),
|
||||
Some(Builtin::MatrixOfMatrix(function)) => Node::Matrix(MatrixNode::OfMatrix {
|
||||
@@ -531,7 +520,6 @@ impl<'src> Sorter<'_, 'src> {
|
||||
}
|
||||
Node::Matrix(MatrixNode::FromValues {
|
||||
function,
|
||||
units: builder_units(bare_name),
|
||||
arguments: self.values(arguments)?,
|
||||
})
|
||||
}
|
||||
@@ -549,32 +537,10 @@ impl<'src> Sorter<'_, 'src> {
|
||||
.by_ref()
|
||||
.take(region_count)
|
||||
.map(|region| self.matrix(region, VALUE_AS_MATRIX))
|
||||
.collect::<Result<Box<[MatrixNode]>, SortError>>()?;
|
||||
.collect::<Result<Vec<MatrixNode>, SortError>>()?;
|
||||
let trailing = arguments.next().map(|trailing| self.value(trailing, MATRIX_AS_VALUE).map(Box::new)).transpose()?;
|
||||
Node::Value(ValueNode::OfValueAndRegions {
|
||||
function,
|
||||
result: region_result(bare_name),
|
||||
value,
|
||||
regions,
|
||||
trailing,
|
||||
})
|
||||
Node::Value(ValueNode::OfValueAndRegions { function, value, regions, trailing })
|
||||
}
|
||||
Some(Builtin::Values { function, .. }) => Node::Value(ValueNode::BuiltinCall(Box::new(BuiltinCall {
|
||||
name: bare_name.to_string(),
|
||||
host_name: (!prefixed).then(|| bare_name.to_string()),
|
||||
function,
|
||||
rule: unit_rule(bare_name).unwrap_or(UnitRule::Plain),
|
||||
arguments: self.values(arguments)?,
|
||||
suffix: None,
|
||||
}))),
|
||||
None if !host_function && let Some(SuffixedFunction { name: base_name, function, argument }) = suffixed_function(bare_name) => Node::Value(ValueNode::BuiltinCall(Box::new(BuiltinCall {
|
||||
name: base_name.to_string(),
|
||||
host_name: (!prefixed).then(|| bare_name.to_string()),
|
||||
function,
|
||||
rule: unit_rule(base_name).unwrap_or(UnitRule::Plain),
|
||||
arguments: self.values(arguments)?,
|
||||
suffix: Some(argument),
|
||||
}))),
|
||||
_ => Node::Value(ValueNode::FnCall {
|
||||
name: name.to_string(),
|
||||
expr: self.values(arguments)?,
|
||||
@@ -655,22 +621,6 @@ impl<'src> Sorter<'_, 'src> {
|
||||
let mut accumulated = first;
|
||||
|
||||
while let Some((op, factor)) = rest.next() {
|
||||
let factor = match (factor, accumulated) {
|
||||
// A value's quotient by a measure is read by the value's units once evaluated
|
||||
(Syntax::Measure { number, units }, Node::Value(dividend)) => {
|
||||
accumulated = self.measure_quotient(dividend, *number, units)?;
|
||||
continue;
|
||||
}
|
||||
(Syntax::Measure { number, units }, matrix) => {
|
||||
accumulated = matrix;
|
||||
self.measure_after_matrix(*number, units, rest)
|
||||
}
|
||||
(factor, value) => {
|
||||
accumulated = value;
|
||||
factor
|
||||
}
|
||||
};
|
||||
|
||||
accumulated = match (accumulated, self.sort(factor)?) {
|
||||
(Node::Matrix(matrix), Node::Value(factor)) => {
|
||||
// Dividing by a value applies the matrix to its reciprocal times the rest, so `M / v w` is `M (v⁻¹ w)`
|
||||
@@ -686,39 +636,6 @@ impl<'src> Sorter<'_, 'src> {
|
||||
Ok(accumulated)
|
||||
}
|
||||
|
||||
/// The factor a matrix divides by for a measure. A matrix's units are known only once evaluated, so it's the whole measure, unless
|
||||
/// a `where` definition makes one of the measure's names a variable, which then goes back to the product to multiply left to right.
|
||||
#[inline(never)]
|
||||
fn measure_after_matrix(&self, number: Syntax<'src>, units: Vec<Syntax<'src>>, rest: &mut std::vec::IntoIter<(BinaryOp, Syntax<'src>)>) -> Syntax<'src> {
|
||||
fn name<'src>(unit: &Syntax<'src>) -> Option<&'src str> {
|
||||
match unit {
|
||||
Syntax::Var(name) => Some(name),
|
||||
Syntax::BinOp { lhs, op: BinaryOp::Pow, .. } => name(lhs),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
let defined = |unit: &Syntax<'src>| name(unit).is_some_and(|name| !name.starts_with('\\') && self.scopes.iter().any(|scope| scope.values.contains(&name)));
|
||||
if !units.iter().any(defined) {
|
||||
return units.into_iter().fold(number, juxtaposed);
|
||||
}
|
||||
|
||||
let remaining = std::mem::take(rest);
|
||||
*rest = units.into_iter().map(|unit| (BinaryOp::Mul, unit)).chain(remaining).collect::<Vec<_>>().into_iter();
|
||||
number
|
||||
}
|
||||
|
||||
/// Sorts a value's quotient by a measure, kept out of [`Self::product`], which recurses once per matrix and must keep a small frame.
|
||||
#[inline(never)]
|
||||
fn measure_quotient(&mut self, dividend: ValueNode, number: Syntax<'src>, units: Vec<Syntax<'src>>) -> Result<Node, SortError> {
|
||||
let number = self.sort(number).and_then(|number| self.value(number, MATRIX_AS_VALUE));
|
||||
let units = self.sort_each(units).into_iter().map(|unit| self.value(unit?, MATRIX_AS_VALUE)).collect::<Result<Vec<_>, _>>();
|
||||
let measure = Box::new(Measure { number: number?, units: units? });
|
||||
Ok(Node::Value(ValueNode::MeasureQuotient {
|
||||
dividend: Box::new(dividend),
|
||||
measure,
|
||||
}))
|
||||
}
|
||||
|
||||
/// A piecewise takes the sort of its cases, which must agree, under conditions that are values.
|
||||
fn piecewise(&mut self, cases: Vec<Case<'src>>, otherwise: Option<Box<Syntax<'src>>>) -> Result<Node, SortError> {
|
||||
let cases = cases
|
||||
|
||||
@@ -1,791 +0,0 @@
|
||||
//! Units of measure: the units the language knows, the products of them a value is measured in, and the exact conversions
|
||||
//! between units of one dimension.
|
||||
|
||||
use crate::ast::BinaryOp;
|
||||
use crate::value::Number;
|
||||
use std::f64::consts::PI;
|
||||
use std::fmt;
|
||||
|
||||
/// The pixels per inch a host supplies when it gives no other, CSS's reference pixel.
|
||||
pub const DEFAULT_PIXELS_PER_INCH: f64 = 96.;
|
||||
|
||||
/// The exponents of length, mass, time, and angle that a unit or a value measures, so a speed is `[1, 0, -1, 0]`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Hash)]
|
||||
pub struct Dimension(pub [i16; 4]);
|
||||
|
||||
impl Dimension {
|
||||
pub const NONE: Self = Self([0; 4]);
|
||||
pub const LENGTH: Self = Self([1, 0, 0, 0]);
|
||||
pub const MASS: Self = Self([0, 1, 0, 0]);
|
||||
pub const TIME: Self = Self([0, 0, 1, 0]);
|
||||
pub const ANGLE: Self = Self([0, 0, 0, 1]);
|
||||
|
||||
const AREA: Self = Self([2, 0, 0, 0]);
|
||||
const VOLUME: Self = Self([3, 0, 0, 0]);
|
||||
const FREQUENCY: Self = Self([0, 0, -1, 0]);
|
||||
const SPEED: Self = Self([1, 0, -1, 0]);
|
||||
const ACCELERATION: Self = Self([1, 0, -2, 0]);
|
||||
const ANGULAR_SPEED: Self = Self([0, 0, -1, 1]);
|
||||
|
||||
pub fn is_none(self) -> bool {
|
||||
self == Self::NONE
|
||||
}
|
||||
|
||||
/// Whether the two share a base dimension, like an angular speed and a time, so a product of them can cancel it.
|
||||
fn overlaps(self, other: Self) -> bool {
|
||||
self.0.iter().zip(other.0).any(|(a, b)| *a != 0 && b != 0)
|
||||
}
|
||||
|
||||
/// What this dimension is called, like `length` or `speed`.
|
||||
pub fn noun(self) -> &'static str {
|
||||
let description = self.description();
|
||||
description.split_once(' ').map_or(description, |(_, noun)| noun)
|
||||
}
|
||||
|
||||
/// What a value of this dimension is called, for error messages.
|
||||
pub fn description(self) -> &'static str {
|
||||
match self {
|
||||
Self::NONE => "a plain number",
|
||||
Self::LENGTH => "a length",
|
||||
Self::AREA => "an area",
|
||||
Self::VOLUME => "a volume",
|
||||
Self::MASS => "a mass",
|
||||
Self::TIME => "a duration",
|
||||
Self::ANGLE => "an angle",
|
||||
Self::FREQUENCY => "a frequency",
|
||||
Self::SPEED => "a speed",
|
||||
Self::ACCELERATION => "an acceleration",
|
||||
Self::ANGULAR_SPEED => "an angular speed",
|
||||
_ => "a compound quantity",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A size as an exact ratio of integers, times a power of π (since degrees and turns are fractions of radians' half and
|
||||
/// whole turn) and a power of the inch per pixel (since a pixel is an inch over the host's pixels per inch).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Size {
|
||||
numerator: i128,
|
||||
denominator: i128,
|
||||
pi: i8,
|
||||
/// The power of the host's pixels per inch the size divides by.
|
||||
pixel: i8,
|
||||
}
|
||||
|
||||
const fn greatest_common_divisor(mut a: i128, mut b: i128) -> i128 {
|
||||
a = a.abs();
|
||||
b = b.abs();
|
||||
while b != 0 {
|
||||
let remainder = a % b;
|
||||
a = b;
|
||||
b = remainder;
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
impl Size {
|
||||
pub(crate) const ONE: Self = Self::exact(1, 1);
|
||||
|
||||
const fn exact(numerator: i128, denominator: i128) -> Self {
|
||||
Self {
|
||||
numerator,
|
||||
denominator,
|
||||
pi: 0,
|
||||
pixel: 0,
|
||||
}
|
||||
}
|
||||
|
||||
const fn with_pi(self, pi: i8) -> Self {
|
||||
Self { pi, ..self }
|
||||
}
|
||||
|
||||
/// The size in lowest terms with a positive denominator, or `None` for a zero denominator.
|
||||
fn reduced(numerator: i128, denominator: i128, pi: i8, pixel: i8) -> Option<Self> {
|
||||
if denominator == 0 {
|
||||
return None;
|
||||
}
|
||||
let divisor = greatest_common_divisor(numerator, denominator);
|
||||
let sign = denominator.signum();
|
||||
Some(Self {
|
||||
numerator: sign * numerator / divisor,
|
||||
denominator: sign * denominator / divisor,
|
||||
pi,
|
||||
pixel,
|
||||
})
|
||||
}
|
||||
|
||||
fn times(self, other: Self) -> Option<Self> {
|
||||
// Cross-reducing first keeps the products as small as they can be
|
||||
let left = greatest_common_divisor(self.numerator, other.denominator).max(1);
|
||||
let right = greatest_common_divisor(other.numerator, self.denominator).max(1);
|
||||
let numerator = (self.numerator / left).checked_mul(other.numerator / right)?;
|
||||
let denominator = (self.denominator / right).checked_mul(other.denominator / left)?;
|
||||
Self::reduced(numerator, denominator, self.pi.checked_add(other.pi)?, self.pixel.checked_add(other.pixel)?)
|
||||
}
|
||||
|
||||
fn inverse(self) -> Option<Self> {
|
||||
Self::reduced(self.denominator, self.numerator, self.pi.checked_neg()?, self.pixel.checked_neg()?)
|
||||
}
|
||||
|
||||
/// The reciprocal of a size that is a ratio of integers alone, which is always representable.
|
||||
pub(crate) fn inverse_exact(self) -> Self {
|
||||
self.inverse().unwrap_or(Self::ONE)
|
||||
}
|
||||
|
||||
fn over(self, other: Self) -> Option<Self> {
|
||||
self.times(other.inverse()?)
|
||||
}
|
||||
|
||||
/// The size raised to an integer power, in O(|exponent|) exact multiplications.
|
||||
fn power(self, exponent: i8) -> Option<Self> {
|
||||
let base = if exponent < 0 { self.inverse()? } else { self };
|
||||
(0..exponent.unsigned_abs()).try_fold(Self::ONE, |power, _| power.times(base))
|
||||
}
|
||||
|
||||
pub(crate) fn is_one(self) -> bool {
|
||||
self == Self::ONE
|
||||
}
|
||||
|
||||
/// The size split into its numerator with any powers of π and the pixels per inch, and its denominator, so a product can
|
||||
/// scale one operand by each before combining them, rounding no more than the conversions would on their own.
|
||||
pub(crate) fn split(self) -> (Self, Self) {
|
||||
(Self { denominator: 1, ..self }, Self::exact(self.denominator, 1))
|
||||
}
|
||||
|
||||
/// The size as a ratio of integers with the pixels per inch substituted, or `None` where a power of π remains or the
|
||||
/// pixels per inch is no short decimal.
|
||||
pub(crate) fn rational(self, pixels_per_inch: f64) -> Option<(i128, i128)> {
|
||||
if self.pi != 0 {
|
||||
return None;
|
||||
}
|
||||
if self.pixel == 0 {
|
||||
return Some((self.numerator, self.denominator));
|
||||
}
|
||||
|
||||
// A pixel is an inch over the pixels per inch, read exactly when it has at most six decimal places
|
||||
let (pixels, per) = (0..=6).find_map(|places| {
|
||||
let scale = 10_i128.pow(places);
|
||||
let scaled = pixels_per_inch * scale as f64;
|
||||
(scaled.fract() == 0. && scaled.abs() < (1_u64 << 53) as f64 && scaled > 0.).then_some((scaled as i128, scale))
|
||||
})?;
|
||||
let size = self.with_pixel(0).times(Self::reduced(per, pixels, 0, 0)?.power(self.pixel)?)?;
|
||||
Some((size.numerator, size.denominator))
|
||||
}
|
||||
|
||||
const fn with_pixel(self, pixel: i8) -> Self {
|
||||
Self { pixel, ..self }
|
||||
}
|
||||
|
||||
/// Multiplies a number by the size: by the numerator, then the denominator, so an integer stays exact and a real rounds
|
||||
/// once for each, then by any powers of π and the pixels per inch.
|
||||
pub(crate) fn apply(self, number: Number, pixels_per_inch: f64) -> Option<Number> {
|
||||
let integer = |integer: i128| i64::try_from(integer).map_or(Number::Real(integer as f64), Number::Integer);
|
||||
|
||||
if let Number::Integer(value) = number
|
||||
&& self.pi == 0
|
||||
&& self.pixel == 0
|
||||
&& let Some(scaled) = (value as i128).checked_mul(self.numerator)
|
||||
&& scaled % self.denominator == 0
|
||||
&& let Ok(exact) = i64::try_from(scaled / self.denominator)
|
||||
{
|
||||
return Some(Number::Integer(exact));
|
||||
}
|
||||
|
||||
let mut result = number;
|
||||
if self.numerator != 1 {
|
||||
result = result.binary_op(BinaryOp::Mul, integer(self.numerator))?.canonical();
|
||||
}
|
||||
if self.denominator != 1 {
|
||||
result = result.binary_op(BinaryOp::Div, integer(self.denominator))?.canonical();
|
||||
}
|
||||
let power_of = |base: f64, exponent: i8| Number::Real(base.powi(exponent.unsigned_abs() as i32));
|
||||
if self.pi != 0 {
|
||||
let operation = if self.pi > 0 { BinaryOp::Mul } else { BinaryOp::Div };
|
||||
result = result.binary_op(operation, power_of(PI, self.pi))?.canonical();
|
||||
}
|
||||
if self.pixel != 0 {
|
||||
let operation = if self.pixel > 0 { BinaryOp::Div } else { BinaryOp::Mul };
|
||||
result = result.binary_op(operation, power_of(pixels_per_inch, self.pixel))?.canonical();
|
||||
}
|
||||
Some(result)
|
||||
}
|
||||
}
|
||||
|
||||
/// One entry of the unit table.
|
||||
#[derive(Debug)]
|
||||
pub struct UnitDefinition {
|
||||
/// The spelling results are written with.
|
||||
pub symbol: &'static str,
|
||||
/// The unit's name, for documentation and completions.
|
||||
pub name: &'static str,
|
||||
/// Every spelling naming the unit, its symbol first, then its other abbreviations and its singular and plural names.
|
||||
pub spellings: &'static [&'static str],
|
||||
pub dimension: Dimension,
|
||||
/// The size in the coherent unit of its dimension: meters, kilograms, seconds, radians, and their products.
|
||||
size: Size,
|
||||
}
|
||||
|
||||
const fn unit(symbol: &'static str, name: &'static str, spellings: &'static [&'static str], dimension: Dimension, size: Size) -> UnitDefinition {
|
||||
UnitDefinition {
|
||||
symbol,
|
||||
name,
|
||||
spellings,
|
||||
dimension,
|
||||
size,
|
||||
}
|
||||
}
|
||||
|
||||
const fn ratio(numerator: i128, denominator: i128) -> Size {
|
||||
Size::exact(numerator, denominator)
|
||||
}
|
||||
|
||||
const INCH: Size = ratio(127, 5000);
|
||||
const GALLON: Size = ratio(3_785_411_784, 1_000_000_000_000);
|
||||
|
||||
/// Every unit the language knows, related units together. The metric prefixes are spelled out per unit rather than applying to
|
||||
/// any unit, since `min`, `ft`, and `cd` would otherwise also read as a milli-inch, a femto-tonne, and a centi-day.
|
||||
pub const UNITS: [UnitDefinition; 54] = [
|
||||
// Length
|
||||
unit("px", "pixel", &["px", "pixel", "pixels"], Dimension::LENGTH, INCH.with_pixel(1)),
|
||||
unit("pt", "point", &["pt", "point", "points"], Dimension::LENGTH, ratio(127, 360_000)),
|
||||
unit("pc", "pica", &["pc", "pica", "picas"], Dimension::LENGTH, ratio(127, 30_000)),
|
||||
unit("nm", "nanometer", &["nm", "nanometer", "nanometers"], Dimension::LENGTH, ratio(1, 1_000_000_000)),
|
||||
unit(
|
||||
"µm",
|
||||
"micrometer",
|
||||
&["µm", "μm", "um", "micrometer", "micrometers", "micron", "microns"],
|
||||
Dimension::LENGTH,
|
||||
ratio(1, 1_000_000),
|
||||
),
|
||||
unit("mm", "millimeter", &["mm", "millimeter", "millimeters"], Dimension::LENGTH, ratio(1, 1000)),
|
||||
unit("cm", "centimeter", &["cm", "centimeter", "centimeters"], Dimension::LENGTH, ratio(1, 100)),
|
||||
unit("m", "meter", &["m", "meter", "meters"], Dimension::LENGTH, ratio(1, 1)),
|
||||
unit("km", "kilometer", &["km", "kilometer", "kilometers"], Dimension::LENGTH, ratio(1000, 1)),
|
||||
unit("thou", "thou", &["thou"], Dimension::LENGTH, ratio(127, 5_000_000)),
|
||||
unit("in", "inch", &["in", "\"", "inch", "inches"], Dimension::LENGTH, INCH),
|
||||
unit("ft", "foot", &["ft", "'", "foot", "feet"], Dimension::LENGTH, ratio(381, 1250)),
|
||||
unit("yd", "yard", &["yd", "yard", "yards"], Dimension::LENGTH, ratio(1143, 1250)),
|
||||
unit("mi", "mile", &["mi", "mile", "miles"], Dimension::LENGTH, ratio(201_168, 125)),
|
||||
unit("nmi", "nautical mile", &["nmi"], Dimension::LENGTH, ratio(1852, 1)),
|
||||
// Area
|
||||
unit("are", "are", &["are", "ares"], Dimension::AREA, ratio(100, 1)),
|
||||
unit("hectare", "hectare", &["hectare", "hectares"], Dimension::AREA, ratio(10_000, 1)),
|
||||
unit("acre", "acre", &["acre", "acres"], Dimension::AREA, ratio(40_468_564_224, 10_000_000)),
|
||||
// Volume
|
||||
unit("ml", "milliliter", &["ml", "milliliter", "milliliters"], Dimension::VOLUME, ratio(1, 1_000_000)),
|
||||
unit("cl", "centiliter", &["cl", "centiliter", "centiliters"], Dimension::VOLUME, ratio(1, 100_000)),
|
||||
unit("l", "liter", &["l", "liter", "liters"], Dimension::VOLUME, ratio(1, 1000)),
|
||||
unit("floz", "fluid ounce", &["floz"], Dimension::VOLUME, ratio(3_785_411_784, 128_000_000_000_000)),
|
||||
unit("cup", "cup", &["cup", "cups"], Dimension::VOLUME, ratio(3_785_411_784, 16_000_000_000_000)),
|
||||
unit("pint", "pint", &["pint", "pints"], Dimension::VOLUME, ratio(3_785_411_784, 8_000_000_000_000)),
|
||||
unit("qt", "quart", &["qt", "quart", "quarts"], Dimension::VOLUME, ratio(3_785_411_784, 4_000_000_000_000)),
|
||||
unit("gal", "gallon", &["gal", "gallon", "gallons"], Dimension::VOLUME, GALLON),
|
||||
// Mass
|
||||
unit("µg", "microgram", &["µg", "μg", "ug", "microgram", "micrograms"], Dimension::MASS, ratio(1, 1_000_000_000)),
|
||||
unit("mg", "milligram", &["mg", "milligram", "milligrams"], Dimension::MASS, ratio(1, 1_000_000)),
|
||||
unit("g", "gram", &["g", "gram", "grams"], Dimension::MASS, ratio(1, 1000)),
|
||||
unit("kg", "kilogram", &["kg", "kilogram", "kilograms"], Dimension::MASS, ratio(1, 1)),
|
||||
unit("tonne", "tonne", &["tonne", "tonnes"], Dimension::MASS, ratio(1000, 1)),
|
||||
unit("gr", "grain", &["gr", "grain", "grains"], Dimension::MASS, ratio(6_479_891, 100_000_000_000)),
|
||||
unit("oz", "ounce", &["oz", "ounce", "ounces"], Dimension::MASS, ratio(28_349_523_125, 1_000_000_000_000)),
|
||||
unit("lb", "pound", &["lb", "lbs", "pound", "pounds"], Dimension::MASS, ratio(45_359_237, 100_000_000)),
|
||||
unit("ton", "ton", &["ton", "tons"], Dimension::MASS, ratio(90_718_474, 100_000)),
|
||||
// Time
|
||||
unit("ns", "nanosecond", &["ns", "nanosecond", "nanoseconds"], Dimension::TIME, ratio(1, 1_000_000_000)),
|
||||
unit("µs", "microsecond", &["µs", "μs", "us", "microsecond", "microseconds"], Dimension::TIME, ratio(1, 1_000_000)),
|
||||
unit("ms", "millisecond", &["ms", "millisecond", "milliseconds"], Dimension::TIME, ratio(1, 1000)),
|
||||
unit("s", "second", &["s", "sec", "second", "seconds"], Dimension::TIME, ratio(1, 1)),
|
||||
unit("min", "minute", &["min", "minute", "minutes"], Dimension::TIME, ratio(60, 1)),
|
||||
unit("h", "hour", &["h", "hr", "hour", "hours"], Dimension::TIME, ratio(3600, 1)),
|
||||
unit("day", "day", &["day", "days"], Dimension::TIME, ratio(86_400, 1)),
|
||||
// Angle
|
||||
unit("rad", "radian", &["rad", "radian", "radians"], Dimension::ANGLE, ratio(1, 1)),
|
||||
unit("°", "degree", &["°", "deg", "degree", "degrees"], Dimension::ANGLE, ratio(1, 180).with_pi(1)),
|
||||
unit("turn", "turn", &["turn", "turns"], Dimension::ANGLE, ratio(2, 1).with_pi(1)),
|
||||
// Frequency
|
||||
unit("Hz", "hertz", &["Hz", "hertz"], Dimension::FREQUENCY, ratio(1, 1)),
|
||||
unit("kHz", "kilohertz", &["kHz", "kilohertz"], Dimension::FREQUENCY, ratio(1000, 1)),
|
||||
unit("MHz", "megahertz", &["MHz", "megahertz"], Dimension::FREQUENCY, ratio(1_000_000, 1)),
|
||||
unit("GHz", "gigahertz", &["GHz", "gigahertz"], Dimension::FREQUENCY, ratio(1_000_000_000, 1)),
|
||||
// Angular speed
|
||||
unit("rpm", "revolution per minute", &["rpm"], Dimension::ANGULAR_SPEED, ratio(1, 30).with_pi(1)),
|
||||
unit("rps", "revolution per second", &["rps"], Dimension::ANGULAR_SPEED, ratio(2, 1).with_pi(1)),
|
||||
// Speed
|
||||
unit("mph", "mile per hour", &["mph"], Dimension::SPEED, ratio(1397, 3125)),
|
||||
unit("knot", "knot", &["knot", "knots"], Dimension::SPEED, ratio(463, 900)),
|
||||
// Dimensionless
|
||||
unit("%", "percent", &["%", "percent"], Dimension::NONE, ratio(1, 100)),
|
||||
];
|
||||
|
||||
/// An index into [`UNITS`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct UnitId(u8);
|
||||
|
||||
impl UnitId {
|
||||
pub fn definition(self) -> &'static UnitDefinition {
|
||||
&UNITS[self.0 as usize]
|
||||
}
|
||||
|
||||
/// The unit whose symbol this is, found as the table is compiled, so naming a unit that isn't in it fails to build.
|
||||
const fn of_symbol(symbol: &str) -> Self {
|
||||
let mut index = 0;
|
||||
while index < UNITS.len() {
|
||||
if bytes_equal(UNITS[index].symbol.as_bytes(), symbol.as_bytes()) {
|
||||
return Self(index as u8);
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
panic!("no unit has this symbol");
|
||||
}
|
||||
|
||||
pub const RADIAN: Self = Self::of_symbol("rad");
|
||||
pub const PIXEL: Self = Self::of_symbol("px");
|
||||
}
|
||||
|
||||
const fn bytes_equal(a: &[u8], b: &[u8]) -> bool {
|
||||
if a.len() != b.len() {
|
||||
return false;
|
||||
}
|
||||
let mut index = 0;
|
||||
while index < a.len() {
|
||||
if a[index] != b[index] {
|
||||
return false;
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The unit a spelling names, like `mm` or `inches`, read after any `\` prefix.
|
||||
pub fn unit_named(name: &str) -> Option<UnitId> {
|
||||
let name = name.strip_prefix('\\').unwrap_or(name);
|
||||
UNITS.iter().position(|unit| unit.spellings.contains(&name)).map(|index| UnitId(index as u8))
|
||||
}
|
||||
|
||||
/// The unit each base dimension is coherently measured in, so a product of them needs no conversion factor.
|
||||
fn coherent_unit(base: usize) -> UnitId {
|
||||
const COHERENT: [UnitId; 4] = [UnitId::of_symbol("m"), UnitId::of_symbol("kg"), UnitId::of_symbol("s"), UnitId::RADIAN];
|
||||
COHERENT[base]
|
||||
}
|
||||
|
||||
/// A unit raised to a nonzero power within a [`Unit`], where an empty slot has unit 0 and exponent 0.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
|
||||
struct Factor {
|
||||
/// One more than the unit's index, so 0 marks an empty slot.
|
||||
unit: u8,
|
||||
exponent: i8,
|
||||
}
|
||||
|
||||
impl Factor {
|
||||
fn id(self) -> UnitId {
|
||||
UnitId(self.unit - 1)
|
||||
}
|
||||
}
|
||||
|
||||
/// What a value is measured in: a product of at most four units from the table, each raised to a nonzero integer power, like
|
||||
/// `km/h` or `m^2`. A value without one is plain.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
|
||||
pub struct Unit {
|
||||
/// Ordered by unit, with the empty slots last, so equal products compare equal.
|
||||
factors: [Factor; 4],
|
||||
}
|
||||
|
||||
/// Why units can't combine.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum UnitError {
|
||||
/// The units' sizes or powers are too far out to represent.
|
||||
Overflow,
|
||||
/// A power leaves a fractional exponent on a unit, like `sqrt(1mm)`.
|
||||
FractionalPower,
|
||||
/// The units measure different dimensions.
|
||||
Incompatible,
|
||||
}
|
||||
|
||||
impl Unit {
|
||||
pub const NONE: Self = Self {
|
||||
factors: [Factor { unit: 0, exponent: 0 }; 4],
|
||||
};
|
||||
|
||||
/// The unit alone, to the first power.
|
||||
pub const fn of(unit: UnitId) -> Self {
|
||||
let mut result = Self::NONE;
|
||||
result.factors[0] = Factor { unit: unit.0 + 1, exponent: 1 };
|
||||
result
|
||||
}
|
||||
|
||||
/// The unit a spelling names, like `mm`.
|
||||
pub fn named(name: &str) -> Option<Self> {
|
||||
unit_named(name).map(Self::of)
|
||||
}
|
||||
|
||||
/// A product of units from their exponents, merging repeated units, or `None` past four distinct units or an exponent past ±127.
|
||||
fn from_factors(factors: &[(UnitId, i8)]) -> Option<Self> {
|
||||
let mut merged: Vec<(UnitId, i8)> = Vec::with_capacity(factors.len());
|
||||
for &(unit, exponent) in factors {
|
||||
match merged.iter_mut().find(|(existing, _)| *existing == unit) {
|
||||
Some((_, total)) => *total = total.checked_add(exponent)?,
|
||||
None => merged.push((unit, exponent)),
|
||||
}
|
||||
}
|
||||
merged.retain(|(_, exponent)| *exponent != 0);
|
||||
if merged.iter().any(|(_, exponent)| *exponent == i8::MIN) {
|
||||
return None;
|
||||
}
|
||||
merged.sort_by_key(|(unit, _)| *unit);
|
||||
if merged.len() > 4 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut result = Self::NONE;
|
||||
for (slot, (unit, exponent)) in result.factors.iter_mut().zip(merged) {
|
||||
*slot = Factor { unit: unit.0 + 1, exponent };
|
||||
}
|
||||
Some(result)
|
||||
}
|
||||
|
||||
fn entries(self) -> impl Iterator<Item = (UnitId, i8)> {
|
||||
self.factors.into_iter().filter(|factor| factor.unit != 0).map(|factor| (factor.id(), factor.exponent))
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn is_none(self) -> bool {
|
||||
self.factors[0].unit == 0
|
||||
}
|
||||
|
||||
/// The unit, if it is one unit to the first power, like `mm` but not `mm^2` or `km/h`.
|
||||
pub fn single(self) -> Option<UnitId> {
|
||||
let mut entries = self.entries();
|
||||
match (entries.next(), entries.next()) {
|
||||
(Some((unit, 1)), None) => Some(unit),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dimension(self) -> Dimension {
|
||||
// Exponents stay within ±127 and a unit's dimension within ±3, so these sums can't overflow
|
||||
let mut dimension = [0_i16; 4];
|
||||
for (unit, exponent) in self.entries() {
|
||||
for (total, base) in dimension.iter_mut().zip(unit.definition().dimension.0) {
|
||||
*total += base * exponent as i16;
|
||||
}
|
||||
}
|
||||
Dimension(dimension)
|
||||
}
|
||||
|
||||
/// Whether the unit is a dimensionless one like `%`, which plain numbers don't add to but which folds away in products.
|
||||
pub fn is_dimensionless(self) -> bool {
|
||||
!self.is_none() && self.dimension().is_none()
|
||||
}
|
||||
|
||||
/// The size of one of this unit in coherent units.
|
||||
pub(crate) fn size(self) -> Option<Size> {
|
||||
self.entries().try_fold(Size::ONE, |size, (unit, exponent)| size.times(unit.definition().size.power(exponent)?))
|
||||
}
|
||||
|
||||
pub fn inverse(self) -> Self {
|
||||
let mut result = self;
|
||||
for factor in result.factors.iter_mut().filter(|factor| factor.unit != 0) {
|
||||
factor.exponent = -factor.exponent;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// The unit raised to a real power, which must leave every exponent an integer, like `0.5` on `mm^2`.
|
||||
pub fn power(self, exponent: f64) -> Result<Self, UnitError> {
|
||||
let factors = self
|
||||
.entries()
|
||||
.map(|(unit, power)| {
|
||||
// A root's reciprocal exponent rounds, so a power within a hair of an integer counts as that integer
|
||||
let raised = power as f64 * exponent;
|
||||
let whole = raised.round();
|
||||
if (raised - whole).abs() > 1e-9 {
|
||||
return Err(UnitError::FractionalPower);
|
||||
}
|
||||
if !(-(i8::MAX as f64)..=i8::MAX as f64).contains(&whole) {
|
||||
return Err(UnitError::Overflow);
|
||||
}
|
||||
Ok((unit, whole as i8))
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
Self::from_factors(&factors).ok_or(UnitError::Overflow)
|
||||
}
|
||||
|
||||
/// The product of two units with the factor its number is multiplied by: units of one dimension merge into one, so a
|
||||
/// value's units never mix (`mm in` is `mm^2`), units whose dimensions overlap expand to cancel (`rpm s` is a fraction of
|
||||
/// a turn), and a dimensionless unit like `%` folds into the number beside any other unit or past its first power.
|
||||
pub(crate) fn product(self, other: Self, pixels_per_inch: f64) -> Result<(Self, Size), UnitError> {
|
||||
// A plain operand leaves the other's unit as it is, unless that is a percentage, which folds past its first power
|
||||
let lone = match (self.is_none(), other.is_none()) {
|
||||
(true, true) => return Ok((Self::NONE, Size::ONE)),
|
||||
(true, false) => Some(other),
|
||||
(false, true) => Some(self),
|
||||
(false, false) => None,
|
||||
};
|
||||
if let Some(lone) = lone
|
||||
&& lone.entries().all(|(unit, exponent)| exponent == 1 || !unit.definition().dimension.is_none())
|
||||
{
|
||||
return Ok((lone, Size::ONE));
|
||||
}
|
||||
|
||||
let mut factors: Vec<(UnitId, i8)> = Vec::with_capacity(8);
|
||||
for (unit, exponent) in self.entries().chain(other.entries()) {
|
||||
match factors.iter_mut().find(|(existing, _)| *existing == unit) {
|
||||
Some((_, total)) => *total = total.checked_add(exponent).ok_or(UnitError::Overflow)?,
|
||||
None => factors.push((unit, exponent)),
|
||||
}
|
||||
}
|
||||
factors.retain(|(_, exponent)| *exponent != 0);
|
||||
|
||||
let mut scale = Size::ONE;
|
||||
loop {
|
||||
// Two units of one dimension merge into the one a sum of them would be measured in
|
||||
let same_dimension = pairs(factors.len()).find(|&(a, b)| factors[a].0.definition().dimension == factors[b].0.definition().dimension);
|
||||
if let Some((a, b)) = same_dimension {
|
||||
let (unit_a, unit_b) = (factors[a].0, factors[b].0);
|
||||
let target = common_unit(Unit::of(unit_a), Unit::of(unit_b), pixels_per_inch);
|
||||
let (from, into) = if target == Unit::of(unit_b) { (a, b) } else { (b, a) };
|
||||
|
||||
// Converting `from^e` into `into^e` multiplies by the ratio of their sizes to the `e`
|
||||
let exponent = factors[from].1;
|
||||
let ratio = factors[from].0.definition().size.over(factors[into].0.definition().size).ok_or(UnitError::Overflow)?;
|
||||
scale = scale.times(ratio.power(exponent).ok_or(UnitError::Overflow)?).ok_or(UnitError::Overflow)?;
|
||||
factors[into].1 = factors[into].1.checked_add(exponent).ok_or(UnitError::Overflow)?;
|
||||
factors.remove(from);
|
||||
factors.retain(|(_, exponent)| *exponent != 0);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Units whose dimensions overlap without matching expand into coherent units, where the shared dimension merges
|
||||
let overlapping = pairs(factors.len()).find(|&(a, b)| factors[a].0.definition().dimension.overlaps(factors[b].0.definition().dimension));
|
||||
if let Some((a, b)) = overlapping {
|
||||
let expanded = [factors[a], factors[b]];
|
||||
factors.retain(|(unit, _)| *unit != expanded[0].0 && *unit != expanded[1].0);
|
||||
for (unit, exponent) in expanded {
|
||||
scale = scale.times(unit.definition().size.power(exponent).ok_or(UnitError::Overflow)?).ok_or(UnitError::Overflow)?;
|
||||
push_coherent(&mut factors, unit.definition().dimension, exponent)?;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
// A dimensionless unit is a plain factor of the number beside any unit with a dimension, and a percentage of a percentage is one percentage
|
||||
let has_dimension = factors.iter().any(|(unit, _)| !unit.definition().dimension.is_none());
|
||||
for (unit, exponent) in factors.iter_mut().filter(|(unit, _)| unit.definition().dimension.is_none()) {
|
||||
let folded = if has_dimension || *exponent < 0 { *exponent } else { *exponent - 1 };
|
||||
scale = scale.times(unit.definition().size.power(folded).ok_or(UnitError::Overflow)?).ok_or(UnitError::Overflow)?;
|
||||
*exponent -= folded;
|
||||
}
|
||||
factors.retain(|(_, exponent)| *exponent != 0);
|
||||
|
||||
// Past four distinct units, everything is measured in coherent units, which take at most one per base dimension
|
||||
if factors.len() > 4 {
|
||||
let mut coherent = Vec::new();
|
||||
for (unit, exponent) in factors {
|
||||
scale = scale.times(unit.definition().size.power(exponent).ok_or(UnitError::Overflow)?).ok_or(UnitError::Overflow)?;
|
||||
push_coherent(&mut coherent, unit.definition().dimension, exponent)?;
|
||||
}
|
||||
factors = coherent;
|
||||
}
|
||||
|
||||
Ok((Self::from_factors(&factors).ok_or(UnitError::Overflow)?, scale))
|
||||
}
|
||||
|
||||
/// The factor that converts a number in this unit into `target`, which must measure the same dimension.
|
||||
pub(crate) fn conversion(self, target: Self) -> Result<Size, UnitError> {
|
||||
if self.dimension() != target.dimension() {
|
||||
return Err(UnitError::Incompatible);
|
||||
}
|
||||
if self == target {
|
||||
return Ok(Size::ONE);
|
||||
}
|
||||
self.size().zip(target.size()).and_then(|(from, into)| from.over(into)).ok_or(UnitError::Overflow)
|
||||
}
|
||||
}
|
||||
|
||||
/// Every pair of distinct indices below `count`.
|
||||
fn pairs(count: usize) -> impl Iterator<Item = (usize, usize)> {
|
||||
(0..count).flat_map(move |a| (a + 1..count).map(move |b| (a, b)))
|
||||
}
|
||||
|
||||
/// Adds the coherent units of a dimension raised to `exponent` to a list of factors.
|
||||
fn push_coherent(factors: &mut Vec<(UnitId, i8)>, dimension: Dimension, exponent: i8) -> Result<(), UnitError> {
|
||||
for (base, power) in dimension.0.into_iter().enumerate().filter(|(_, power)| *power != 0) {
|
||||
let raised = i8::try_from(power * exponent as i16).ok().filter(|raised| *raised != i8::MIN).ok_or(UnitError::Overflow)?;
|
||||
let unit = coherent_unit(base);
|
||||
match factors.iter_mut().find(|(existing, _)| *existing == unit) {
|
||||
Some((_, total)) => *total = total.checked_add(raised).ok_or(UnitError::Overflow)?,
|
||||
None => factors.push((unit, raised)),
|
||||
}
|
||||
}
|
||||
factors.retain(|(_, exponent)| *exponent != 0);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether a ratio's denominator divides a power of ten, so the ratio is a terminating decimal.
|
||||
fn terminates(mut denominator: i128) -> bool {
|
||||
for prime in [2, 5] {
|
||||
while denominator % prime == 0 {
|
||||
denominator /= prime;
|
||||
}
|
||||
}
|
||||
denominator == 1
|
||||
}
|
||||
|
||||
/// Which of two units of one dimension a sum of them is measured in: the one the other converts into by an integer, like
|
||||
/// millimeters beside meters, or else by a terminating decimal, like meters beside feet, or else the one whose size has no
|
||||
/// factor of π, like radians beside degrees, or else the left one.
|
||||
pub fn common_unit(left: Unit, right: Unit, pixels_per_inch: f64) -> Unit {
|
||||
if left == right {
|
||||
return left;
|
||||
}
|
||||
let (Some(left_size), Some(right_size)) = (left.size(), right.size()) else { return left };
|
||||
let Some(ratio) = left_size.over(right_size) else { return left };
|
||||
|
||||
// The ratio is how many of the right unit one of the left makes
|
||||
match ratio.rational(pixels_per_inch) {
|
||||
Some((_, 1)) => right,
|
||||
Some((1, _)) => left,
|
||||
Some((_, denominator)) if terminates(denominator) => right,
|
||||
Some((numerator, _)) if terminates(numerator) => left,
|
||||
Some(_) => left,
|
||||
None if left_size.pi != 0 && right_size.pi == 0 => right,
|
||||
None => left,
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Unit {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let write_factor = |f: &mut fmt::Formatter<'_>, unit: UnitId, exponent: i8| {
|
||||
let symbol = unit.definition().symbol;
|
||||
if exponent.unsigned_abs() == 1 {
|
||||
f.write_str(symbol)
|
||||
} else {
|
||||
write!(f, "{symbol}^{}", exponent.unsigned_abs())
|
||||
}
|
||||
};
|
||||
|
||||
let numerator: Vec<_> = self.entries().filter(|(_, exponent)| *exponent > 0).collect();
|
||||
let denominator: Vec<_> = self.entries().filter(|(_, exponent)| *exponent < 0).collect();
|
||||
|
||||
if numerator.is_empty() && !denominator.is_empty() {
|
||||
f.write_str("1")?;
|
||||
}
|
||||
for (index, (unit, exponent)) in numerator.iter().enumerate() {
|
||||
if index > 0 {
|
||||
f.write_str(" ")?;
|
||||
}
|
||||
write_factor(f, *unit, *exponent)?;
|
||||
}
|
||||
|
||||
if !denominator.is_empty() {
|
||||
f.write_str("/")?;
|
||||
let grouped = denominator.len() > 1;
|
||||
if grouped {
|
||||
f.write_str("(")?;
|
||||
}
|
||||
for (index, (unit, exponent)) in denominator.iter().enumerate() {
|
||||
if index > 0 {
|
||||
f.write_str(" ")?;
|
||||
}
|
||||
write_factor(f, *unit, *exponent)?;
|
||||
}
|
||||
if grouped {
|
||||
f.write_str(")")?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Unit {
|
||||
/// Whether a number is written right against this unit, like `45°` or `50%`, rather than with a space, like `5 mm`.
|
||||
pub fn attaches_without_space(self) -> bool {
|
||||
let first = self.entries().find(|(_, exponent)| *exponent > 0);
|
||||
first.is_some_and(|(unit, _)| !unit.definition().symbol.starts_with(char::is_alphabetic))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn unit(name: &str) -> Unit {
|
||||
Unit::named(name).unwrap_or_else(|| panic!("`{name}` should be a unit"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spellings_are_unique_and_symbols_lead() {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for definition in &UNITS {
|
||||
assert_eq!(definition.spellings[0], definition.symbol, "`{}` lists its symbol first", definition.name);
|
||||
for spelling in definition.spellings {
|
||||
assert!(seen.insert(*spelling), "`{spelling}` names two units");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sums_take_the_unit_that_converts_exactly() {
|
||||
let ppi = DEFAULT_PIXELS_PER_INCH;
|
||||
assert_eq!(common_unit(unit("m"), unit("mm"), ppi), unit("mm"));
|
||||
assert_eq!(common_unit(unit("mm"), unit("m"), ppi), unit("mm"));
|
||||
assert_eq!(common_unit(unit("m"), unit("ft"), ppi), unit("m"));
|
||||
assert_eq!(common_unit(unit("ft"), unit("m"), ppi), unit("m"));
|
||||
assert_eq!(common_unit(unit("in"), unit("mm"), ppi), unit("mm"));
|
||||
assert_eq!(common_unit(unit("in"), unit("px"), ppi), unit("px"));
|
||||
assert_eq!(common_unit(unit("deg"), unit("rad"), ppi), unit("rad"));
|
||||
assert_eq!(common_unit(unit("rad"), unit("deg"), ppi), unit("rad"));
|
||||
assert_eq!(common_unit(unit("turn"), unit("deg"), ppi), unit("deg"));
|
||||
assert_eq!(common_unit(unit("px"), unit("mm"), ppi), unit("px"));
|
||||
assert_eq!(common_unit(unit("mm"), unit("px"), ppi), unit("mm"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn products_merge_units_of_one_dimension() {
|
||||
let ppi = DEFAULT_PIXELS_PER_INCH;
|
||||
let (product, scale) = unit("mm").product(unit("in"), ppi).unwrap();
|
||||
assert_eq!(product, unit("mm").power(2.).unwrap());
|
||||
assert_eq!(scale.apply(Number::Integer(1), ppi), Some(Number::Real(25.4)));
|
||||
|
||||
let (quotient, scale) = unit("m").product(unit("mm").inverse(), ppi).unwrap();
|
||||
assert_eq!(quotient, Unit::NONE);
|
||||
assert_eq!(scale.apply(Number::Integer(1), ppi), Some(Number::Integer(1000)));
|
||||
|
||||
// An angular speed over a duration expands so the time cancels
|
||||
let (angle, _) = unit("rpm").product(unit("s"), ppi).unwrap();
|
||||
assert_eq!(angle.dimension(), Dimension::ANGLE);
|
||||
|
||||
// A percentage folds into the number beside a length, and stays once beside a plain number
|
||||
let (length, scale) = unit("%").product(unit("mm"), ppi).unwrap();
|
||||
assert_eq!(length, unit("mm"));
|
||||
assert_eq!(scale.apply(Number::Integer(50), ppi).and_then(Number::as_real), Some(0.5));
|
||||
let (percent, scale) = unit("%").product(unit("%"), ppi).unwrap();
|
||||
assert_eq!(percent, unit("%"));
|
||||
assert_eq!(scale.apply(Number::Integer(2500), ppi).and_then(Number::as_real), Some(25.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conversions_are_exact_ratios() {
|
||||
let ppi = DEFAULT_PIXELS_PER_INCH;
|
||||
let convert = |value: i64, from: &str, into: &str| unit(from).conversion(unit(into)).unwrap().apply(Number::Integer(value), ppi).unwrap().canonical();
|
||||
assert_eq!(convert(3, "ft", "in"), Number::Integer(36));
|
||||
assert_eq!(convert(1, "in", "px"), Number::Integer(96));
|
||||
assert_eq!(convert(72, "pt", "in"), Number::Integer(1));
|
||||
assert_eq!(convert(1, "turn", "deg"), Number::Integer(360));
|
||||
assert_eq!(convert(1, "h", "s"), Number::Integer(3600));
|
||||
assert_eq!(convert(254, "mm", "in").as_real(), Some(10.));
|
||||
assert!(unit("mm").conversion(unit("s")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn units_display_as_written() {
|
||||
assert_eq!(unit("km").product(unit("h").inverse(), 96.).unwrap().0.to_string(), "km/h");
|
||||
assert_eq!(unit("m").product(unit("s").power(-2.).unwrap(), 96.).unwrap().0.to_string(), "m/s^2");
|
||||
assert_eq!(unit("s").inverse().to_string(), "1/s");
|
||||
assert_eq!(unit("deg").to_string(), "°");
|
||||
assert!(unit("deg").attaches_without_space());
|
||||
assert!(!unit("mm").attaches_without_space());
|
||||
}
|
||||
}
|
||||
@@ -1,392 +0,0 @@
|
||||
use crate::ast::Node;
|
||||
use crate::context::{EvalContext, NothingMap, ValueProvider};
|
||||
use crate::object::Object;
|
||||
use crate::quantity::Quantity;
|
||||
use crate::units::{Dimension, Unit};
|
||||
use crate::value::Value;
|
||||
|
||||
const EPSILON: f64 = 1e-9;
|
||||
|
||||
fn evaluate_with(source: &str, pixels_per_inch: f64) -> Result<Object, String> {
|
||||
let node = Node::try_parse_from_str(source).map_err(|error| error.to_string())?;
|
||||
node.eval(&EvalContext::new(NothingMap, NothingMap).with_pixels_per_inch(pixels_per_inch))
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn quantity(source: &str) -> Quantity {
|
||||
match evaluate_with(source, 96.) {
|
||||
Ok(Object::Value(quantity)) => quantity,
|
||||
result => panic!("`{source}` should be a value, not {result:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn shown(source: &str) -> String {
|
||||
quantity(source).to_string()
|
||||
}
|
||||
|
||||
fn error(source: &str) -> String {
|
||||
match evaluate_with(source, 96.) {
|
||||
Err(error) => error,
|
||||
Ok(result) => panic!("`{source}` should fail, not give {result}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn unit(name: &str) -> Unit {
|
||||
Unit::named(name).unwrap_or_else(|| panic!("`{name}` should name a unit"))
|
||||
}
|
||||
|
||||
/// The value read in the given unit.
|
||||
fn read(source: &str, unit_name: &str) -> f64 {
|
||||
let quantity = quantity(source);
|
||||
quantity
|
||||
.convert(unit(unit_name), 96.)
|
||||
.unwrap_or_else(|error| panic!("`{source}` should convert to `{unit_name}`: {error:?}"))
|
||||
.as_real()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn assert_close(actual: f64, expected: f64, source: &str) {
|
||||
assert!((actual - expected).abs() <= EPSILON * expected.abs().max(1.), "`{source}` gave {actual}, expected {expected}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_before_a_unit_measures_in_it() {
|
||||
assert_eq!(shown("5mm"), "5 mm");
|
||||
assert_eq!(shown("5 mm"), "5 mm");
|
||||
assert_eq!(shown("2.5 inches"), "2.5 in");
|
||||
assert_eq!(shown("3 feet"), "3 ft");
|
||||
assert_eq!(shown("90 degrees"), "90°");
|
||||
assert_eq!(shown("45deg"), "45°");
|
||||
assert_eq!(shown("45°"), "45°");
|
||||
assert_eq!(shown("50%"), "50%");
|
||||
assert_eq!(shown("12.5 %"), "12.5%");
|
||||
assert_eq!(shown("5Hz"), "5 Hz");
|
||||
assert_eq!(shown("2 kHz"), "2 kHz");
|
||||
assert_eq!(shown("1000um"), "1000 µm");
|
||||
assert_eq!(shown("1000µm"), "1000 µm");
|
||||
assert_eq!(shown("9.8m/s^2"), "9.8 m/s^2");
|
||||
assert_eq!(shown("-5mm"), "-5 mm");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sums_take_the_unit_that_converts_exactly() {
|
||||
assert_eq!(shown("5m + 3m"), "8 m");
|
||||
assert_eq!(shown("5ft + 3ft"), "8 ft");
|
||||
assert_eq!(shown("1m + 1mm"), "1001 mm");
|
||||
assert_eq!(shown("1ft + 1in"), "13 in");
|
||||
assert_eq!(shown("90deg + 0.25turn"), "180°");
|
||||
assert_eq!(shown("1in + 1px"), "97 px");
|
||||
assert_close(read("5m + 3ft", "m"), 5.9144, "5m + 3ft");
|
||||
assert_eq!(quantity("5m + 3ft").unit, unit("m"));
|
||||
assert_close(read("1in + 1mm", "mm"), 26.4, "1in + 1mm");
|
||||
assert_eq!(quantity("1in + 1mm").unit, unit("mm"));
|
||||
|
||||
// Radians are coherent, so a mix with them keeps them
|
||||
assert_eq!(quantity("asin(0.5) + 30deg").unit, unit("rad"));
|
||||
assert_close(read("asin(0.5) + 30deg", "rad"), std::f64::consts::PI / 3., "asin(0.5) + 30deg");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plain_number_only_adds_to_a_unit_when_it_is_zero() {
|
||||
assert!(error("1in + 5").contains("A plain number can't be added to a value in `in`"));
|
||||
assert!(error("5 - 1in").contains("A plain number can't be subtracted from a value in `in`"));
|
||||
assert!(error("1 + 50%").contains("plain number"));
|
||||
assert!(error("asin(0.5) + 1").contains("A plain number can't be added to a value in `rad`"));
|
||||
assert_eq!(shown("0 + 5mm"), "5 mm");
|
||||
assert_eq!(shown("5mm - 0"), "5 mm");
|
||||
assert_eq!(read("max(0, 3mm - 5mm)", "mm"), 0.);
|
||||
assert_eq!(evaluate_with("0 < 1mm", 96.).unwrap().as_bool(), Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_dimensions_never_mix() {
|
||||
assert!(error("1mm + 1s").contains("measure different things"));
|
||||
assert!(error("1mm < 1s").contains("measure different things"));
|
||||
assert!(error("max(1mm, 1kg)").contains("measure different things"));
|
||||
assert!(error("1mm == 1s").contains("measure different things"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_and_unit_after_a_value_with_a_unit_is_the_divisor() {
|
||||
assert_eq!(quantity("10mm/2mm").value, Value::from_i64(5));
|
||||
assert!(quantity("10mm/2mm").is_plain());
|
||||
assert_eq!(shown("100km/2h"), "50 km/h");
|
||||
assert_eq!(shown("10mm / 2 mm"), "5");
|
||||
assert_eq!(shown("1in/2.54cm"), "1");
|
||||
assert_eq!(quantity("10mm/2mm^2").unit, unit("mm").inverse());
|
||||
assert_eq!(shown("3mm * 2 / 4mm"), "1.5");
|
||||
|
||||
// The dividend's value decides, however its name is spelled
|
||||
assert_eq!(shown("a / 2mm where a = 10mm"), "5");
|
||||
assert_eq!(shown("x / 2mm where x = 3"), "1.5 mm");
|
||||
|
||||
// Without a unit in the dividend, a unit after the number applies to the whole quotient
|
||||
assert_eq!(shown("3/4in"), "0.75 in");
|
||||
assert_close(read("pi/2 rad", "rad"), std::f64::consts::FRAC_PI_2, "pi/2 rad");
|
||||
assert_close(quantity("1/2pi").value.as_real().unwrap(), std::f64::consts::FRAC_PI_2, "1/2pi");
|
||||
assert_eq!(shown("50% / 2mm"), "0.25 mm");
|
||||
|
||||
// A name defined as a variable is no unit, so it multiplies left to right like any other factor
|
||||
assert_eq!(shown("s/2m where s = 12, m = 3"), "18");
|
||||
assert_eq!(shown("a/2m where a = 12mm, m = 3"), "18 mm");
|
||||
let node = Node::try_parse_from_str("10mm / 2m").unwrap();
|
||||
let host = crate::context::ValueMap([("m".to_string(), Value::from_i64(3))].into_iter().collect());
|
||||
assert_eq!(node.eval(&EvalContext::new(host, NothingMap)).unwrap().to_string(), "15 mm");
|
||||
|
||||
// Only juxtaposition joins the divisor
|
||||
assert_eq!(shown("10mm/2*mm"), "5 mm^2");
|
||||
|
||||
// A matrix's units are known only once evaluated, so it divides by the whole measure, unless one of its names is a variable
|
||||
assert_eq!(shown("(0mm..10mm) / 2mm"), "5");
|
||||
assert_eq!(shown("(0..12) / 2m where m = 3"), "18");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feet_then_inches_sum() {
|
||||
assert_eq!(shown("5'6\""), "66 in");
|
||||
assert_eq!(shown("5'"), "5 ft");
|
||||
assert_eq!(shown("6\""), "6 in");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn percentages_scale_and_stay_percentages_beside_plain_numbers() {
|
||||
assert_eq!(shown("50% + 10%"), "60%");
|
||||
assert_eq!(shown("50% / 2"), "25%");
|
||||
assert_eq!(shown("2 * 50%"), "100%");
|
||||
assert_eq!(shown("50% * 50%"), "25%");
|
||||
assert_eq!(shown("50% * 10mm"), "5 mm");
|
||||
assert_eq!(quantity("100 / (50%)").value, Value::from_i64(200));
|
||||
assert_eq!(quantity("x / 50% where x = 3").value, Value::from_i64(6));
|
||||
assert_eq!(quantity("50% / 25%").value, Value::from_i64(2));
|
||||
assert_eq!(evaluate_with("50%", 96.).unwrap().as_real(), Some(0.5));
|
||||
assert!(evaluate_with("7 % 3", 96.).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn products_merge_units_of_one_dimension() {
|
||||
assert_eq!(shown("3mm * 2mm"), "6 mm^2");
|
||||
assert_eq!(quantity("3mm * 2in").unit, unit("mm").power(2.).unwrap());
|
||||
assert_close(quantity("3mm * 2in").value.as_real().unwrap(), 152.4, "3mm * 2in");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn powers_and_roots_raise_units() {
|
||||
assert_eq!(shown("(2mm)^2"), "4 mm^2");
|
||||
assert_eq!(shown("sqrt(9mm^2)"), "3 mm");
|
||||
assert_eq!(shown("cbrt(8mm^3)"), "2 mm");
|
||||
assert_eq!(shown("root(16mm^4, 4)"), "2 mm");
|
||||
assert_eq!(shown("(4mm^2)^0.5"), "2 mm");
|
||||
assert_eq!(shown("(2mm)^0"), "1");
|
||||
assert!(error("sqrt(1mm)").contains("fractional exponent"));
|
||||
assert!(error("2^(1mm)").contains("An exponent can't be in `mm`"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn circular_functions_take_angles_or_radians() {
|
||||
assert_close(quantity("sin(30deg)").value.as_real().unwrap(), 0.5, "sin(30deg)");
|
||||
assert_close(quantity("sin(pi/6)").value.as_real().unwrap(), 0.5, "sin(pi/6)");
|
||||
assert_close(quantity("cos(0.5turn)").value.as_real().unwrap(), -1., "cos(0.5turn)");
|
||||
assert!(error("sin(1mm)").contains("`sin` takes an angle or a plain number"));
|
||||
// The inverse functions give angles in radians, which the circular functions read back
|
||||
assert_eq!(quantity("asin(1)").unit, unit("rad"));
|
||||
assert_close(read("asin(1)", "deg"), 90., "asin(1)");
|
||||
assert_close(quantity("sin(asin(0.5))").value.as_real().unwrap(), 0.5, "sin(asin(0.5))");
|
||||
assert_close(read("atan2(1, 1)", "deg"), 45., "atan2(1, 1)");
|
||||
assert_close(quantity("atan2(1, 1) / turn + 0.5").value.as_real().unwrap(), 0.625, "atan2(1, 1) / turn + 0.5");
|
||||
assert!(error("atan2(1, 1) / (2pi) + 0.5").contains("A plain number can't be added to a value in `rad`"));
|
||||
assert_eq!(quantity("atan2(3mm, 4mm)").unit, unit("rad"));
|
||||
assert_close(read("atan2(3mm, 4cm)", "rad"), (3_f64).atan2(40.), "atan2(3mm, 4cm)");
|
||||
assert_eq!(quantity("angle(i, j)").unit, unit("rad"));
|
||||
assert_close(read("angle(1mm i, 1mm j)", "deg"), 90., "angle(1mm i, 1mm j)");
|
||||
|
||||
// Dividing by `rad` reads an angle as plain radians
|
||||
assert_close(quantity("asin(1)/rad + 1").value.as_real().unwrap(), std::f64::consts::FRAC_PI_2 + 1., "asin(1)/rad + 1");
|
||||
|
||||
// An exponent with no plain part rotates, read in radians
|
||||
let rotation = quantity("e^(i 90deg)").number().to_quaternion();
|
||||
assert!(rotation.w.abs() < EPSILON && (rotation.x - 1.).abs() < EPSILON);
|
||||
assert!(evaluate_with("e^(2 + i 90deg)", 96.).is_err());
|
||||
assert!(evaluate_with("exp(i 90deg)", 96.).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rounding_takes_plain_numbers_and_snap_rounds_in_a_unit() {
|
||||
assert!(error("floor(1.5mm)").contains("snap(x, 1 mm)"));
|
||||
assert!(error("round(2.5in)").contains("snap(x, 1 in)"));
|
||||
assert_eq!(shown("snap(13mm, 5mm)"), "15 mm");
|
||||
assert_eq!(shown("mod(13mm, 5mm)"), "3 mm");
|
||||
assert_eq!(shown("floor(150%)"), "1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builtins_carry_units_by_their_rules() {
|
||||
assert_eq!(shown("max(1mm, 1in)"), "25.4 mm");
|
||||
assert_eq!(shown("min(1cm, 1mm)"), "1 mm");
|
||||
assert_eq!(shown("abs(-3mm)"), "3 mm");
|
||||
assert_eq!(shown("sign(-3mm)"), "-1");
|
||||
assert_eq!(shown("hypot(3mm, 4mm)"), "5 mm");
|
||||
assert_eq!(shown("mean(1mm, 3mm)"), "2 mm");
|
||||
assert_eq!(quantity("variance(1mm, 3mm)").unit, unit("mm").power(2.).unwrap());
|
||||
assert_eq!(shown("lerp(0mm, 10mm, 50%)"), "5 mm");
|
||||
assert_eq!(shown("count(1mm, 2s)"), "2");
|
||||
assert_eq!(shown("|3mm i + 4mm j|"), "5 mm");
|
||||
assert!(quantity("normalize(3mm i + 4mm j)").is_plain());
|
||||
assert_eq!(shown("dot(1mm i, 2mm i)"), "2 mm^2");
|
||||
assert_eq!(quantity("distance(1mm i, 4mm i)").unit, unit("mm"));
|
||||
let rotated = quantity("rotate(1mm i, 90deg)");
|
||||
assert_eq!(rotated.unit, unit("mm"));
|
||||
assert!((rotated.number().to_quaternion().y - 1.).abs() < EPSILON);
|
||||
assert!(error("ln(2mm)").contains("`ln` takes plain numbers"));
|
||||
assert!(error("5mm!").contains("`!` takes plain numbers"));
|
||||
assert!(evaluate_with("1mm && 1", 96.).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn angles_and_cycles_divide_out_explicitly() {
|
||||
assert_eq!(quantity("720deg / turn").value, Value::from_i64(2));
|
||||
assert_eq!(quantity("720deg / deg").value, Value::from_i64(720));
|
||||
assert_close(quantity("720deg / rad").value.as_real().unwrap(), 4. * std::f64::consts::PI, "720deg / rad");
|
||||
assert_eq!(quantity("60rpm / turn").dimension(), quantity("1Hz").dimension());
|
||||
assert_close(read("60rpm / turn", "Hz"), 1., "60rpm / turn");
|
||||
assert_close(read("1rpm * 1s", "turn"), 1. / 60., "1rpm * 1s");
|
||||
assert_eq!(quantity("1Hz * 1min").value, Value::from_i64(60));
|
||||
assert_eq!(quantity("2px * 3deg").dimension(), Dimension([1, 0, 0, 1]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixels_are_sized_by_the_pixels_per_inch() {
|
||||
assert_eq!(read("1in", "px"), 96.);
|
||||
assert_close(read("10mm", "px"), 10. / 25.4 * 96., "10mm");
|
||||
assert_eq!(read("72pt", "px"), 96.);
|
||||
let at_300 = match evaluate_with("1in", 300.).unwrap() {
|
||||
Object::Value(quantity) => quantity.convert(unit("px"), 300.).unwrap().as_real().unwrap(),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
assert_eq!(at_300, 300.);
|
||||
assert_eq!(shown("1in + 1px"), "97 px");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_field_reads_a_plain_result_in_its_own_unit() {
|
||||
let px = unit("px");
|
||||
assert_eq!(quantity("5").read_in(px, 96.).unwrap().as_real(), Some(5.));
|
||||
assert_eq!(quantity("1in").read_in(px, 96.).unwrap().as_real(), Some(96.));
|
||||
assert!(quantity("1s").read_in(px, 96.).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hosts_read_angles_as_radians_and_lengths_not_at_all() {
|
||||
assert_close(evaluate_with("90deg", 96.).unwrap().as_real().unwrap(), std::f64::consts::FRAC_PI_2, "90deg");
|
||||
assert_eq!(evaluate_with("5mm", 96.).unwrap().as_real(), None);
|
||||
assert_eq!(evaluate_with("5", 96.).unwrap().as_real(), Some(5.));
|
||||
}
|
||||
|
||||
struct Bindings;
|
||||
|
||||
impl ValueProvider for Bindings {
|
||||
fn get_value(&self, name: &str) -> Option<Value> {
|
||||
(name == "m").then(|| Value::from_i64(3))
|
||||
}
|
||||
|
||||
fn get_quantity(&self, name: &str) -> Option<Quantity> {
|
||||
match name {
|
||||
"x" => Some(Quantity::new(Value::from_i64(10), Unit::named("px")?)),
|
||||
_ => self.get_value(name).map(Quantity::plain),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bindings_shadow_units_and_carry_their_own() {
|
||||
let evaluate = |source: &str| Node::try_parse_from_str(source).unwrap().eval(&EvalContext::new(Bindings, NothingMap)).unwrap();
|
||||
assert_eq!(evaluate("2m").as_real(), Some(6.));
|
||||
assert_eq!(evaluate("2\\m").as_quantity().unwrap().unit, unit("m"));
|
||||
assert_eq!(evaluate("x + 1in").to_string(), "106 px");
|
||||
assert_eq!(evaluate("x * 2").to_string(), "20 px");
|
||||
assert_eq!(evaluate("a where a = 5mm").to_string(), "5 mm");
|
||||
assert_eq!(evaluate("f(2mm) where f(t) = t * 2").to_string(), "4 mm");
|
||||
assert_eq!(evaluate("{1mm if 1 > 0, 2mm otherwise}").to_string(), "1 mm");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ranges_and_matrices_carry_units() {
|
||||
assert_eq!(shown("clamp(15mm, 0..10mm)"), "10 mm");
|
||||
assert_close(read("clamp(5mm, 0..1cm)", "mm"), 5., "clamp(5mm, 0..1cm)");
|
||||
assert_eq!(shown("remap(5mm, 0..10mm, 0..1)"), "0.5");
|
||||
assert_eq!(shown("remap(0.5, 0..1, 0..10mm)"), "5 mm");
|
||||
assert_eq!(evaluate_with("within(5mm, 0..1cm)", 96.).unwrap().as_bool(), Some(true));
|
||||
assert_eq!(shown("(0..10mm) 0.5"), "5 mm");
|
||||
assert_eq!(shown("(0..10mm)^-1 (5mm)"), "0.5");
|
||||
assert_eq!(shown("(I + 5mm i) (1mm i)"), "(6i) mm");
|
||||
assert_eq!(quantity("det(0..(2mm i + 3mm j))").unit, unit("mm").power(2.).unwrap());
|
||||
assert!(error("clamp(5, 0..10mm)").contains("plain number"));
|
||||
|
||||
let rotated = quantity("rotation(90deg) (1mm i)");
|
||||
assert_eq!(rotated.unit, unit("mm"));
|
||||
assert!((rotated.number().to_quaternion().y - 1.).abs() < EPSILON);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exponents_stay_in_range() {
|
||||
assert_eq!(quantity("1 / (1m^-127)").unit, unit("m").power(127.).unwrap());
|
||||
assert!(evaluate_with("1m^-128", 96.).is_err());
|
||||
assert!(evaluate_with("1m^200", 96.).is_err());
|
||||
assert_eq!(shown("root(1m^49, 49)"), "1 m");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_conversions_survive_large_operands() {
|
||||
assert_eq!(quantity("2540000000000000127mm / in").value, Value::from_i64(100_000_000_000_000_005));
|
||||
assert_close(quantity("1e308m / (1e308cm)").value.as_real().unwrap(), 100., "1e308m / (1e308cm)");
|
||||
assert_close(read("50% * (1e308mm)", "mm"), 5e307, "50% * (1e308mm)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matrices_with_units_apply_compose_and_compare() {
|
||||
assert_eq!(shown("(1mm I + 1) 0"), "1");
|
||||
assert_eq!(shown("((1mm..2mm)^1) 0.5"), "1.5 mm");
|
||||
assert_eq!(evaluate_with("within(i, (0..10mm)^0)", 96.).unwrap().as_bool(), Some(false));
|
||||
assert_eq!(evaluate_with("[1m] != [2m] != [1001mm]", 96.).unwrap().as_bool(), Some(true));
|
||||
assert_eq!(evaluate_with("[1m] == [1000mm]", 96.).unwrap().as_bool(), Some(true));
|
||||
assert_eq!(shown("shear(1m i, 1m j, 1) j"), shown("shear(100cm i, 100cm j, 1) j"));
|
||||
assert_eq!(shown("scale(50%) 1"), shown("scale(0.5) 1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sign_before_feet_and_inches_applies_to_both() {
|
||||
assert_eq!(shown("-5'6\""), "-66 in");
|
||||
assert_eq!(shown("1ft - 5'6\""), "-54 in");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equal_ranges_in_different_units_compare_equal() {
|
||||
assert_eq!(evaluate_with("(0..1cm) == (0..10mm)", 96.).unwrap().as_bool(), Some(true));
|
||||
assert_eq!(evaluate_with("(0..1in) != (0..1cm) != (0..10mm)", 96.).unwrap().as_bool(), Some(false));
|
||||
// A part outside a range's axes passes through untouched
|
||||
assert_eq!(quantity("((0..1in) (0..1cm)) (0.5 + 2j)").number().to_quaternion().y, 2.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn percentages_stand_for_their_fraction_where_plain_numbers_go() {
|
||||
assert_eq!(shown("clamp(150%, 0..1)"), "1");
|
||||
assert_eq!(shown("remap(50%, 0..1, 0..10mm)"), "5 mm");
|
||||
assert_eq!(evaluate_with("within(50%, 0..1)", 96.).unwrap().as_bool(), Some(true));
|
||||
assert_eq!(quantity("100 / 50%").value, Value::from_i64(200));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inches_convert_to_pixels_exactly_at_any_whole_resolution() {
|
||||
for pixels_per_inch in 1..=4000 {
|
||||
let pixels_per_inch = pixels_per_inch as f64;
|
||||
let pixels = match evaluate_with("1in", pixels_per_inch).unwrap() {
|
||||
Object::Value(quantity) => quantity.convert(unit("px"), pixels_per_inch).unwrap().as_real().unwrap(),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
assert_eq!(pixels, pixels_per_inch);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_matrices_are_named_plainly_in_errors() {
|
||||
assert!(error("I + (0..10mm)").contains("A plain number can't be added to a value in `mm`"));
|
||||
}
|
||||
+24
-2
@@ -32,7 +32,7 @@ pub struct DocumentNodeDefinition {
|
||||
}
|
||||
```
|
||||
|
||||
Only the definitions of nodes built from a nested network, such as the empty "Custom Node", are written by hand in that file. A node implemented as a single proto-node has its definition generated from the metadata the `node` macro records about its function signature (see [Creating a new node](#creating-a-new-node)), keyed by the proto-node identifier, which for the Opacity node is `graphene_std::blending_nodes::opacity::IDENTIFIER`.
|
||||
None of these definitions are written by hand. A node implemented as a single proto-node has its definition generated from the metadata the `node` macro records about its function signature (see [Creating a new node](#creating-a-new-node)), keyed by the proto-node identifier, which for the Opacity node is `graphene_std::blending_nodes::opacity::IDENTIFIER`. A built-in node made from a subgraph has its definition generated from the `graph` macro (see [Creating a node from a subgraph](#creating-a-node-from-a-subgraph)), keyed by its name.
|
||||
|
||||
## Inspector
|
||||
|
||||
@@ -127,7 +127,29 @@ fn opacity<T>(
|
||||
|
||||
## Additional Macro Options
|
||||
|
||||
The macro invocation can be extended with additional attributes. The currently supported attributes are (`name`, `path`, `skip_impl`, `category`). When using generics the `#[implementations()]` attribute can be used to automatically populate the node_registry for you. You can also use the `default`, `expose`, `soft`, `hard`, `range`, `unit`, `multiline`, and `progression` attributes to influence how the Inspector widgets are generated. The `#[unit("...")]` attribute appends a suffix like `%` or ` px` to a number's widget, while `#[multiline]` gives a `String` the text area widget and `#[progression]` splits a number into its whole and fractional parts. The `#[soft(a..b)]` and `#[hard(a..b)]` attributes set the slider's suggested extent and its enforced clamp, respectively (either endpoint may be omitted, e.g. `0..` or `..100`; both endpoints are inclusive, so there is no `..=` form), and `#[range]` renders the input as a draggable slider. Values typed into the input may exceed the soft extent but are clamped to the hard bounds, so `#[soft]` is only meaningful together with `#[range]`.
|
||||
The macro invocation can be extended with additional attributes. The currently supported attributes are (`name`, `path`, `skip_impl`, `category`). When using generics the `#[implementations()]` attribute can be used to automatically populate the node_registry for you. You can also use the `default`, `expose`, `soft`, `hard`, `range`, `step`, `display_decimal_places`, `unit`, `integer`, `labels`, `blank_assist`, `multiline`, and `progression` attributes to influence how the Inspector widgets are generated. The `#[unit("...")]` attribute appends a suffix like `%` or ` px` to a number's widget, `#[display_decimal_places(2)]` sets how many decimal places a number's widget shows, `#[integer]` makes a number or Vec2 widget take only integers, `#[labels("W", "H")]` names a Vec2 widget's two fields, and `#[blank_assist(false)]` drops the space a widget leaves for its assist area. `#[multiline]` gives a `String` the text area widget and `#[progression]` splits a number into its whole and fractional parts. The `#[soft(a..b)]` and `#[hard(a..b)]` attributes set the slider's suggested extent and its enforced clamp, respectively (either endpoint may be omitted, e.g. `0..` or `..100`; both endpoints are inclusive, so there is no `..=` form), and `#[range]` renders the input as a draggable slider. Values typed into the input may exceed the soft extent but are clamped to the hard bounds, so `#[soft]` is only meaningful together with `#[range]`.
|
||||
|
||||
## Creating a node from a subgraph
|
||||
|
||||
A node built from other nodes uses the `graph` macro, which registers the subgraph as a catalog definition. It takes `category`, `icon`, `name`, and `version` as `node` does, plus `layer` for a node that starts as a layer. Unlike a proto node's, a graph's name (or the title derived from its function name) is also its catalog identifier, which documents store. The function's parameters are the subgraph's imports, which are parsed like a proto node's parameters and take the same value and widget attributes. On an import, `#[hard]` bounds the Inspector widget without clamping a value wired into it. `out!(...)` names the exports. In the body, `>>` feeds its left side into the primary input of the node on its right, every other parameter is named in the call, and a bare name feeds the binding or import of that name into the parameter of the same name. State methods after a call, each written once, set the node's position in grid units (`.at(x, y)`), its display name (`.named("…")`), its flags (`.layer()`, `.hidden()`, `.locked()`, and `.pinned()`), and its call argument (`.call_argument::<Footprint>()`, or `impl Any` for a generic one). An output's name after the call or a binding, like `.captures`, wires from that output instead of the primary one, and goes after any state methods. The body ends with one value per export, as a final expression or with `return`. This is the Load Image node as it exists in `node-graph/nodes/gstd/src/subgraphs.rs`:
|
||||
|
||||
```rs
|
||||
/// Loads an image from a given URL.
|
||||
#[node_macro::graph(category("Data: I/O"), icon("NodeLoadImage"))]
|
||||
pub fn load_image(
|
||||
_: (),
|
||||
/// The web address or local asset path of the image to load.
|
||||
#[name("URL")]
|
||||
url: Item<String>,
|
||||
) -> out!(
|
||||
/// The loaded image.
|
||||
image,
|
||||
) {
|
||||
load_resource(url).at(0, 0) >> bytes_to_image().at(7, 0)
|
||||
}
|
||||
```
|
||||
|
||||
Each node, parameter, and output name resolves through the module the `node` or `graph` macro generates for that node, named after its function, so a misspelled one is reported where it's written. The module's `PARAMETER_COUNT` lets the macro reject `>>` into a node with no parameters. Proto nodes don't name their outputs in that module, so only a graph's outputs can be chosen by name. Every input a call leaves out keeps the default from the node's own definition.
|
||||
|
||||
## Executing a document `NodeNetwork`
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@ use core_types::color::SRGBA8;
|
||||
use core_types::list::{Item, List, NodeIdPath};
|
||||
use core_types::transfer_curve::TransferCurve;
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::units::{Angle, AngleUnit, DEFAULT_PIXELS_PER_INCH, Length, LengthUnit, TypedAngle, TypedLength};
|
||||
use core_types::{CacheHash, Color, ContextModification, MemoHash, Node, Poll, RuntimeHandle, SourceId, Type, TypeDescriptor};
|
||||
pub use dyn_any::StaticType;
|
||||
pub use glam::{DAffine2, DVec2, IVec2, UVec2};
|
||||
@@ -84,11 +83,6 @@ macro_rules! tagged_value {
|
||||
BoxCorners(Vec<f64>),
|
||||
/// Stored compactly as a `Vec<DVec2>` of control points, materializes as an `Item<TransferCurve>` at runtime via `to_dynany`/`to_any`.
|
||||
TransferCurve(Vec<DVec2>),
|
||||
/// A length in the unit it was typed in, materializing as an `Item<Length>` in pixels. A physical unit needs the document's resolution,
|
||||
/// so the preprocessor replaces it with a conversion node reading that from the scope.
|
||||
Length(TypedLength),
|
||||
/// An angle in the unit it was typed in, materializing as an `Item<Angle>`.
|
||||
Angle(TypedAngle),
|
||||
/// Stored as the `GradientRamp` exchange struct (nested `{ stops: { color, position?, midpoint? } }`), materializing as an `Item<Gradient>` at runtime. Aliases recover legacy on-disk shapes.
|
||||
/// (Old documents stored flat stops, a tuple list, or the ancient full `Gradient` struct under the legacy `"Gradient"` tag, all routed by `deserialize_tagged_value_with_legacy_migration`.)
|
||||
#[serde(alias = "Gradient", alias = "GradientTable", alias = "GradientPositions", alias = "GradientStops")]
|
||||
@@ -138,8 +132,6 @@ macro_rules! tagged_value {
|
||||
Self::DashPattern(lengths) => lengths.cache_hash(state),
|
||||
Self::BoxCorners(values) => values.cache_hash(state),
|
||||
Self::TransferCurve(points) => points.cache_hash(state),
|
||||
Self::Length(length) => length.cache_hash(state),
|
||||
Self::Angle(angle) => angle.cache_hash(state),
|
||||
Self::GradientRamp(ramp) => ramp.cache_hash(state),
|
||||
Self::Strokes(strokes) => strokes.cache_hash(state),
|
||||
Self::BrushCache(cache) => cache.cache_hash(state),
|
||||
@@ -197,8 +189,6 @@ macro_rules! tagged_value {
|
||||
Self::DashPattern(lengths) => Box::new(Item::new_from_element(DashPattern::from(lengths))),
|
||||
Self::BoxCorners(values) => Box::new(Item::new_from_element(BoxCorners::from(values))),
|
||||
Self::TransferCurve(points) => Box::new(Item::new_from_element(TransferCurve::from(points))),
|
||||
Self::Length(length) => Box::new(Item::new_from_element(length.to_length(DEFAULT_PIXELS_PER_INCH))),
|
||||
Self::Angle(angle) => Box::new(Item::new_from_element(angle.to_angle())),
|
||||
Self::GradientRamp(ramp) => Box::new(Item::<Gradient>::from(ramp)),
|
||||
Self::Strokes(strokes) => {
|
||||
let list: List<Stroke> = strokes.into_iter().map(core_types::list::Item::new_from_element).collect();
|
||||
@@ -259,8 +249,6 @@ macro_rules! tagged_value {
|
||||
Self::DashPattern(lengths) => Arc::new(Item::new_from_element(DashPattern::from(lengths))),
|
||||
Self::BoxCorners(values) => Arc::new(Item::new_from_element(BoxCorners::from(values))),
|
||||
Self::TransferCurve(points) => Arc::new(Item::new_from_element(TransferCurve::from(points))),
|
||||
Self::Length(length) => Arc::new(Item::new_from_element(length.to_length(DEFAULT_PIXELS_PER_INCH))),
|
||||
Self::Angle(angle) => Arc::new(Item::new_from_element(angle.to_angle())),
|
||||
Self::GradientRamp(ramp) => Arc::new(Item::<Gradient>::from(ramp)),
|
||||
Self::Strokes(strokes) => {
|
||||
let list: List<Stroke> = strokes.into_iter().map(core_types::list::Item::new_from_element).collect();
|
||||
@@ -296,8 +284,6 @@ macro_rules! tagged_value {
|
||||
Self::DashPattern(_) => item!(DashPattern),
|
||||
Self::BoxCorners(_) => item!(BoxCorners),
|
||||
Self::TransferCurve(_) => item!(TransferCurve),
|
||||
Self::Length(_) => item!(Length),
|
||||
Self::Angle(_) => item!(Angle),
|
||||
Self::GradientRamp(_) => item!(Gradient),
|
||||
Self::Strokes(_) => list!(Stroke),
|
||||
Self::BrushCache(_) => item!(BrushCache),
|
||||
@@ -339,10 +325,6 @@ macro_rules! tagged_value {
|
||||
x if x == TypeId::of::<Item<BoxCorners>>() => Ok(TaggedValue::BoxCorners(input.downcast::<Item<BoxCorners>>().unwrap().into_element().0.iter_element_values().copied().collect())),
|
||||
x if x == TypeId::of::<TransferCurve>() => Ok(TaggedValue::TransferCurve(input.downcast::<TransferCurve>().unwrap().points().to_vec())),
|
||||
x if x == TypeId::of::<Item<TransferCurve>>() => Ok(TaggedValue::TransferCurve(input.downcast::<Item<TransferCurve>>().unwrap().into_element().points().to_vec())),
|
||||
x if x == TypeId::of::<Length>() => Ok(TaggedValue::Length(TypedLength::pixels(input.downcast::<Length>().unwrap().pixels()))),
|
||||
x if x == TypeId::of::<Item<Length>>() => Ok(TaggedValue::Length(TypedLength::pixels(input.downcast::<Item<Length>>().unwrap().into_element().pixels()))),
|
||||
x if x == TypeId::of::<Angle>() => Ok(TaggedValue::Angle(TypedAngle::degrees(input.downcast::<Angle>().unwrap().degrees()))),
|
||||
x if x == TypeId::of::<Item<Angle>>() => Ok(TaggedValue::Angle(TypedAngle::degrees(input.downcast::<Item<Angle>>().unwrap().into_element().degrees()))),
|
||||
x if x == TypeId::of::<Gradient>() => Ok(TaggedValue::GradientRamp(GradientRamp::from(*input.downcast::<Gradient>().unwrap()))),
|
||||
x if x == TypeId::of::<Item<Gradient>>() => Ok(TaggedValue::GradientRamp(GradientRamp::from(&*input.downcast::<Item<Gradient>>().unwrap()))),
|
||||
x if x == TypeId::of::<List<Stroke>>() => Ok(TaggedValue::Strokes(input.downcast::<List<Stroke>>().unwrap().into_iter().map(Item::into_element).collect())),
|
||||
@@ -379,10 +361,6 @@ macro_rules! tagged_value {
|
||||
x if x == TypeId::of::<Item<BoxCorners>>() => Ok(TaggedValue::BoxCorners(input.downcast_ref::<Item<BoxCorners>>().unwrap().element().0.iter_element_values().copied().collect())),
|
||||
x if x == TypeId::of::<TransferCurve>() => Ok(TaggedValue::TransferCurve(input.downcast_ref::<TransferCurve>().unwrap().points().to_vec())),
|
||||
x if x == TypeId::of::<Item<TransferCurve>>() => Ok(TaggedValue::TransferCurve(input.downcast_ref::<Item<TransferCurve>>().unwrap().element().points().to_vec())),
|
||||
x if x == TypeId::of::<Length>() => Ok(TaggedValue::Length(TypedLength::pixels(input.downcast_ref::<Length>().unwrap().pixels()))),
|
||||
x if x == TypeId::of::<Item<Length>>() => Ok(TaggedValue::Length(TypedLength::pixels(input.downcast_ref::<Item<Length>>().unwrap().element().pixels()))),
|
||||
x if x == TypeId::of::<Angle>() => Ok(TaggedValue::Angle(TypedAngle::degrees(input.downcast_ref::<Angle>().unwrap().degrees()))),
|
||||
x if x == TypeId::of::<Item<Angle>>() => Ok(TaggedValue::Angle(TypedAngle::degrees(input.downcast_ref::<Item<Angle>>().unwrap().element().degrees()))),
|
||||
x if x == TypeId::of::<Gradient>() => Ok(TaggedValue::GradientRamp(GradientRamp::from(input.downcast_ref::<Gradient>().unwrap()))),
|
||||
x if x == TypeId::of::<Item<Gradient>>() => Ok(TaggedValue::GradientRamp(GradientRamp::from(input.downcast_ref::<Item<Gradient>>().unwrap()))),
|
||||
x if x == TypeId::of::<List<Stroke>>() => Ok(TaggedValue::Strokes(input.downcast_ref::<List<Stroke>>().unwrap().iter_element_values().cloned().collect())),
|
||||
@@ -414,8 +392,6 @@ macro_rules! tagged_value {
|
||||
if name == std::any::type_name::<DashPattern>() { return Some(TaggedValue::DashPattern(Vec::new())) }
|
||||
if name == std::any::type_name::<BoxCorners>() { return Some(TaggedValue::BoxCorners(Vec::new())) }
|
||||
if name == std::any::type_name::<TransferCurve>() { return Some(TaggedValue::TransferCurve(TransferCurve::default().points().to_vec())) }
|
||||
if name == std::any::type_name::<Length>() { return Some(TaggedValue::Length(TypedLength::default())) }
|
||||
if name == std::any::type_name::<Angle>() { return Some(TaggedValue::Angle(TypedAngle::default())) }
|
||||
$( if name == std::any::type_name::<$ty>() { return Some(TaggedValue::$identifier(Default::default())) } )*
|
||||
if name == std::any::type_name::<List<Stroke>>() { return Some(TaggedValue::Strokes(Vec::new())) }
|
||||
if name == std::any::type_name::<BrushCache>() { return Some(TaggedValue::BrushCache(Default::default())) }
|
||||
@@ -466,8 +442,6 @@ macro_rules! tagged_value {
|
||||
Self::DashPattern(lengths) => format!("DashPattern({lengths:?})"),
|
||||
Self::BoxCorners(values) => format!("BoxCorners({values:?})"),
|
||||
Self::TransferCurve(points) => format!("TransferCurve({points:?})"),
|
||||
Self::Length(length) => format!("Length({} {})", length.value, length.unit.symbol()),
|
||||
Self::Angle(angle) => format!("Angle({} {})", angle.value, angle.unit.symbol()),
|
||||
Self::GradientRamp(ramp) => format!("GradientRamp({ramp:?})"),
|
||||
Self::Strokes(strokes) => format!("Strokes({strokes:?})"),
|
||||
Self::BrushCache(cache) => format!("{cache:?}"),
|
||||
@@ -600,8 +574,6 @@ tagged_value! {
|
||||
TextAlign(text_nodes::TextAlign),
|
||||
TextDenomination(text_nodes::TextDenomination),
|
||||
ScaleType(core_types::transform::ScaleType),
|
||||
LengthUnit(LengthUnit),
|
||||
AngleUnit(AngleUnit),
|
||||
// Legacy
|
||||
PaintOrder(vector::style::PaintOrder), // TODO: Eventually remove this document upgrade code
|
||||
#[serde(alias = "Fill")]
|
||||
@@ -611,48 +583,6 @@ tagged_value! {
|
||||
}
|
||||
|
||||
impl TaggedValue {
|
||||
/// A length input's value in pixels, whether stored as a typed length or as a plain number of pixels.
|
||||
pub fn as_length_pixels(&self, pixels_per_inch: f64) -> Option<f64> {
|
||||
match self {
|
||||
Self::Length(length) => Some(length.to_length(pixels_per_inch).pixels()),
|
||||
Self::Number(pixels) => Some(*pixels),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A length in pixels as a value for a length input, kept in the unit `self` was typed in, like a dragged radius that stays in millimeters.
|
||||
pub fn length_in_same_unit(&self, pixels: f64, pixels_per_inch: f64) -> Self {
|
||||
let unit = match self {
|
||||
Self::Length(length) => length.unit,
|
||||
_ => LengthUnit::Pixel,
|
||||
};
|
||||
Self::Length(TypedLength {
|
||||
value: LengthUnit::Pixel.convert(pixels, unit, pixels_per_inch),
|
||||
unit,
|
||||
})
|
||||
}
|
||||
|
||||
/// An angle input's value in degrees, whether stored as a typed angle or as a plain number of degrees.
|
||||
pub fn as_angle_degrees(&self) -> Option<f64> {
|
||||
match self {
|
||||
Self::Angle(angle) => Some(angle.to_angle().degrees()),
|
||||
Self::Number(degrees) => Some(*degrees),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// An angle in degrees as a value for an angle input, kept in the unit `self` was typed in.
|
||||
pub fn angle_in_same_unit(&self, degrees: f64) -> Self {
|
||||
let unit = match self {
|
||||
Self::Angle(angle) => angle.unit,
|
||||
_ => AngleUnit::Degree,
|
||||
};
|
||||
Self::Angle(TypedAngle {
|
||||
value: unit.from_angle(Angle::from_degrees(degrees)),
|
||||
unit,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn to_primitive_string(&self) -> String {
|
||||
match self {
|
||||
TaggedValue::None => "()".to_string(),
|
||||
@@ -828,8 +758,6 @@ impl TaggedValue {
|
||||
() if ty == TypeId::of::<core_types::blending::BlendMode>() => to_blend_mode(string).map(TaggedValue::BlendMode)?,
|
||||
() if ty == TypeId::of::<DashPattern>() => TaggedValue::DashPattern(core_types::misc::parse_f64_list(string)),
|
||||
() if ty == TypeId::of::<BoxCorners>() => TaggedValue::BoxCorners(core_types::misc::parse_f64_list(string)),
|
||||
() if ty == TypeId::of::<Length>() => to_number(string).map(|pixels| TaggedValue::Length(TypedLength::pixels(pixels)))?,
|
||||
() if ty == TypeId::of::<Angle>() => to_number(string).map(|degrees| TaggedValue::Angle(TypedAngle::degrees(degrees)))?,
|
||||
_ => {
|
||||
log::error!("No parser for a default value of type `{}`: {string}", concrete_type.name);
|
||||
return None;
|
||||
|
||||
@@ -1120,7 +1120,7 @@ mod test {
|
||||
// If this assert fails: These NodeIds seem to be changing when you modify TaggedValue, just update them.
|
||||
assert_eq!(
|
||||
ids,
|
||||
vec![NodeId(7958315323958235311), NodeId(7951824047151403135), NodeId(16894780098949252642), NodeId(8854475046694858618)]
|
||||
vec![NodeId(7074930193456627328), NodeId(651950451264872860), NodeId(15983493604836528424), NodeId(2458326405488235061)]
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -95,7 +95,7 @@ pub async fn editor_api(gdd: Option<&GddV1>) -> (Arc<PlatformApplicationIo>, Arc
|
||||
/// Compile `network`, writing the path of each of its `layers` onto what that layer renders.
|
||||
pub fn compile_graph(mut network: NodeNetwork, layers: &[Vec<NodeId>], editor_api: Arc<PlatformEditorApi>, gdd: Option<&GddV1>, runtime: RuntimeHandle) -> Result<ProtoNetwork, Box<dyn Error>> {
|
||||
write_layer_paths(&mut network, layers);
|
||||
let mut network = wrap_network_in_scope(network, editor_api, runtime, graphene_std::units::DEFAULT_PIXELS_PER_INCH);
|
||||
let mut network = wrap_network_in_scope(network, editor_api, runtime);
|
||||
|
||||
let preprocessor = preprocessor::Preprocessor::new();
|
||||
let preprocessed = match gdd {
|
||||
|
||||
@@ -13,12 +13,7 @@ pub fn setup_network(name: &str) -> (DynamicExecutor, OutputHandle, ProtoNetwork
|
||||
.unwrap()
|
||||
.network;
|
||||
let editor_api = std::sync::Arc::new(EditorApi::default());
|
||||
let mut network = wrap_network_in_scope(
|
||||
network,
|
||||
editor_api,
|
||||
AsyncRuntime::new(std::sync::Arc::new(DummySpawner)).handle(),
|
||||
graphene_std::units::DEFAULT_PIXELS_PER_INCH,
|
||||
);
|
||||
let mut network = wrap_network_in_scope(network, editor_api, AsyncRuntime::new(std::sync::Arc::new(DummySpawner)).handle());
|
||||
let preprocessor = preprocessor::Preprocessor::new();
|
||||
preprocessor.preprocess(&mut network, &|_| None).unwrap();
|
||||
let proto_network = compile(network);
|
||||
|
||||
@@ -70,7 +70,7 @@ impl Session {
|
||||
|
||||
/// Recompiles the document graph into the executor and renders the viewport, as the runtime does after an edit.
|
||||
fn update(&mut self, document: NodeNetwork) {
|
||||
let mut network = wrap_network_in_scope(document, self.editor_api.clone(), self.runtime.handle(), graphene_std::units::DEFAULT_PIXELS_PER_INCH);
|
||||
let mut network = wrap_network_in_scope(document, self.editor_api.clone(), self.runtime.handle());
|
||||
self.preprocessor.preprocess(&mut network, &|_| None).expect("Failed to preprocess the document");
|
||||
let proto_network = Compiler {}.compile_single(network).expect("Failed to compile the document").network;
|
||||
(self.output, _) = self.executor.update(proto_network).expect("Failed to update the executor");
|
||||
|
||||
@@ -231,7 +231,7 @@ fn generator_frames_over_a_list_parameter() {
|
||||
|
||||
let radii = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Numbers(vec![10., 20., 30.]).into()), vec![NodeId(1)]);
|
||||
let mut radius_adapter = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1)]), vec![NodeId(2)]);
|
||||
radius_adapter.identifier = ProtoNodeIdentifier::new("input_adapter<Length>");
|
||||
radius_adapter.identifier = ProtoNodeIdentifier::new("input_adapter<f64>");
|
||||
|
||||
let mut circle_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(2)]), vec![NodeId(3)]);
|
||||
circle_node.identifier = graphene_std::vector_nodes::circle::IDENTIFIER;
|
||||
@@ -415,7 +415,7 @@ fn as_graphic_converts_a_vector_list_element_wise() {
|
||||
let radii = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Numbers(vec![10., 20.]).into()), vec![NodeId(1)]);
|
||||
|
||||
let mut radius_adapter = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1)]), vec![NodeId(2)]);
|
||||
radius_adapter.identifier = ProtoNodeIdentifier::new("input_adapter<Length>");
|
||||
radius_adapter.identifier = ProtoNodeIdentifier::new("input_adapter<f64>");
|
||||
|
||||
let mut circle_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(2)]), vec![NodeId(3)]);
|
||||
circle_node.identifier = graphene_std::vector_nodes::circle::IDENTIFIER;
|
||||
|
||||
@@ -21,7 +21,6 @@ use graphene_std::text::{Font, TextAlign};
|
||||
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
|
||||
use graphene_std::transfer_curve::TransferCurve;
|
||||
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType};
|
||||
use graphene_std::units::{Angle, AngleUnit, Length, LengthUnit};
|
||||
use graphene_std::vector::misc::{
|
||||
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod,
|
||||
WeldMethod,
|
||||
@@ -321,10 +320,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
RowsOrColumns,
|
||||
Resource,
|
||||
AnimationCurve,
|
||||
Length,
|
||||
Angle,
|
||||
LengthUnit,
|
||||
AngleUnit,
|
||||
)
|
||||
};
|
||||
}
|
||||
@@ -376,8 +371,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
String,
|
||||
DVec2,
|
||||
DAffine2,
|
||||
Length,
|
||||
Angle,
|
||||
BlendMode,
|
||||
GradientForm,
|
||||
GradientSpread,
|
||||
@@ -490,12 +483,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
// Numeric wires cast between numeric element types, splat to fill both axes of a `DVec2` connector, and format into a `String` connector
|
||||
node_types.extend(convert_adapter_wildcard!(from: f64, to: [i64, DVec2, String]));
|
||||
node_types.extend(convert_adapter_wildcard!(from: i64, to: [f64, DVec2, String]));
|
||||
// A number wire may feed a length or angle connector, read in pixels or degrees as their fields show them
|
||||
node_types.extend(convert_adapter_wildcard!(from: f64, to: [Length, Angle]));
|
||||
node_types.extend(convert_adapter_wildcard!(from: i64, to: [Length, Angle]));
|
||||
// Length and angle wires may feed a ranked String connector by formatting each element with its unit
|
||||
node_types.extend(convert_adapter_node!(from_element: Length, element: String));
|
||||
node_types.extend(convert_adapter_node!(from_element: Angle, element: String));
|
||||
// A bool embeds in number types as exactly 0 or 1 and formats as text as true or false, but deliberately has no `DVec2` row, which would silently turn a stray bool wire into (1., 1.)
|
||||
node_types.extend(convert_adapter_wildcard!(from: bool, to: [f64, i64, String]));
|
||||
// Position and transform wires may feed a ranked `String` connector by formatting each element as text
|
||||
|
||||
@@ -9,9 +9,7 @@ use graphene_std::RuntimeHandle;
|
||||
use graphene_std::uuid::NodeId;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Wraps the document network in the scope the runtime supplies: the editor API, the async runtime, and the pixels per inch that
|
||||
/// sizes lengths typed in a physical unit.
|
||||
pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, runtime: RuntimeHandle, pixels_per_inch: f64) -> NodeNetwork {
|
||||
pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, runtime: RuntimeHandle) -> NodeNetwork {
|
||||
let definitions = std::mem::take(&mut network.definitions);
|
||||
|
||||
let inner_network = DocumentNode {
|
||||
@@ -130,16 +128,10 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
|
||||
inputs: vec![NodeInput::value(TaggedValue::Runtime(runtime), false)],
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER),
|
||||
inputs: vec![NodeInput::value(TaggedValue::Number(pixels_per_inch), false)],
|
||||
..Default::default()
|
||||
},
|
||||
];
|
||||
let scope_injections = vec![
|
||||
("editor-api".to_string(), (NodeId(2), item!(Arc<PlatformEditorApi>))),
|
||||
("runtime".to_string(), (NodeId(3), item!(RuntimeHandle))),
|
||||
(graphene_std::units::PIXELS_PER_INCH_SCOPE.to_string(), (NodeId(4), item!(f64))),
|
||||
];
|
||||
|
||||
NodeNetwork {
|
||||
|
||||
@@ -64,9 +64,6 @@ pub struct RenderConfig {
|
||||
pub export_format: ExportFormat,
|
||||
pub for_export: bool,
|
||||
pub for_eyedropper: bool,
|
||||
/// The document's pixels per inch, which an export states its physical size by, or `None` where it's CSS's 96 or no export.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub pixels_per_inch: Option<f64>,
|
||||
}
|
||||
|
||||
impl RenderConfig {
|
||||
|
||||
@@ -24,7 +24,6 @@ wasm = ["tsify", "wasm-bindgen"]
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
graphene-hash = { workspace = true, features = ["derive"] }
|
||||
math-parser = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
color = { workspace = true }
|
||||
|
||||
@@ -19,7 +19,6 @@ pub mod registry;
|
||||
pub mod runtime;
|
||||
pub mod transfer_curve;
|
||||
pub mod transform;
|
||||
pub mod units;
|
||||
pub mod uuid;
|
||||
pub mod value;
|
||||
|
||||
|
||||
@@ -60,6 +60,12 @@ pub struct FieldMetadata {
|
||||
pub progression: bool,
|
||||
/// Whether the input must be fed by a value known at compile time, from `#[constant]`.
|
||||
pub constant: bool,
|
||||
/// The X and Y labels of a Vec2 parameter's widget, from `#[labels("W", "H")]`.
|
||||
pub labels: Option<(&'static str, &'static str)>,
|
||||
/// Whether a number or Vec2 parameter's widget only takes integers, from `#[integer]`. Integer types always do.
|
||||
pub integer: bool,
|
||||
/// Whether the widget leaves room for the assist area beside it, which `#[blank_assist(false)]` turns off.
|
||||
pub blank_assist: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -203,7 +209,6 @@ pub const CATEGORY_ORDER: &[&str] = &[
|
||||
"Math: Numeric",
|
||||
"Math: Trig",
|
||||
"Math: Vec2",
|
||||
"Math: Units",
|
||||
"Data: List",
|
||||
"Data: Context",
|
||||
"Data: Animation",
|
||||
@@ -223,6 +228,167 @@ pub static NODE_REGISTRY: NodeRegistry = LazyLock::new(|| Mutex::new(HashMap::ne
|
||||
|
||||
pub static NODE_METADATA: LazyLock<Mutex<HashMap<ProtoNodeIdentifier, NodeMetadata>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
/// Every node defined as a subgraph by the `#[graph]` macro, in registration order.
|
||||
pub static GRAPH_METADATA: LazyLock<Mutex<Vec<GraphMetadata>>> = LazyLock::new(|| Mutex::new(Vec::new()));
|
||||
|
||||
/// A node defined as a subgraph by `#[graph]`, which the editor turns into a catalog definition alongside the proto nodes.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GraphMetadata {
|
||||
/// The definition's identifier and display name.
|
||||
pub identifier: &'static str,
|
||||
pub category: &'static str,
|
||||
pub icon: Option<&'static str>,
|
||||
pub description: &'static str,
|
||||
/// The declaration version from `#[graph(version(N))]`, starting at 1.
|
||||
pub version: u32,
|
||||
/// Whether a new instance starts as a layer, from `#[graph(layer)]`.
|
||||
pub layer: bool,
|
||||
/// The subgraph's imports, which become the inputs of each instance, described like a proto node's parameters.
|
||||
/// Each one's `default_type` is the type it was declared with.
|
||||
pub imports: Vec<FieldMetadata>,
|
||||
pub exports: Vec<GraphExportMetadata>,
|
||||
/// The nodes inside the subgraph, where each node's position in this list is its ID.
|
||||
pub nodes: Vec<GraphNodeMetadata>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GraphExportMetadata {
|
||||
pub name: &'static str,
|
||||
pub description: &'static str,
|
||||
pub source: GraphInputSource,
|
||||
}
|
||||
|
||||
/// A node inside a subgraph defined by `#[graph]`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GraphNodeMetadata {
|
||||
pub implementation: GraphNodeImplementation,
|
||||
/// The inputs the definition sets, by index. Every other input keeps the default from the node's own definition.
|
||||
pub inputs: Vec<(usize, GraphInputSource)>,
|
||||
/// The absolute position in grid units, from `.at(x, y)`.
|
||||
pub position: Option<(i32, i32)>,
|
||||
/// From `.layer()`.
|
||||
pub layer: bool,
|
||||
/// From `.named("…")`.
|
||||
pub display_name: Option<&'static str>,
|
||||
/// From `.hidden()`.
|
||||
pub hidden: bool,
|
||||
/// From `.locked()`.
|
||||
pub locked: bool,
|
||||
/// From `.pinned()`.
|
||||
pub pinned: bool,
|
||||
/// From `.call_argument::<T>()`.
|
||||
pub call_argument: Option<Type>,
|
||||
}
|
||||
|
||||
/// What a node inside a subgraph is an instance of.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum GraphNodeImplementation {
|
||||
ProtoNode(ProtoNodeIdentifier),
|
||||
/// Another node defined by `#[graph]`, named by its identifier.
|
||||
Graph(&'static str),
|
||||
}
|
||||
|
||||
impl From<ProtoNodeIdentifier> for GraphNodeImplementation {
|
||||
fn from(identifier: ProtoNodeIdentifier) -> Self {
|
||||
Self::ProtoNode(identifier)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&'static str> for GraphNodeImplementation {
|
||||
fn from(identifier: &'static str) -> Self {
|
||||
Self::Graph(identifier)
|
||||
}
|
||||
}
|
||||
|
||||
/// What feeds an input, or an export, of a subgraph defined by `#[graph]`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum GraphInputSource {
|
||||
/// The output of another node in the subgraph, by its position in [`GraphMetadata::nodes`].
|
||||
Node { node: usize, output: usize },
|
||||
/// One of the subgraph's imports, with the type its wire records.
|
||||
Import { index: usize, ty: Type },
|
||||
/// A value. Without an exposure, the input keeps the one from the node's own definition.
|
||||
Value { value: GraphValue, exposed: Option<bool> },
|
||||
/// A scope input, from `scope("…")`.
|
||||
Scope(&'static str),
|
||||
/// The document path of the node, from `reflect(NodePath)`.
|
||||
NodePath,
|
||||
/// The source ID of the node, from `reflect(SourceId)`.
|
||||
SourceId,
|
||||
}
|
||||
|
||||
/// A value written in a subgraph definition. The editor converts it to the type of the input it feeds.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum GraphValue {
|
||||
/// A number written without a fractional part, which feeds an integer input as an integer and any other as a number.
|
||||
Integer(i64),
|
||||
Number(f64),
|
||||
Bool(bool),
|
||||
String(String),
|
||||
Vec2(glam::DVec2),
|
||||
Color(Color),
|
||||
}
|
||||
|
||||
impl GraphValue {
|
||||
pub fn vec2(x: f64, y: f64) -> Self {
|
||||
Self::Vec2(glam::DVec2::new(x, y))
|
||||
}
|
||||
|
||||
/// An opaque color from `rgb(0xRRGGBB)`.
|
||||
pub fn rgb(hex: u32) -> Self {
|
||||
let [_, red, green, blue] = hex.to_be_bytes();
|
||||
Self::Color(crate::color::SRGBA8::new(red, green, blue, 255).into())
|
||||
}
|
||||
|
||||
/// A color with alpha from `rgba(0xRRGGBBAA)`.
|
||||
pub fn rgba(hex: u32) -> Self {
|
||||
let [red, green, blue, alpha] = hex.to_be_bytes();
|
||||
Self::Color(crate::color::SRGBA8::new(red, green, blue, alpha).into())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for GraphValue {
|
||||
fn from(value: &str) -> Self {
|
||||
Self::String(value.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for GraphValue {
|
||||
fn from(value: String) -> Self {
|
||||
Self::String(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<bool> for GraphValue {
|
||||
fn from(value: bool) -> Self {
|
||||
Self::Bool(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<f64> for GraphValue {
|
||||
fn from(value: f64) -> Self {
|
||||
Self::Number(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<i64> for GraphValue {
|
||||
fn from(value: i64) -> Self {
|
||||
Self::Integer(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<glam::DVec2> for GraphValue {
|
||||
fn from(value: glam::DVec2) -> Self {
|
||||
Self::Vec2(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Color> for GraphValue {
|
||||
fn from(value: Color) -> Self {
|
||||
Self::Color(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// All multi-output proto nodes (those returning a [`Destructure`] struct), keyed by their identifier.
|
||||
/// Snapshotted on first access, which must happen after startup registration of the node metadata completes.
|
||||
pub static MULTI_OUTPUT_NODES: LazyLock<HashMap<ProtoNodeIdentifier, DestructureMetadata>> = LazyLock::new(|| {
|
||||
|
||||
@@ -1,465 +0,0 @@
|
||||
//! Lengths and angles as the node graph carries them, and the units an input remembers its value was typed in.
|
||||
|
||||
use dyn_any::DynAny;
|
||||
use math_parser::quantity::Quantity;
|
||||
use math_parser::units::Unit;
|
||||
use math_parser::value::Value;
|
||||
use std::iter::Sum;
|
||||
use std::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign};
|
||||
|
||||
/// The pixels per inch of a document that sets none of its own, CSS's reference pixel, which every SVG reader also assumes.
|
||||
pub const DEFAULT_PIXELS_PER_INCH: f64 = math_parser::units::DEFAULT_PIXELS_PER_INCH;
|
||||
|
||||
/// The scope key under which the graph's runtime injects the document's pixels per inch.
|
||||
pub const PIXELS_PER_INCH_SCOPE: &str = "pixels-per-inch";
|
||||
|
||||
/// A distance across the canvas, measured in pixels: the one type a length travels the node graph as, whatever unit it was typed in.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd, DynAny, graphene_hash::CacheHash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(transparent))]
|
||||
pub struct Length(f64);
|
||||
|
||||
impl Length {
|
||||
pub const ZERO: Self = Self(0.);
|
||||
|
||||
pub const fn from_pixels(pixels: f64) -> Self {
|
||||
Self(pixels)
|
||||
}
|
||||
|
||||
pub const fn pixels(self) -> f64 {
|
||||
self.0
|
||||
}
|
||||
|
||||
pub fn abs(self) -> Self {
|
||||
Self(self.0.abs())
|
||||
}
|
||||
|
||||
pub fn min(self, other: Self) -> Self {
|
||||
Self(self.0.min(other.0))
|
||||
}
|
||||
|
||||
pub fn max(self, other: Self) -> Self {
|
||||
Self(self.0.max(other.0))
|
||||
}
|
||||
}
|
||||
|
||||
/// An angle, which node bodies read in radians or degrees as their math needs.
|
||||
/// It's held in degrees, so sums and comparisons of whole degrees stay exact.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd, DynAny, graphene_hash::CacheHash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(transparent))]
|
||||
pub struct Angle(f64);
|
||||
|
||||
impl Angle {
|
||||
pub const ZERO: Self = Self(0.);
|
||||
|
||||
pub const fn from_radians(radians: f64) -> Self {
|
||||
Self(radians.to_degrees())
|
||||
}
|
||||
|
||||
pub const fn from_degrees(degrees: f64) -> Self {
|
||||
Self(degrees)
|
||||
}
|
||||
|
||||
pub const fn radians(self) -> f64 {
|
||||
self.0.to_radians()
|
||||
}
|
||||
|
||||
pub const fn degrees(self) -> f64 {
|
||||
self.0
|
||||
}
|
||||
|
||||
pub fn abs(self) -> Self {
|
||||
Self(self.0.abs())
|
||||
}
|
||||
|
||||
pub fn min(self, other: Self) -> Self {
|
||||
Self(self.0.min(other.0))
|
||||
}
|
||||
|
||||
pub fn max(self, other: Self) -> Self {
|
||||
Self(self.0.max(other.0))
|
||||
}
|
||||
}
|
||||
|
||||
/// Arithmetic that keeps a measurement's meaning: sums and differences of like measurements, scaling by a plain number, and the
|
||||
/// plain ratio of two like measurements.
|
||||
macro_rules! measurement_arithmetic {
|
||||
($($measurement:ident),*) => {
|
||||
$(
|
||||
impl Add for $measurement {
|
||||
type Output = Self;
|
||||
fn add(self, other: Self) -> Self {
|
||||
Self(self.0 + other.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Sub for $measurement {
|
||||
type Output = Self;
|
||||
fn sub(self, other: Self) -> Self {
|
||||
Self(self.0 - other.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl AddAssign for $measurement {
|
||||
fn add_assign(&mut self, other: Self) {
|
||||
self.0 += other.0;
|
||||
}
|
||||
}
|
||||
|
||||
impl SubAssign for $measurement {
|
||||
fn sub_assign(&mut self, other: Self) {
|
||||
self.0 -= other.0;
|
||||
}
|
||||
}
|
||||
|
||||
impl Neg for $measurement {
|
||||
type Output = Self;
|
||||
fn neg(self) -> Self {
|
||||
Self(-self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Mul<f64> for $measurement {
|
||||
type Output = Self;
|
||||
fn mul(self, factor: f64) -> Self {
|
||||
Self(self.0 * factor)
|
||||
}
|
||||
}
|
||||
|
||||
impl Mul<$measurement> for f64 {
|
||||
type Output = $measurement;
|
||||
fn mul(self, measurement: $measurement) -> $measurement {
|
||||
$measurement(self * measurement.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Div<f64> for $measurement {
|
||||
type Output = Self;
|
||||
fn div(self, divisor: f64) -> Self {
|
||||
Self(self.0 / divisor)
|
||||
}
|
||||
}
|
||||
|
||||
impl Div for $measurement {
|
||||
type Output = f64;
|
||||
fn div(self, divisor: Self) -> f64 {
|
||||
self.0 / divisor.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Sum for $measurement {
|
||||
fn sum<I: Iterator<Item = Self>>(iterator: I) -> Self {
|
||||
Self(iterator.map(|measurement| measurement.0).sum())
|
||||
}
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
measurement_arithmetic!(Length, Angle);
|
||||
|
||||
impl std::fmt::Display for Length {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{} px", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Angle {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}°", self.degrees())
|
||||
}
|
||||
}
|
||||
|
||||
/// A unit a length can be typed in.
|
||||
#[repr(C)]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash, graphene_hash::CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[widget(Dropdown)]
|
||||
pub enum LengthUnit {
|
||||
/// A pixel of the canvas, which the document's resolution sizes against an inch.
|
||||
#[default]
|
||||
Pixel,
|
||||
/// A typographic point, 1/72 of an inch.
|
||||
Point,
|
||||
/// A typographic pica, 12 points or 1/6 of an inch.
|
||||
Pica,
|
||||
/// An inch, 25.4 millimeters.
|
||||
Inch,
|
||||
/// A foot, 12 inches.
|
||||
Foot,
|
||||
/// A yard, 3 feet.
|
||||
Yard,
|
||||
/// A mile, 5280 feet.
|
||||
Mile,
|
||||
/// A thou, 1/1000 of an inch.
|
||||
Thou,
|
||||
/// A micrometer, 1/1000 of a millimeter.
|
||||
Micrometer,
|
||||
/// A millimeter.
|
||||
Millimeter,
|
||||
/// A centimeter, 10 millimeters.
|
||||
Centimeter,
|
||||
/// A meter, 100 centimeters.
|
||||
Meter,
|
||||
/// A kilometer, 1000 meters.
|
||||
Kilometer,
|
||||
}
|
||||
|
||||
impl LengthUnit {
|
||||
pub const ALL: [Self; 13] = [
|
||||
Self::Pixel,
|
||||
Self::Point,
|
||||
Self::Pica,
|
||||
Self::Inch,
|
||||
Self::Foot,
|
||||
Self::Yard,
|
||||
Self::Mile,
|
||||
Self::Thou,
|
||||
Self::Micrometer,
|
||||
Self::Millimeter,
|
||||
Self::Centimeter,
|
||||
Self::Meter,
|
||||
Self::Kilometer,
|
||||
];
|
||||
|
||||
/// The unit's symbol as the expression language spells it, like `mm`.
|
||||
pub fn symbol(self) -> &'static str {
|
||||
match self {
|
||||
Self::Pixel => "px",
|
||||
Self::Point => "pt",
|
||||
Self::Pica => "pc",
|
||||
Self::Inch => "in",
|
||||
Self::Foot => "ft",
|
||||
Self::Yard => "yd",
|
||||
Self::Mile => "mi",
|
||||
Self::Thou => "thou",
|
||||
Self::Micrometer => "µm",
|
||||
Self::Millimeter => "mm",
|
||||
Self::Centimeter => "cm",
|
||||
Self::Meter => "m",
|
||||
Self::Kilometer => "km",
|
||||
}
|
||||
}
|
||||
|
||||
/// The unit a math expression's unit is, if it is one of these.
|
||||
pub fn from_unit(unit: Unit) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|candidate| candidate.unit() == unit)
|
||||
}
|
||||
|
||||
/// The expression language's unit of the same size.
|
||||
pub fn unit(self) -> Unit {
|
||||
Unit::named(self.symbol()).unwrap_or(Unit::NONE)
|
||||
}
|
||||
|
||||
/// Whether the unit is a physical size, which converts to pixels by the document's resolution.
|
||||
pub fn is_physical(self) -> bool {
|
||||
self != Self::Pixel
|
||||
}
|
||||
|
||||
/// Converts a number in this unit into another, exactly where the ratio between them allows.
|
||||
pub fn convert(self, value: f64, into: Self, pixels_per_inch: f64) -> f64 {
|
||||
if self == into {
|
||||
return value;
|
||||
}
|
||||
Quantity::new(Value::from_f64(value), self.unit())
|
||||
.convert(into.unit(), pixels_per_inch)
|
||||
.ok()
|
||||
.and_then(|converted| converted.as_real())
|
||||
.unwrap_or(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// A unit an angle can be typed in.
|
||||
#[repr(C)]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash, graphene_hash::CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[widget(Dropdown)]
|
||||
pub enum AngleUnit {
|
||||
/// A degree, 1/360 of a turn.
|
||||
#[default]
|
||||
Degree,
|
||||
/// A radian, the angle of an arc as long as its radius, 1/(2π) of a turn.
|
||||
Radian,
|
||||
/// A whole turn around the circle.
|
||||
Turn,
|
||||
}
|
||||
|
||||
impl AngleUnit {
|
||||
pub const ALL: [Self; 3] = [Self::Degree, Self::Radian, Self::Turn];
|
||||
|
||||
/// The unit's symbol as the expression language spells it, like `°`.
|
||||
pub fn symbol(self) -> &'static str {
|
||||
match self {
|
||||
Self::Degree => "°",
|
||||
Self::Radian => "rad",
|
||||
Self::Turn => "turn",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_unit(unit: Unit) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|candidate| candidate.unit() == unit)
|
||||
}
|
||||
|
||||
pub fn unit(self) -> Unit {
|
||||
Unit::named(self.symbol()).unwrap_or(Unit::NONE)
|
||||
}
|
||||
|
||||
pub fn to_angle(self, value: f64) -> Angle {
|
||||
match self {
|
||||
Self::Degree => Angle::from_degrees(value),
|
||||
Self::Radian => Angle::from_radians(value),
|
||||
Self::Turn => Angle::from_degrees(value * 360.),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_angle(self, angle: Angle) -> f64 {
|
||||
match self {
|
||||
Self::Degree => angle.degrees(),
|
||||
Self::Radian => angle.radians(),
|
||||
Self::Turn => angle.degrees() / 360.,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A length as typed into an input, kept in its unit so a physical size stays physical when the document's resolution changes.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, DynAny, graphene_hash::CacheHash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct TypedLength {
|
||||
pub value: f64,
|
||||
pub unit: LengthUnit,
|
||||
}
|
||||
|
||||
impl TypedLength {
|
||||
pub const fn pixels(pixels: f64) -> Self {
|
||||
Self {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_length(self, pixels_per_inch: f64) -> Length {
|
||||
Length::from_pixels(self.unit.convert(self.value, LengthUnit::Pixel, pixels_per_inch))
|
||||
}
|
||||
}
|
||||
|
||||
/// An angle as typed into an input, kept in its unit for display.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, DynAny, graphene_hash::CacheHash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct TypedAngle {
|
||||
pub value: f64,
|
||||
pub unit: AngleUnit,
|
||||
}
|
||||
|
||||
impl TypedAngle {
|
||||
pub const fn degrees(degrees: f64) -> Self {
|
||||
Self {
|
||||
value: degrees,
|
||||
unit: AngleUnit::Degree,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_angle(self) -> Angle {
|
||||
self.unit.to_angle(self.value)
|
||||
}
|
||||
}
|
||||
|
||||
// A plain number wired into a length or angle reads in the unit its field shows, pixels or degrees
|
||||
impl crate::ops::Convert<Length, ()> for f64 {
|
||||
fn convert(self, _: crate::transform::Footprint, _converter: ()) -> Length {
|
||||
Length::from_pixels(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::ops::Convert<Length, ()> for i64 {
|
||||
fn convert(self, _: crate::transform::Footprint, _converter: ()) -> Length {
|
||||
Length::from_pixels(self as f64)
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::ops::Convert<Angle, ()> for f64 {
|
||||
fn convert(self, _: crate::transform::Footprint, _converter: ()) -> Angle {
|
||||
Angle::from_degrees(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::ops::Convert<Angle, ()> for i64 {
|
||||
fn convert(self, _: crate::transform::Footprint, _converter: ()) -> Angle {
|
||||
Angle::from_degrees(self as f64)
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::ops::Convert<String, ()> for Length {
|
||||
fn convert(self, _: crate::transform::Footprint, _converter: ()) -> String {
|
||||
format!("{} px", crate::math::float_noise::round_away_float_noise(self.pixels()))
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::ops::Convert<String, ()> for Angle {
|
||||
fn convert(self, _: crate::transform::Footprint, _converter: ()) -> String {
|
||||
format!("{}°", crate::math::float_noise::round_away_float_noise(self.degrees()))
|
||||
}
|
||||
}
|
||||
|
||||
// A length's bounds are in pixels and an angle's in degrees, the units their fields show
|
||||
impl crate::misc::Clampable for Length {
|
||||
fn clamp_hard_min(self, min: f64) -> Self {
|
||||
Self(self.0.max(min))
|
||||
}
|
||||
fn clamp_hard_max(self, max: f64) -> Self {
|
||||
Self(self.0.min(max))
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::misc::Clampable for Angle {
|
||||
fn clamp_hard_min(self, min: f64) -> Self {
|
||||
Self(self.0.max(min))
|
||||
}
|
||||
fn clamp_hard_max(self, max: f64) -> Self {
|
||||
Self(self.0.min(max))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_unit_is_one_of_the_expression_language() {
|
||||
for unit in LengthUnit::ALL {
|
||||
assert_eq!(LengthUnit::from_unit(unit.unit()), Some(unit), "`{}`", unit.symbol());
|
||||
assert_eq!(unit.unit().dimension(), math_parser::units::Dimension::LENGTH);
|
||||
}
|
||||
for unit in AngleUnit::ALL {
|
||||
assert_eq!(AngleUnit::from_unit(unit.unit()), Some(unit), "`{}`", unit.symbol());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_lengths_convert_to_pixels_by_the_resolution() {
|
||||
assert_eq!(TypedLength { value: 1., unit: LengthUnit::Inch }.to_length(96.), Length::from_pixels(96.));
|
||||
assert_eq!(TypedLength { value: 1., unit: LengthUnit::Inch }.to_length(300.), Length::from_pixels(300.));
|
||||
assert_eq!(TypedLength { value: 72., unit: LengthUnit::Point }.to_length(96.), Length::from_pixels(96.));
|
||||
assert_eq!(TypedLength::pixels(12.).to_length(300.), Length::from_pixels(12.));
|
||||
let millimeters = TypedLength {
|
||||
value: 25.4,
|
||||
unit: LengthUnit::Millimeter,
|
||||
}
|
||||
.to_length(96.)
|
||||
.pixels();
|
||||
assert!((millimeters - 96.).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn angles_read_in_any_unit() {
|
||||
assert!((TypedAngle::degrees(90.).to_angle().radians() - std::f64::consts::FRAC_PI_2).abs() < 1e-12);
|
||||
assert!((AngleUnit::Turn.to_angle(0.25).degrees() - 90.).abs() < 1e-12);
|
||||
assert!((AngleUnit::Turn.from_angle(Angle::from_degrees(180.)) - 0.5).abs() < 1e-12);
|
||||
}
|
||||
|
||||
// Arithmetic on whole degrees compares equal to the degrees it should give
|
||||
#[test]
|
||||
fn whole_degrees_stay_exact_through_arithmetic() {
|
||||
assert_eq!(Angle::from_degrees(1.) + Angle::from_degrees(5.), Angle::from_degrees(6.));
|
||||
assert_eq!(AngleUnit::Turn.to_angle(0.25), Angle::from_degrees(90.));
|
||||
}
|
||||
}
|
||||
@@ -1900,15 +1900,10 @@ impl SvgRender {
|
||||
self.svg.push("</svg>".into());
|
||||
}
|
||||
|
||||
/// Wraps the SVG with `<svg><g transform="...">...</g></svg>`, which allows for rotation. Given a resolution, its width and height
|
||||
/// state its physical size in inches, which SVG readers otherwise take from CSS's 96 pixels per inch.
|
||||
pub fn wrap_with_transform(&mut self, transform: DAffine2, size: Option<DVec2>, pixels_per_inch: Option<f64>) {
|
||||
let dimension = |pixels: f64| match pixels_per_inch {
|
||||
Some(pixels_per_inch) if pixels_per_inch.is_finite() && pixels_per_inch > 0. => format!("{}in", pixels / pixels_per_inch),
|
||||
_ => pixels.to_string(),
|
||||
};
|
||||
/// Wraps the SVG with `<svg><g transform="...">...</g></svg>`, which allows for rotation
|
||||
pub fn wrap_with_transform(&mut self, transform: DAffine2, size: Option<DVec2>) {
|
||||
let view_box = size
|
||||
.map(|size| format!("viewBox=\"0 0 {} {}\" width=\"{}\" height=\"{}\"", size.x, size.y, dimension(size.x), dimension(size.y)))
|
||||
.map(|size| format!("viewBox=\"0 0 {} {}\" width=\"{}\" height=\"{}\"", size.x, size.y, size.x, size.y))
|
||||
.unwrap_or_default();
|
||||
|
||||
let matrix = format_transform_matrix(transform);
|
||||
@@ -2047,9 +2042,6 @@ pub struct RenderParams {
|
||||
pub canvas_image_scale: f64,
|
||||
/// The nearest ancestor's appearance, cascading to items that lack their own.
|
||||
pub inherited_appearance: Option<Appearance>,
|
||||
/// The document's pixels per inch, which an exported SVG states its physical size by, or `None` where it's CSS's 96 or no export.
|
||||
#[cache_hash(skip)]
|
||||
pub pixels_per_inch: Option<f64>,
|
||||
}
|
||||
|
||||
impl RenderParams {
|
||||
@@ -5861,17 +5853,6 @@ impl SvgRenderAttrs<'_> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn an_svg_states_its_physical_size_at_a_resolution() {
|
||||
let mut render = SvgRender::new();
|
||||
render.wrap_with_transform(DAffine2::IDENTITY, Some(DVec2::new(960., 480.)), Some(96.));
|
||||
assert!(render.svg.to_svg_string().contains(r#"width="10in" height="5in""#));
|
||||
|
||||
let mut render = SvgRender::new();
|
||||
render.wrap_with_transform(DAffine2::IDENTITY, Some(DVec2::new(960., 480.)), None);
|
||||
assert!(render.svg.to_svg_string().contains(r#"width="960" height="480""#));
|
||||
}
|
||||
use vector_types::gradient::GradientSpace;
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -3,6 +3,7 @@ use convert_case::{Case, Casing};
|
||||
use proc_macro2::TokenStream as TokenStream2;
|
||||
use quote::{ToTokens, format_ident, quote, quote_spanned};
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use syn::ext::IdentExt;
|
||||
use syn::punctuated::Punctuated;
|
||||
use syn::spanned::Spanned;
|
||||
use syn::token::Comma;
|
||||
@@ -112,15 +113,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let data_field_names: Vec<_> = data_fields.iter().map(|f| &f.pat_ident.ident).collect();
|
||||
|
||||
// Only regular fields have input names/descriptions (for UI)
|
||||
let input_names: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.map(|f| &f.name)
|
||||
.zip(regular_field_names.iter())
|
||||
.map(|zipped| match zipped {
|
||||
(Some(name), _) => name.value(),
|
||||
(_, name) => name.to_string().to_case(Case::Title),
|
||||
})
|
||||
.collect();
|
||||
let input_names: Vec<_> = regular_fields.iter().map(|field| parameter_display_name(field)).collect();
|
||||
|
||||
// The primary input is not a parameter, so generators can name their unused one `_primary` without it becoming internal
|
||||
let input_internal = regular_field_names
|
||||
@@ -174,56 +167,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Only regular fields have UI metadata (data fields are internal state)
|
||||
let widget_override: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.map(|field| match &field.widget_override {
|
||||
ParsedWidgetOverride::None => quote!(RegistryWidgetOverride::None),
|
||||
ParsedWidgetOverride::Hidden => quote!(RegistryWidgetOverride::Hidden),
|
||||
ParsedWidgetOverride::String(lit_str) => quote!(RegistryWidgetOverride::String(#lit_str)),
|
||||
ParsedWidgetOverride::Custom(lit_str) => quote!(RegistryWidgetOverride::Custom(#lit_str)),
|
||||
})
|
||||
.collect();
|
||||
|
||||
let value_sources: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.map(|field| match field.ty.value_source() {
|
||||
ParsedValueSource::Default(data) => {
|
||||
// Check if the data is a string literal by parsing the token stream
|
||||
let data_str = data.to_string();
|
||||
if data_str.starts_with('"') && data_str.ends_with('"') && data_str.len() >= 2 {
|
||||
quote!(RegistryValueSource::Default(#data))
|
||||
} else {
|
||||
quote!(RegistryValueSource::Default(stringify!(#data)))
|
||||
}
|
||||
}
|
||||
ParsedValueSource::Scope(data) => {
|
||||
if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(_), .. }) = data.as_ref() {
|
||||
quote!(RegistryValueSource::Scope(#data))
|
||||
} else {
|
||||
quote!(RegistryValueSource::Scope(#data.as_static_str()))
|
||||
}
|
||||
}
|
||||
ParsedValueSource::SourceId => quote!(RegistryValueSource::SourceId),
|
||||
ParsedValueSource::NodePath => quote!(RegistryValueSource::NodePath),
|
||||
_ => quote!(RegistryValueSource::None),
|
||||
})
|
||||
.collect();
|
||||
|
||||
let default_colors: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.map(|field| match field.ty.regular() {
|
||||
Some(RegularParsedField {
|
||||
value_source: ParsedValueSource::Default(data),
|
||||
..
|
||||
}) => match color_constant_paths(data) {
|
||||
Some(paths) => quote!(Some(&[#(#paths),*])),
|
||||
None => quote!(None),
|
||||
},
|
||||
_ => quote!(None),
|
||||
})
|
||||
.collect();
|
||||
|
||||
let default_types: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
@@ -270,64 +213,12 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
})
|
||||
.collect();
|
||||
|
||||
let bound_values = |select: fn(&RegularParsedField) -> &Option<NumberBound>| -> Vec<_> {
|
||||
regular_fields
|
||||
.iter()
|
||||
.map(|field| match field.ty.regular() {
|
||||
Some(regular) => select(regular).as_ref().map_or(quote!(None), |bound| quote!(Some(#bound))),
|
||||
None => quote!(None),
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let number_soft_min_values = bound_values(|field| &field.number_soft_min);
|
||||
let number_soft_max_values = bound_values(|field| &field.number_soft_max);
|
||||
let number_hard_min_values = bound_values(|field| &field.number_hard_min);
|
||||
let number_hard_max_values = bound_values(|field| &field.number_hard_max);
|
||||
let number_mode_range_values: Vec<_> = regular_fields
|
||||
// Only regular fields have UI metadata (data fields are internal state)
|
||||
let field_metadata: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.map(|field| match field.ty.regular() {
|
||||
Some(RegularParsedField { number_mode_range, .. }) => quote!(#number_mode_range),
|
||||
None => quote!(false),
|
||||
})
|
||||
.collect();
|
||||
let number_display_decimal_places: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.map(|field| field.number_display_decimal_places.as_ref().map_or(quote!(None), |i| quote!(Some(#i))))
|
||||
.collect();
|
||||
let number_step: Vec<_> = regular_fields.iter().map(|field| field.number_step.as_ref().map_or(quote!(None), |i| quote!(Some(#i)))).collect();
|
||||
|
||||
let unit_suffix: Vec<_> = regular_fields.iter().map(|field| field.unit.as_ref().map_or(quote!(None), |i| quote!(Some(#i)))).collect();
|
||||
let multiline: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.map(|field| {
|
||||
let multiline = field.multiline;
|
||||
quote!(#multiline)
|
||||
})
|
||||
.collect();
|
||||
let progression: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.map(|field| {
|
||||
let progression = field.progression;
|
||||
quote!(#progression)
|
||||
})
|
||||
.collect();
|
||||
let constant: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.map(|field| {
|
||||
let constant = field.constant;
|
||||
quote!(#constant)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let exposed: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.map(|field| match field.ty.regular() {
|
||||
Some(RegularParsedField { exposed, .. }) => quote!(#exposed),
|
||||
None => {
|
||||
let exposed = !field.is_environment();
|
||||
quote!(#exposed)
|
||||
}
|
||||
})
|
||||
.zip(&input_internal)
|
||||
.zip(&default_types)
|
||||
.map(|((field, internal), default_type)| field_metadata_tokens(field, *internal, default_type, core_types))
|
||||
.collect();
|
||||
|
||||
// Only eval regular fields (data fields are accessed directly as self.field_name)
|
||||
@@ -858,7 +749,8 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
Some(cfg) => quote!(#[cfg(#cfg)]),
|
||||
None => quote!(),
|
||||
};
|
||||
let node_input_accessor = generate_node_input_references(parsed, &field_idents, core_types, &identifier, &cfg);
|
||||
let parameter_idents: Vec<_> = regular_fields.iter().filter(|field| !field.is_environment()).map(|field| &field.pat_ident).collect();
|
||||
let node_input_accessor = generate_node_input_references(parsed, ¶meter_idents, core_types, &identifier, &cfg);
|
||||
|
||||
let mapped_node_impl = match (&mapped_struct_where_clause, &mapped_eval_impl) {
|
||||
(Some(mapped_where_clause), Some(mapped_eval)) => quote! {
|
||||
@@ -1009,7 +901,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
use gcore::{Node, NodeIOTypes, concrete, fn_type, ProtoNodeIdentifier, WasmNotSync, NodeIO, ContextFeature};
|
||||
use gcore::value::ClonedNode;
|
||||
use gcore::ops::TypeNode;
|
||||
use gcore::registry::{NodeMetadata, FieldMetadata, NODE_REGISTRY, NODE_METADATA, DynAnyNode, DowncastBothNode, TypeErasedBox, PanicNode, RegistryValueSource, RegistryWidgetOverride};
|
||||
use gcore::registry::{NodeMetadata, NODE_REGISTRY, NODE_METADATA, DynAnyNode, DowncastBothNode, TypeErasedBox, PanicNode};
|
||||
use gcore::ctor::ctor;
|
||||
|
||||
// Use the types specified in the implementation
|
||||
@@ -1056,31 +948,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
},
|
||||
version: #version,
|
||||
output_fields: #output_fields,
|
||||
fields: vec![
|
||||
#(
|
||||
FieldMetadata {
|
||||
name: #input_names,
|
||||
widget_override: #widget_override,
|
||||
description: #input_descriptions,
|
||||
internal: #input_internal,
|
||||
exposed: #exposed,
|
||||
value_source: #value_sources,
|
||||
default_colors: #default_colors,
|
||||
default_type: #default_types,
|
||||
number_soft_min: #number_soft_min_values,
|
||||
number_soft_max: #number_soft_max_values,
|
||||
number_hard_min: #number_hard_min_values,
|
||||
number_hard_max: #number_hard_max_values,
|
||||
number_mode_range: #number_mode_range_values,
|
||||
number_display_decimal_places: #number_display_decimal_places,
|
||||
number_step: #number_step,
|
||||
unit: #unit_suffix,
|
||||
multiline: #multiline,
|
||||
progression: #progression,
|
||||
constant: #constant,
|
||||
},
|
||||
)*
|
||||
],
|
||||
fields: vec![#(#field_metadata,)*],
|
||||
};
|
||||
NODE_METADATA.lock().unwrap().insert(#identifier(), metadata);
|
||||
}
|
||||
@@ -1088,6 +956,131 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
})
|
||||
}
|
||||
|
||||
/// The display name an identifier derives, in Title Case.
|
||||
pub(crate) fn derived_display_name(ident: &Ident) -> String {
|
||||
// A lone `_` comes out of the case conversion as a space
|
||||
ident.unraw().to_string().to_case(Case::Title).trim().to_string()
|
||||
}
|
||||
|
||||
/// The name a parameter shows in the UI: its `#[name("…")]`, or else its identifier in Title Case.
|
||||
pub(crate) fn parameter_display_name(field: &ParsedField) -> String {
|
||||
match &field.name {
|
||||
Some(name) => name.value(),
|
||||
None => derived_display_name(&field.pat_ident.ident),
|
||||
}
|
||||
}
|
||||
|
||||
/// The symbol naming a parameter or output in a node's module, like `CountInput` for the `count` parameter.
|
||||
pub(crate) fn symbol_name(ident: &Ident, suffix: &str) -> Ident {
|
||||
format_ident!("{}{suffix}", ident.unraw().to_string().to_case(Case::Pascal), span = ident.span())
|
||||
}
|
||||
|
||||
/// Generated code for `Some(value)` or `None`, by full path so no name in the author's module can stand in for either.
|
||||
pub(crate) fn option_tokens(value: Option<TokenStream2>) -> TokenStream2 {
|
||||
match value {
|
||||
Some(value) => quote!(::core::option::Option::Some(#value)),
|
||||
None => quote!(::core::option::Option::None),
|
||||
}
|
||||
}
|
||||
|
||||
/// The registry's `FieldMetadata` for a parameter, shared by proto node fields and graph imports, which differ only in
|
||||
/// how they work out whether it's internal state and which type its default is built from.
|
||||
pub(crate) fn field_metadata_tokens(field: &ParsedField, internal: bool, default_type: &TokenStream2, core_types: &TokenStream2) -> TokenStream2 {
|
||||
let registry = quote!(#core_types::registry);
|
||||
|
||||
let name = parameter_display_name(field);
|
||||
let description = &field.description;
|
||||
let exposed = match field.ty.regular() {
|
||||
Some(regular) => regular.exposed,
|
||||
None => !field.is_environment(),
|
||||
};
|
||||
|
||||
let widget_override = match &field.widget_override {
|
||||
ParsedWidgetOverride::None => quote!(#registry::RegistryWidgetOverride::None),
|
||||
ParsedWidgetOverride::Hidden => quote!(#registry::RegistryWidgetOverride::Hidden),
|
||||
ParsedWidgetOverride::String(text) => quote!(#registry::RegistryWidgetOverride::String(#text)),
|
||||
ParsedWidgetOverride::Custom(key) => quote!(#registry::RegistryWidgetOverride::Custom(#key)),
|
||||
};
|
||||
|
||||
// A string literal default keeps its contents, and any other expression is stringified for the editor to parse by type
|
||||
let value_source = match field.ty.value_source() {
|
||||
ParsedValueSource::Default(data) => {
|
||||
let data_string = data.to_string();
|
||||
if data_string.starts_with('"') && data_string.ends_with('"') && data_string.len() >= 2 {
|
||||
quote!(#registry::RegistryValueSource::Default(#data))
|
||||
} else {
|
||||
quote!(#registry::RegistryValueSource::Default(::core::stringify!(#data)))
|
||||
}
|
||||
}
|
||||
ParsedValueSource::Scope(data) => {
|
||||
if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(_), .. }) = data.as_ref() {
|
||||
quote!(#registry::RegistryValueSource::Scope(#data))
|
||||
} else {
|
||||
quote!(#registry::RegistryValueSource::Scope(#data.as_static_str()))
|
||||
}
|
||||
}
|
||||
ParsedValueSource::SourceId => quote!(#registry::RegistryValueSource::SourceId),
|
||||
ParsedValueSource::NodePath => quote!(#registry::RegistryValueSource::NodePath),
|
||||
ParsedValueSource::None => quote!(#registry::RegistryValueSource::None),
|
||||
};
|
||||
|
||||
let default_colors = match field.ty.regular() {
|
||||
Some(RegularParsedField {
|
||||
value_source: ParsedValueSource::Default(data),
|
||||
..
|
||||
}) => option_tokens(color_constant_paths(data).map(|paths| quote!(&[#(#paths),*]))),
|
||||
_ => option_tokens(None),
|
||||
};
|
||||
|
||||
let regular = field.ty.regular();
|
||||
let bound = |select: fn(&RegularParsedField) -> &Option<NumberBound>| option_tokens(regular.and_then(|regular| select(regular).as_ref()).map(ToTokens::to_token_stream));
|
||||
let number_soft_min = bound(|regular| ®ular.number_soft_min);
|
||||
let number_soft_max = bound(|regular| ®ular.number_soft_max);
|
||||
let number_hard_min = bound(|regular| ®ular.number_hard_min);
|
||||
let number_hard_max = bound(|regular| ®ular.number_hard_max);
|
||||
let number_mode_range = regular.is_some_and(|regular| regular.number_mode_range);
|
||||
|
||||
let number_display_decimal_places = option_tokens(field.number_display_decimal_places.as_ref().map(ToTokens::to_token_stream));
|
||||
let number_step = option_tokens(field.number_step.as_ref().map(ToTokens::to_token_stream));
|
||||
let unit = option_tokens(field.unit.as_ref().map(ToTokens::to_token_stream));
|
||||
let labels = option_tokens(field.labels.as_ref().map(|(x, y)| quote!((#x, #y))));
|
||||
let ParsedField {
|
||||
multiline,
|
||||
progression,
|
||||
constant,
|
||||
integer,
|
||||
blank_assist,
|
||||
..
|
||||
} = field;
|
||||
|
||||
quote! {
|
||||
#registry::FieldMetadata {
|
||||
name: #name,
|
||||
description: #description,
|
||||
internal: #internal,
|
||||
exposed: #exposed,
|
||||
widget_override: #widget_override,
|
||||
value_source: #value_source,
|
||||
default_colors: #default_colors,
|
||||
default_type: #default_type,
|
||||
number_soft_min: #number_soft_min,
|
||||
number_soft_max: #number_soft_max,
|
||||
number_hard_min: #number_hard_min,
|
||||
number_hard_max: #number_hard_max,
|
||||
number_mode_range: #number_mode_range,
|
||||
number_display_decimal_places: #number_display_decimal_places,
|
||||
number_step: #number_step,
|
||||
unit: #unit,
|
||||
multiline: #multiline,
|
||||
progression: #progression,
|
||||
constant: #constant,
|
||||
labels: #labels,
|
||||
integer: #integer,
|
||||
blank_assist: #blank_assist,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `Color::*` constant paths making up a default expression, when it consists solely of them (the form used by color and gradient parameter defaults).
|
||||
fn color_constant_paths(tokens: &TokenStream2) -> Option<Vec<ExprPath>> {
|
||||
use syn::parse::Parser;
|
||||
@@ -1108,26 +1101,25 @@ fn color_constant_paths(tokens: &TokenStream2) -> Option<Vec<ExprPath>> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Generates the per-parameter symbol types used to reference this node's inputs.
|
||||
fn generate_node_input_references(parsed: &ParsedNodeFn, field_idents: &[&PatIdent], core_types: &TokenStream2, identifier: &Ident, cfg: &TokenStream2) -> TokenStream2 {
|
||||
let inputs_module_name = format_ident!("{}", parsed.struct_name.to_string().to_case(Case::Snake));
|
||||
/// Generates the module named after the node's function, holding its identifier, its parameter count, and a symbol for each parameter.
|
||||
/// The inputs the compiler fills in come after the parameters and get no symbol, so a graph can't name one.
|
||||
fn generate_node_input_references(parsed: &ParsedNodeFn, parameter_idents: &[&PatIdent], core_types: &TokenStream2, identifier: &Ident, cfg: &TokenStream2) -> TokenStream2 {
|
||||
let inputs_module_name = &parsed.fn_name;
|
||||
|
||||
let mut generated_input_accessor = Vec::new();
|
||||
if !parsed.attributes.flags.skip_impl {
|
||||
for (input_index, input_ident) in field_idents.iter().enumerate() {
|
||||
// TODO: figure out a better name that doesn't conflict with so many types
|
||||
let struct_name = format_ident!("{}Input", input_ident.ident.to_string().to_case(Case::Pascal));
|
||||
|
||||
// Every parameter gets a plain unit struct: the symbol used across the codebase to name this input
|
||||
generated_input_accessor.push(quote! {
|
||||
pub struct #struct_name;
|
||||
impl #core_types::NodeParameter for #struct_name {
|
||||
const NODE_IDENTIFIER: #core_types::ProtoNodeIdentifier = #inputs_module_name::IDENTIFIER;
|
||||
const INDEX: usize = #input_index;
|
||||
}
|
||||
});
|
||||
// Every parameter gets a plain unit struct: the symbol used across the codebase to name this input
|
||||
let generated_input_accessor = parameter_idents.iter().enumerate().map(|(input_index, input_ident)| {
|
||||
// TODO: figure out a better name that doesn't conflict with so many types
|
||||
let struct_name = symbol_name(&input_ident.ident, "Input");
|
||||
quote! {
|
||||
pub struct #struct_name;
|
||||
impl #core_types::NodeParameter for #struct_name {
|
||||
const NODE_IDENTIFIER: #core_types::ProtoNodeIdentifier = #inputs_module_name::IDENTIFIER;
|
||||
const INDEX: usize = #input_index;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let parameter_count = parameter_idents.len();
|
||||
|
||||
quote! {
|
||||
#cfg
|
||||
@@ -1136,6 +1128,8 @@ fn generate_node_input_references(parsed: &ParsedNodeFn, field_idents: &[&PatIde
|
||||
|
||||
/// The `ProtoNodeIdentifier` of this node without any generics attached to it
|
||||
pub const IDENTIFIER: #core_types::ProtoNodeIdentifier = #identifier();
|
||||
/// How many parameters this node has, which come before the inputs the compiler fills in.
|
||||
pub const PARAMETER_COUNT: usize = #parameter_count;
|
||||
#(#generated_input_accessor)*
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -5,6 +5,7 @@ mod codegen;
|
||||
mod crate_ident;
|
||||
mod derive_choice_type;
|
||||
mod destructure;
|
||||
mod graph;
|
||||
mod parsing;
|
||||
mod validation;
|
||||
|
||||
@@ -16,6 +17,38 @@ pub fn node(attr: TokenStream, item: TokenStream) -> TokenStream {
|
||||
parsing::new_node_fn(attr.into(), item.into()).unwrap_or_else(|err| err.to_compile_error()).into()
|
||||
}
|
||||
|
||||
/// Defines a node as a subgraph of other nodes, the way `#[node]` defines a proto node.
|
||||
///
|
||||
/// The function's parameters are the subgraph's imports, parsed like a proto node's parameters, so they take the same
|
||||
/// value and widget attributes. On an import, `#[hard]` bounds the widget without clamping a wired value.
|
||||
/// `out!(...)` names its exports. The body binds nodes with `let`, wires them with `>>` (which feeds its left side
|
||||
/// into the primary input of the node on its right), and ends with `return`, giving one value per export. Every
|
||||
/// parameter is named in a call, and a bare name feeds the binding or import of that name to the parameter of the same
|
||||
/// name. Node state goes in methods after the call, each written once: `.at(x, y)`, `.layer()`, `.hidden()`, `.locked()`,
|
||||
/// `.pinned()`, `.named("…")`, and `.call_argument::<Footprint>()`. After those, an output's name like `.captures` wires from that
|
||||
/// output of the node, which also works on a binding.
|
||||
///
|
||||
/// ```ignore
|
||||
/// /// Outlines its content.
|
||||
/// #[node_macro::graph(category("Vector: Style"))]
|
||||
/// pub fn outlined(
|
||||
/// content: List<Graphic>,
|
||||
/// /// Outline thickness.
|
||||
/// #[unit(" px")]
|
||||
/// width: Item<f64>,
|
||||
/// ) -> out!(
|
||||
/// /// The outlined content.
|
||||
/// out,
|
||||
/// ) {
|
||||
/// return content >> stroke(weight = width).at(7, 0);
|
||||
/// }
|
||||
/// ```
|
||||
#[proc_macro_error]
|
||||
#[proc_macro_attribute]
|
||||
pub fn graph(attr: TokenStream, item: TokenStream) -> TokenStream {
|
||||
graph::new_graph_fn(attr.into(), item.into()).unwrap_or_else(|err| err.to_compile_error()).into()
|
||||
}
|
||||
|
||||
/// Derives `Destructure` for a struct returned by a multi-output node, making each of its `Item<T>` or `List<T>` fields an output connector.
|
||||
///
|
||||
/// A node function returning such a struct (rather than an `Item` or `List`) becomes a multi-output node. The preprocessor
|
||||
|
||||
@@ -137,6 +137,10 @@ pub struct ParsedField {
|
||||
pub progression: bool,
|
||||
pub constant: bool,
|
||||
pub is_data_field: bool,
|
||||
/// The X and Y labels of a Vec2 widget, from `#[labels("W", "H")]`.
|
||||
pub labels: Option<(LitStr, LitStr)>,
|
||||
pub integer: bool,
|
||||
pub blank_assist: bool,
|
||||
}
|
||||
|
||||
impl ParsedField {
|
||||
@@ -170,6 +174,9 @@ impl ParsedField {
|
||||
progression: false,
|
||||
constant: false,
|
||||
is_data_field: false,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -319,8 +326,8 @@ impl ToTokens for NumberBound {
|
||||
/// Unlike a Rust range there is no `..=` form, `..` is purely this attribute DSL's bounds operator.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct NumberRange {
|
||||
start: Option<NumberBound>,
|
||||
end: Option<NumberBound>,
|
||||
pub(crate) start: Option<NumberBound>,
|
||||
pub(crate) end: Option<NumberBound>,
|
||||
}
|
||||
|
||||
impl Parse for NumberRange {
|
||||
@@ -819,7 +826,8 @@ fn parse_node_implementations<T: Parse>(attr: &Attribute, name: &Ident) -> syn::
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Result<ParsedField> {
|
||||
/// Parses a parameter and its attributes, for a proto node's field or a graph's import.
|
||||
pub(crate) fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Result<ParsedField> {
|
||||
let ident = &pat_ident.ident;
|
||||
|
||||
// Checks for the #[data] attribute, indicating that this is a data field rather than an input parameter to the node.
|
||||
@@ -978,6 +986,22 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
})
|
||||
.transpose()?;
|
||||
|
||||
// `#[labels("W", "H")]` names a Vec2 widget's two fields, and `#[integer]` makes a number or Vec2 widget take only integers
|
||||
let labels = extract_attribute(attrs, "labels")
|
||||
.map(|attr| {
|
||||
let labels: Vec<LitStr> = attr.parse_args_with(Punctuated::<LitStr, Comma>::parse_terminated)?.into_iter().collect();
|
||||
let [x, y] = <[LitStr; 2]>::try_from(labels).map_err(|_| Error::new_spanned(attr, "Give a Vec2 widget two labels, like `#[labels(\"W\", \"H\")]`"))?;
|
||||
Ok::<_, Error>((x, y))
|
||||
})
|
||||
.transpose()?;
|
||||
let integer = extract_attribute(attrs, "integer").is_some();
|
||||
|
||||
// `#[blank_assist(false)]` drops the space a widget leaves for the assist area beside it
|
||||
let blank_assist = extract_attribute(attrs, "blank_assist")
|
||||
.map(|attr| attr.parse_args::<syn::LitBool>().map(|enabled| enabled.value))
|
||||
.transpose()?
|
||||
.unwrap_or(true);
|
||||
|
||||
let (is_node, node_input_type, node_output_type) = parse_node_type(&ty);
|
||||
let description = attrs
|
||||
.iter()
|
||||
@@ -1036,6 +1060,9 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
progression,
|
||||
constant,
|
||||
is_data_field,
|
||||
labels,
|
||||
integer,
|
||||
blank_assist,
|
||||
})
|
||||
} else {
|
||||
let implementations = extract_attribute(attrs, "implementations")
|
||||
@@ -1088,6 +1115,9 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
progression,
|
||||
constant,
|
||||
is_data_field,
|
||||
labels,
|
||||
integer,
|
||||
blank_assist,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1387,6 +1417,9 @@ mod tests {
|
||||
progression: false,
|
||||
constant: false,
|
||||
is_data_field: false,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
description: String::from("Multi\nLine\n"),
|
||||
@@ -1449,6 +1482,9 @@ mod tests {
|
||||
progression: false,
|
||||
constant: false,
|
||||
is_data_field: false,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
},
|
||||
ParsedField {
|
||||
pat_ident: pat_ident("translate"),
|
||||
@@ -1473,6 +1509,9 @@ mod tests {
|
||||
progression: false,
|
||||
constant: false,
|
||||
is_data_field: false,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
},
|
||||
],
|
||||
body: TokenStream2::new(),
|
||||
@@ -1536,6 +1575,9 @@ mod tests {
|
||||
progression: false,
|
||||
constant: false,
|
||||
is_data_field: false,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
description: "Test\n".into(),
|
||||
@@ -1602,6 +1644,9 @@ mod tests {
|
||||
progression: false,
|
||||
constant: false,
|
||||
is_data_field: false,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
description: String::new(),
|
||||
@@ -1671,6 +1716,9 @@ mod tests {
|
||||
progression: false,
|
||||
constant: false,
|
||||
is_data_field: false,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
description: String::new(),
|
||||
@@ -1765,6 +1813,9 @@ mod tests {
|
||||
progression: false,
|
||||
constant: false,
|
||||
is_data_field: false,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
description: String::new(),
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
use crate::parsing::{Implementation, NodeOutputTier, NodeParsedField, ParsedFieldType, ParsedNodeFn, RegularParsedField, output_payload, output_tier};
|
||||
use crate::graph::VALUE_HELPERS;
|
||||
use crate::parsing::{Implementation, NodeOutputTier, NodeParsedField, ParsedField, ParsedFieldType, ParsedNodeFn, RegularParsedField, output_payload, output_tier};
|
||||
use proc_macro_error3::{abort_if_dirty, emit_error};
|
||||
use quote::quote;
|
||||
use syn::spanned::Spanned;
|
||||
use syn::{GenericParam, Type};
|
||||
use syn::{GenericParam, Ident, Type};
|
||||
|
||||
pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> {
|
||||
let validators: &[fn(&ParsedNodeFn)] = &[
|
||||
// Add more validators here as needed
|
||||
validate_implementations_for_generics,
|
||||
validate_implementations_row_counts,
|
||||
validate_primary_input_expose,
|
||||
validate_min_max,
|
||||
validate_range_slider_bounds,
|
||||
|parsed| validate_parameters(&parsed.fields),
|
||||
validate_no_item_parameters,
|
||||
validate_element_wise,
|
||||
validate_ranked_inputs,
|
||||
validate_async,
|
||||
validate_non_parameters_trail,
|
||||
|parsed| validate_name_isnt_a_value_helper(&parsed.fn_name),
|
||||
];
|
||||
|
||||
for validator in validators {
|
||||
@@ -28,6 +28,20 @@ pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A graph body reads a call to a value helper like `rgb(...)` as a value, so a node or graph of that name couldn't be called there.
|
||||
pub(crate) fn validate_name_isnt_a_value_helper(name: &Ident) {
|
||||
if let Some(message) = value_helper_name_violation(name) {
|
||||
emit_error!(name.span(), "{}", message);
|
||||
}
|
||||
}
|
||||
|
||||
fn value_helper_name_violation(name: &Ident) -> Option<String> {
|
||||
let name = name.to_string();
|
||||
VALUE_HELPERS
|
||||
.contains(&name.as_str())
|
||||
.then(|| format!("A node can't be named `{name}`, since graphs use that name for a value helper"))
|
||||
}
|
||||
|
||||
fn validate_no_item_parameters(parsed: &ParsedNodeFn) {
|
||||
if parsed.attributes.flags.skip_impl {
|
||||
return;
|
||||
@@ -291,8 +305,15 @@ fn is_unit_type(ty: &Type) -> bool {
|
||||
matches!(ty, Type::Tuple(tuple) if tuple.elems.is_empty())
|
||||
}
|
||||
|
||||
fn validate_min_max(parsed: &ParsedNodeFn) {
|
||||
for field in &parsed.fields {
|
||||
/// The checks on a node's parameters, shared by proto node fields and graph imports, where the first is the primary input.
|
||||
pub(crate) fn validate_parameters(fields: &[ParsedField]) {
|
||||
validate_primary_input_expose(fields);
|
||||
validate_min_max(fields);
|
||||
validate_range_slider_bounds(fields);
|
||||
}
|
||||
|
||||
fn validate_min_max(fields: &[ParsedField]) {
|
||||
for field in fields {
|
||||
if let Some(RegularParsedField {
|
||||
number_hard_max,
|
||||
number_hard_min,
|
||||
@@ -351,8 +372,8 @@ fn validate_min_max(parsed: &ParsedNodeFn) {
|
||||
|
||||
/// A `#[range]` slider needs a defined extent on both ends. The extent comes from `#[soft]` when present,
|
||||
/// otherwise it falls back to `#[hard]`, so each end must be covered by at least one of the two attributes.
|
||||
fn validate_range_slider_bounds(parsed: &ParsedNodeFn) {
|
||||
for field in &parsed.fields {
|
||||
fn validate_range_slider_bounds(fields: &[ParsedField]) {
|
||||
for field in fields {
|
||||
if let Some(RegularParsedField {
|
||||
number_mode_range: true,
|
||||
number_soft_min,
|
||||
@@ -384,8 +405,8 @@ fn validate_range_slider_bounds(parsed: &ParsedNodeFn) {
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_primary_input_expose(parsed: &ParsedNodeFn) {
|
||||
if let Some(field) = parsed.fields.first()
|
||||
fn validate_primary_input_expose(fields: &[ParsedField]) {
|
||||
if let Some(field) = fields.first()
|
||||
&& let Some(RegularParsedField { exposed: true, .. }) = field.ty.regular()
|
||||
{
|
||||
let pat_ident = &field.pat_ident;
|
||||
@@ -394,7 +415,7 @@ fn validate_primary_input_expose(parsed: &ParsedNodeFn) {
|
||||
"Unnecessary #[expose] attribute on primary input `{}`. Primary inputs are always exposed.",
|
||||
pat_ident.ident;
|
||||
help = "You can safely remove the #[expose] attribute from this field.";
|
||||
note = "The function's second argument, `{}`, is the node's primary input and it's always exposed by default", pat_ident.ident
|
||||
note = "`{}` is the node's primary input, which is always exposed by default", pat_ident.ident
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -462,7 +483,7 @@ fn validate_async(parsed: &ParsedNodeFn) {
|
||||
}
|
||||
|
||||
/// The arguments that aren't parameters, which are `#[data]` state and the inputs the compiler fills in, go after the parameters.
|
||||
/// That keeps the primary input at index 0, where the editor's chain flow and other nodes feeding the primary input expect it.
|
||||
/// That keeps the primary input at index 0, where the editor's chain flow and a graph's `>>` expect it.
|
||||
fn validate_non_parameters_trail(parsed: &ParsedNodeFn) {
|
||||
if let Some((span, message)) = non_parameter_order_violation(parsed) {
|
||||
emit_error!(span, "{}", message);
|
||||
@@ -475,7 +496,7 @@ fn non_parameter_order_violation(parsed: &ParsedNodeFn) -> Option<(proc_macro2::
|
||||
|
||||
let (parameter, non_parameter) = (¶meter.pat_ident, &non_parameter.pat_ident.ident);
|
||||
let message = format!(
|
||||
"The parameter `{}` comes after `{non_parameter}`, which isn't a parameter. Move `{non_parameter}` after the parameters: `#[data]` state and the inputs the compiler fills in (`#[scope]`, `#[source_id]`, and `#[node_path]`) go last, so the primary input is always the node's first input, which is the one the editor's chain flow feeds.",
|
||||
"The parameter `{}` comes after `{non_parameter}`, which isn't a parameter. Move `{non_parameter}` after the parameters: `#[data]` state and the inputs the compiler fills in (`#[scope]`, `#[source_id]`, and `#[node_path]`) go last, so the primary input is always the node's first input, which is the one the editor's chain flow and a graph's `>>` feed.",
|
||||
parameter.ident
|
||||
);
|
||||
Some((parameter.span(), message))
|
||||
@@ -727,6 +748,25 @@ mod tests {
|
||||
assert_eq!(only_non_parameters, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_node_named_like_a_value_helper_is_rejected() {
|
||||
let named = |input: TokenStream| value_helper_name_violation(&parse_node_fn(quote::quote!(category("Test")), input).expect("The test node fn should parse").fn_name);
|
||||
|
||||
let message = named(quote::quote!(
|
||||
fn rgb(_: impl Ctx, value: Item<f64>) -> Item<f64> {
|
||||
value
|
||||
}
|
||||
));
|
||||
assert!(message.is_some_and(|message| message.contains("can't be named `rgb`")));
|
||||
|
||||
let other = named(quote::quote!(
|
||||
fn tint(_: impl Ctx, value: Item<f64>) -> Item<f64> {
|
||||
value
|
||||
}
|
||||
));
|
||||
assert_eq!(other, None);
|
||||
}
|
||||
|
||||
fn row_count_violations(input: TokenStream) -> Vec<String> {
|
||||
let parsed = parse_node_fn(quote::quote!(category("Test")), input).expect("The test node fn should parse");
|
||||
implementations_row_count_violations(&parsed).into_iter().map(|(_, message)| message).collect()
|
||||
|
||||
@@ -5,6 +5,7 @@ pub mod render_background;
|
||||
pub mod render_cache;
|
||||
pub mod render_node;
|
||||
pub mod render_pixel_preview;
|
||||
pub mod subgraphs;
|
||||
pub mod text;
|
||||
pub use blending_nodes;
|
||||
pub use brush_nodes as brush;
|
||||
|
||||
@@ -106,7 +106,7 @@ fn render_background(
|
||||
}
|
||||
|
||||
let logical_resolution = render_params.footprint.resolution.as_dvec2() / render_params.scale;
|
||||
render.wrap_with_transform(logical_transform, Some(logical_resolution), render_params.pixels_per_inch);
|
||||
render.wrap_with_transform(logical_transform, Some(logical_resolution));
|
||||
|
||||
let background = SvgRenderOutput::from(render);
|
||||
assert!(background.svg_defs.is_empty());
|
||||
|
||||
@@ -125,7 +125,7 @@ fn render(
|
||||
let logical_resolution = footprint.resolution.as_dvec2() / render_params.scale;
|
||||
|
||||
let mut render = SvgRender::from(data.as_ref());
|
||||
render.wrap_with_transform(logical_transform, Some(logical_resolution), render_params.pixels_per_inch);
|
||||
render.wrap_with_transform(logical_transform, Some(logical_resolution));
|
||||
|
||||
let output = SvgRenderOutput::from(render);
|
||||
assert!(output.svg_defs.is_empty());
|
||||
@@ -210,7 +210,6 @@ fn create_context(
|
||||
scale: render_config.scale,
|
||||
viewport_zoom: Some(logical_viewport.scale_magnitudes().x),
|
||||
canvas_image_scale,
|
||||
pixels_per_inch: render_config.pixels_per_inch,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
use crate::artboard::create_artboard;
|
||||
use crate::context::{read_index, read_vector};
|
||||
use crate::graphic::{as_graphic, extend, flatten_vector, into_group, item_at_index, map, remove_at_index};
|
||||
use crate::platform_application_io::{bytes_to_image, load_resource};
|
||||
use crate::vector::misc::InterpolationDistribution;
|
||||
use crate::vector::{as_vector, combine_paths, count, morph, path_is_closed, points_to_polyline, separate_paths};
|
||||
use crate::{Artboard, Color, Graphic, Vector};
|
||||
use glam::DVec2;
|
||||
use math_nodes::{add, as_number, divide, floor, max, modulo, multiply, subtract, switch};
|
||||
use repeat_nodes::repeat;
|
||||
use transform_nodes::{decompose_translation, extract_transform};
|
||||
|
||||
/// Merges the provided content as a new item in the layer's compositing stack.
|
||||
#[node_macro::graph(category("Graphic"), icon("NodeMerge"), layer)]
|
||||
pub fn merge(
|
||||
/// The stack of layers below this one, which the content is placed above.
|
||||
base: List<Graphic>,
|
||||
/// The artwork this layer adds to the stack as a single item.
|
||||
#[expose]
|
||||
content: List<Graphic>,
|
||||
) -> out!(
|
||||
/// The stack of layers with this layer's content placed on top.
|
||||
out,
|
||||
) {
|
||||
let grouped = content >> into_group().at(-7, -1);
|
||||
base >> as_graphic().at(-7, -2) >> extend(new = grouped).at(0, -2)
|
||||
}
|
||||
|
||||
/// Creates a new Artboard which can be used as a working surface.
|
||||
#[node_macro::graph(category("Graphic"), icon("NodeArtboard"), layer)]
|
||||
pub fn artboard(
|
||||
/// The stack of artboards below this one, which this artboard is placed above.
|
||||
base: List<Artboard>,
|
||||
/// Graphics to include within the artboard.
|
||||
#[expose]
|
||||
content: List<Graphic>,
|
||||
/// Coordinate of the top-left corner of the artboard within the document.
|
||||
#[labels("X", "Y")]
|
||||
#[unit(" px")]
|
||||
#[integer]
|
||||
location: Item<DVec2>,
|
||||
/// Width and height of the artboard within the document.
|
||||
#[labels("W", "H")]
|
||||
#[unit(" px")]
|
||||
#[integer]
|
||||
#[default(1920., 1080.)]
|
||||
dimensions: Item<DVec2>,
|
||||
/// Color of the artboard background.
|
||||
#[widget(ParsedWidgetOverride::Custom = "artboard_background")]
|
||||
#[default(Color::WHITE)]
|
||||
background: Item<Color>,
|
||||
/// Whether to cut off the contained content that extends outside the artboard, or keep it visible.
|
||||
#[default(true)]
|
||||
clip: Item<bool>,
|
||||
) -> out!(
|
||||
/// The stack of artboards with this artboard placed on top.
|
||||
out,
|
||||
) {
|
||||
let board = create_artboard(content, location, dimensions, background, clip).at(-7, -3);
|
||||
base >> extend(new = board).at(0, -4)
|
||||
}
|
||||
|
||||
/// Creates a series of intermediate shapes that gradually transition between vector objects, optionally along a control path.
|
||||
#[node_macro::graph(category("Vector: Deform"), icon("NodeBlend"))]
|
||||
pub fn blend(
|
||||
/// The vector objects to create intermediate shapes between.
|
||||
content: List<Vector>,
|
||||
/// The number of shapes spanning from the first object to the last, repeated for each subpath of the control path.
|
||||
#[default(10)]
|
||||
count: Item<i64>,
|
||||
/// Flip the stacking order of the shapes, so the ones nearest the first object are on top.
|
||||
reverse: Item<bool>,
|
||||
/// What changes evenly from one shape to the next, which sets how the intermediate shapes are spaced.
|
||||
distribution: Item<InterpolationDistribution>,
|
||||
/// An optional control path with one anchor point per object. Curved segments shape the trajectory of the blend instead of traveling straight.
|
||||
path: Item<Vector>,
|
||||
) -> out!(
|
||||
/// The blended shapes, from the first object to the last.
|
||||
out,
|
||||
) {
|
||||
// Each clamps to at least 1, which also covers an empty control path
|
||||
let shapes_per_path = count >> as_number().at(2, 13) >> max(other_value = 1).at(9, 13);
|
||||
let path_count = path >> separate_paths().at(2, 0) >> count().at(2, 2) >> max(other_value = 1).at(9, 2);
|
||||
|
||||
// Split the repetition index into which subpath it's on and where along that subpath
|
||||
let index = read_index().at(2, 7);
|
||||
let path_index = index >> divide(denominator = shapes_per_path).at(16, 10) >> floor().at(23, 4);
|
||||
let local_index = index >> modulo(modulus = shapes_per_path).at(16, 7);
|
||||
|
||||
// A closed subpath spaces its shapes by the count, and an open one by one fewer (at least 1) so its last shape lands on the end
|
||||
let open_spacing = shapes_per_path >> subtract(subtrahend = 1).at(16, 14) >> max(other_value = 1).at(23, 14);
|
||||
let spacing = path >> path_is_closed(index = path_index).at(30, 2) >> switch(if_true = shapes_per_path, if_false = open_spacing).at(30, 12);
|
||||
|
||||
// Scaling just below 1 keeps the last shape from overflowing into the next subpath
|
||||
let fraction = local_index >> divide(denominator = spacing).at(23, 7) >> multiply(multiplicand = 0.9999999999).at(30, 7);
|
||||
let progression = path_index >> add(addend = fraction).at(37, 4);
|
||||
|
||||
let total = shapes_per_path >> multiply(multiplicand = path_count).at(16, 1);
|
||||
content >> morph(progression, distribution, path).at(44, 3) >> repeat(count = total, reverse).at(51, 0)
|
||||
}
|
||||
|
||||
/// Connects the origins of vector objects in order with an open polyline, such as to make a control path for the **Blend** and **Morph** nodes.
|
||||
#[node_macro::graph(category("Vector: Path"), icon("NodeOriginsToPolyline"), name("Origins to Polyline"))]
|
||||
pub fn origins_to_polyline(
|
||||
/// The vector objects to connect in order by their origins.
|
||||
vector: List<Vector>,
|
||||
) -> out!(
|
||||
/// An open polyline with an anchor point at the origin of each object.
|
||||
vector,
|
||||
) {
|
||||
// Each object's origin, read from the item being mapped, as a single-anchor vector
|
||||
let origin = read_vector().at(0, 1) >> extract_transform().at(7, 1) >> decompose_translation().at(14, 1) >> as_vector().at(21, 1);
|
||||
|
||||
vector >> flatten_vector().at(21, 0) >> map(mapped = origin).at(28, 0) >> combine_paths().at(35, 0) >> points_to_polyline(closed = false).at(42, 0)
|
||||
}
|
||||
|
||||
/// Loads an image from a given URL.
|
||||
#[node_macro::graph(category("Data: I/O"), icon("NodeLoadImage"))]
|
||||
pub fn load_image(
|
||||
_: (),
|
||||
/// The web address or local asset path of the image to load.
|
||||
#[name("URL")]
|
||||
url: Item<String>,
|
||||
) -> out!(
|
||||
/// The loaded image.
|
||||
image,
|
||||
) {
|
||||
load_resource(url).at(0, 0) >> bytes_to_image().at(7, 0)
|
||||
}
|
||||
|
||||
/// Finds a portion of the string matching a regular expression pattern. With "Match Index" at its default 0, it selects the first non-overlapping occurrence, but others may be selected. Capture groups, if any, are produced as a list in the "Captures" output.
|
||||
#[node_macro::graph(category("String: Regex"), icon("NodeRegexFind"))]
|
||||
pub fn regex_find(
|
||||
/// The string to search within.
|
||||
string: Item<String>,
|
||||
/// The regular expression pattern to search for.
|
||||
pattern: Item<String>,
|
||||
/// Which non-overlapping occurrence of the pattern to return, starting from 0 for the first match. Negative indices count backwards from the last match.
|
||||
match_index: Item<i64>,
|
||||
/// Match letters regardless of case.
|
||||
case_insensitive: Item<bool>,
|
||||
/// Make `^` and `$` match the start and end of each line, not just the whole string.
|
||||
multiline: Item<bool>,
|
||||
) -> out!(
|
||||
/// The whole portion of the string matching the pattern, or empty if there is no match.
|
||||
r#match,
|
||||
/// The text matched by each capture group in the pattern, in order.
|
||||
captures,
|
||||
) {
|
||||
// The whole match, then each capture group, where each item carries `start`, `end`, and `name` attributes
|
||||
let found = string >> text_nodes::regex::regex_find(pattern, match_index, case_insensitive, multiline).at(0, 0);
|
||||
|
||||
let whole_match = found >> item_at_index(index = 0).at(8, 0);
|
||||
let capture_groups = found >> remove_at_index(index = 0).at(8, 2);
|
||||
|
||||
(whole_match, capture_groups)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::registry::GraphInputSource;
|
||||
|
||||
/// Finds the capture groups of a pattern.
|
||||
#[node_macro::graph(category("Test"))]
|
||||
fn regex_captures(string: Item<String>, pattern: Item<String>) -> out!(captures) {
|
||||
return string >> regex_find(pattern).captures;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_output_chosen_by_name_wires_from_that_output() {
|
||||
let graph = _regex_captures_graph_metadata();
|
||||
assert!(matches!(graph.exports[0].source, GraphInputSource::Node { node: 0, output: 1 }));
|
||||
}
|
||||
|
||||
/// Puts its content on a board, setting every piece of node state.
|
||||
#[node_macro::graph(category("Test"))]
|
||||
fn boarded(content: List<Graphic>) -> out!(out) {
|
||||
return create_artboard(content, background = rgb(0x102030), clip = exposed(false))
|
||||
.named("Board")
|
||||
.hidden()
|
||||
.locked()
|
||||
.pinned()
|
||||
.layer()
|
||||
.call_argument::<impl Any>()
|
||||
.at(3, -4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn node_state_and_values_reach_the_metadata() {
|
||||
use core_types::NodeParameter;
|
||||
use core_types::registry::GraphValue;
|
||||
|
||||
let graph = _boarded_graph_metadata();
|
||||
let node = &graph.nodes[0];
|
||||
assert_eq!(node.display_name, Some("Board"));
|
||||
assert!(node.hidden && node.locked && node.pinned && node.layer);
|
||||
assert_eq!(node.position, Some((3, -4)));
|
||||
assert!(matches!(node.call_argument, Some(core_types::Type::Generic(_))));
|
||||
|
||||
let source = |index: usize| &node.inputs.iter().find(|(input_index, _)| *input_index == index).expect("the input should be set").1;
|
||||
assert!(matches!(source(create_artboard::ContentInput::INDEX), GraphInputSource::Import { index: 0, .. }));
|
||||
assert!(matches!(
|
||||
source(create_artboard::BackgroundInput::INDEX),
|
||||
GraphInputSource::Value {
|
||||
value: GraphValue::Color(_),
|
||||
exposed: None
|
||||
}
|
||||
));
|
||||
assert!(matches!(
|
||||
source(create_artboard::ClipInput::INDEX),
|
||||
GraphInputSource::Value {
|
||||
value: GraphValue::Bool(false),
|
||||
exposed: Some(true)
|
||||
}
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
use core_types::context::{CloneVarArgs, ExtractAll};
|
||||
use core_types::list::{Bundle, Item, List};
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::units::{Angle, DEFAULT_PIXELS_PER_INCH, Length};
|
||||
use core_types::{Color, Ctx, OwnedContextImpl, num_traits};
|
||||
use core_types::{Context, Interrupt};
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
@@ -14,16 +13,12 @@ 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::quantity::Quantity;
|
||||
use math_parser::reducer::{Reducer, classify_reducer};
|
||||
use math_parser::units::{Unit, UnitId, unit_named};
|
||||
use math_parser::value::{Value, Vector2, Vector3};
|
||||
use rand::{RngExt, SeedableRng};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use vector_types::Gradient;
|
||||
|
||||
pub mod units;
|
||||
|
||||
/// Why a math node's expression or operator gives no result.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum MathExpressionError {
|
||||
@@ -35,6 +30,8 @@ pub enum MathExpressionError {
|
||||
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`")]
|
||||
@@ -90,12 +87,7 @@ impl ParseCache {
|
||||
|
||||
/// Evaluates a parsed expression with the given variable bindings.
|
||||
fn evaluate_expression(expression: &ast::Node, provider: impl ValueProvider) -> Result<Object, MathExpressionError> {
|
||||
evaluate_measured_expression(expression, provider, DEFAULT_PIXELS_PER_INCH)
|
||||
}
|
||||
|
||||
/// Evaluates a parsed expression with the given variable bindings, sizing its pixels by the document's resolution.
|
||||
fn evaluate_measured_expression(expression: &ast::Node, provider: impl ValueProvider, pixels_per_inch: f64) -> Result<Object, MathExpressionError> {
|
||||
Ok(expression.eval(&EvalContext::new(provider, NothingMap).with_pixels_per_inch(pixels_per_inch))?)
|
||||
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.
|
||||
@@ -103,10 +95,6 @@ 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>;
|
||||
/// Reads an evaluated result as [`Self::from_object`] does, sizing a length's physical units by the document's resolution.
|
||||
fn from_measured_object(object: &Object, _pixels_per_inch: f64) -> Option<Self> {
|
||||
Self::from_object(object)
|
||||
}
|
||||
/// Gathers a list of this type as the items of its sort.
|
||||
fn items(items: impl Iterator<Item = Self>) -> Items;
|
||||
}
|
||||
@@ -135,10 +123,10 @@ trait ExpressionItem: Copy + Default + 'static {
|
||||
|
||||
impl<T: ExpressionItem> ExpressionValue for T {
|
||||
fn into_object(self) -> Object {
|
||||
Object::from(self.into_value())
|
||||
Object::Value(self.into_value())
|
||||
}
|
||||
fn from_object(object: &Object) -> Option<Self> {
|
||||
T::from_value(&object.as_value()?)
|
||||
T::from_value(object.as_value()?)
|
||||
}
|
||||
fn items(items: impl Iterator<Item = Self>) -> Items {
|
||||
Items::Values(items.map(T::into_value).collect())
|
||||
@@ -161,53 +149,12 @@ impl ExpressionItem for f64 {
|
||||
|
||||
/// Reads an expression's result as the node's output type.
|
||||
fn output<T: ExpressionValue>(result: &Object) -> Result<T, MathExpressionError> {
|
||||
measured_output(result, DEFAULT_PIXELS_PER_INCH)
|
||||
}
|
||||
|
||||
/// Reads an expression's result as the node's output type, sizing a length's physical units by the document's resolution.
|
||||
fn measured_output<T: ExpressionValue>(result: &Object, pixels_per_inch: f64) -> Result<T, MathExpressionError> {
|
||||
T::from_measured_object(result, pixels_per_inch).ok_or_else(|| MathExpressionError::OutputType {
|
||||
T::from_object(result).ok_or_else(|| MathExpressionError::OutputType {
|
||||
result: result.to_string(),
|
||||
output_type: core_types::concrete!(T).to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
impl ExpressionValue for Length {
|
||||
fn into_object(self) -> Object {
|
||||
Object::Value(Quantity::new(Value::from_f64(self.pixels()), Unit::of(UnitId::PIXEL)))
|
||||
}
|
||||
|
||||
fn from_object(object: &Object) -> Option<Self> {
|
||||
Self::from_measured_object(object, DEFAULT_PIXELS_PER_INCH)
|
||||
}
|
||||
|
||||
// A plain result reads in pixels, as a plain number wired into a length does
|
||||
fn from_measured_object(object: &Object, pixels_per_inch: f64) -> Option<Self> {
|
||||
let pixels = object.as_quantity()?.read_in(Unit::of(UnitId::PIXEL), pixels_per_inch).ok()?.as_real()?;
|
||||
Some(Length::from_pixels(pixels))
|
||||
}
|
||||
|
||||
fn items(items: impl Iterator<Item = Self>) -> Items {
|
||||
Items::Values(items.map(|length| Value::from_f64(length.pixels())).collect())
|
||||
}
|
||||
}
|
||||
|
||||
impl ExpressionValue for Angle {
|
||||
fn into_object(self) -> Object {
|
||||
Object::Value(Quantity::new(Value::from_f64(self.radians()), Unit::of(UnitId::RADIAN)))
|
||||
}
|
||||
|
||||
// A plain result reads in radians, as the circular functions read a plain angle
|
||||
fn from_object(object: &Object) -> Option<Self> {
|
||||
let radians = object.as_quantity()?.read_in(Unit::of(UnitId::RADIAN), DEFAULT_PIXELS_PER_INCH).ok()?.as_real()?;
|
||||
Some(Angle::from_radians(radians))
|
||||
}
|
||||
|
||||
fn items(items: impl Iterator<Item = Self>) -> Items {
|
||||
Items::Values(items.map(|angle| Value::from_f64(angle.radians())).collect())
|
||||
}
|
||||
}
|
||||
|
||||
impl ExpressionItem for i64 {
|
||||
fn into_value(self) -> Value {
|
||||
Value::from_i64(self)
|
||||
@@ -277,29 +224,23 @@ struct SingleVariableMathContext<'a> {
|
||||
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()).flatten()
|
||||
}
|
||||
|
||||
// A length or an angle binds with its unit
|
||||
fn get_quantity(&self, name: &str) -> Option<Quantity> {
|
||||
(name == "x").then(|| self.x.as_quantity().copied()).flatten()
|
||||
(name == "x").then(|| self.x.as_value().copied()).flatten()
|
||||
}
|
||||
|
||||
fn get_matrix(&self, name: &str) -> Option<Matrix> {
|
||||
(name == "X").then(|| self.x.as_matrix()).flatten()
|
||||
(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`, a Transform takes a matrix like `rotation(pi/4) + 5i`, a Length reads a plain number as pixels, and an Angle reads a plain number as radians. A boolean input reads as 0 or 1, a Vec2 input as such a vector, and a Length or Angle input with its unit, so `x + 5mm` adds five millimeters.
|
||||
#[node_macro::node(category("Math"), icon("NodeMathFunction"), version(3))]
|
||||
/// 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, f64, f64, i64, i64, i64, i64, i64, i64, i64, bool, bool, bool, bool, bool, bool, bool, DVec2, DVec2, DVec2, DVec2, DVec2, DVec2, DVec2, DAffine2, DAffine2, DAffine2,
|
||||
DAffine2, DAffine2, DAffine2, DAffine2, Length, Length, Length, Length, Length, Length, Length, Angle, Angle, Angle, Angle, Angle, Angle, Angle
|
||||
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.
|
||||
@@ -309,13 +250,11 @@ fn math_function<T: ExpressionValue, U: ExpressionValue>(
|
||||
fx: Item<String>,
|
||||
/// The type the result is read as.
|
||||
#[implementations(
|
||||
f64, i64, bool, DVec2, DAffine2, Length, Angle, f64, i64, bool, DVec2, DAffine2, Length, Angle, f64, i64, bool, DVec2, DAffine2, Length, Angle, f64, i64, bool, DVec2, DAffine2, Length, Angle,
|
||||
f64, i64, bool, DVec2, DAffine2, Length, Angle, f64, i64, bool, DVec2, DAffine2, Length, Angle, f64, i64, bool, DVec2, DAffine2, Length, Angle
|
||||
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>,
|
||||
#[scope("pixels-per-inch")] pixels_per_inch: Item<f64>,
|
||||
#[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
|
||||
@@ -327,16 +266,19 @@ fn math_function<T: ExpressionValue, U: ExpressionValue>(
|
||||
|
||||
// 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 pixels_per_inch = *pixels_per_inch.element();
|
||||
let evaluate = |expression: &ast::Node| evaluate_measured_expression(expression, SingleVariableMathContext { x: &x }, pixels_per_inch).and_then(|result| measured_output(&result, pixels_per_inch));
|
||||
let error = match parsed.parse(source).and_then(|expression| evaluate(&expression)) {
|
||||
Ok(result) => return Ok(Item::from_parts(result, attributes)),
|
||||
Err(error) => error,
|
||||
};
|
||||
let result = parsed
|
||||
.parse(source)
|
||||
.and_then(|expression| evaluate_expression(&expression, SingleVariableMathContext { x: &x }))
|
||||
.and_then(|result| output(&result));
|
||||
|
||||
// The input passes through as the default `x` reads it, or else the output type's default stands in
|
||||
let stand_in = U::from_measured_object(&x, pixels_per_inch).unwrap_or_default();
|
||||
Err((Item::from_parts(stand_in, attributes), error))
|
||||
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.
|
||||
@@ -355,11 +297,11 @@ 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 or unit spelled by its letter (`e` as the fifth item, `m` as the thirteenth), which stay
|
||||
// reachable as `\e` and `\m`; an unwired letter reads as its default of 0, except that a constant's or unit's letter stays itself
|
||||
// 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() || unit_named(name).is_some() => None,
|
||||
None if Constant::from_name(name).is_some() => None,
|
||||
None => Some(Value::from_i64(0)),
|
||||
}
|
||||
}
|
||||
@@ -456,7 +398,7 @@ fn math_aggregate<T: ExpressionValue, U: ExpressionValue>(
|
||||
let items = T::items(values.iter_element_values().copied());
|
||||
|
||||
let result = match &items {
|
||||
Items::Values(values) => reducer.evaluate(values).map(Object::from),
|
||||
Items::Values(values) => reducer.evaluate(values).map(Object::Value),
|
||||
Items::Matrices(matrices) => reducer.evaluate_matrices(matrices),
|
||||
};
|
||||
let Some(result) = result else {
|
||||
@@ -510,7 +452,7 @@ fn math_running<T: ExpressionValue, U: ExpressionValue>(
|
||||
// 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::from)).collect(),
|
||||
Items::Values(values) => reducer.evaluate_running(values).into_iter().map(|result| result.map(Object::Value)).collect(),
|
||||
Items::Matrices(matrices) => reducer.evaluate_running_matrices(matrices),
|
||||
};
|
||||
|
||||
@@ -2328,57 +2270,6 @@ mod test {
|
||||
use core_types::generic::FnNode;
|
||||
use core_types::{Node, concrete};
|
||||
|
||||
/// Runs 'Math f(x)' on a value at a resolution, reading the result as the output type `U`.
|
||||
fn function_of<T: ExpressionValue, U: ExpressionValue>(value: T, expression: &str, pixels_per_inch: f64) -> Result<U, MathExpressionError> {
|
||||
let output_type = Item::new_from_element(U::default());
|
||||
let result = math_function(
|
||||
(),
|
||||
&ParseCache::default(),
|
||||
Item::new_from_element(value),
|
||||
Item::new_from_element(expression.to_string()),
|
||||
output_type,
|
||||
Item::new_from_element(pixels_per_inch),
|
||||
);
|
||||
result.map(|item| item.into_element()).map_err(|(_, error)| error)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn math_function_measures_lengths_by_the_resolution() {
|
||||
let length = |expression: &str, pixels_per_inch: f64| function_of::<Length, Length>(Length::from_pixels(10.), expression, pixels_per_inch).unwrap().pixels();
|
||||
assert_eq!(length("x * 2", 96.), 20.);
|
||||
assert_eq!(length("x + 1in", 96.), 106.);
|
||||
assert_eq!(length("x + 1in", 300.), 310.);
|
||||
assert_eq!(length("5", 96.), 5.);
|
||||
assert!((length("25.4mm", 96.) - 96.).abs() < 1e-9);
|
||||
|
||||
// A length isn't a plain number, so reading it as one fails rather than dropping its unit
|
||||
assert!(function_of::<Length, f64>(Length::from_pixels(10.), "x", 96.).is_err());
|
||||
assert_eq!(function_of::<Length, f64>(Length::from_pixels(10.), "x / (1px)", 96.).unwrap(), 10.);
|
||||
assert!(function_of::<f64, Length>(2., "x * 1s", 96.).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn math_function_divides_by_a_whole_measure_only_where_the_input_has_a_unit() {
|
||||
assert_eq!(function_of::<Length, f64>(Length::from_pixels(10.), "x / 2px", 96.).unwrap(), 5.);
|
||||
assert_eq!(function_of::<f64, Length>(10., "x / 2px", 96.).unwrap().pixels(), 5.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn math_function_reports_the_expression_error_where_the_input_cannot_pass_through() {
|
||||
let error = function_of::<Length, f64>(Length::from_pixels(10.), "x / 1mm +", 96.).unwrap_err();
|
||||
assert!(matches!(error, MathExpressionError::Invalid(_)), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn math_function_turns_angles() {
|
||||
let degrees = |expression: &str| function_of::<Angle, Angle>(Angle::from_degrees(30.), expression, 96.).unwrap().degrees();
|
||||
assert!((degrees("x + 60deg") - 90.).abs() < 1e-9);
|
||||
assert!((degrees("x + 0.25turn") - 120.).abs() < 1e-9);
|
||||
// A plain result reads in radians, as the circular functions read a plain angle
|
||||
assert!((degrees("pi") - 180.).abs() < 1e-9);
|
||||
assert!((function_of::<Angle, f64>(Angle::from_degrees(90.), "sin(x)", 96.).unwrap() - 1.).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn dot_product_function() {
|
||||
let vector_a = Item::new_from_element(DVec2::new(1., 2.));
|
||||
@@ -2525,7 +2416,6 @@ mod test {
|
||||
Item::new_from_element(value),
|
||||
Item::new_from_element(expression.to_string()),
|
||||
Item::new_from_element(0_i64),
|
||||
Item::new_from_element(96.),
|
||||
)
|
||||
.unwrap()
|
||||
.into_element()
|
||||
@@ -2554,8 +2444,7 @@ mod test {
|
||||
&ParseCache::default(),
|
||||
Item::new_from_element(2.5),
|
||||
Item::new_from_element("x * 2".to_string()),
|
||||
Item::new_from_element(0_i64),
|
||||
Item::new_from_element(96.),
|
||||
Item::new_from_element(0_i64)
|
||||
)
|
||||
.unwrap()
|
||||
.into_element(),
|
||||
@@ -2567,8 +2456,7 @@ mod test {
|
||||
&ParseCache::default(),
|
||||
Item::new_from_element(3_i64),
|
||||
Item::new_from_element("x > 2".to_string()),
|
||||
Item::new_from_element(false),
|
||||
Item::new_from_element(96.),
|
||||
Item::new_from_element(false)
|
||||
)
|
||||
.unwrap()
|
||||
.into_element()
|
||||
@@ -2579,8 +2467,7 @@ mod test {
|
||||
&ParseCache::default(),
|
||||
Item::new_from_element(true),
|
||||
Item::new_from_element("x / 2".to_string()),
|
||||
Item::new_from_element(0.),
|
||||
Item::new_from_element(96.),
|
||||
Item::new_from_element(0.)
|
||||
)
|
||||
.unwrap()
|
||||
.into_element(),
|
||||
@@ -2613,7 +2500,6 @@ mod test {
|
||||
Item::new_from_element(0.),
|
||||
Item::new_from_element("2 + 2".to_string()),
|
||||
Item::new_from_element(0.),
|
||||
Item::new_from_element(96.),
|
||||
);
|
||||
assert_eq!(result.unwrap().into_element(), 4.);
|
||||
}
|
||||
@@ -2626,7 +2512,6 @@ mod test {
|
||||
Item::new_from_element(0.),
|
||||
Item::new_from_element("(5 * 3) + (10 / 2)".to_string()),
|
||||
Item::new_from_element(0.),
|
||||
Item::new_from_element(96.),
|
||||
);
|
||||
assert_eq!(result.unwrap().into_element(), 20.);
|
||||
}
|
||||
@@ -2639,7 +2524,6 @@ mod test {
|
||||
Item::new_from_element(7.),
|
||||
Item::new_from_element("x * 2".to_string()),
|
||||
Item::new_from_element(0.),
|
||||
Item::new_from_element(96.),
|
||||
);
|
||||
assert_eq!(result.unwrap().into_element(), 14.);
|
||||
}
|
||||
@@ -2652,7 +2536,6 @@ mod test {
|
||||
Item::new_from_element(0.),
|
||||
Item::new_from_element("invalid".to_string()),
|
||||
Item::new_from_element(0.),
|
||||
Item::new_from_element(96.),
|
||||
);
|
||||
assert_eq!(result.unwrap_err().0.into_element(), 0.);
|
||||
}
|
||||
@@ -2671,55 +2554,25 @@ mod test {
|
||||
// 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(),
|
||||
Item::new_from_element(96.)
|
||||
)
|
||||
.unwrap()
|
||||
.into_element()
|
||||
!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(),
|
||||
Item::new_from_element(96.)
|
||||
)
|
||||
.unwrap()
|
||||
.into_element()
|
||||
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(),
|
||||
Item::new_from_element(96.),
|
||||
)
|
||||
.unwrap_err();
|
||||
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(),
|
||||
Item::new_from_element(96.),
|
||||
)
|
||||
.unwrap_err();
|
||||
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::OutputType { output_type, .. } if output_type == "Bool"));
|
||||
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());
|
||||
@@ -2736,7 +2589,6 @@ mod test {
|
||||
Item::new_from_element(value),
|
||||
Item::new_from_element(expression.to_string()),
|
||||
Item::new_from_element(output_type),
|
||||
Item::new_from_element(96.),
|
||||
)
|
||||
.map(Item::into_element)
|
||||
.map_err(|(stand_in, _)| stand_in.into_element())
|
||||
@@ -2796,7 +2648,6 @@ mod test {
|
||||
Item::new_from_element(value),
|
||||
Item::new_from_element(expression.to_string()),
|
||||
Item::new_from_element(output_type),
|
||||
Item::new_from_element(96.),
|
||||
)
|
||||
.unwrap_or_else(|(_, error)| panic!("`{expression}` fails: {error}"))
|
||||
.into_element()
|
||||
@@ -2982,7 +2833,6 @@ mod test {
|
||||
Item::new_from_element(value),
|
||||
Item::new_from_element(expression.to_string()),
|
||||
Item::new_from_element(0.),
|
||||
Item::new_from_element(96.),
|
||||
)
|
||||
.map(Item::into_element)
|
||||
.map_err(|(stand_in, error)| (stand_in.into_element(), error))
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
//! Nodes converting between plain numbers and the lengths and angles the graph carries, sizing physical units by the document's resolution.
|
||||
|
||||
use core_types::Ctx;
|
||||
use core_types::list::Item;
|
||||
use core_types::units::{Angle, AngleUnit, Length, LengthUnit};
|
||||
|
||||
/// Constructs a length, typed in pixels or a physical unit like millimeters or inches, which the document's resolution sizes in pixels.
|
||||
#[node_macro::node(category("Value"))]
|
||||
fn length_value(_: impl Ctx, _primary: (), length: Item<Length>) -> Item<Length> {
|
||||
length
|
||||
}
|
||||
|
||||
/// Constructs an angle, typed in degrees, radians, or turns.
|
||||
#[node_macro::node(category("Value"))]
|
||||
fn angle_value(_: impl Ctx, _primary: (), angle: Item<Angle>) -> Item<Angle> {
|
||||
angle
|
||||
}
|
||||
|
||||
/// Converts a number into a length, reading it in the chosen unit.
|
||||
///
|
||||
/// A physical unit like millimeters is sized in pixels by the document's resolution.
|
||||
#[node_macro::node(category("Math: Units"))]
|
||||
fn number_to_length(
|
||||
_: impl Ctx,
|
||||
/// The number to read as a length.
|
||||
number: Item<f64>,
|
||||
/// The unit the number is in.
|
||||
unit: Item<LengthUnit>,
|
||||
#[scope("pixels-per-inch")] pixels_per_inch: Item<f64>,
|
||||
) -> Item<Length> {
|
||||
let (number, attributes) = number.into_parts();
|
||||
let pixels = unit.element().convert(number, LengthUnit::Pixel, *pixels_per_inch.element());
|
||||
|
||||
Item::from_parts(Length::from_pixels(pixels), attributes)
|
||||
}
|
||||
|
||||
/// Converts a length into a number, measuring it in the chosen unit.
|
||||
///
|
||||
/// A physical unit like millimeters is sized in pixels by the document's resolution.
|
||||
#[node_macro::node(category("Math: Units"))]
|
||||
fn length_to_number(
|
||||
_: impl Ctx,
|
||||
/// The length to measure.
|
||||
length: Item<Length>,
|
||||
/// The unit to measure the length in.
|
||||
unit: Item<LengthUnit>,
|
||||
#[scope("pixels-per-inch")] pixels_per_inch: Item<f64>,
|
||||
) -> Item<f64> {
|
||||
let (length, attributes) = length.into_parts();
|
||||
let number = LengthUnit::Pixel.convert(length.pixels(), *unit.element(), *pixels_per_inch.element());
|
||||
|
||||
Item::from_parts(number, attributes)
|
||||
}
|
||||
|
||||
/// Converts a number into an angle, reading it in the chosen unit.
|
||||
#[node_macro::node(category("Math: Units"))]
|
||||
fn number_to_angle(
|
||||
_: impl Ctx,
|
||||
/// The number to read as an angle.
|
||||
number: Item<f64>,
|
||||
/// The unit the number is in.
|
||||
unit: Item<AngleUnit>,
|
||||
) -> Item<Angle> {
|
||||
let (number, attributes) = number.into_parts();
|
||||
|
||||
Item::from_parts(unit.element().to_angle(number), attributes)
|
||||
}
|
||||
|
||||
/// Converts an angle into a number, measuring it in the chosen unit.
|
||||
#[node_macro::node(category("Math: Units"))]
|
||||
fn angle_to_number(
|
||||
_: impl Ctx,
|
||||
/// The angle to measure.
|
||||
angle: Item<Angle>,
|
||||
/// The unit to measure the angle in.
|
||||
unit: Item<AngleUnit>,
|
||||
) -> Item<f64> {
|
||||
let (angle, attributes) = angle.into_parts();
|
||||
|
||||
Item::from_parts(unit.element().from_angle(angle), attributes)
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
use crate::grid_topology::Lattice;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::units::Length;
|
||||
use core_types::{CacheHash, Ctx};
|
||||
use dyn_any::DynAny;
|
||||
use glam::DVec2;
|
||||
@@ -11,9 +10,15 @@ use vector_types::vector::misc::SpiralType;
|
||||
use vector_types::vector::misc::{ArcType, BoxCorners, GridTopology, GridType};
|
||||
|
||||
/// Generates a circle shape with a chosen radius.
|
||||
#[node_macro::node(category("Vector: Geometry"), icon("NodeCircle"), version(2))]
|
||||
fn circle(_: impl Ctx, _primary: (), #[default(50.)] radius: Item<Length>) -> Item<Vector> {
|
||||
let radius = radius.element().pixels().abs();
|
||||
#[node_macro::node(category("Vector: Geometry"), icon("NodeCircle"))]
|
||||
fn circle(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
#[unit(" px")]
|
||||
#[default(50.)]
|
||||
radius: Item<f64>,
|
||||
) -> Item<Vector> {
|
||||
let radius = radius.element().abs();
|
||||
Vector::item_from_bezpath(&shapes::ellipse_bezpath(DVec2::splat(-radius), DVec2::splat(radius)))
|
||||
}
|
||||
|
||||
|
||||
@@ -123,21 +123,6 @@ impl Preprocessor {
|
||||
id
|
||||
})
|
||||
}
|
||||
// A length typed in a physical unit is sized in pixels by the resolution the document's scope supplies
|
||||
TaggedValue::Length(length) if length.unit.is_physical() => {
|
||||
let id = producer_node_id(&graphene_std::math_nodes::units::number_to_length::IDENTIFIER, (consumer_id, input_index));
|
||||
let conversion = DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::value(TaggedValue::Number(length.value), false),
|
||||
NodeInput::value(TaggedValue::LengthUnit(length.unit), false),
|
||||
NodeInput::scope(graphene_std::units::PIXELS_PER_INCH_SCOPE),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::math_nodes::units::number_to_length::IDENTIFIER),
|
||||
..Default::default()
|
||||
};
|
||||
new_nodes.push((id, conversion));
|
||||
id
|
||||
}
|
||||
TaggedValue::AnimationCurve(curve) => {
|
||||
let id = producer_node_id(&graphene_core::animation::evaluate_curve::IDENTIFIER, (consumer_id, input_index));
|
||||
let curve_node = DocumentNode {
|
||||
@@ -431,7 +416,8 @@ pub fn node_inputs(fields: &[registry::FieldMetadata], first_node_io: &NodeIOTyp
|
||||
return NodeInput::value(TaggedValue::None, true);
|
||||
};
|
||||
let ty = ty.clone().normalize_rank();
|
||||
let exposed = if index == 0 { ty != fn_type!(Context, ()) } else { field.exposed };
|
||||
// A `()` primary has nothing to connect, whether it's a proto node's lazy input or a graph's import
|
||||
let exposed = if index == 0 { ty != fn_type!(Context, ()) && ty != concrete!(()) } else { field.exposed };
|
||||
|
||||
match &field.value_source {
|
||||
RegistryValueSource::None => {}
|
||||
@@ -558,7 +544,7 @@ mod destructure_tests {
|
||||
fn vec2_to_numbers_network() -> NodeNetwork {
|
||||
let vec2_to_numbers = DocumentNode {
|
||||
inputs: vec![NodeInput::value(TaggedValue::DVec2(DVec2::new(3., 5.)), false)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER),
|
||||
..Default::default()
|
||||
};
|
||||
multi_output_into_add_network(vec2_to_numbers, [1, 2])
|
||||
@@ -576,7 +562,7 @@ mod destructure_tests {
|
||||
|
||||
#[test]
|
||||
fn multi_output_node_expands_into_generated_destructure_network() {
|
||||
let vec2_to_numbers_identifier = graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER;
|
||||
let vec2_to_numbers_identifier = graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER;
|
||||
let destructure = registry::MULTI_OUTPUT_NODES
|
||||
.get(&vec2_to_numbers_identifier)
|
||||
.expect("Vec2 to Numbers should be registered as a multi-output node");
|
||||
|
||||
Loaded 100 of 103 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user