mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1404b36081 | ||
|
|
06467de601 | ||
|
|
430b2030ed | ||
|
|
284ca6d509 | ||
|
|
056bec13e5 |
No files matched your search
Generated
+1
@@ -1900,6 +1900,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "928452f9c953e142b2f0973e4bd5f34445fcaa8069556ea97a3c9d34d15a4cf8"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"libm",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
|
||||
+2
-2
@@ -194,7 +194,7 @@ color = "0.3"
|
||||
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
|
||||
rand_chacha = "0.9"
|
||||
glam = { version = "0.33", default-features = false, features = [
|
||||
"std",
|
||||
"nostd-libm",
|
||||
"scalar-math",
|
||||
"bytemuck",
|
||||
"debug-glam-assert",
|
||||
@@ -220,7 +220,7 @@ pretty_assertions = "1.4"
|
||||
fern = { version = "0.7", features = ["colored"] }
|
||||
num_enum = { version = "0.7", default-features = false }
|
||||
num-derive = "0.4"
|
||||
num-traits = "0.2"
|
||||
num-traits = { version = "0.2", default-features = false, features = ["libm"] }
|
||||
tsify = { version = "0.5", default-features = false, features = ["js"] }
|
||||
syn = { version = "2.0", default-features = false, features = [
|
||||
"full",
|
||||
|
||||
@@ -11,6 +11,7 @@ use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::blending::BlendMode;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::core_types::misc::format_f64;
|
||||
use graphene_std::generator::Generator;
|
||||
use graphene_std::gradient::Gradient;
|
||||
use graphene_std::list::{INTERNAL_ATTRIBUTE_PREFIX, Item, List, NodeIdPath};
|
||||
use graphene_std::math::float_noise::round_away_float_noise;
|
||||
@@ -377,6 +378,7 @@ macro_rules! inspectable_types {
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<String>,
|
||||
List<f64>,
|
||||
List<i64>,
|
||||
@@ -433,6 +435,7 @@ macro_rules! inspectable_types {
|
||||
Item<Raster<GPU>>,
|
||||
Item<Color>,
|
||||
Item<Gradient>,
|
||||
Item<Generator>,
|
||||
Item<String>,
|
||||
Item<f64>,
|
||||
Item<i64>,
|
||||
@@ -880,6 +883,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::RasterGPU(item) => item.identifier(),
|
||||
Self::Color(item) => item.identifier(),
|
||||
Self::Gradient(item) => item.identifier(),
|
||||
Self::Generator(item) => item.identifier(),
|
||||
Self::Text(item) => item.identifier(),
|
||||
Self::NoneList(list) => list.identifier(),
|
||||
Self::GraphicList(list) => list.identifier(),
|
||||
@@ -888,6 +892,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::RasterGPUList(list) => list.identifier(),
|
||||
Self::ColorList(list) => list.identifier(),
|
||||
Self::GradientList(list) => list.identifier(),
|
||||
Self::GeneratorList(list) => list.identifier(),
|
||||
Self::TextList(list) => list.identifier(),
|
||||
Self::StrokeList(list) => list.identifier(),
|
||||
}
|
||||
@@ -905,6 +910,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::RasterGPU(item) => item.layout_with_breadcrumb(data),
|
||||
Self::Color(item) => item.layout_with_breadcrumb(data),
|
||||
Self::Gradient(item) => item.layout_with_breadcrumb(data),
|
||||
Self::Generator(item) => item.layout_with_breadcrumb(data),
|
||||
Self::Text(item) => item.layout_with_breadcrumb(data),
|
||||
Self::NoneList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::GraphicList(list) => list.layout_with_breadcrumb(data),
|
||||
@@ -913,6 +919,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::RasterGPUList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::ColorList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::GradientList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::GeneratorList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::TextList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::StrokeList(list) => list.layout_with_breadcrumb(data),
|
||||
}
|
||||
@@ -1245,6 +1252,7 @@ impl_table_item_layout_for_choice_enum!(
|
||||
BevelDirection,
|
||||
BevelStyle,
|
||||
EffectKind,
|
||||
Generator,
|
||||
GlowSource,
|
||||
GradientForm,
|
||||
GradientSpread,
|
||||
@@ -1392,9 +1400,11 @@ macro_rules! known_item_types {
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<String>,
|
||||
List<f64>,
|
||||
Gradient,
|
||||
Generator,
|
||||
Color,
|
||||
NodeId,
|
||||
DAffine2,
|
||||
|
||||
@@ -34,6 +34,8 @@ impl FrontendGraphDataType {
|
||||
"Gradient" => Self::Gradient,
|
||||
"String" => Self::Typography,
|
||||
"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,
|
||||
_ => Self::General,
|
||||
}
|
||||
|
||||
@@ -1857,6 +1857,56 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// Noise Pattern and Mandelbrot once drew images cut off at a square, 100 units for a clipped Noise Pattern and 1 for Mandelbrot, where their
|
||||
// patterns now fill the plane. An old Noise Pattern has a Clip toggle, after the primary input or first from before that input existed,
|
||||
// and an old Mandelbrot lacks the primary input. Each takes the current inputs, with a square filled by its pattern where it was cut off.
|
||||
const NOISE_SETTINGS: usize = 14;
|
||||
let old_pattern_nodes = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter_map(|(node_id, node, path)| {
|
||||
let reference = document.network_interface.reference(node_id, &path)?;
|
||||
let clipped = |clip_index: usize| !matches!(node.inputs.get(clip_index).and_then(|input| input.as_value()), Some(TaggedValue::Bool(false)));
|
||||
let pipeline = NodeInput::scope(graphene_std::raster_nodes::raster_kernel::raster_kernel_pipeline::IDENTIFIER);
|
||||
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER) {
|
||||
let starts_with_clip = matches!(node.inputs.first().and_then(|input| input.as_value()), Some(TaggedValue::Bool(_)));
|
||||
let clip_index = match node.inputs.len() {
|
||||
// Also with the pipeline input these nodes took when they rendered on the GPU themselves
|
||||
17 if node.inputs.last() == Some(&pipeline) => 1,
|
||||
16 => 1,
|
||||
15 if starts_with_clip => 0,
|
||||
_ => return None,
|
||||
};
|
||||
return Some((*node_id, path, reference, Some(clip_index), clipped(clip_index).then_some(100.)));
|
||||
}
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER) && (node.inputs.is_empty() || node.inputs == [pipeline]) {
|
||||
return Some((*node_id, path, reference, None, Some(1.)));
|
||||
}
|
||||
None
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
for (node_id, network_path, reference, clip_index, clipped_size) in &old_pattern_nodes {
|
||||
let Some(definition) = resolve_document_node_type(reference) else { continue };
|
||||
let mut node_template = definition.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
// The noise settings follow the Clip toggle, in the same order as the current inputs after the primary one
|
||||
if let Some(clip_index) = clip_index {
|
||||
for (offset, input) in old_inputs.iter().skip(clip_index + 1).take(NOISE_SETTINGS).enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1 + offset), input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(size) = clipped_size {
|
||||
fill_square_with_pattern(document, node_id, network_path, *size);
|
||||
}
|
||||
}
|
||||
|
||||
// Parameters that historically accepted fractional numbers are now integers (the polygon and star "Sides", the index,
|
||||
// shift amount, and slice bound parameters of the list, string, and regex nodes, the "Path is Closed" index, and the
|
||||
// "Blend" count), so a stored F64 truncates as those slots' own casts and Floor node did, preserving what documents drew
|
||||
@@ -1910,6 +1960,76 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
document.require_whole_document_stage();
|
||||
}
|
||||
|
||||
/// Splices a rectangle filled with the pattern node's output onto the wires leaving it, covering the square from the origin of the pattern's space out to `size`.
|
||||
/// The rectangle is centered on its origin, so a Transform moves it onto the square, and the paint is moved back by the same amount to stay in place.
|
||||
fn fill_square_with_pattern(document: &mut DocumentMessageHandler, pattern_node_id: &NodeId, network_path: &[NodeId], size: f64) -> Option<()> {
|
||||
let downstream_consumers: Vec<InputConnector> = document
|
||||
.network_interface
|
||||
.outward_wires(network_path)
|
||||
.and_then(|wires| wires.get(&OutputConnector::node(*pattern_node_id, 0)))
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let was_in_chain = document.network_interface.is_chain(pattern_node_id, network_path);
|
||||
|
||||
let template = |identifier| resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier)).map(|definition| definition.default_node_template());
|
||||
let rectangle_template = template(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER)?;
|
||||
let fill_template = template(graphene_std::vector_nodes::fill::IDENTIFIER)?;
|
||||
let transform_template = template(graphene_std::transform_nodes::transform::IDENTIFIER)?;
|
||||
|
||||
let [rectangle_id, fill_id, paint_transform_id, placement_transform_id] = [(); 4].map(|_| NodeId::new());
|
||||
document.network_interface.insert_node(rectangle_id, rectangle_template, network_path);
|
||||
document.network_interface.insert_node(fill_id, fill_template, network_path);
|
||||
document.network_interface.insert_node(paint_transform_id, transform_template.clone(), network_path);
|
||||
document.network_interface.insert_node(placement_transform_id, transform_template, network_path);
|
||||
|
||||
let set_value = |document: &mut DocumentMessageHandler, node_id: NodeId, index: usize, value: TaggedValue| {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::value(value, false), network_path);
|
||||
};
|
||||
let wire = |document: &mut DocumentMessageHandler, node_id: NodeId, index: usize, source: NodeId| {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::node(source, 0), network_path);
|
||||
};
|
||||
|
||||
// The rectangle's width and height, and the half-square translations of the paint and the filled rectangle
|
||||
set_value(document, rectangle_id, 1, TaggedValue::Number(size));
|
||||
set_value(document, rectangle_id, 2, TaggedValue::Number(size));
|
||||
set_value(document, paint_transform_id, 1, TaggedValue::DVec2(DVec2::splat(-size / 2.)));
|
||||
set_value(document, placement_transform_id, 1, TaggedValue::DVec2(DVec2::splat(size / 2.)));
|
||||
|
||||
wire(document, paint_transform_id, 0, *pattern_node_id);
|
||||
wire(document, fill_id, 0, rectangle_id);
|
||||
wire(document, fill_id, 1, paint_transform_id);
|
||||
wire(document, placement_transform_id, 0, fill_id);
|
||||
for consumer in &downstream_consumers {
|
||||
document.network_interface.set_input(consumer, NodeInput::node(placement_transform_id, 0), network_path);
|
||||
}
|
||||
|
||||
// A pattern in a layer chain gives way to the filled rectangle there, moving below to paint it, and otherwise the new nodes sit beside it
|
||||
if was_in_chain {
|
||||
document.network_interface.force_set_upstream_to_chain(&placement_transform_id, network_path);
|
||||
|
||||
if let Some(fill_position) = document.network_interface.position(&fill_id, network_path) {
|
||||
document.network_interface.set_absolute_position(&paint_transform_id, fill_position + IVec2::new(-7, 3), network_path);
|
||||
document.network_interface.set_absolute_position(pattern_node_id, fill_position + IVec2::new(-14, 3), network_path);
|
||||
}
|
||||
} else if let Some(position) = document.network_interface.position(pattern_node_id, network_path) {
|
||||
let offsets = [
|
||||
(paint_transform_id, IVec2::new(7, 0)),
|
||||
(rectangle_id, IVec2::new(7, -3)),
|
||||
(fill_id, IVec2::new(14, 0)),
|
||||
(placement_transform_id, IVec2::new(21, 0)),
|
||||
];
|
||||
for (node_id, offset) in offsets {
|
||||
document.network_interface.shift_absolute_node_position(&node_id, position + offset, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.
|
||||
fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
|
||||
let NodeInput::Value { tagged_value, exposed } = input else { return None };
|
||||
@@ -2760,20 +2880,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
}
|
||||
}
|
||||
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER) && inputs_count == 15 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 0), NodeInput::value(TaggedValue::None, false), network_path);
|
||||
for (i, input) in old_inputs.iter().enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, i + 1), input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// The Threshold node's luminance calculation input was retired
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::adjustments::threshold::IDENTIFIER) && inputs_count == 4 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
@@ -3583,8 +3689,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
graphene_std::raster_nodes::std_nodes::channels_to_image::IDENTIFIER,
|
||||
graphene_std::raster_nodes::std_nodes::mask::IDENTIFIER,
|
||||
graphene_std::raster_nodes::std_nodes::extend_image_to_bounds::IDENTIFIER,
|
||||
graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER,
|
||||
graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER,
|
||||
graphene_std::raster_nodes::filter::median_filter::IDENTIFIER,
|
||||
graphene_std::raster_nodes::effects::blur::IDENTIFIER,
|
||||
graphene_std::raster_nodes::image_color_palette::image_color_palette::IDENTIFIER,
|
||||
@@ -5316,4 +5420,81 @@ mod tests {
|
||||
assert_eq!(interface.display_name(&node_id, &[]), "Image", "node {node_id}");
|
||||
}
|
||||
}
|
||||
|
||||
// Noise Pattern and Mandelbrot once drew a square of their patterns, which now fill the plane, so the square becomes a rectangle filled with the pattern
|
||||
#[tokio::test]
|
||||
async fn clipped_patterns_become_rectangles_filled_with_them() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
|
||||
let proto = |identifier| DefinitionIdentifier::ProtoNode(identifier);
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let noise = editor.create_node_by_name(proto(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER)).await;
|
||||
let mandelbrot = editor.create_node_by_name(proto(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER)).await;
|
||||
let noise_reader = editor.create_node_by_name(proto(graphene_std::transform_nodes::transform::IDENTIFIER)).await;
|
||||
let mandelbrot_reader = editor.create_node_by_name(proto(graphene_std::transform_nodes::transform::IDENTIFIER)).await;
|
||||
|
||||
let document = editor.active_document_mut();
|
||||
for (reader, pattern) in [(noise_reader, noise), (mandelbrot_reader, mandelbrot)] {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(reader, 0), NodeInput::node(pattern, 0), &[]);
|
||||
}
|
||||
|
||||
// Save them as an older editor did, the Noise Pattern with its Clip toggle on and the Mandelbrot without a primary input
|
||||
let mut noise_inputs = document.network_interface.document_node(&noise, &[]).unwrap().inputs.clone();
|
||||
noise_inputs.insert(1, NodeInput::value(TaggedValue::Bool(true), false));
|
||||
noise_inputs[2] = NodeInput::value(TaggedValue::Integer(7), false);
|
||||
for (node_id, inputs) in [(noise, noise_inputs), (mandelbrot, Vec::new())] {
|
||||
let mut legacy = NodeTemplate { inputs, ..Default::default() };
|
||||
legacy.normalize_input_metadata();
|
||||
document.network_interface.replace_inputs(&node_id, &[], &mut legacy);
|
||||
}
|
||||
let serialized = document.serialize_document();
|
||||
|
||||
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||
let interface = &opened.network_interface;
|
||||
let input = |node_id: NodeId, index: usize| interface.document_node(&node_id, &[]).and_then(|node| node.inputs.get(index)).cloned();
|
||||
let upstream = |node_id: NodeId, index: usize| input(node_id, index).and_then(|input| input.as_node());
|
||||
let value = |node_id: NodeId, index: usize| input(node_id, index).and_then(|input| input.as_value().cloned());
|
||||
|
||||
// Each reader now reads a rectangle of the square's size, moved onto the square, filled with the pattern moved back by the same amount
|
||||
for (reader, pattern, size) in [(noise_reader, noise, 100.), (mandelbrot_reader, mandelbrot, 1.)] {
|
||||
let placement = upstream(reader, 0).expect("the reader should read the placement transform");
|
||||
assert_eq!(value(placement, 1), Some(TaggedValue::DVec2(DVec2::splat(size / 2.))));
|
||||
|
||||
let fill = upstream(placement, 0).expect("the placement should move the filled rectangle");
|
||||
let rectangle = upstream(fill, 0).expect("the fill should paint a rectangle");
|
||||
assert_eq!((value(rectangle, 1), value(rectangle, 2)), (Some(TaggedValue::Number(size)), Some(TaggedValue::Number(size))));
|
||||
|
||||
let paint = upstream(fill, 1).expect("the fill should paint with the moved pattern");
|
||||
assert_eq!(value(paint, 1), Some(TaggedValue::DVec2(DVec2::splat(-size / 2.))));
|
||||
assert_eq!(upstream(paint, 0), Some(pattern));
|
||||
}
|
||||
|
||||
// The noise settings shift down past the removed Clip toggle, and the Mandelbrot gains its primary input
|
||||
assert_eq!(interface.document_node(&noise, &[]).unwrap().inputs.len(), 15);
|
||||
assert_eq!(value(noise, 1), Some(TaggedValue::Integer(7)));
|
||||
assert_eq!(interface.document_node(&mandelbrot, &[]).unwrap().inputs.len(), 1);
|
||||
}
|
||||
|
||||
// The demo draws its patterns through layers and adjustments, which must all take the generators the patterns now are
|
||||
#[tokio::test]
|
||||
async fn marbled_mandelbrot_renders_after_migration() {
|
||||
use crate::messages::portfolio::ingest::utility_types::IngestAction;
|
||||
use crate::messages::prelude::IngestMessage;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
let content = std::fs::read_to_string("../demo-artwork/marbled-mandelbrot.graphite").unwrap();
|
||||
editor.editor.handle_message(IngestMessage::Ingest {
|
||||
data: content.into_bytes(),
|
||||
action: IngestAction::Open,
|
||||
mime_type: String::new(),
|
||||
path: Some("marbled-mandelbrot.graphite".into()),
|
||||
});
|
||||
if let Err(error) = editor.eval_graph_until_finished().await {
|
||||
panic!("The migrated demo failed to render: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ use graphene_animation::AnimationCurve;
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::any::DynAnyNode;
|
||||
use graphene_std::brush::Stroke;
|
||||
use graphene_std::generator::Generator;
|
||||
use graphene_std::gradient::Gradient;
|
||||
use graphene_std::list::{AttributeValueDyn, Bundle, Item, List, ListDyn, NodeIdPath};
|
||||
#[cfg(feature = "gpu")]
|
||||
@@ -46,6 +47,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Raster<GPU>>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Color>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Gradient>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Generator>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Artboard>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Graphic>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Vector>]),
|
||||
@@ -56,6 +58,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<wgpu_executor::WgpuPipelineCache>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Color>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Gradient>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Generator>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<DashPattern>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<BoxCorners>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<TransferCurve>]),
|
||||
@@ -104,6 +107,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Raster<CPU>>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Color>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Gradient>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Generator>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<String>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<NodeIdPath>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<f64>]),
|
||||
@@ -124,6 +128,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Raster<GPU>>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Color>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Gradient>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Generator>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<DashPattern>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<BoxCorners>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<TransferCurve>]),
|
||||
@@ -370,6 +375,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
Graphic,
|
||||
Color,
|
||||
Gradient,
|
||||
Generator,
|
||||
String,
|
||||
f64,
|
||||
DVec2,
|
||||
@@ -422,6 +428,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
Raster<CPU>,
|
||||
Color,
|
||||
Gradient,
|
||||
Generator,
|
||||
f64,
|
||||
i64,
|
||||
bool,
|
||||
@@ -462,6 +469,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
String,
|
||||
Color,
|
||||
Gradient,
|
||||
Generator,
|
||||
Artboard,
|
||||
));
|
||||
#[cfg(feature = "gpu")]
|
||||
@@ -515,6 +523,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
// This is what lets a paint list zip element-wise against the content it paints.
|
||||
node_types.extend(embed_adapter_row!(from_element: Color, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: Gradient, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: Generator, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: String, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: Vector, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: Raster<CPU>, element: Graphic));
|
||||
@@ -572,6 +581,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
attribute_value_node!(List<String>),
|
||||
attribute_value_node!(List<Color>),
|
||||
attribute_value_node!(List<Gradient>),
|
||||
attribute_value_node!(List<Generator>),
|
||||
attribute_value_node!(List<Vector>),
|
||||
attribute_value_node!(List<Raster<CPU>>),
|
||||
#[cfg(feature = "gpu")]
|
||||
@@ -599,6 +609,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
transform_list_node!(element: Raster<GPU>),
|
||||
transform_list_node!(element: Color),
|
||||
transform_list_node!(element: Gradient),
|
||||
transform_list_node!(element: Generator),
|
||||
];
|
||||
node_types.extend(transform_list_rows);
|
||||
let mut map: HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>> = HashMap::new();
|
||||
|
||||
@@ -17,6 +17,7 @@ workspace = true
|
||||
[features]
|
||||
default = ["serde"]
|
||||
serde = ["dep:serde", "glam/serde", "half/serde"]
|
||||
nightly = []
|
||||
type_id_logging = []
|
||||
dealloc_nodes = []
|
||||
wasm = ["tsify", "wasm-bindgen"]
|
||||
|
||||
@@ -15,9 +15,11 @@ publish.workspace = true
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = ["dep:kurbo"]
|
||||
derive = ["graphene-hash-derive"]
|
||||
|
||||
[dependencies]
|
||||
graphene-hash-derive = { path = "derive", optional = true }
|
||||
glam = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
kurbo = { workspace = true, optional = true }
|
||||
@@ -1,3 +1,8 @@
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
extern crate std;
|
||||
|
||||
#[cfg(feature = "derive")]
|
||||
pub use graphene_hash_derive::CacheHash;
|
||||
|
||||
@@ -61,6 +66,7 @@ impl_via_hash! {
|
||||
glam::BVec2, glam::BVec3, glam::BVec4,
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl_via_hash! {
|
||||
String,
|
||||
}
|
||||
@@ -148,6 +154,7 @@ impl_glam_array! {
|
||||
}
|
||||
|
||||
// kurbo path types: hash each element's verb and point coordinates via to_bits().
|
||||
#[cfg(feature = "std")]
|
||||
impl CacheHash for kurbo::Point {
|
||||
#[inline]
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
@@ -156,6 +163,7 @@ impl CacheHash for kurbo::Point {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl CacheHash for kurbo::PathEl {
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
core::hash::Hash::hash(&core::mem::discriminant(self), state);
|
||||
@@ -175,6 +183,7 @@ impl CacheHash for kurbo::PathEl {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl CacheHash for kurbo::BezPath {
|
||||
#[inline]
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
@@ -215,6 +224,7 @@ impl<T: CacheHash, const N: usize> CacheHash for [T; N] {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<T: CacheHash> CacheHash for Vec<T> {
|
||||
#[inline]
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
@@ -222,6 +232,7 @@ impl<T: CacheHash> CacheHash for Vec<T> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<T: CacheHash> CacheHash for std::collections::BTreeSet<T> {
|
||||
#[inline]
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
@@ -232,6 +243,7 @@ impl<T: CacheHash> CacheHash for std::collections::BTreeSet<T> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<T: CacheHash + ?Sized> CacheHash for Box<T> {
|
||||
#[inline]
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
@@ -239,6 +251,7 @@ impl<T: CacheHash + ?Sized> CacheHash for Box<T> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<T: CacheHash + ?Sized> CacheHash for std::sync::Arc<T> {
|
||||
#[inline]
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Color adjustments as plain data holding their nodes' settings in the nodes' own units, decoded from effect rows, carried out by the kernels of the `raster-kernels` crate.
|
||||
|
||||
use crate::Graphic;
|
||||
use crate::effects::{EffectKind, ParameterVisitor};
|
||||
use crate::effects::EffectKind;
|
||||
use crate::parameters::ParameterVisitor;
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::SRGBA8;
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use crate::Graphic;
|
||||
use crate::adjustment::Adjustment;
|
||||
use crate::parameters::{ParameterVisitor, ReadParameters, WriteParameters};
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
@@ -193,7 +194,7 @@ impl Effect {
|
||||
/// Decodes the parameters into an [`EffectOperation`], falling back to the default for any absent attribute.
|
||||
pub fn operation(&self) -> EffectOperation {
|
||||
let mut operation = EffectOperation::placeholder(self.kind());
|
||||
operation.visit_parameters(&mut ReadParameters(&self.0));
|
||||
operation.visit_parameters(&mut ReadParameters(&|key| self.0.attributes().get_any(key)));
|
||||
|
||||
// A solid paint mixes the same into every pixel, so the renderers carry it out with the other adjustments
|
||||
match operation {
|
||||
@@ -546,35 +547,6 @@ impl EffectOperation {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a value needs to ride an attribute.
|
||||
pub(crate) trait ParameterValue: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static {}
|
||||
impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static> ParameterValue for T {}
|
||||
|
||||
/// Handles each parameter of an operation, given the attribute key it rides and its implicit default.
|
||||
pub(crate) trait ParameterVisitor {
|
||||
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T);
|
||||
}
|
||||
|
||||
/// Stamps each parameter that differs from its default onto a row.
|
||||
struct WriteParameters<'a>(&'a mut Item<EffectKind>);
|
||||
|
||||
impl ParameterVisitor for WriteParameters<'_> {
|
||||
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T) {
|
||||
if *value != default {
|
||||
self.0.set_attribute(key, value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads each parameter from a row, or its default where the row lacks it.
|
||||
struct ReadParameters<'a>(&'a Item<EffectKind>);
|
||||
|
||||
impl ParameterVisitor for ReadParameters<'_> {
|
||||
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T) {
|
||||
*value = self.0.attribute::<T>(key).cloned().unwrap_or(default);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
//! Procedural patterns described by their settings, rendered at whatever resolution is needed of whatever part is seen by the kernels of the `raster-kernels` crate.
|
||||
|
||||
use crate::parameters::{ParameterVisitor, ReadParameters, StampParameters};
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::Item;
|
||||
use dyn_any::DynAny;
|
||||
use glam::DAffine2;
|
||||
use std::any::Any;
|
||||
|
||||
/// Style of noise pattern.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -90,7 +96,7 @@ pub enum DomainWarpType {
|
||||
}
|
||||
|
||||
/// The settings of a noise pattern, whose lengths are measured in the document units of the space it's sampled in.
|
||||
#[derive(Debug, Clone, PartialEq, CacheHash)]
|
||||
#[derive(Debug, Clone, Default, PartialEq, CacheHash)]
|
||||
pub struct NoiseSettings {
|
||||
pub seed: i64,
|
||||
pub scale: f64,
|
||||
@@ -115,3 +121,82 @@ pub enum GeneratorPattern {
|
||||
/// The Mandelbrot set, with the unit square spanning -2 to 1 along the real axis and -1.5 to 1.5 along the imaginary axis.
|
||||
Mandelbrot,
|
||||
}
|
||||
|
||||
/// A procedural pattern filling the whole plane, which renderers draw at whatever resolution they need across whatever part they see.
|
||||
/// The item's transform places the pattern's own space, and a noise pattern's settings ride the item as attributes named after the Noise Pattern node's parameters.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny)]
|
||||
pub enum Generator {
|
||||
#[default]
|
||||
Noise,
|
||||
/// The Mandelbrot set, with the unit square spanning -2 to 1 along the real axis and -1.5 to 1.5 along the imaginary axis.
|
||||
Mandelbrot,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Generator {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::Noise => "Noise",
|
||||
Self::Mandelbrot => "Mandelbrot",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl BoundingBox for Generator {
|
||||
fn bounding_box(&self, transform: DAffine2, _include_stroke: bool) -> RenderBoundingBox {
|
||||
match transform.matrix2.determinant() == 0. {
|
||||
true => RenderBoundingBox::None,
|
||||
false => RenderBoundingBox::Infinite,
|
||||
}
|
||||
}
|
||||
|
||||
fn thumbnail_bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
||||
self.bounding_box(transform, include_stroke)
|
||||
}
|
||||
}
|
||||
|
||||
impl NoiseSettings {
|
||||
/// Stamps every setting onto the generator's item, whatever its value, so which attributes the item carries doesn't depend on them.
|
||||
pub fn stamp(&self, item: &mut Item<Generator>) {
|
||||
self.clone().visit_parameters(&mut StampParameters(item));
|
||||
}
|
||||
|
||||
/// Visits each setting with the attribute it rides, named after the Noise Pattern node's parameter, and its default, which is the node's.
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) {
|
||||
visitor.parameter("seed", &mut self.seed, 0);
|
||||
visitor.parameter("scale", &mut self.scale, 10.);
|
||||
visitor.parameter("noise_type", &mut self.noise_type, NoiseType::default());
|
||||
visitor.parameter("domain_warp_type", &mut self.domain_warp_type, DomainWarpType::default());
|
||||
visitor.parameter("domain_warp_amplitude", &mut self.domain_warp_amplitude, 100.);
|
||||
visitor.parameter("fractal_type", &mut self.fractal_type, FractalType::default());
|
||||
visitor.parameter("fractal_octaves", &mut self.fractal_octaves, 3);
|
||||
visitor.parameter("fractal_lacunarity", &mut self.fractal_lacunarity, 2.);
|
||||
visitor.parameter("fractal_gain", &mut self.fractal_gain, 0.5);
|
||||
visitor.parameter("fractal_weighted_strength", &mut self.fractal_weighted_strength, 0.);
|
||||
visitor.parameter("fractal_ping_pong_strength", &mut self.fractal_ping_pong_strength, 2.);
|
||||
visitor.parameter("cellular_distance_function", &mut self.cellular_distance_function, CellularDistanceFunction::default());
|
||||
visitor.parameter("cellular_return_type", &mut self.cellular_return_type, CellularReturnType::default());
|
||||
visitor.parameter("cellular_jitter", &mut self.cellular_jitter, 1.);
|
||||
}
|
||||
}
|
||||
|
||||
impl GeneratorPattern {
|
||||
/// The pattern a generator draws, reading a noise pattern's settings with `attribute`, which looks one of the item's attributes up by key.
|
||||
/// Each setting the item lacks takes its default.
|
||||
pub fn decode<'a>(generator: Generator, attribute: &'a dyn Fn(&str) -> Option<&'a dyn Any>) -> Self {
|
||||
match generator {
|
||||
Generator::Noise => {
|
||||
let mut settings = NoiseSettings::default();
|
||||
settings.visit_parameters(&mut ReadParameters(attribute));
|
||||
Self::Noise(settings)
|
||||
}
|
||||
Generator::Mandelbrot => Self::Mandelbrot,
|
||||
}
|
||||
}
|
||||
|
||||
/// The pattern a generator item draws.
|
||||
pub fn of_item(item: &Item<Generator>) -> Self {
|
||||
Self::decode(*item.element(), &|key| item.attributes().get_any(key))
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
use crate::appearance::{Appearance, Cover, Coverage};
|
||||
use crate::generator::Generator;
|
||||
use brush_types::Stroke;
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
@@ -26,6 +27,7 @@ pub enum Graphic {
|
||||
RasterGPU(Item<Raster<GPU>>),
|
||||
Color(Item<Color>),
|
||||
Gradient(Item<Gradient>),
|
||||
Generator(Item<Generator>),
|
||||
Text(Item<String>),
|
||||
NoneList(List<none::None>),
|
||||
GraphicList(List<Graphic>),
|
||||
@@ -34,6 +36,7 @@ pub enum Graphic {
|
||||
RasterGPUList(List<Raster<GPU>>),
|
||||
ColorList(List<Color>),
|
||||
GradientList(List<Gradient>),
|
||||
GeneratorList(List<Generator>),
|
||||
TextList(List<String>),
|
||||
StrokeList(List<Stroke>),
|
||||
}
|
||||
@@ -137,6 +140,23 @@ impl From<List<Gradient>> for Graphic {
|
||||
}
|
||||
}
|
||||
|
||||
// Generator
|
||||
impl From<Generator> for Graphic {
|
||||
fn from(generator: Generator) -> Self {
|
||||
Graphic::Generator(Item::new_from_element(generator))
|
||||
}
|
||||
}
|
||||
impl From<Item<Generator>> for Graphic {
|
||||
fn from(generator: Item<Generator>) -> Self {
|
||||
Graphic::Generator(generator)
|
||||
}
|
||||
}
|
||||
impl From<List<Generator>> for Graphic {
|
||||
fn from(generator: List<Generator>) -> Self {
|
||||
Graphic::GeneratorList(generator)
|
||||
}
|
||||
}
|
||||
|
||||
// Stroke
|
||||
impl From<Stroke> for Graphic {
|
||||
fn from(stroke: Stroke) -> Self {
|
||||
@@ -312,12 +332,14 @@ pub fn bake_paint_transforms(attributes: &mut ItemAttributeValues, transform: DA
|
||||
Graphic::RasterCPU(item) => bake_item_transform(item, transform),
|
||||
Graphic::RasterGPU(item) => bake_item_transform(item, transform),
|
||||
Graphic::Gradient(item) => bake_item_transform(item, transform),
|
||||
Graphic::Generator(item) => bake_item_transform(item, transform),
|
||||
Graphic::Text(item) => bake_item_transform(item, transform),
|
||||
Graphic::GraphicList(list) => bake_list_transform(list, transform),
|
||||
Graphic::VectorList(list) => bake_list_transform(list, transform),
|
||||
Graphic::RasterCPUList(list) => bake_list_transform(list, transform),
|
||||
Graphic::RasterGPUList(list) => bake_list_transform(list, transform),
|
||||
Graphic::GradientList(list) => bake_list_transform(list, transform),
|
||||
Graphic::GeneratorList(list) => bake_list_transform(list, transform),
|
||||
Graphic::TextList(list) => bake_list_transform(list, transform),
|
||||
Graphic::StrokeList(list) => bake_list_transform(list, transform),
|
||||
// A color has no spatial extent, so there is no placement for a transform to move
|
||||
@@ -390,6 +412,16 @@ impl TryFromGraphic for Gradient {
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFromGraphic for Generator {
|
||||
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||
match graphic {
|
||||
Graphic::Generator(item) => Some(List::new_from_item(item)),
|
||||
Graphic::GeneratorList(list) => Some(list),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFromGraphic for String {
|
||||
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||
match graphic {
|
||||
@@ -457,6 +489,12 @@ impl IntoGraphicList for List<Gradient> {
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for List<Generator> {
|
||||
fn into_graphic_list(self) -> List<Graphic> {
|
||||
List::new_from_element(Graphic::GeneratorList(self))
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for List<Stroke> {
|
||||
fn into_graphic_list(self) -> List<Graphic> {
|
||||
let layer_path: NodeIdPath = self.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, 0);
|
||||
@@ -570,6 +608,7 @@ impl Graphic {
|
||||
Graphic::RasterGPU(item) => item_clipped(item),
|
||||
Graphic::Color(item) => item_clipped(item),
|
||||
Graphic::Gradient(item) => item_clipped(item),
|
||||
Graphic::Generator(item) => item_clipped(item),
|
||||
Graphic::Text(item) => item_clipped(item),
|
||||
Graphic::NoneList(list) => all_clipped(list),
|
||||
Graphic::VectorList(list) => all_clipped(list),
|
||||
@@ -578,6 +617,7 @@ impl Graphic {
|
||||
Graphic::RasterGPUList(list) => all_clipped(list),
|
||||
Graphic::ColorList(list) => all_clipped(list),
|
||||
Graphic::GradientList(list) => all_clipped(list),
|
||||
Graphic::GeneratorList(list) => all_clipped(list),
|
||||
Graphic::TextList(list) => all_clipped(list),
|
||||
Graphic::StrokeList(list) => all_clipped(list),
|
||||
}
|
||||
@@ -616,6 +656,7 @@ impl Graphic {
|
||||
}
|
||||
Graphic::RasterCPU(_) | Graphic::RasterCPUList(_) => false,
|
||||
Graphic::RasterGPU(_) | Graphic::RasterGPUList(_) => false,
|
||||
Graphic::Generator(_) | Graphic::GeneratorList(_) => false,
|
||||
Graphic::Color(item) => item_opacity_is_full(item) && item.element().is_opaque(),
|
||||
Graphic::ColorList(list) => !list.is_empty() && every_item_has_full_opacity(list) && list.iter_element_values().all(|color| color.is_opaque()),
|
||||
// A `Clear` spread cuts off to transparency past the ends, leaving the rest of the region unpainted
|
||||
@@ -662,9 +703,11 @@ impl Graphic {
|
||||
// Their content is never inspected, so zeroed opacity is the only invisibility these can report
|
||||
Graphic::RasterCPU(item) => item_opacity_is_zero(item),
|
||||
Graphic::RasterGPU(item) => item_opacity_is_zero(item),
|
||||
Graphic::Generator(item) => item_opacity_is_zero(item),
|
||||
Graphic::Text(item) => item_opacity_is_zero(item),
|
||||
Graphic::RasterCPUList(list) => every_item_has_zero_opacity(list),
|
||||
Graphic::RasterGPUList(list) => every_item_has_zero_opacity(list),
|
||||
Graphic::GeneratorList(list) => every_item_has_zero_opacity(list),
|
||||
Graphic::TextList(list) => every_item_has_zero_opacity(list),
|
||||
Graphic::StrokeList(list) => every_item_has_zero_opacity(list),
|
||||
}
|
||||
@@ -680,11 +723,12 @@ impl Graphic {
|
||||
match self {
|
||||
// A leaf always holds exactly one element, so only the none-typed content is truly empty
|
||||
Graphic::None(_) | Graphic::NoneList(_) => true,
|
||||
Graphic::Graphic(_) | Graphic::Vector(_) | Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Color(_) | Graphic::Gradient(_) | Graphic::Text(_) => false,
|
||||
Graphic::Graphic(_) | Graphic::Vector(_) | Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Color(_) | Graphic::Gradient(_) | Graphic::Generator(_) | Graphic::Text(_) => false,
|
||||
Graphic::GraphicList(list) => list.is_empty(),
|
||||
Graphic::VectorList(list) => list.is_empty(),
|
||||
Graphic::ColorList(list) => list.is_empty(),
|
||||
Graphic::GradientList(list) => list.is_empty(),
|
||||
Graphic::GeneratorList(list) => list.is_empty(),
|
||||
Graphic::RasterCPUList(list) => list.is_empty(),
|
||||
Graphic::RasterGPUList(list) => list.is_empty(),
|
||||
Graphic::TextList(list) => list.is_empty(),
|
||||
@@ -841,6 +885,7 @@ impl BoundingBox for Graphic {
|
||||
Graphic::RasterGPU(item) => item.bounding_box(transform, include_stroke),
|
||||
Graphic::Color(item) => item.bounding_box(transform, include_stroke),
|
||||
Graphic::Gradient(item) => item.bounding_box(transform, include_stroke),
|
||||
Graphic::Generator(item) => item.bounding_box(transform, include_stroke),
|
||||
Graphic::Text(item) => item.bounding_box(transform, include_stroke),
|
||||
Graphic::VectorList(list) => vector_list_bounding_box(list, transform, include_stroke),
|
||||
Graphic::RasterCPUList(list) => list.bounding_box(transform, include_stroke),
|
||||
@@ -848,6 +893,7 @@ impl BoundingBox for Graphic {
|
||||
Graphic::GraphicList(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::ColorList(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::GradientList(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::GeneratorList(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::TextList(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::StrokeList(list) => list.bounding_box(transform, include_stroke),
|
||||
}
|
||||
@@ -862,6 +908,7 @@ impl BoundingBox for Graphic {
|
||||
Graphic::RasterGPU(item) => item.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Color(item) => item.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Gradient(item) => item.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Generator(item) => item.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Text(item) => item.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::VectorList(vector) => vector_list_bounding_box(vector, transform, include_stroke),
|
||||
Graphic::RasterCPUList(raster) => raster.thumbnail_bounding_box(transform, include_stroke),
|
||||
@@ -869,6 +916,7 @@ impl BoundingBox for Graphic {
|
||||
Graphic::GraphicList(list) => list.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::ColorList(color) => color.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::GradientList(gradient) => gradient.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::GeneratorList(generator) => generator.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::TextList(list) => list.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::StrokeList(list) => list.thumbnail_bounding_box(transform, include_stroke),
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ pub mod artboard;
|
||||
pub mod effects;
|
||||
pub mod generator;
|
||||
pub mod graphic;
|
||||
pub(crate) mod parameters;
|
||||
|
||||
// Re-export all transitive dependencies so downstream crates only need to depend on graphic-types
|
||||
pub use core_types;
|
||||
@@ -15,6 +16,7 @@ pub use adjustment::Adjustment;
|
||||
pub use appearance::{Appearance, Cover, CoverPlacement, Coverage, FillAndStroke, stamp_coverage};
|
||||
pub use artboard::Artboard;
|
||||
pub use effects::{BevelDirection, BevelStyle, Effect, EffectKind, EffectOperation, Effects, GlowSource, fitted_paint, stamp_effect};
|
||||
pub use generator::Generator;
|
||||
pub use graphic::{Graphic, IntoGraphicList, TryFromGraphic, Vector};
|
||||
|
||||
pub mod migrations {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
//! Parameters riding an item as attributes, each read as its default when absent, which one listing per operation both writes and reads.
|
||||
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::Item;
|
||||
use std::any::Any;
|
||||
use std::fmt::Debug;
|
||||
|
||||
/// What a value needs to ride an attribute.
|
||||
pub(crate) trait ParameterValue: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static {}
|
||||
impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static> ParameterValue for T {}
|
||||
|
||||
/// Handles each parameter of an operation, given the attribute key it rides and its default.
|
||||
pub(crate) trait ParameterVisitor {
|
||||
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T);
|
||||
}
|
||||
|
||||
/// Stamps each parameter that differs from its default onto an item, for rows whose attributes are part of their value.
|
||||
pub(crate) struct WriteParameters<'a, T>(pub &'a mut Item<T>);
|
||||
|
||||
impl<T> ParameterVisitor for WriteParameters<'_, T> {
|
||||
fn parameter<U: ParameterValue>(&mut self, key: &str, value: &mut U, default: U) {
|
||||
if *value != default {
|
||||
self.0.set_attribute(key, value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stamps every parameter onto an item, for an item on a wire, whose attributes mustn't come and go with their values.
|
||||
pub(crate) struct StampParameters<'a, T>(pub &'a mut Item<T>);
|
||||
|
||||
impl<T> ParameterVisitor for StampParameters<'_, T> {
|
||||
fn parameter<U: ParameterValue>(&mut self, key: &str, value: &mut U, _default: U) {
|
||||
self.0.set_attribute(key, value.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads each parameter from the attribute that the lookup finds by key, or its default where there's none.
|
||||
pub(crate) struct ReadParameters<'a>(pub &'a dyn Fn(&str) -> Option<&'a dyn Any>);
|
||||
|
||||
impl ParameterVisitor for ReadParameters<'_> {
|
||||
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T) {
|
||||
*value = (self.0)(key).and_then(|value| value.downcast_ref::<T>()).cloned().unwrap_or(default);
|
||||
}
|
||||
}
|
||||
@@ -269,10 +269,12 @@ impl RenderExt for Graphic {
|
||||
| Graphic::Vector(_)
|
||||
| Graphic::RasterCPU(_)
|
||||
| Graphic::RasterGPU(_)
|
||||
| Graphic::Generator(_)
|
||||
| Graphic::Text(_)
|
||||
| Graphic::VectorList(_)
|
||||
| Graphic::RasterCPUList(_)
|
||||
| Graphic::RasterGPUList(_)
|
||||
| Graphic::GeneratorList(_)
|
||||
| Graphic::GraphicList(_)
|
||||
| Graphic::GradientList(_)
|
||||
| Graphic::TextList(_)
|
||||
|
||||
@@ -24,6 +24,7 @@ use core_types::{
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphene_resource::Resource;
|
||||
use graphic_types::generator::GeneratorPattern;
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster, Storage, Texture};
|
||||
use graphic_types::vector_types::gradient::{Gradient, GradientForm, wrapped_dial};
|
||||
use graphic_types::vector_types::vector::click_target::{ClickTarget, FreePoint, TargetPath};
|
||||
@@ -32,7 +33,7 @@ use graphic_types::vector_types::vector::style::{RenderMode, StrokeAlign, Stroke
|
||||
use graphic_types::vector_types::vector::{
|
||||
GeometryCache, Path, PlacedContours, contour_bezpaths, contours_bounding_box, contours_stroke_inclusive_bounding_box, edit_item_geometry, edit_list_row_geometry, no_paths,
|
||||
};
|
||||
use graphic_types::{Adjustment, Appearance, Artboard, BevelStyle, Cover, Coverage, EffectOperation, Effects, FillAndStroke, Graphic, Vector, fitted_paint};
|
||||
use graphic_types::{Adjustment, Appearance, Artboard, BevelStyle, Cover, Coverage, EffectOperation, Effects, FillAndStroke, Generator, Graphic, Vector, fitted_paint};
|
||||
use kurbo::{Affine, BezPath, Cap, Join, PathEl, Shape};
|
||||
use num_traits::Zero;
|
||||
use raster_kernels::adjustments::{adjust_color, adjusted_raster, leading_adjustments, preserves_alpha};
|
||||
@@ -76,6 +77,13 @@ impl<'a, T> ItemRef<'a, T> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn attribute_any(self, key: &str) -> Option<&'a dyn std::any::Any> {
|
||||
match self {
|
||||
ItemRef::ListItem(list, index) => list.attribute_any(key, index),
|
||||
ItemRef::Item(item) => item.attributes().get_any(key),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn attribute_cloned_or<A: Clone + 'static>(self, key: &str, fallback: A) -> A {
|
||||
match self {
|
||||
ItemRef::ListItem(list, index) => list.attribute_cloned_or(key, index, fallback),
|
||||
@@ -386,6 +394,7 @@ fn nested_effects_reach(graphic: &Graphic) -> f64 {
|
||||
Graphic::RasterGPU(item) => item_reach(item),
|
||||
Graphic::Color(item) => item_reach(item),
|
||||
Graphic::Gradient(item) => item_reach(item),
|
||||
Graphic::Generator(item) => item_reach(item),
|
||||
Graphic::Text(item) => item_reach(item),
|
||||
Graphic::GraphicList(list) => list_reach(list, nested_effects_reach),
|
||||
Graphic::VectorList(list) => list_reach(list, |_| 0.),
|
||||
@@ -393,6 +402,7 @@ fn nested_effects_reach(graphic: &Graphic) -> f64 {
|
||||
Graphic::RasterGPUList(list) => list_reach(list, |_| 0.),
|
||||
Graphic::ColorList(list) => list_reach(list, |_| 0.),
|
||||
Graphic::GradientList(list) => list_reach(list, |_| 0.),
|
||||
Graphic::GeneratorList(list) => list_reach(list, |_| 0.),
|
||||
Graphic::TextList(list) => list_reach(list, |_| 0.),
|
||||
}
|
||||
}
|
||||
@@ -1873,6 +1883,7 @@ impl Render for Graphic {
|
||||
Graphic::RasterGPU(item) => render_raster_gpu_item_svg(ItemRef::Item(item), render, render_params),
|
||||
Graphic::Color(item) => render_color_item_svg(ItemRef::Item(item), render, render_params),
|
||||
Graphic::Gradient(item) => render_gradient_item_svg(ItemRef::Item(item), render, render_params),
|
||||
Graphic::Generator(_) => (),
|
||||
Graphic::Text(item) => render_text_item_svg(ItemRef::Item(item), render, render_params),
|
||||
Graphic::GraphicList(list) => list.render_svg(render, render_params),
|
||||
Graphic::VectorList(list) => list.render_svg(render, render_params),
|
||||
@@ -1880,6 +1891,7 @@ impl Render for Graphic {
|
||||
Graphic::RasterGPUList(list) => list.render_svg(render, render_params),
|
||||
Graphic::ColorList(list) => list.render_svg(render, render_params),
|
||||
Graphic::GradientList(list) => list.render_svg(render, render_params),
|
||||
Graphic::GeneratorList(list) => list.render_svg(render, render_params),
|
||||
Graphic::TextList(list) => list.render_svg(render, render_params),
|
||||
Graphic::StrokeList(_) => (),
|
||||
}
|
||||
@@ -1901,6 +1913,7 @@ impl Render for Graphic {
|
||||
Graphic::RasterGPU(item) => render_raster_gpu_item_to_vello(ItemRef::Item(item), scene, transform, render_params),
|
||||
Graphic::Color(item) => render_color_item_to_vello(ItemRef::Item(item), scene, transform, render_params),
|
||||
Graphic::Gradient(item) => render_gradient_item_to_vello(ItemRef::Item(item), scene, transform, render_params),
|
||||
Graphic::Generator(item) => render_generator_item_to_vello(ItemRef::Item(item), scene, transform, render_params),
|
||||
Graphic::Text(item) => render_text_item_to_vello(ItemRef::Item(item), scene, transform, render_params),
|
||||
Graphic::GraphicList(list) => list.render_to_vello(scene, transform, render_params),
|
||||
Graphic::VectorList(list) => list.render_to_vello(scene, transform, render_params),
|
||||
@@ -1908,6 +1921,7 @@ impl Render for Graphic {
|
||||
Graphic::RasterGPUList(list) => list.render_to_vello(scene, transform, render_params),
|
||||
Graphic::ColorList(list) => list.render_to_vello(scene, transform, render_params),
|
||||
Graphic::GradientList(list) => list.render_to_vello(scene, transform, render_params),
|
||||
Graphic::GeneratorList(list) => list.render_to_vello(scene, transform, render_params),
|
||||
Graphic::TextList(list) => list.render_to_vello(scene, transform, render_params),
|
||||
Graphic::StrokeList(_) => (),
|
||||
}
|
||||
@@ -1929,10 +1943,12 @@ impl Render for Graphic {
|
||||
| Graphic::RasterCPU(_)
|
||||
| Graphic::Color(_)
|
||||
| Graphic::Gradient(_)
|
||||
| Graphic::Generator(_)
|
||||
| Graphic::Text(_)
|
||||
| Graphic::RasterCPUList(_)
|
||||
| Graphic::ColorList(_)
|
||||
| Graphic::GradientList(_)
|
||||
| Graphic::GeneratorList(_)
|
||||
| Graphic::TextList(_)
|
||||
| Graphic::StrokeList(_) => {}
|
||||
}
|
||||
@@ -1969,6 +1985,7 @@ impl Render for Graphic {
|
||||
Graphic::RasterGPU(item) => first_item_inserts(metadata, item.attribute_cloned_or_default(ATTR_TRANSFORM)),
|
||||
Graphic::Color(item) => first_item_inserts(metadata, item.attribute_cloned_or_default(ATTR_TRANSFORM)),
|
||||
Graphic::Gradient(item) => first_item_inserts(metadata, item.attribute_cloned_or_default(ATTR_TRANSFORM)),
|
||||
Graphic::Generator(item) => first_item_inserts(metadata, item.attribute_cloned_or_default(ATTR_TRANSFORM)),
|
||||
Graphic::Text(item) => first_item_inserts(metadata, item.attribute_cloned_or_default(ATTR_TRANSFORM)),
|
||||
Graphic::RasterCPUList(list) => {
|
||||
metadata.upstream_footprints.insert(element_id, footprint);
|
||||
@@ -2002,6 +2019,14 @@ impl Render for Graphic {
|
||||
metadata.local_transforms.insert(element_id, list.attribute_cloned_or_default(ATTR_TRANSFORM, 0));
|
||||
}
|
||||
}
|
||||
Graphic::GeneratorList(list) => {
|
||||
metadata.upstream_footprints.insert(element_id, footprint);
|
||||
|
||||
// TODO: Find a way to handle more than the first item
|
||||
if !list.is_empty() {
|
||||
metadata.local_transforms.insert(element_id, list.attribute_cloned_or_default(ATTR_TRANSFORM, 0));
|
||||
}
|
||||
}
|
||||
Graphic::TextList(list) => {
|
||||
metadata.upstream_footprints.insert(element_id, footprint);
|
||||
|
||||
@@ -2029,6 +2054,7 @@ impl Render for Graphic {
|
||||
Graphic::RasterGPU(item) => collect_raster_metadata(Some(ItemRef::Item(item)), metadata, footprint, element_id),
|
||||
Graphic::Color(_) => (),
|
||||
Graphic::Gradient(item) => collect_gradient_items_metadata(std::iter::once(ItemRef::Item(item)), metadata, element_id),
|
||||
Graphic::Generator(_) => (),
|
||||
Graphic::Text(item) => collect_text_items_metadata(std::iter::once(ItemRef::Item(item)), metadata, footprint, element_id),
|
||||
Graphic::GraphicList(list) => list.collect_metadata(metadata, footprint, element_id, inherited_appearance),
|
||||
Graphic::VectorList(list) => list.collect_metadata(metadata, footprint, element_id, inherited_appearance),
|
||||
@@ -2036,6 +2062,7 @@ impl Render for Graphic {
|
||||
Graphic::RasterGPUList(list) => list.collect_metadata(metadata, footprint, element_id, inherited_appearance),
|
||||
Graphic::ColorList(list) => list.collect_metadata(metadata, footprint, element_id, inherited_appearance),
|
||||
Graphic::GradientList(list) => list.collect_metadata(metadata, footprint, element_id, inherited_appearance),
|
||||
Graphic::GeneratorList(list) => list.collect_metadata(metadata, footprint, element_id, inherited_appearance),
|
||||
Graphic::TextList(list) => list.collect_metadata(metadata, footprint, element_id, inherited_appearance),
|
||||
Graphic::StrokeList(list) => list.collect_metadata(metadata, footprint, element_id, inherited_appearance),
|
||||
}
|
||||
@@ -2050,6 +2077,7 @@ impl Render for Graphic {
|
||||
Graphic::RasterGPU(item) => add_unit_square_click_target(item.attribute_cloned_or_default(ATTR_TRANSFORM), click_targets),
|
||||
Graphic::Color(_) => (),
|
||||
Graphic::Gradient(item) => add_gradient_item_click_targets(ItemRef::Item(item), click_targets),
|
||||
Graphic::Generator(_) => (),
|
||||
Graphic::Text(item) => add_text_item_click_targets(ItemRef::Item(item), click_targets),
|
||||
Graphic::GraphicList(list) => list.add_upstream_click_targets(click_targets, inherited_appearance),
|
||||
Graphic::VectorList(list) => list.add_upstream_click_targets(click_targets, inherited_appearance),
|
||||
@@ -2057,6 +2085,7 @@ impl Render for Graphic {
|
||||
Graphic::RasterGPUList(list) => list.add_upstream_click_targets(click_targets, inherited_appearance),
|
||||
Graphic::ColorList(list) => list.add_upstream_click_targets(click_targets, inherited_appearance),
|
||||
Graphic::GradientList(list) => list.add_upstream_click_targets(click_targets, inherited_appearance),
|
||||
Graphic::GeneratorList(list) => list.add_upstream_click_targets(click_targets, inherited_appearance),
|
||||
Graphic::TextList(list) => list.add_upstream_click_targets(click_targets, inherited_appearance),
|
||||
Graphic::StrokeList(list) => list.add_upstream_click_targets(click_targets, inherited_appearance),
|
||||
}
|
||||
@@ -2071,6 +2100,7 @@ impl Render for Graphic {
|
||||
Graphic::RasterGPU(item) => add_unit_square_click_target(item.attribute_cloned_or_default(ATTR_TRANSFORM), outlines),
|
||||
Graphic::Color(_) => (),
|
||||
Graphic::Gradient(item) => add_gradient_item_outline_targets(ItemRef::Item(item), outlines),
|
||||
Graphic::Generator(_) => (),
|
||||
Graphic::Text(item) => add_text_item_click_targets(ItemRef::Item(item), outlines),
|
||||
Graphic::GraphicList(list) => list.add_upstream_outline_targets(outlines, inherited_appearance),
|
||||
Graphic::VectorList(list) => list.add_upstream_outline_targets(outlines, inherited_appearance),
|
||||
@@ -2078,6 +2108,7 @@ impl Render for Graphic {
|
||||
Graphic::RasterGPUList(list) => list.add_upstream_outline_targets(outlines, inherited_appearance),
|
||||
Graphic::ColorList(list) => list.add_upstream_outline_targets(outlines, inherited_appearance),
|
||||
Graphic::GradientList(list) => list.add_upstream_outline_targets(outlines, inherited_appearance),
|
||||
Graphic::GeneratorList(list) => list.add_upstream_outline_targets(outlines, inherited_appearance),
|
||||
Graphic::TextList(list) => list.add_upstream_outline_targets(outlines, inherited_appearance),
|
||||
Graphic::StrokeList(list) => list.add_upstream_outline_targets(outlines, inherited_appearance),
|
||||
}
|
||||
@@ -2787,10 +2818,12 @@ fn render_vector_item_to_vello(
|
||||
| Graphic::Vector(_)
|
||||
| Graphic::RasterCPU(_)
|
||||
| Graphic::RasterGPU(_)
|
||||
| Graphic::Generator(_)
|
||||
| Graphic::Text(_)
|
||||
| Graphic::VectorList(_)
|
||||
| Graphic::RasterCPUList(_)
|
||||
| Graphic::RasterGPUList(_)
|
||||
| Graphic::GeneratorList(_)
|
||||
| Graphic::GraphicList(_)
|
||||
| Graphic::TextList(_)
|
||||
| Graphic::StrokeList(_) => {
|
||||
@@ -2877,10 +2910,12 @@ fn render_vector_item_to_vello(
|
||||
| Graphic::Vector(_)
|
||||
| Graphic::RasterCPU(_)
|
||||
| Graphic::RasterGPU(_)
|
||||
| Graphic::Generator(_)
|
||||
| Graphic::Text(_)
|
||||
| Graphic::VectorList(_)
|
||||
| Graphic::RasterCPUList(_)
|
||||
| Graphic::RasterGPUList(_)
|
||||
| Graphic::GeneratorList(_)
|
||||
| Graphic::GraphicList(_)
|
||||
| Graphic::TextList(_)
|
||||
| Graphic::StrokeList(_) => {
|
||||
@@ -3477,6 +3512,56 @@ fn render_raster_cpu_item_to_vello(item: ItemRef<'_, Raster<CPU>>, scene: &mut V
|
||||
/// The most pixels an image may have for its adjustments to be carried out on a texture of it, past which an effects group carries them out at the render's resolution.
|
||||
const MAX_ADJUSTED_TEXTURE_PIXELS: u64 = 4096 * 4096;
|
||||
|
||||
/// Draws one item of generator content into the Vello scene, which renders its pattern for each render at the resolution it needs.
|
||||
fn render_generator_item_to_vello(item: ItemRef<'_, Generator>, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) {
|
||||
let Some(&generator) = item.element() else { return };
|
||||
|
||||
// Outline mode shows only geometry, and a generator filling the plane has none
|
||||
if let RenderMode::Outline = render_params.render_mode {
|
||||
return;
|
||||
}
|
||||
|
||||
let blend_mode_attr: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE);
|
||||
let compositing = item.compositing(render_params);
|
||||
let local_to_scene = transform * item.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM);
|
||||
let bounds = generator.bounding_box(local_to_scene, false);
|
||||
if bounds == RenderBoundingBox::None {
|
||||
return;
|
||||
}
|
||||
|
||||
// Opacity and blend modes composite through a layer covering the whole render
|
||||
let mut layer = false;
|
||||
if compositing.opacity < 1. || blend_mode_attr != BlendMode::default() {
|
||||
let blending = peniko::BlendMode::new(blend_mode_attr.to_peniko(), peniko::Compose::SrcOver);
|
||||
scene.push_viewport_layer(blending, compositing.opacity);
|
||||
layer = true;
|
||||
}
|
||||
|
||||
let pattern = GeneratorPattern::decode(generator, &|key| item.attribute_any(key));
|
||||
compositing.draw_with_effects(
|
||||
scene,
|
||||
transform,
|
||||
render_params,
|
||||
|| bounds,
|
||||
|scene| scene.draw_generator(&pattern, kurbo::Affine::new(local_to_scene.to_cols_array())),
|
||||
);
|
||||
|
||||
if layer {
|
||||
scene.pop_layer();
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for List<Generator> {
|
||||
// A generator's pattern is rendered by GPU kernels, which SVG output has no GPU to run, so it draws nothing as a GPU raster does
|
||||
fn render_svg(&self, _render: &mut SvgRender, _render_params: &RenderParams) {}
|
||||
|
||||
fn render_to_vello(&self, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) {
|
||||
for index in 0..self.len() {
|
||||
render_generator_item_to_vello(ItemRef::ListItem(self, index), scene, transform, render_params);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The metadata a raster contributes under an `element_id`: a unit-square click target,
|
||||
/// plus the first item's transform and any merged-layers snapshot when a first item exists.
|
||||
fn collect_raster_metadata<T>(first_row: Option<ItemRef<'_, T>>, metadata: &mut RenderMetadata, footprint: Footprint, element_id: Option<NodeId>) {
|
||||
@@ -4768,7 +4853,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn solid_vector_paints_take_their_adjustments_into_their_colors() {
|
||||
use crate::vello_scene_builder::{EffectsRenderer, VelloSceneBuilder};
|
||||
use crate::vello_scene_builder::{EffectsRenderer, GeneratorTile, VelloSceneBuilder};
|
||||
use graphic_types::{Effect, EffectOperation, stamp_effect};
|
||||
use kurbo::Shape;
|
||||
|
||||
@@ -4811,6 +4896,10 @@ mod tests {
|
||||
fn adjust_raster(&mut self, _: &Raster<CPU>, _: &[Adjustment]) -> Option<graphic_types::raster_types::Texture> {
|
||||
None
|
||||
}
|
||||
|
||||
fn prepare_generator_tile(&mut self, _: &GeneratorPattern, _: GeneratorTile) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
let mut effects_renderer = NoEffectsGroups;
|
||||
let mut scene = VelloSceneBuilder::new(16, 16, kurbo::Affine::IDENTITY, 4096).with_effects_renderer(&mut effects_renderer);
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use glam::{DMat2, UVec2};
|
||||
use glam::{DMat2, DVec2, UVec2};
|
||||
use graphene_hash::CacheHash;
|
||||
use graphic_types::generator::GeneratorPattern;
|
||||
use graphic_types::raster_types::{CPU, Raster, Texture};
|
||||
use graphic_types::{Adjustment, Effects};
|
||||
use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape, Stroke};
|
||||
@@ -13,6 +15,16 @@ const SHAPE_TOLERANCE: f64 = 0.1;
|
||||
/// The texture size an effects group's area rounds up to a multiple of, so a group moving across renders keeps reusing the same pooled textures.
|
||||
const EFFECTS_SIZE_CLASS: u32 = 64;
|
||||
|
||||
/// The pixels across and down a generator's tile covers, besides the samples bordering it that let neighboring tiles overlap seamlessly.
|
||||
const GENERATOR_TILE_PIXELS: u32 = 256;
|
||||
|
||||
/// The samples bordering each side of a generator's tile, and how many of them its neighbor's drawing overlaps.
|
||||
const GENERATOR_TILE_BORDER: u32 = 2;
|
||||
const GENERATOR_TILE_OVERLAP: u32 = 1;
|
||||
|
||||
/// The most tiles one generator draws in a render, past which larger tiles render at a lower resolution, as for a view skewed far along one axis.
|
||||
const MAX_GENERATOR_TILES_PER_DRAW: f64 = 256.;
|
||||
|
||||
/// Builds a Vello GPU scene of a fixed size, recording the images it draws so the renderer can supply their textures at render time.
|
||||
pub struct VelloSceneBuilder<'a> {
|
||||
scene: vello_gpu::Scene,
|
||||
@@ -50,6 +62,9 @@ pub trait EffectsRenderer: Send {
|
||||
/// A straight-alpha texture of the size of the CPU `raster`, with `adjustments` carried out on its pixels, kept for as long as they're drawn that way.
|
||||
/// `None` if they can't be carried out.
|
||||
fn adjust_raster(&mut self, raster: &Raster<CPU>, adjustments: &[Adjustment]) -> Option<Texture>;
|
||||
|
||||
/// Makes `tile` of `pattern` ready to be drawn as an image, rendering it unless it's been kept from an earlier render. `false` if it can't be rendered.
|
||||
fn prepare_generator_tile(&mut self, pattern: &GeneratorPattern, tile: GeneratorTile) -> bool;
|
||||
}
|
||||
|
||||
/// What a fill or stroke paints with.
|
||||
@@ -100,6 +115,8 @@ pub enum SceneImage {
|
||||
Raster(Raster<CPU>),
|
||||
/// Straight-alpha pixels in a GPU texture, whose copy for sampling gets mipmaps if it's drawn `minified`.
|
||||
Texture { texture: Texture, minified: bool },
|
||||
/// One tile of a generator's pattern, which the renderer made and kept when it was drawn.
|
||||
GeneratorTile(GeneratorTile),
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
|
||||
@@ -107,6 +124,36 @@ enum ImageKey {
|
||||
Blob(u64),
|
||||
Raster(u64),
|
||||
Texture(Texture, bool),
|
||||
GeneratorTile(GeneratorTile),
|
||||
}
|
||||
|
||||
/// One tile of a generator's pattern, from a grid in the pattern's space whose tiles span a power of two of units.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
|
||||
pub struct GeneratorTile {
|
||||
/// Identifies the pattern by the hash of its settings.
|
||||
pub pattern: u64,
|
||||
/// The tiles span `2^-level` units, so a tile is about the same number of pixels in view at any zoom.
|
||||
pub level: i32,
|
||||
pub column: i64,
|
||||
pub row: i64,
|
||||
}
|
||||
|
||||
impl GeneratorTile {
|
||||
/// The samples across and down the tile and its border.
|
||||
pub const SAMPLES: u32 = GENERATOR_TILE_PIXELS + 2 * GENERATOR_TILE_BORDER;
|
||||
|
||||
/// The area of the pattern's space the tile and its border's samples cover, from its minimum to its maximum corner.
|
||||
pub fn area(&self) -> [DVec2; 2] {
|
||||
let (corner, texel) = self.corner_and_texel();
|
||||
[corner, corner + DVec2::splat(Self::SAMPLES as f64 * texel)]
|
||||
}
|
||||
|
||||
/// The corner of the tile's samples, including its border, in the pattern's space, and the span of one sample.
|
||||
fn corner_and_texel(&self) -> (DVec2, f64) {
|
||||
let span = 2_f64.powi(-self.level);
|
||||
let texel = span / GENERATOR_TILE_PIXELS as f64;
|
||||
(DVec2::new(self.column as f64, self.row as f64) * span - GENERATOR_TILE_BORDER as f64 * texel, texel)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -287,6 +334,76 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
self.effects_renderer.as_deref_mut().filter(|renderer| renderer.renders_effects())?.adjust_raster(raster, adjustments)
|
||||
}
|
||||
|
||||
/// Draws a generator's pattern, whose own space `transform` places, across the part of the scene it covers as tiles the renderer makes the first time each is seen.
|
||||
/// The tiles span a power of two of the pattern's units, so a pan reuses them, as does a zoom until the scale nears the next power.
|
||||
pub fn draw_generator(&mut self, pattern: &GeneratorPattern, transform: Affine) {
|
||||
if !self.effects_renderer.as_ref().is_some_and(|renderer| renderer.renders_effects()) {
|
||||
return;
|
||||
}
|
||||
|
||||
let local_to_device = self.view * transform;
|
||||
let [a, b, c, d, _, _] = local_to_device.as_coeffs();
|
||||
let determinant = a * d - b * c;
|
||||
if !determinant.is_normal() {
|
||||
return;
|
||||
}
|
||||
|
||||
// The part of the pattern's space in view
|
||||
let viewport = Rect::new(0., 0., self.width() as f64, self.height() as f64);
|
||||
let visible = local_to_device.inverse().transform_rect_bbox(viewport);
|
||||
if visible.width() <= 0. || visible.height() <= 0. {
|
||||
return;
|
||||
}
|
||||
|
||||
// The tile size nearest to a tile's pixels in view, grown if the view would otherwise need too many
|
||||
let pixels_per_unit = determinant.abs().sqrt();
|
||||
let tile_span = |level: i32| 2_f64.powi(-level);
|
||||
let tile_range = |start: f64, end: f64, span: f64| (start / span).floor() as i64..(end / span).ceil() as i64;
|
||||
let tile_count = |level: i32| {
|
||||
let span = tile_span(level);
|
||||
(tile_range(visible.x0, visible.x1, span).count() * tile_range(visible.y0, visible.y1, span).count()) as f64
|
||||
};
|
||||
let mut level = (pixels_per_unit / GENERATOR_TILE_PIXELS as f64).log2().round() as i32;
|
||||
while tile_count(level) > MAX_GENERATOR_TILES_PER_DRAW {
|
||||
level -= 1;
|
||||
}
|
||||
let span = tile_span(level);
|
||||
|
||||
let mut hasher = std::hash::DefaultHasher::new();
|
||||
pattern.cache_hash(&mut hasher);
|
||||
let pattern_hash = std::hash::Hasher::finish(&hasher);
|
||||
|
||||
let (border, overlap) = (GENERATOR_TILE_BORDER as f64, GENERATOR_TILE_OVERLAP as f64);
|
||||
for row in tile_range(visible.y0, visible.y1, span) {
|
||||
for column in tile_range(visible.x0, visible.x1, span) {
|
||||
let tile = GeneratorTile {
|
||||
pattern: pattern_hash,
|
||||
level,
|
||||
column,
|
||||
row,
|
||||
};
|
||||
if !self.effects_renderer.as_deref_mut().is_some_and(|renderer| renderer.prepare_generator_tile(pattern, tile)) {
|
||||
continue;
|
||||
}
|
||||
let id = *self.image_ids.entry(ImageKey::GeneratorTile(tile)).or_insert_with(|| {
|
||||
self.images.push(SceneImage::GeneratorTile(tile));
|
||||
TextureId(self.images.len() as u64 - 1)
|
||||
});
|
||||
|
||||
// Drawn across the tile and part of its border, overlapping its neighbors' identical samples so no seam shows between them
|
||||
let (corner, texel) = tile.corner_and_texel();
|
||||
self.scene.set_transform(local_to_device * Affine::translate((corner.x, corner.y)) * Affine::scale(texel));
|
||||
self.scene.set_paint(PaintType::Image(Image {
|
||||
image: ImageSource::external_texture(id, TextureRegion::Full, true),
|
||||
sampler: peniko::ImageSampler::new(),
|
||||
}));
|
||||
self.scene.set_paint_transform(Affine::IDENTITY);
|
||||
let (start, end) = (border - overlap, border + GENERATOR_TILE_PIXELS as f64 + overlap);
|
||||
self.scene.fill_rect(&Rect::new(start, start, end, end));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws the content `draw` draws with `effects` carried out on it, within `bounds` in the space of the drawn content (or everywhere for `None`), drawing again for each part of a split render.
|
||||
/// `draw_paint` draws each paint overlay's paint by its index among them, and `fill` fades the content but not the shadows and glows cast from it.
|
||||
pub fn draw_effects(&mut self, effects: &Effects, fill: f32, bounds: Option<Rect>, draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder), draw: &mut dyn FnMut(&mut VelloSceneBuilder)) {
|
||||
@@ -373,6 +490,7 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
SceneImage::Pixels(data) => (data.width, data.height),
|
||||
SceneImage::Raster(raster) => (raster.width, raster.height),
|
||||
SceneImage::Texture { texture, .. } => (texture.width(), texture.height()),
|
||||
SceneImage::GeneratorTile(_) => (GeneratorTile::SAMPLES, GeneratorTile::SAMPLES),
|
||||
};
|
||||
if width == 0 || height == 0 {
|
||||
return None;
|
||||
@@ -382,6 +500,7 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
SceneImage::Pixels(data) => ImageKey::Blob(data.data.id()),
|
||||
SceneImage::Raster(raster) => ImageKey::Raster(raster.buffer_id()),
|
||||
SceneImage::Texture { texture, minified } => ImageKey::Texture(texture.clone(), *minified),
|
||||
SceneImage::GeneratorTile(tile) => ImageKey::GeneratorTile(*tile),
|
||||
};
|
||||
let id = *self.image_ids.entry(key).or_insert_with(|| {
|
||||
self.images.push(image);
|
||||
|
||||
@@ -152,20 +152,12 @@ impl WgpuExecutor {
|
||||
);
|
||||
self.context().queue.lock().submit([encoder.finish()]);
|
||||
|
||||
let (sender, receiver) = futures::channel::oneshot::channel();
|
||||
let (sender, mut receiver) = futures::channel::oneshot::channel();
|
||||
buffer.slice(..).map_async(wgpu::MapMode::Read, move |result| {
|
||||
let _ = sender.send(result);
|
||||
});
|
||||
let _ = device.poll(wgpu::wgt::PollType::wait_indefinitely());
|
||||
// A poll on another thread can be the one running the callback, which may not have finished by the time this poll returns
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
let mapping = futures::executor::block_on(receiver).ok();
|
||||
#[cfg(target_family = "wasm")]
|
||||
let mapping = {
|
||||
let mut receiver = receiver;
|
||||
receiver.try_recv().ok().flatten()
|
||||
};
|
||||
let Some(mapping) = mapping else {
|
||||
let Ok(Some(mapping)) = receiver.try_recv() else {
|
||||
anyhow::bail!("The GPU didn't map the texture's pixels for reading");
|
||||
};
|
||||
mapping?;
|
||||
|
||||
@@ -48,6 +48,12 @@ impl PipelineCache {
|
||||
pub fn executor(&self) -> Option<&WgpuExecutor> {
|
||||
self.executor.get()
|
||||
}
|
||||
|
||||
/// Runs the pipeline, or returns `None` when it was never initialized because no GPU is available.
|
||||
pub fn try_run<P: Pipeline>(&self, args: &P::Args<'_>) -> Option<P::Out> {
|
||||
self.executor.get()?;
|
||||
self.run::<P>(args).ok()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for PipelineCache {
|
||||
|
||||
@@ -12,7 +12,7 @@ use raster_kernels::adjustments::{AdjustmentVisitor, visit_kernel};
|
||||
use raster_kernels::blur::{BlurHalve, BlurHorizontal, BlurPass, BlurSpace, BlurUpsample, BlurVertical, MAX_BLUR_REACH, blur_extent};
|
||||
use raster_kernels::generators::visit_generator_kernel;
|
||||
use raster_kernels::{GpuParams, MapColor, RasterKernel, RasterKernelVisitor, ToGpuParams, map_color_module, raster_kernel_module};
|
||||
use raster_types::{GPU, ImageError, Raster, Storage};
|
||||
use raster_types::{GPU, Raster, Storage};
|
||||
use std::any::{TypeId, type_name};
|
||||
|
||||
/// The format of intermediate rasters a [`RasterKernel::FILTERED`] kernel reads, half-float precision but filterable on WebGL2 unlike [`RASTER_FORMAT`].
|
||||
@@ -41,17 +41,9 @@ fn run<K: ToGpuParams + 'static>(
|
||||
output_size,
|
||||
output_format,
|
||||
};
|
||||
if let Some(executor) = pipeline.executor() {
|
||||
let limit = executor.context().device.limits().max_texture_dimension_2d;
|
||||
if output_size.max_element() > limit {
|
||||
return Err(ImageError::TooLarge {
|
||||
width: output_size.x,
|
||||
height: output_size.y,
|
||||
}
|
||||
.into());
|
||||
}
|
||||
}
|
||||
Ok(pipeline.run::<RasterKernelRuntime>(&args)?)
|
||||
pipeline
|
||||
.try_run::<RasterKernelRuntime>(&args)
|
||||
.ok_or_else(|| NodeError::new("A GPU is required to process a GPU raster"))
|
||||
}
|
||||
|
||||
fn raster_format(pipeline: &WgpuPipelineCache) -> WgpuTextureFormat {
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
use crate::WgpuPipelineCache;
|
||||
use crate::raster_effects::apply_effects;
|
||||
use crate::raster_kernel::adjust_raster;
|
||||
use crate::raster_kernel::{adjust_raster, render_generator};
|
||||
use core_types::NodeError;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::ops::Convert;
|
||||
use core_types::transform::Footprint;
|
||||
use glam::{DMat2, UVec2};
|
||||
use graphic_types::generator::GeneratorPattern;
|
||||
use graphic_types::{Adjustment, Effects, Graphic};
|
||||
use raster_types::{CPU, GPU, Raster, Texture, WeakCPU};
|
||||
use rendering::vello_scene_builder::{EffectsRenderer, SceneImage, VelloSceneBuilder, image_downscale_factor, image_texture_size};
|
||||
use rendering::vello_scene_builder::{EffectsRenderer, GeneratorTile, SceneImage, VelloSceneBuilder, image_downscale_factor, image_texture_size};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
use vello_gpu::kurbo::Affine;
|
||||
@@ -25,6 +26,9 @@ const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
|
||||
/// How many renders a GPU texture's premultiplied copy survives without being drawn before it is freed.
|
||||
const UNUSED_IMAGE_RENDER_LIMIT: u64 = 60;
|
||||
|
||||
/// The most tiles of generators kept between renders, past which the least recently drawn are freed.
|
||||
const MAX_CACHED_GENERATOR_TILES: usize = 256;
|
||||
|
||||
/// How many times a render with too much content for Vello GPU is halved, reaching areas 1/4096 the size of the original.
|
||||
const MAX_SPLIT_DEPTH: u32 = 12;
|
||||
|
||||
@@ -351,6 +355,59 @@ impl EffectsRenderer for RenderContext<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare_generator_tile(&mut self, pattern: &GeneratorPattern, tile: GeneratorTile) -> bool {
|
||||
let key = ImageKey::GeneratorTile(tile);
|
||||
let render_count = self.canvas.images.render_count;
|
||||
if let Some(image_texture) = self.canvas.images.textures.get_mut(&key) {
|
||||
image_texture.last_used = render_count;
|
||||
return true;
|
||||
}
|
||||
|
||||
let size = UVec2::splat(GeneratorTile::SAMPLES);
|
||||
let rendered = render_generator(pattern, tile.area(), size, self.kernels);
|
||||
let source = match rendered.as_ref().map(|raster| raster.texture()) {
|
||||
Ok(Some(source)) => source,
|
||||
Ok(None) => return false,
|
||||
Err(error) => {
|
||||
log::error!("Failed to render a generator's tile: {error}");
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// Unlike a raster's texture, which the texture cache may hand back with new contents, the tile's pixels stay as they are, so its copy for sampling is made once
|
||||
let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("vello_gpu_generator_tile"),
|
||||
});
|
||||
let texture = premultiplied_image_texture(self.device, source, true);
|
||||
self.renderer.alpha_conversion.premultiply_with_mipmaps(self.device, &mut encoder, source, &texture);
|
||||
self.queue.lock().submit([encoder.finish()]);
|
||||
|
||||
self.canvas.images.textures.insert(
|
||||
key,
|
||||
ImageTexture {
|
||||
texture,
|
||||
last_used: render_count,
|
||||
raster: None,
|
||||
},
|
||||
);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// A texture to hold the premultiplied copy of `source` that Vello GPU samples, with mipmaps if it's drawn `minified`.
|
||||
fn premultiplied_image_texture(device: &wgpu::Device, source: &wgpu::Texture, minified: bool) -> wgpu::Texture {
|
||||
let level_count = if minified { source.width().max(source.height()).ilog2() + 1 } else { 1 };
|
||||
device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("vello_gpu_premultiplied_image"),
|
||||
size: source.size(),
|
||||
mip_level_count: level_count,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: TEXTURE_FORMAT,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
view_formats: &[],
|
||||
})
|
||||
}
|
||||
|
||||
/// Leaves `target` transparent.
|
||||
@@ -360,12 +417,13 @@ fn clear(device: &wgpu::Device, queue: &Queue, target: &wgpu::Texture) {
|
||||
queue.submit([encoder.finish()]);
|
||||
}
|
||||
|
||||
/// Identifies the pixels behind an image texture: a blob of CPU pixels, or a GPU texture.
|
||||
/// Identifies the pixels behind an image texture: a blob of CPU pixels, a GPU texture, or a tile of a generator's pattern.
|
||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||
enum ImageKey {
|
||||
Blob(u64),
|
||||
Raster(u64),
|
||||
Texture(wgpu::Texture, bool),
|
||||
GeneratorTile(GeneratorTile),
|
||||
}
|
||||
|
||||
/// A premultiplied copy of an image's pixels that Vello GPU samples as an external texture.
|
||||
@@ -399,6 +457,7 @@ impl ImageTextures {
|
||||
SceneImage::Pixels(data) => ImageKey::Blob(data.data.id()),
|
||||
SceneImage::Raster(raster) => ImageKey::Raster(raster.buffer_id()),
|
||||
SceneImage::Texture { texture, minified } => ImageKey::Texture((**texture).clone(), *minified),
|
||||
SceneImage::GeneratorTile(tile) => ImageKey::GeneratorTile(*tile),
|
||||
};
|
||||
|
||||
if !self.textures.contains_key(&key) {
|
||||
@@ -415,23 +474,13 @@ impl ImageTextures {
|
||||
let (pixels, width, height) = raster.to_flat_u8();
|
||||
upload_pixels(device, queue, &pixels, width, height, peniko::ImageAlphaType::Alpha, max_texture_size)?
|
||||
}
|
||||
SceneImage::Texture { texture, minified } => {
|
||||
let level_count = if *minified { texture.width().max(texture.height()).ilog2() + 1 } else { 1 };
|
||||
device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("vello_gpu_premultiplied_image"),
|
||||
size: texture.size(),
|
||||
mip_level_count: level_count,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: TEXTURE_FORMAT,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
view_formats: &[],
|
||||
})
|
||||
}
|
||||
SceneImage::Texture { texture, minified } => premultiplied_image_texture(device, texture, *minified),
|
||||
// Kept since it was drawn, so there's nothing to supply if it couldn't be made
|
||||
SceneImage::GeneratorTile(_) => return None,
|
||||
};
|
||||
let raster = match image {
|
||||
SceneImage::Raster(raster) => Some(raster.downgrade()),
|
||||
SceneImage::Pixels(_) | SceneImage::Texture { .. } => None,
|
||||
SceneImage::Pixels(_) | SceneImage::Texture { .. } | SceneImage::GeneratorTile(_) => None,
|
||||
};
|
||||
self.textures.insert(key.clone(), ImageTexture { texture, last_used: 0, raster });
|
||||
}
|
||||
@@ -441,22 +490,7 @@ impl ImageTextures {
|
||||
let view = image_texture.texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
|
||||
if let SceneImage::Texture { texture: source, .. } = image {
|
||||
let level_view = |level: u32| {
|
||||
image_texture.texture.create_view(&wgpu::TextureViewDescriptor {
|
||||
base_mip_level: level,
|
||||
mip_level_count: Some(1),
|
||||
..Default::default()
|
||||
})
|
||||
};
|
||||
|
||||
let source_view = source.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let loads_linear_light = source.format().is_srgb() || matches!(source.format(), crate::RASTER_FORMAT | crate::FALLBACK_RASTER_FORMAT);
|
||||
alpha_conversion.premultiply(device, encoder, &source_view, loads_linear_light, &level_view(0));
|
||||
|
||||
// Each mipmap level halves the one before it, so a minified image averages its pixels rather than skipping over them
|
||||
for level in 1..image_texture.texture.mip_level_count() {
|
||||
alpha_conversion.halve(device, encoder, &level_view(level - 1), &level_view(level));
|
||||
}
|
||||
alpha_conversion.premultiply_with_mipmaps(device, encoder, source, &image_texture.texture);
|
||||
}
|
||||
|
||||
Some(view)
|
||||
@@ -470,9 +504,21 @@ impl ImageTextures {
|
||||
// CPU pixels get a new blob ID at every render, so a blob this render didn't draw is unlikely to return
|
||||
ImageKey::Blob(_) => unused_renders == 0,
|
||||
ImageKey::Raster(_) => unused_renders == 0 || (unused_renders < UNUSED_IMAGE_RENDER_LIMIT && image_texture.raster.as_ref().is_some_and(WeakCPU::is_alive)),
|
||||
ImageKey::Texture(..) => unused_renders < UNUSED_IMAGE_RENDER_LIMIT,
|
||||
ImageKey::Texture(..) | ImageKey::GeneratorTile(_) => unused_renders < UNUSED_IMAGE_RENDER_LIMIT,
|
||||
}
|
||||
});
|
||||
|
||||
// Panning and zooming across a generator leaves tiles behind faster than they go unused for long, so the least recent beyond a limit are freed too
|
||||
let mut tile_ages: Vec<u64> = (self.textures.iter())
|
||||
.filter(|(key, _)| matches!(key, ImageKey::GeneratorTile(_)))
|
||||
.map(|(_, image_texture)| image_texture.last_used)
|
||||
.collect();
|
||||
if tile_ages.len() > MAX_CACHED_GENERATOR_TILES {
|
||||
let excess = tile_ages.len() - MAX_CACHED_GENERATOR_TILES;
|
||||
let (_, &mut oldest_kept, _) = tile_ages.select_nth_unstable(excess);
|
||||
self.textures
|
||||
.retain(|key, image_texture| !matches!(key, ImageKey::GeneratorTile(_)) || image_texture.last_used >= oldest_kept);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -837,6 +883,26 @@ impl AlphaConversion {
|
||||
self.run(device, encoder, &self.premultiply_pipeline, parameters, source, target);
|
||||
}
|
||||
|
||||
/// Fills `target` and each of its mipmap levels with the premultiplied pixels of the straight-alpha `source`.
|
||||
fn premultiply_with_mipmaps(&self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, source: &wgpu::Texture, target: &wgpu::Texture) {
|
||||
let level_view = |level: u32| {
|
||||
target.create_view(&wgpu::TextureViewDescriptor {
|
||||
base_mip_level: level,
|
||||
mip_level_count: Some(1),
|
||||
..Default::default()
|
||||
})
|
||||
};
|
||||
|
||||
let source_view = source.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let loads_linear_light = source.format().is_srgb() || matches!(source.format(), crate::RASTER_FORMAT | crate::FALLBACK_RASTER_FORMAT);
|
||||
self.premultiply(device, encoder, &source_view, loads_linear_light, &level_view(0));
|
||||
|
||||
// Each mipmap level halves the one before it, so a minified image averages its pixels rather than skipping over them
|
||||
for level in 1..target.mip_level_count() {
|
||||
self.halve(device, encoder, &level_view(level - 1), &level_view(level));
|
||||
}
|
||||
}
|
||||
|
||||
fn halve(&self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, source: &wgpu::TextureView, target: &wgpu::TextureView) {
|
||||
self.run(device, encoder, &self.halve_pipeline, &self.linear_source_parameters, source, target);
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ fn executor() -> Option<&'static WgpuExecutor> {
|
||||
EXECUTOR.get_or_init(|| futures::executor::block_on(WgpuExecutor::new())).as_ref()
|
||||
}
|
||||
|
||||
/// Held while a test uses the shared GPU, since another test's work can delay a render's readback.
|
||||
/// Held while a test uses the shared GPU, since another test's work can delay or intercept a render's readback.
|
||||
fn take_turn() -> std::sync::MutexGuard<'static, ()> {
|
||||
static TURN: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
TURN.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
@@ -1054,6 +1054,17 @@ fn effects_groups_carry_out_adjustments_like_their_kernels_map_colors() {
|
||||
|
||||
let mut worst = 0;
|
||||
for (index, color) in colors.iter().enumerate() {
|
||||
// A half-float raster rounds a color's gamma channels by up to about 0.0004, which can carry a luminance this close to a Threshold level across it
|
||||
let [r, g, b, _] = color.to_gamma_srgb_channels();
|
||||
let luminance = (4915. * r + 9667. * g + 1802. * b) / 16384.;
|
||||
let near_level = |level: f64| (luminance as f64 - level / 100.).abs() < 0.001;
|
||||
if run
|
||||
.iter()
|
||||
.any(|adjustment| matches!(adjustment, Adjustment::Threshold { min_luminance, max_luminance } if near_level(*min_luminance) || near_level(*max_luminance)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
let mapped = run.iter().fold(*color, |color, adjustment| adjust_color(adjustment, color));
|
||||
let cpu = mapped.to_gamma_srgb_channels().map(|channel| (channel * 255.).round() as i32);
|
||||
for channel in 0..3 {
|
||||
@@ -1263,3 +1274,97 @@ fn images_reveal_the_colors_of_transparent_pixels_when_adjusted() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A noise pattern with features a few units across.
|
||||
fn noise_pattern() -> graphic_types::generator::GeneratorPattern {
|
||||
use graphic_types::generator::*;
|
||||
|
||||
GeneratorPattern::Noise(NoiseSettings {
|
||||
seed: 11,
|
||||
scale: 6.,
|
||||
noise_type: NoiseType::OpenSimplex2,
|
||||
domain_warp_type: DomainWarpType::None,
|
||||
domain_warp_amplitude: 0.,
|
||||
fractal_type: FractalType::FBm,
|
||||
fractal_octaves: 3,
|
||||
fractal_lacunarity: 2.,
|
||||
fractal_gain: 0.5,
|
||||
fractal_weighted_strength: 0.,
|
||||
fractal_ping_pong_strength: 2.,
|
||||
cellular_distance_function: CellularDistanceFunction::Euclidean,
|
||||
cellular_return_type: CellularReturnType::Nearest,
|
||||
cellular_jitter: 1.,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generators_draw_their_pattern_at_the_resolution_in_view() {
|
||||
use crate::raster_kernel::render_generator;
|
||||
use core_types::ops::ConvertAsync;
|
||||
use core_types::transform::Footprint;
|
||||
use graphic_types::raster_types::{CPU, Raster};
|
||||
|
||||
// Each unit of the pattern drawn across two pixels, so its tiles sample the pattern at every pixel's center
|
||||
let size = UVec2::new(80, 80);
|
||||
let pattern = noise_pattern();
|
||||
let Some(pixels) = render(size, |scene| scene.draw_generator(&pattern, Affine::translate((8., 8.)) * Affine::scale(2.))) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let executor = executor().unwrap();
|
||||
let _turn = take_turn();
|
||||
let kernel = render_generator(&pattern, [glam::DVec2::ZERO, glam::DVec2::splat(32.)], UVec2::splat(64), &executor.render_kernels()).unwrap();
|
||||
let kernel: Raster<CPU> = futures::executor::block_on(kernel.convert(Footprint::DEFAULT, executor.clone()));
|
||||
let (expected, _, _) = kernel.to_flat_u8();
|
||||
|
||||
let mut worst = 0;
|
||||
for y in 0..64 {
|
||||
for x in 0..64 {
|
||||
let drawn = pixel(&pixels, size, x + 8, y + 8);
|
||||
let sampled = &expected[((y * 64 + x) * 4) as usize..][..4];
|
||||
worst = (0..3).map(|channel| drawn[channel].abs_diff(sampled[channel])).fold(worst, u8::max);
|
||||
}
|
||||
}
|
||||
assert!(worst <= 2, "the drawn pattern differs from the kernel's own samples by up to {worst} levels");
|
||||
|
||||
// The pattern fills the plane, past the area compared
|
||||
assert_eq!(pixel(&pixels, size, 2, 2)[3], 255);
|
||||
assert_eq!(pixel(&pixels, size, 76, 76)[3], 255);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generator_tiles_are_reused_across_a_pan() {
|
||||
let Some(executor) = executor() else { return };
|
||||
let _turn = take_turn();
|
||||
let tiles = |canvas: &crate::VelloCanvas| {
|
||||
canvas
|
||||
.images
|
||||
.textures
|
||||
.values()
|
||||
.map(|image_texture| image_texture.texture.clone())
|
||||
.collect::<std::collections::HashSet<_>>()
|
||||
};
|
||||
|
||||
// A pattern drawn two pixels to a unit, in tiles of 256 pixels, panned by part of a tile
|
||||
let mut canvas = crate::VelloCanvas::default();
|
||||
let pattern = noise_pattern();
|
||||
let size = UVec2::splat(512);
|
||||
let target = executor.request_texture(size);
|
||||
let render = |canvas: &mut crate::VelloCanvas, offset: f64| {
|
||||
let mut draw = |scene: &mut VelloSceneBuilder| scene.draw_generator(&pattern, Affine::translate((offset, 0.)) * Affine::scale(2.));
|
||||
let context = executor.context();
|
||||
(executor.inner.vello_renderer)
|
||||
.render(canvas, &context.device, &context.queue, &executor.render_kernels(), &mut draw, Affine::IDENTITY, size, &target)
|
||||
.unwrap();
|
||||
};
|
||||
render(&mut canvas, 0.);
|
||||
let first = tiles(&canvas);
|
||||
assert!(!first.is_empty(), "the view should draw tiles");
|
||||
render(&mut canvas, 0.);
|
||||
assert_eq!(tiles(&canvas), first, "drawing the same view again renders no tiles");
|
||||
|
||||
render(&mut canvas, -100.);
|
||||
let panned = tiles(&canvas);
|
||||
assert!(panned.is_superset(&first), "panning keeps the tiles it has rendered");
|
||||
assert!(panned.len() < first.len() * 2, "panning renders only the tiles newly in view, not all {} again", first.len());
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
use core_types::list::Item;
|
||||
use core_types::{ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_OPACITY, ATTR_OPACITY_FILL, BlendMode, Color, Ctx};
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::Vector;
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||
use graphic_types::{Generator, Graphic};
|
||||
use vector_types::Gradient;
|
||||
|
||||
/// Applies the blend mode to the input graphics. Setting this allows for customizing how overlapping content is composited together.
|
||||
@@ -10,7 +10,7 @@ use vector_types::Gradient;
|
||||
fn blend_mode<T>(
|
||||
_: impl Ctx,
|
||||
/// The content that will be composited when rendering.
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String)]
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// The choice of equation that controls how brightness and color blends between overlapping pixels.
|
||||
blend_mode: Item<BlendMode>,
|
||||
@@ -29,7 +29,7 @@ fn blend_mode<T>(
|
||||
fn opacity<T>(
|
||||
_: impl Ctx,
|
||||
/// The content that will be composited when rendering.
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String)]
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// Whether the *Opacity* property is enabled, multiplying the existing opacity by the chosen percentage.
|
||||
#[widget(ParsedWidgetOverride::Hidden)]
|
||||
@@ -76,7 +76,7 @@ fn opacity<T>(
|
||||
fn clipping_mask<T>(
|
||||
_: impl Ctx,
|
||||
/// The content that will be composited when rendering.
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String)]
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// Whether the content inherits the alpha of the content beneath it.
|
||||
clip: Item<bool>,
|
||||
|
||||
@@ -3,6 +3,7 @@ use core_types::transform::Footprint;
|
||||
use core_types::{CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, Interrupt, OwnedContextImpl};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_animation::AnimationCurve;
|
||||
use graphic_types::Generator;
|
||||
use graphic_types::vector_types::Gradient;
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
@@ -89,6 +90,7 @@ fn step_real_time<T>(
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Color>,
|
||||
Context -> Item<Gradient>,
|
||||
Context -> Item<Generator>,
|
||||
Context -> Item<Artboard>,
|
||||
Context -> List<String>,
|
||||
Context -> List<f64>,
|
||||
@@ -99,6 +101,7 @@ fn step_real_time<T>(
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<Artboard>,
|
||||
)]
|
||||
value: impl Node<Context<'static>, Output = T>,
|
||||
@@ -135,6 +138,7 @@ fn step_animation_time<T>(
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Color>,
|
||||
Context -> Item<Gradient>,
|
||||
Context -> Item<Generator>,
|
||||
Context -> Item<Artboard>,
|
||||
Context -> List<String>,
|
||||
Context -> List<f64>,
|
||||
@@ -145,6 +149,7 @@ fn step_animation_time<T>(
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<Artboard>,
|
||||
)]
|
||||
value: impl Node<Context<'static>, Output = T>,
|
||||
|
||||
@@ -5,6 +5,7 @@ use core_types::transform::Footprint;
|
||||
use core_types::{Color, Interrupt, OwnedContextImpl};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_animation::AnimationCurve;
|
||||
use graphic_types::Generator;
|
||||
use graphic_types::vector_types::Gradient;
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
@@ -30,6 +31,7 @@ fn context_modification<T>(
|
||||
Context -> Item<Color>,
|
||||
Context -> Item<Artboard>,
|
||||
Context -> Item<Gradient>,
|
||||
Context -> Item<Generator>,
|
||||
Context -> Item<NodeIdPath>,
|
||||
Context -> Item<AttributeValueDyn>,
|
||||
Context -> Item<AnimationCurve>,
|
||||
@@ -43,6 +45,7 @@ fn context_modification<T>(
|
||||
Context -> List<Color>,
|
||||
Context -> List<Artboard>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<AnimationCurve>,
|
||||
Context -> ListDyn,
|
||||
)]
|
||||
|
||||
@@ -2,6 +2,7 @@ use core_types::list::{Item, List};
|
||||
use core_types::transform::TransformMut;
|
||||
use core_types::{ATTR_BACKGROUND, ATTR_CLIP, ATTR_DIMENSIONS, ATTR_LOCATION, CloneVarArgs, Color, Context, Ctx, ExtractAll, Interrupt, OwnedContextImpl};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::Generator;
|
||||
use graphic_types::graphic::{Graphic, IntoGraphicList};
|
||||
use graphic_types::{Artboard, Vector};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
@@ -20,6 +21,7 @@ fn create_artboard<T: IntoGraphicList>(
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> Item<DAffine2>, // TODO: Remove this
|
||||
)]
|
||||
content: impl Node<Context<'static>, Output = T>,
|
||||
|
||||
@@ -7,7 +7,7 @@ use core_types::{
|
||||
};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::graphic::{Graphic, IntoGraphicList, is_lone_anonymous_leaf};
|
||||
use graphic_types::{Artboard, Vector};
|
||||
use graphic_types::{Artboard, Generator, Vector};
|
||||
use rand::SeedableRng;
|
||||
use rand::seq::SliceRandom;
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
@@ -34,6 +34,7 @@ fn remove_at_index<T: graphic_types::graphic::OmitIndex + Clone + Default>(
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
)]
|
||||
list: T,
|
||||
@@ -68,6 +69,7 @@ fn item_at_index<T: Clone + Default + Send + Sync + 'static>(
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
)]
|
||||
list: List<T>,
|
||||
@@ -106,6 +108,7 @@ fn filter<T: Send + Sync + Clone + 'static>(
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
)]
|
||||
list: List<T>,
|
||||
@@ -139,6 +142,7 @@ fn reverse<T: Send + Sync + Clone + 'static>(
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
)]
|
||||
list: List<T>,
|
||||
@@ -164,6 +168,7 @@ fn shift<T: Send + Sync + Clone + 'static>(
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
)]
|
||||
list: List<T>,
|
||||
@@ -209,6 +214,7 @@ fn shuffle<T: Send + Sync + Clone + 'static>(
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
)]
|
||||
list: List<T>,
|
||||
@@ -281,6 +287,7 @@ fn slice<T: Send + Sync + Clone + 'static>(
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
)]
|
||||
list: List<T>,
|
||||
@@ -416,6 +423,7 @@ fn map<Item: AnyHash + Send + Sync + CacheHash + Clone>(
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
)]
|
||||
content: List<Item>,
|
||||
@@ -432,6 +440,7 @@ fn map<Item: AnyHash + Send + Sync + CacheHash + Clone>(
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<Artboard>,
|
||||
)]
|
||||
mapped: impl Node<Context<'static>, Output = List<Item>>,
|
||||
@@ -602,6 +611,7 @@ fn write_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>(
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
List<BlendMode>,
|
||||
List<GradientForm>,
|
||||
@@ -915,6 +925,7 @@ fn extend<T: Send + Clone>(
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
List<Stroke>,
|
||||
)]
|
||||
@@ -934,6 +945,7 @@ fn extend<T: Send + Clone>(
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
List<Stroke>,
|
||||
)]
|
||||
@@ -951,9 +963,9 @@ fn extend<T: Send + Clone>(
|
||||
#[node_macro::node(category(""))]
|
||||
fn legacy_layer_extend<T: Send + Clone>(
|
||||
_: impl Ctx,
|
||||
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>)] base: List<T>,
|
||||
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>, List<Generator>)] base: List<T>,
|
||||
#[expose]
|
||||
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>)]
|
||||
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>, List<Generator>)]
|
||||
new: List<T>,
|
||||
nested_node_path: Item<NodeIdPath>,
|
||||
) -> List<T> {
|
||||
@@ -985,6 +997,7 @@ fn into_group<T: Into<Graphic>>(
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<String>,
|
||||
List<DVec2>,
|
||||
Item<DAffine2>, // TODO: Remove this
|
||||
|
||||
@@ -60,6 +60,10 @@ pub mod gradient {
|
||||
pub use vector_types::{Gradient, GradientStop};
|
||||
}
|
||||
|
||||
pub mod generator {
|
||||
pub use graphic_types::generator::*;
|
||||
}
|
||||
|
||||
pub mod transform {
|
||||
pub use core_types::transform::*;
|
||||
pub use vector_types::ReferencePoint;
|
||||
|
||||
@@ -5,6 +5,7 @@ use core_types::{CloneVarArgs, ExtractAll, ExtractVarArgs};
|
||||
use core_types::{Color, Context, Ctx, ExtractFootprint, Interrupt, NodeError, OwnedContextImpl, WasmNotSend};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType};
|
||||
use graphene_application_io::{ExportFormat, RenderConfig};
|
||||
use graphic_types::Generator;
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster, Texture};
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use rendering::vello_scene_builder::VelloSceneBuilder;
|
||||
@@ -34,6 +35,7 @@ fn render_intermediate<T: 'static + Render + WasmNotSend + Send + Sync>(
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<String>,
|
||||
)]
|
||||
data: impl Node<Context<'static>, Output = T>,
|
||||
|
||||
@@ -5,7 +5,7 @@ use core_types::{Color, Ctx, OwnedContextImpl, num_traits};
|
||||
use core_types::{Context, Interrupt};
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use graphic_types::{Artboard, Generator, Graphic, Vector};
|
||||
use math_parser::ast;
|
||||
use math_parser::context::{EvalContext, NothingMap, ValueProvider};
|
||||
use math_parser::executer::EvalError;
|
||||
@@ -1613,6 +1613,7 @@ fn switch<T: Send>(
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Color>,
|
||||
Context -> Item<Gradient>,
|
||||
Context -> Item<Generator>,
|
||||
Context -> Item<Artboard>,
|
||||
Context -> Item<Bundle<String>>,
|
||||
Context -> Item<Bundle<bool>>,
|
||||
@@ -1643,6 +1644,7 @@ fn switch<T: Send>(
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Color>,
|
||||
Context -> Item<Gradient>,
|
||||
Context -> Item<Generator>,
|
||||
Context -> Item<Artboard>,
|
||||
Context -> Item<Bundle<String>>,
|
||||
Context -> Item<Bundle<bool>>,
|
||||
|
||||
@@ -281,9 +281,9 @@ fn flatten_vector(graphic_list: &List<Graphic>) -> Result<List<Vector>, BooleanO
|
||||
boolean_operation_on_vector_list(&flattened, BooleanOperation::Union)?.into_iter().collect::<Vec<_>>()
|
||||
}
|
||||
}
|
||||
// Rasters, colors, and gradients bound no region, so they contribute no operand
|
||||
Graphic::None(_) | Graphic::NoneList(_) | Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Color(_) | Graphic::Gradient(_) => Vec::new(),
|
||||
Graphic::RasterCPUList(_) | Graphic::RasterGPUList(_) | Graphic::ColorList(_) | Graphic::GradientList(_) => Vec::new(),
|
||||
// Rasters, colors, gradients, and generators bound no region, so they contribute no operand
|
||||
Graphic::None(_) | Graphic::NoneList(_) | Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Color(_) | Graphic::Gradient(_) | Graphic::Generator(_) => Vec::new(),
|
||||
Graphic::RasterCPUList(_) | Graphic::RasterGPUList(_) | Graphic::ColorList(_) | Graphic::GradientList(_) | Graphic::GeneratorList(_) => Vec::new(),
|
||||
// Strokes have no vector outline representation; a brush node renders them to rasters
|
||||
Graphic::StrokeList(_) => Vec::new(),
|
||||
// Normalized to GraphicList above
|
||||
|
||||
@@ -17,7 +17,7 @@ use graphic_types::adjustment::{
|
||||
};
|
||||
pub use graphic_types::adjustment::{DesaturateMethod, RelativeAbsolute, SelectiveColorChoice};
|
||||
pub use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, NoiseType};
|
||||
use graphic_types::{Graphic, Vector};
|
||||
use graphic_types::{Generator, Graphic, Vector};
|
||||
use num_enum::{FromPrimitive, IntoPrimitive};
|
||||
use raster_kernels::color_lookup_table::parse_cached;
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
@@ -32,7 +32,7 @@ fn adjust<T: ApplyEffect>(item: Item<T>, adjustment: Adjustment, pipeline: Item<
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeDesaturate"))]
|
||||
fn desaturate<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] input: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
|
||||
method: Item<DesaturateMethod>,
|
||||
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
|
||||
) -> Result<Item<T>, Interrupt> {
|
||||
@@ -42,7 +42,7 @@ fn desaturate<T: ApplyEffect>(
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeGammaCorrection"))]
|
||||
fn gamma_correction<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] input: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
|
||||
#[default(2.2)]
|
||||
#[range]
|
||||
#[hard(0.0001..)]
|
||||
@@ -116,7 +116,7 @@ impl MapColor for ExtractChannel {
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeMakeOpaque"))]
|
||||
fn make_opaque<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] input: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
|
||||
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
|
||||
) -> Result<Item<T>, Interrupt> {
|
||||
adjust(input, Adjustment::MakeOpaque, pipeline)
|
||||
@@ -133,7 +133,7 @@ fn make_opaque<T: ApplyEffect>(
|
||||
#[node_macro::node(name("Brightness/Contrast"), category("Raster: Adjustment"), icon("NodeBrightnessContrast"), inspector("brightness_contrast_inspector"))]
|
||||
fn brightness_contrast<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] input: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(-150..150)]
|
||||
@@ -186,7 +186,7 @@ pub enum AdjustmentChannel {
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeLevels"), inspector("levels_inspector"))]
|
||||
fn levels<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
@@ -359,7 +359,7 @@ fn levels<T: ApplyEffect>(
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeCurves"), inspector("transfer_curves_inspector"))]
|
||||
fn curves<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
curve: Item<TransferCurve>,
|
||||
#[name("(Red) Curve")] red_curve: Item<TransferCurve>,
|
||||
#[name("(Green) Curve")] green_curve: Item<TransferCurve>,
|
||||
@@ -407,7 +407,7 @@ fn points_to_transfer_curve(
|
||||
#[node_macro::node(name("Black & White"), category("Raster: Adjustment"), icon("NodeBlackAndWhite"), inspector("black_and_white_inspector"))]
|
||||
fn black_and_white<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
use_tint: Item<bool>,
|
||||
#[default("#e1d3b3")] tint: Item<Color>,
|
||||
#[unit("%")]
|
||||
@@ -481,7 +481,7 @@ pub enum HueSaturationRange {
|
||||
#[node_macro::node(name("Hue/Saturation"), category("Raster: Adjustment"), icon("NodeHueSaturation"), inspector("hue_saturation_inspector"))]
|
||||
fn hue_saturation<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] input: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
|
||||
#[unit("°")]
|
||||
#[range]
|
||||
#[soft(-180..180)]
|
||||
@@ -818,7 +818,7 @@ fn hue_saturation<T: ApplyEffect>(
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeInvert"))]
|
||||
fn invert<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] input: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
|
||||
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
|
||||
) -> Result<Item<T>, Interrupt> {
|
||||
adjust(input, Adjustment::Invert, pipeline)
|
||||
@@ -829,7 +829,7 @@ fn invert<T: ApplyEffect>(
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeThreshold"), inspector("threshold_inspector"))]
|
||||
fn threshold<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
@@ -868,7 +868,7 @@ fn threshold<T: ApplyEffect>(
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeGradientMap"))]
|
||||
fn gradient_map<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
#[default(Color::BLACK, Color::WHITE)] gradient: Item<Gradient>,
|
||||
reverse: Item<bool>,
|
||||
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
|
||||
@@ -889,7 +889,7 @@ fn gradient_map<T: ApplyEffect>(
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeVibrance"), inspector("vibrance_inspector"))]
|
||||
fn vibrance<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(-100..100)]
|
||||
@@ -943,7 +943,7 @@ pub enum RedGreenBlueAlpha {
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeChannelMixer"), inspector("channel_mixer_inspector"))]
|
||||
fn channel_mixer<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
|
||||
monochrome: Item<bool>,
|
||||
|
||||
@@ -1077,7 +1077,7 @@ fn channel_mixer<T: ApplyEffect>(
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeSelectiveColor"), inspector("selective_color_inspector"))]
|
||||
fn selective_color<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
|
||||
mode: Item<RelativeAbsolute>,
|
||||
|
||||
@@ -1300,7 +1300,7 @@ fn selective_color<T: ApplyEffect>(
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodePosterize"))]
|
||||
fn posterize<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] input: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
|
||||
#[default(4)]
|
||||
#[hard(2..)]
|
||||
levels: Item<i64>,
|
||||
@@ -1318,7 +1318,7 @@ fn posterize<T: ApplyEffect>(
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeExposure"), inspector("exposure_inspector"))]
|
||||
fn exposure<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] input: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
|
||||
#[range]
|
||||
#[soft(-20..20)]
|
||||
exposure: Item<f64>,
|
||||
@@ -1364,7 +1364,7 @@ pub enum TonalRange {
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeColorBalance"), inspector("color_balance_inspector"))]
|
||||
fn color_balance<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
|
||||
#[name("(Shadows) Cyan-Red")]
|
||||
#[unit("%")]
|
||||
@@ -1441,7 +1441,7 @@ fn color_balance<T: ApplyEffect>(
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodePhotoFilter"))]
|
||||
fn photo_filter<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
#[default("#ec8a00")] color: Item<Color>,
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
@@ -1472,7 +1472,7 @@ fn photo_filter<T: ApplyEffect>(
|
||||
fn color_lookup<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
/// The image whose colors are remapped by the LUT (lookup table).
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)]
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)]
|
||||
image: Item<T>,
|
||||
/// A LUT (lookup table) file in the `.cube`, `.3dl`, `.look`, `.csp`, or `.icc` (*abstract* or *device link* ICC profile) format.
|
||||
#[name("LUT File")]
|
||||
|
||||
@@ -4,7 +4,7 @@ use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_
|
||||
use core_types::{ATTR_OPACITY_FILL, CacheHash, Color, Ctx, Interrupt, NodeError};
|
||||
use glam::DVec2;
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||
use graphic_types::{Adjustment, BevelDirection, BevelStyle, Effect, EffectOperation, Effects, GlowSource, Graphic, Vector, stamp_effect};
|
||||
use graphic_types::{Adjustment, BevelDirection, BevelStyle, Effect, EffectOperation, Effects, Generator, GlowSource, Graphic, Vector, stamp_effect};
|
||||
use raster_kernels::adjustments::{adjust_color, adjust_gradient, preserves_alpha};
|
||||
use std::hash::{DefaultHasher, Hasher};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
@@ -33,6 +33,7 @@ impl ApplyEffect for Graphic {}
|
||||
impl ApplyEffect for Vector {}
|
||||
impl ApplyEffect for Raster<CPU> {}
|
||||
impl ApplyEffect for String {}
|
||||
impl ApplyEffect for Generator {}
|
||||
|
||||
/// A color has no pixels for an effect to read, so an adjustment is carried out on the color itself with its kernel's mapping.
|
||||
impl ApplyEffect for Color {
|
||||
@@ -85,7 +86,7 @@ fn apply_effect<T: ApplyEffect>(content: Item<T>, operation: EffectOperation, pi
|
||||
fn blur<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
/// The content to blur.
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// How far the blur spreads each point of the content.
|
||||
#[unit(" px")]
|
||||
@@ -115,7 +116,7 @@ fn blur<T: ApplyEffect>(
|
||||
fn drop_shadow<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
/// The content casting the shadow.
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// The shadow's color, with its opacity.
|
||||
#[default("#00000080")]
|
||||
@@ -154,7 +155,7 @@ fn drop_shadow<T: ApplyEffect>(
|
||||
fn inner_shadow<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
/// The content the shadow falls inside.
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// The shadow's color, with its opacity.
|
||||
#[default("#00000080")]
|
||||
@@ -193,7 +194,7 @@ fn inner_shadow<T: ApplyEffect>(
|
||||
fn outer_glow<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
/// The content to glow around.
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// The glow's color, with its opacity.
|
||||
#[default("#ffffbebf")]
|
||||
@@ -227,7 +228,7 @@ fn outer_glow<T: ApplyEffect>(
|
||||
fn inner_glow<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
/// The content to glow within.
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// The glow's color, with its opacity.
|
||||
#[default("#ffffbebf")]
|
||||
@@ -264,7 +265,7 @@ fn inner_glow<T: ApplyEffect>(
|
||||
fn satin<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
/// The content to shade.
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// The shading's color, with its opacity.
|
||||
#[default("#00000080")]
|
||||
@@ -302,7 +303,7 @@ fn satin<T: ApplyEffect>(
|
||||
fn outline<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
/// The content to outline.
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// The outline's color, with its opacity.
|
||||
#[default(Color::BLACK)]
|
||||
@@ -335,7 +336,7 @@ fn outline<T: ApplyEffect>(
|
||||
fn bevel_and_emboss<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
/// The content to raise.
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// Where the slope lies: inside the edge, outside it, across it, or across it with the edge pressed in.
|
||||
style: Item<BevelStyle>,
|
||||
@@ -403,7 +404,7 @@ fn bevel_and_emboss<T: ApplyEffect>(
|
||||
fn paint_overlay<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
/// The content to paint over.
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// The color, gradient, image, or other graphic to paint with. A gradient or image without its own placement stretches across the content.
|
||||
#[default(Color::BLACK)]
|
||||
|
||||
@@ -5,6 +5,7 @@ pub mod dehaze;
|
||||
pub mod effects;
|
||||
pub mod filter;
|
||||
pub mod image_color_palette;
|
||||
pub mod parallel_rows;
|
||||
pub mod raster_kernel;
|
||||
pub mod std_nodes;
|
||||
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
//! Spreads per-row image work across threads on platforms that have them.
|
||||
|
||||
/// Below this many pixels, starting threads costs more than they save.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
const MIN_PIXELS_FOR_THREADS: usize = 65_536;
|
||||
|
||||
/// Calls `fill_row` with the index and pixels of each row of `pixels`, an image `width` pixels wide.
|
||||
/// On native platforms, bands of rows run on separate threads, so `fill_row` must not depend on the order rows are filled in.
|
||||
pub fn fill_rows<P: Send>(pixels: &mut [P], width: usize, fill_row: impl Fn(usize, &mut [P]) + Sync) {
|
||||
if width == 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
if pixels.len() >= MIN_PIXELS_FOR_THREADS {
|
||||
let threads = std::thread::available_parallelism().map_or(1, |threads| threads.get());
|
||||
let rows_per_band = (pixels.len() / width).div_ceil(threads).max(1);
|
||||
|
||||
std::thread::scope(|scope| {
|
||||
for (band_index, band) in pixels.chunks_mut(rows_per_band * width).enumerate() {
|
||||
let fill_row = &fill_row;
|
||||
let fill_band = move |band: &mut [P]| {
|
||||
for (row_in_band, row) in band.chunks_mut(width).enumerate() {
|
||||
fill_row(band_index * rows_per_band + row_in_band, row);
|
||||
}
|
||||
};
|
||||
|
||||
// The band is handed over only once its thread has started, so it can be filled here instead if the system won't start one
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
match std::thread::Builder::new().spawn_scoped(scope, move || receiver.recv().map(fill_band)) {
|
||||
Ok(_) => {
|
||||
let _ = sender.send(band);
|
||||
}
|
||||
Err(_) => fill_band(band),
|
||||
}
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
for (y, row) in pixels.chunks_mut(width).enumerate() {
|
||||
fill_row(y, row);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_row_is_filled_with_its_own_index() {
|
||||
// Large enough to run on threads where there are any, with a ragged count of rows per band
|
||||
let (width, height) = (300, 301);
|
||||
let mut pixels = vec![0_usize; width * height];
|
||||
|
||||
fill_rows(&mut pixels, width, |y, row| row.iter_mut().enumerate().for_each(|(x, pixel)| *pixel = y * width + x));
|
||||
|
||||
assert!(pixels.iter().enumerate().all(|(index, pixel)| *pixel == index));
|
||||
}
|
||||
}
|
||||
@@ -2,18 +2,17 @@ use crate::adjustments::{CellularDistanceFunction, CellularReturnType, DomainWar
|
||||
use crate::gpu_params;
|
||||
use crate::raster_kernel::{KernelFrame, RasterKernel, Wgsl, raster_kernel_pipeline, raster_placement, run_raster_kernel, union_frame};
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::context::{Ctx, ExtractFootprint};
|
||||
use core_types::context::Ctx;
|
||||
use core_types::list::Item;
|
||||
use core_types::math::bbox::Bbox;
|
||||
use core_types::transform::Transform;
|
||||
use core_types::{Interrupt, NodeError};
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_resource::Resource;
|
||||
use graphic_types::generator::{GeneratorPattern, NoiseSettings};
|
||||
use graphic_types::generator::{Generator, NoiseSettings};
|
||||
use raster_types::{CPU, GPU, Raster, Storage};
|
||||
use raster_types::{Image, ImageError};
|
||||
use wgpu_executor::WgpuPipelineCache;
|
||||
use wgpu_executor::raster_kernel::render_generator;
|
||||
|
||||
#[node_macro::node(category("Raster"), icon("NodeChannelsToImage"), name("Channels to Image"), memoize)]
|
||||
fn channels_to_image(
|
||||
@@ -217,9 +216,8 @@ fn image(
|
||||
#[node_macro::node(category("Raster"), icon("NodeNoisePattern"))]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn noise_pattern(
|
||||
ctx: impl ExtractFootprint + Ctx,
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
#[default(true)] clip: Item<bool>,
|
||||
#[hard(0..)] seed: Item<i64>,
|
||||
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_scale")]
|
||||
#[default(10.)]
|
||||
@@ -249,90 +247,30 @@ fn noise_pattern(
|
||||
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_cellular_jitter")]
|
||||
#[default(1.)]
|
||||
cellular_jitter: Item<f64>,
|
||||
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
|
||||
) -> Result<Item<Raster<GPU>>, Interrupt> {
|
||||
let (clip, seed, scale, domain_warp_amplitude) = (*clip.element(), *seed.element(), *scale.element(), *domain_warp_amplitude.element());
|
||||
let (fractal_octaves, fractal_lacunarity, fractal_gain) = (*fractal_octaves.element(), *fractal_lacunarity.element(), *fractal_gain.element());
|
||||
let (fractal_weighted_strength, fractal_ping_pong_strength, cellular_jitter) = (*fractal_weighted_strength.element(), *fractal_ping_pong_strength.element(), *cellular_jitter.element());
|
||||
let (noise_type, domain_warp_type, fractal_type) = (noise_type.into_element(), domain_warp_type.into_element(), fractal_type.into_element());
|
||||
let (cellular_distance_function, cellular_return_type) = (cellular_distance_function.into_element(), cellular_return_type.into_element());
|
||||
) -> Item<Generator> {
|
||||
let settings = NoiseSettings {
|
||||
seed: seed.into_element(),
|
||||
scale: scale.into_element(),
|
||||
noise_type: noise_type.into_element(),
|
||||
domain_warp_type: domain_warp_type.into_element(),
|
||||
domain_warp_amplitude: domain_warp_amplitude.into_element(),
|
||||
fractal_type: fractal_type.into_element(),
|
||||
fractal_octaves: fractal_octaves.into_element(),
|
||||
fractal_lacunarity: fractal_lacunarity.into_element(),
|
||||
fractal_gain: fractal_gain.into_element(),
|
||||
fractal_weighted_strength: fractal_weighted_strength.into_element(),
|
||||
fractal_ping_pong_strength: fractal_ping_pong_strength.into_element(),
|
||||
cellular_distance_function: cellular_distance_function.into_element(),
|
||||
cellular_return_type: cellular_return_type.into_element(),
|
||||
cellular_jitter: cellular_jitter.into_element(),
|
||||
};
|
||||
|
||||
let footprint = ctx.footprint();
|
||||
let viewport_bounds = footprint.viewport_bounds_in_local_space();
|
||||
|
||||
// TODO: Remove "clip" entirely (and its arbitrary 100x100 clipping square) once we have proper resolution-aware layer clipping
|
||||
const CLIPPING_SQUARE_SIZE: f64 = 100.;
|
||||
let logical_transform = if clip { DAffine2::from_scale(DVec2::splat(CLIPPING_SQUARE_SIZE)) } else { DAffine2::IDENTITY };
|
||||
|
||||
let mut size = viewport_bounds.size();
|
||||
let mut offset = viewport_bounds.start;
|
||||
if clip {
|
||||
let image_bounds = Bbox::from_transform(logical_transform).to_axis_aligned_bbox();
|
||||
let intersection = viewport_bounds.intersect(&image_bounds);
|
||||
|
||||
offset = (intersection.start - image_bounds.start).max(DVec2::ZERO);
|
||||
size = intersection.size();
|
||||
}
|
||||
|
||||
// If the image would not be visible, return an empty image
|
||||
if size.x <= 0. || size.y <= 0. {
|
||||
return Ok(Item::default().with_attribute(ATTR_TRANSFORM, logical_transform));
|
||||
}
|
||||
|
||||
let transform = DAffine2::from_translation(offset) * DAffine2::from_scale(size);
|
||||
|
||||
let footprint_scale = footprint.scale();
|
||||
let width = (size.x * footprint_scale.x) as u32;
|
||||
let height = (size.y * footprint_scale.y) as u32;
|
||||
if width == 0 || height == 0 {
|
||||
return Ok(Item::default().with_attribute(ATTR_TRANSFORM, logical_transform));
|
||||
}
|
||||
|
||||
let noise = GeneratorPattern::Noise(NoiseSettings {
|
||||
seed,
|
||||
scale,
|
||||
noise_type,
|
||||
domain_warp_type,
|
||||
domain_warp_amplitude,
|
||||
fractal_type,
|
||||
fractal_octaves,
|
||||
fractal_lacunarity,
|
||||
fractal_gain,
|
||||
fractal_weighted_strength,
|
||||
fractal_ping_pong_strength,
|
||||
cellular_distance_function,
|
||||
cellular_return_type,
|
||||
cellular_jitter,
|
||||
});
|
||||
let raster = render_generator(&noise, [offset, offset + size], UVec2::new(width, height), pipeline.element())?;
|
||||
|
||||
Ok(Item::new_from_element(raster.with_coverage(logical_transform.inverse() * transform)).with_attribute(ATTR_TRANSFORM, logical_transform))
|
||||
let mut generator = Item::new_from_element(Generator::Noise);
|
||||
settings.stamp(&mut generator);
|
||||
generator
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Raster"), icon("NodeMandelbrot"))]
|
||||
fn mandelbrot(ctx: impl ExtractFootprint + Send, #[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>) -> Result<Item<Raster<GPU>>, Interrupt> {
|
||||
let footprint = ctx.footprint();
|
||||
let viewport_bounds = footprint.viewport_bounds_in_local_space();
|
||||
|
||||
let image_bounds = Bbox::from_transform(DAffine2::IDENTITY).to_axis_aligned_bbox();
|
||||
let intersection = viewport_bounds.intersect(&image_bounds);
|
||||
let size = intersection.size();
|
||||
|
||||
let offset = (intersection.start - image_bounds.start).max(DVec2::ZERO);
|
||||
|
||||
// If the image would not be visible, return an empty image
|
||||
if size.x <= 0. || size.y <= 0. {
|
||||
return Ok(Item::default());
|
||||
}
|
||||
|
||||
let scale = footprint.scale();
|
||||
let width = (size.x * scale.x) as u32;
|
||||
let height = (size.y * scale.y) as u32;
|
||||
if width == 0 || height == 0 {
|
||||
return Ok(Item::default());
|
||||
}
|
||||
|
||||
let raster = render_generator(&GeneratorPattern::Mandelbrot, [offset, offset + size], UVec2::new(width, height), pipeline.element())?;
|
||||
|
||||
Ok(Item::new_from_element(raster.with_coverage(DAffine2::from_translation(offset) * DAffine2::from_scale(size))))
|
||||
fn mandelbrot(_: impl Ctx, _primary: ()) -> Item<Generator> {
|
||||
Item::new_from_element(Generator::Mandelbrot)
|
||||
}
|
||||
@@ -4,6 +4,7 @@ use core_types::list::{Item, List};
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::{ATTR_TRANSFORM, CloneVarArgs, Color, Ctx, ExtractAll, InjectVarArgs, Interrupt, LazyInput, Node, OwnedContextImpl};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::Generator;
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
use vector_types::Gradient;
|
||||
@@ -57,6 +58,7 @@ fn repeat<T: Send + Clone + 'static>(
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<Artboard>,
|
||||
)]
|
||||
content: impl Node<Context<'static>, Output = List<T>>,
|
||||
@@ -102,6 +104,7 @@ fn repeat_array<T: Send + Clone + 'static>(
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<Artboard>,
|
||||
)]
|
||||
content: impl Node<Context<'static>, Output = List<T>>,
|
||||
@@ -164,6 +167,7 @@ fn repeat_radial<T: Send + Clone + 'static>(
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<Artboard>,
|
||||
)]
|
||||
content: impl Node<Context<'static>, Output = List<T>>,
|
||||
@@ -224,6 +228,7 @@ fn repeat_on_points<T: Send + Clone + 'static>(
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<Artboard>,
|
||||
)]
|
||||
content: impl Node<Context<'static>, Output = List<T>>,
|
||||
|
||||
@@ -5,7 +5,7 @@ use core_types::transform::{ApplyTransform, ScaleType, Transform};
|
||||
use core_types::{ATTR_TRANSFORM, CloneVarArgs, Context, Ctx, ExtractAll, Interrupt, LazyInput, ModifyFootprint, Node, OwnedContextImpl};
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use graphic_types::{Artboard, Generator, Graphic, Vector};
|
||||
use vector_types::Gradient;
|
||||
|
||||
/// Applies the specified transform to the input content.
|
||||
@@ -22,6 +22,7 @@ fn transform<T: Send + 'static>(
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Color>,
|
||||
Context -> Item<Gradient>,
|
||||
Context -> Item<Generator>,
|
||||
)]
|
||||
content: impl Node<Context<'static>, Output = Item<T>>,
|
||||
#[widget(ParsedWidgetOverride::Custom = "transform_translation")] translation: Item<DVec2>,
|
||||
@@ -182,7 +183,7 @@ fn replaced_transform_context<T, N: Node<Context<'static>, Output = Item<T>>>(
|
||||
|
||||
/// Obtains the transform of the input content.
|
||||
#[node_macro::node(category("Transform"), icon("NodeExtractTransform"), path(core_types::vector))]
|
||||
fn extract_transform<T: Send>(_: impl Ctx, #[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Artboard)] content: Item<T>) -> Item<DAffine2> {
|
||||
fn extract_transform<T: Send>(_: impl Ctx, #[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, Generator, String, Artboard)] content: Item<T>) -> Item<DAffine2> {
|
||||
Item::new_from_element(content.attribute_cloned_or_default(ATTR_TRANSFORM))
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphic_types::Vector;
|
||||
use graphic_types::graphic::{bake_paint_transforms, is_paint_present};
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||
use graphic_types::{Appearance, Cover, CoverPlacement, Coverage, Graphic, IntoGraphicList, stamp_coverage};
|
||||
use graphic_types::{Appearance, Cover, CoverPlacement, Coverage, Generator, Graphic, IntoGraphicList, stamp_coverage};
|
||||
use kurbo::simplify::{SimplifyOptions, simplify_bezpath};
|
||||
use kurbo::{Affine, BezPath, DEFAULT_ACCURACY, Line, ParamCurve, ParamCurveArclen, PathEl, PathSeg, Shape};
|
||||
use rand::{Rng, SeedableRng};
|
||||
@@ -557,6 +557,7 @@ fn copy_to_points<I: Send + Clone>(
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
)]
|
||||
content: impl Node<Context<'static>, Output = List<I>>,
|
||||
/// Minimum range of randomized sizes given to each placed copy.
|
||||
|
||||
@@ -919,69 +919,4 @@ mod tests {
|
||||
"neither the adapter nor what feeds it should read the footprint, leaving it unaffected by panning"
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn a_footprint_dependent_raster_warns_at_a_footprint_invariant_node_and_feeds_others_unconverted() {
|
||||
use graph_craft::application_io::PlatformEditorApi;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::graphene_compiler::Compiler;
|
||||
use graph_craft::proto::{GraphErrorType, TypingContext};
|
||||
use graphene_std::raster_nodes::dehaze::dehaze;
|
||||
use graphene_std::raster_nodes::filter::median_filter;
|
||||
use graphene_std::raster_nodes::raster_kernel::raster_kernel_pipeline;
|
||||
use graphene_std::raster_nodes::std_nodes::mandelbrot;
|
||||
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use std::sync::Arc;
|
||||
|
||||
struct NoSpawner;
|
||||
impl Spawn for NoSpawner {
|
||||
fn spawn(&self, _: Task) {}
|
||||
}
|
||||
|
||||
let compile = |consumer: ProtoNodeIdentifier| {
|
||||
let network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
(
|
||||
NodeId(0),
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::scope(raster_kernel_pipeline::IDENTIFIER)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(mandelbrot::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
(
|
||||
NodeId(1),
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::node(NodeId(0), 0),
|
||||
NodeInput::value(TaggedValue::Number(10.), false),
|
||||
NodeInput::scope(raster_kernel_pipeline::IDENTIFIER),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(consumer),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let runtime = AsyncRuntime::new(Arc::new(NoSpawner), Arc::new(std::time::Instant::now()));
|
||||
let mut network = wrap_network_in_scope(network, Arc::new(PlatformEditorApi::default()), runtime.handle());
|
||||
Preprocessor::new().preprocess(&mut network, &|_| None).unwrap();
|
||||
let compiled = Compiler {}.compile_single(network).unwrap();
|
||||
|
||||
let mut typing_context = TypingContext::new(&interpreted_executor::node_registry::NODE_REGISTRY);
|
||||
typing_context.update(&compiled.network).expect("a GPU raster should reach the GPU-only input");
|
||||
compiled.warnings
|
||||
};
|
||||
|
||||
let warnings = compile(dehaze::IDENTIFIER);
|
||||
assert_eq!(warnings.len(), 1, "Dehaze should warn about reading the footprint through its input: {warnings:?}");
|
||||
assert!(warnings[0].error == GraphErrorType::FootprintDependentInput);
|
||||
|
||||
assert!(compile(median_filter::IDENTIFIER).is_empty(), "a node that isn't footprint invariant shouldn't warn");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user