mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-05 19:12:08 -10:00
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3f5ed7909d | ||
|
|
2cb2dd31fc | ||
|
|
86e6a9f08f | ||
|
|
dee8681459 | ||
|
|
239df7af7c | ||
|
|
86b16c3558 | ||
|
|
506c413cd0 | ||
|
|
dd996adbcb | ||
|
|
a1bb538b9d | ||
|
|
acd7726dee |
No files matched your search
@@ -3,4 +3,3 @@
|
||||
use migration_core::rename;
|
||||
|
||||
rename!("raster_nodes::filter::BlurNode"@1 => "blending_nodes::effects::BlurNode"@2);
|
||||
rename!("blending_nodes::filters::AddNoiseNode"@1 => "blending_nodes::filters::SpeckleNode"@2);
|
||||
@@ -5,14 +5,10 @@ use crate::test_utils::gpu_executor;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use glam::{DAffine2, UVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::application_io::Texture;
|
||||
use graphene_std::blending_nodes::effects::{blur, drop_shadow};
|
||||
use graphene_std::graphic::{IntoGraphicList, extend};
|
||||
use graphene_std::list::{Item, List};
|
||||
use graphene_std::math_nodes::{color_value, gradient_value};
|
||||
use graphene_std::raster_nodes::std_nodes::noise_pattern;
|
||||
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
use graphene_std::{Graphic, NodeParameter, ProtoNodeIdentifier, Vector};
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -140,111 +136,6 @@ fn assert_clip(name: &str, graphic: &Graphic, blurred: bool) {
|
||||
assert_eq!(pixel(170, 90)[3], 0, "{name}: the red is clipped away well past the base");
|
||||
}
|
||||
|
||||
/// Endless content a layer can hold, which fills the whole canvas unless something clips it.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Endless {
|
||||
Color,
|
||||
Gradient,
|
||||
NoisePattern,
|
||||
}
|
||||
|
||||
/// A document viewed in the `render_mode` with a blue rectangle filling (50, 50) to (130, 130).
|
||||
async fn document_with_a_rectangle(render_mode: RenderMode) -> EditorTestUtils {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.handle_message(DocumentMessage::SetRenderMode { render_mode }).await;
|
||||
|
||||
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
|
||||
editor.select_primary_color(blue).await;
|
||||
editor.select_secondary_color(blue).await;
|
||||
editor.draw_rect(50., 50., 130., 130.).await;
|
||||
|
||||
editor
|
||||
}
|
||||
|
||||
/// Adds a new layer of `endless` content above the selected layer, clipped to it as by an Alt-click between them.
|
||||
async fn add_clipped_endless_layer(editor: &mut EditorTestUtils, endless: Endless) {
|
||||
editor.handle_message(DocumentMessage::CreateEmptyFolder).await;
|
||||
let layer = editor.get_selected_layer().await.expect("the new layer is selected");
|
||||
let node = match endless {
|
||||
Endless::Color => color_value::IDENTIFIER,
|
||||
Endless::Gradient => gradient_value::IDENTIFIER,
|
||||
Endless::NoisePattern => noise_pattern::IDENTIFIER,
|
||||
};
|
||||
let node_type = DefinitionIdentifier::ProtoNode(node);
|
||||
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type, layer }).await;
|
||||
editor.handle_message(DocumentMessage::ClipLayer { id: layer.to_node() }).await;
|
||||
}
|
||||
|
||||
/// Evaluates the document for a viewport of `size` as the app does, returning what the frontend is sent and the frame the runtime presents.
|
||||
async fn evaluate_viewport(editor: &mut EditorTestUtils, size: UVec2) -> (Vec<FrontendMessage>, Option<Texture>) {
|
||||
let portfolio = editor.portfolio_message_handler_mut();
|
||||
let document_id = portfolio.active_document_id.expect("a document is open");
|
||||
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
|
||||
let document = documents.get_mut(&document_id).expect("the active document exists");
|
||||
let submitted = executor
|
||||
.submit_node_graph_evaluation(document, document_id, size, 1., Default::default(), Vec::new(), true, DVec2::ZERO)
|
||||
.expect("the evaluation is submitted");
|
||||
|
||||
let mut messages = editor.dispatch(submitted);
|
||||
editor.runtime.update();
|
||||
let frame = editor.runtime.run().await;
|
||||
messages.extend(editor.dispatch(Message::Wake));
|
||||
|
||||
(messages, frame)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn endless_layers_clip_to_the_shape_beneath_them() {
|
||||
let size = UVec2::new(256, 256);
|
||||
|
||||
let frame_pixels = async |editor: &mut EditorTestUtils| {
|
||||
let (_, frame) = evaluate_viewport(editor, size).await;
|
||||
let frame = frame.expect("the viewport presents a frame");
|
||||
gpu_executor().read_texture_pixels(&frame).expect("the frame reads back")
|
||||
};
|
||||
let pixel = |pixels: &[u8], x: u32, y: u32| {
|
||||
let index = (y * size.x + x) as usize * 4;
|
||||
[pixels[index], pixels[index + 1], pixels[index + 2], pixels[index + 3]]
|
||||
};
|
||||
|
||||
for endless in [Endless::Color, Endless::Gradient, Endless::NoisePattern] {
|
||||
// In the viewport's Vello render, the endless content covers the rectangle but leaves the canvas past it as the rectangle alone left it
|
||||
let mut editor = document_with_a_rectangle(RenderMode::Normal).await;
|
||||
let rectangle_alone = frame_pixels(&mut editor).await;
|
||||
add_clipped_endless_layer(&mut editor, endless).await;
|
||||
let clipped = frame_pixels(&mut editor).await;
|
||||
|
||||
assert_ne!(pixel(&clipped, 90, 90), pixel(&rectangle_alone, 90, 90), "{endless:?}: the content shows within the rectangle");
|
||||
for (x, y) in [(20, 20), (200, 90), (90, 200), (230, 230)] {
|
||||
assert_eq!(
|
||||
pixel(&clipped, x, y),
|
||||
pixel(&rectangle_alone, x, y),
|
||||
"{endless:?}: the content is clipped away at ({x}, {y}), past the rectangle"
|
||||
);
|
||||
}
|
||||
|
||||
// In SVG Preview, the endless content is drawn only within the rectangle's mask
|
||||
let mut editor = document_with_a_rectangle(RenderMode::SvgPreview).await;
|
||||
add_clipped_endless_layer(&mut editor, endless).await;
|
||||
let (messages, _) = evaluate_viewport(&mut editor, size).await;
|
||||
let svg = messages
|
||||
.into_iter()
|
||||
.find_map(|message| match message {
|
||||
FrontendMessage::UpdateDocumentArtwork { svg } => Some(svg),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the viewport's artwork is sent as SVG");
|
||||
|
||||
let (unmasked, masked) = svg.split_once(r#"mask="url(#mask-"#).unwrap_or_else(|| panic!("{endless:?}: the content is masked: {svg}"));
|
||||
let draws_endless_content = |markup: &str| ["<polyline", "<foreignObject"].iter().any(|tag| markup.contains(tag));
|
||||
assert!(
|
||||
!draws_endless_content(unmasked) && draws_endless_content(masked),
|
||||
"{endless:?}: the content is drawn within the mask: {svg}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn clipping_bases_clip_by_their_filters_but_not_the_shadows_they_cast() {
|
||||
for (effect_name, effect, blurred) in [("Blur", blur::IDENTIFIER, true), ("Drop Shadow", drop_shadow::IDENTIFIER, false)] {
|
||||
|
||||
@@ -4138,7 +4138,7 @@ impl DocumentMessageHandler {
|
||||
})
|
||||
.unwrap_or((None, None, None));
|
||||
|
||||
let blend_mode_menu_entries = BlendMode::list()
|
||||
let blend_mode_menu_entries = BlendMode::list_svg_subset()
|
||||
.iter()
|
||||
.map(|modes| {
|
||||
modes
|
||||
@@ -4155,7 +4155,7 @@ impl DocumentMessageHandler {
|
||||
|
||||
let widgets = vec![
|
||||
DropdownInput::new(blend_mode_menu_entries)
|
||||
.selected_index(blend_mode.and_then(|blend_mode| blend_mode.index_in_list()).map(|index| index as u32))
|
||||
.selected_index(blend_mode.and_then(|blend_mode| blend_mode.index_in_list_svg_subset()).map(|index| index as u32))
|
||||
.disabled(disabled)
|
||||
.draw_icon(false)
|
||||
.sizing(WidgetSizing::default().grow(false))
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use crate::application::Environment;
|
||||
use crate::consts::{
|
||||
DOUBLE_CLICK_ALLOWED_TRAVEL, VIEWPORT_ROTATE_SNAP_INTERVAL, VIEWPORT_SCROLL_RATE, VIEWPORT_ZOOM_LEVELS, VIEWPORT_ZOOM_MIN_FRACTION_COVER, VIEWPORT_ZOOM_MOUSE_RATE, VIEWPORT_ZOOM_SCALE_MAX,
|
||||
VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR,
|
||||
VIEWPORT_ROTATE_SNAP_INTERVAL, VIEWPORT_SCROLL_RATE, VIEWPORT_ZOOM_LEVELS, VIEWPORT_ZOOM_MIN_FRACTION_COVER, VIEWPORT_ZOOM_MOUSE_RATE, VIEWPORT_ZOOM_SCALE_MAX, VIEWPORT_ZOOM_SCALE_MIN,
|
||||
VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR,
|
||||
};
|
||||
use crate::messages::frontend::utility_types::MouseCursorIcon;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, MouseMotion};
|
||||
use crate::messages::input_mapper::utility_types::pointer::{MouseKeys, ViewportPosition};
|
||||
use crate::messages::input_mapper::utility_types::pointer::ViewportPosition;
|
||||
use crate::messages::portfolio::document::navigation::utility_types::NavigationOperation;
|
||||
use crate::messages::portfolio::document::utility_types::misc::PTZ;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
|
||||
@@ -34,8 +34,6 @@ pub struct NavigationMessageHandler {
|
||||
abortable_pan_start: Option<f64>,
|
||||
/// Whether the current drag navigates the artwork behind the open node graph, rather than the graph itself.
|
||||
artwork_behind_graph: bool,
|
||||
/// Where a middle press began panning the open node graph, kept until the pointer travels too far for its release to still be a click.
|
||||
graph_middle_click_start: Option<ViewportPosition>,
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
@@ -101,10 +99,6 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
return;
|
||||
};
|
||||
self.navigation_operation = NavigationOperation::Pan { pan_original_for_abort: ptz.pan };
|
||||
|
||||
// Released before traveling far, a middle press that pans the open graph is instead a click on the node under it
|
||||
let middle_press_in_graph = graph_view_overlay_open && ipp.mouse.mouse_keys == MouseKeys::MIDDLE;
|
||||
self.graph_middle_click_start = middle_press_in_graph.then_some(ipp.mouse.position);
|
||||
}
|
||||
NavigationMessage::BeginCanvasTilt { was_dispatched_from_menu } => {
|
||||
let Some(ptz) = get_ptz(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
|
||||
@@ -347,13 +341,6 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
responses.add(ToolMessage::UpdateCursor);
|
||||
responses.add(ToolMessage::UpdateHints);
|
||||
responses.add(NavigateToolMessage::End);
|
||||
|
||||
// Not a pan after all, but a middle click in the graph
|
||||
let middle_click_start = self.graph_middle_click_start.take();
|
||||
let middle_released = !ipp.mouse.mouse_keys.contains(MouseKeys::MIDDLE);
|
||||
if !abort_transform && middle_released && middle_click_start.is_some_and(|start| start.distance(ipp.mouse.position) <= DOUBLE_CLICK_ALLOWED_TRAVEL) {
|
||||
responses.add(NodeGraphMessage::MiddleClick);
|
||||
}
|
||||
}
|
||||
NavigationMessage::EndCanvasPTZWithClick { commit_key } => {
|
||||
self.finish_operation_with_click = false;
|
||||
@@ -430,10 +417,6 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
}
|
||||
}
|
||||
NavigationMessage::PointerMove { snap } => {
|
||||
if self.graph_middle_click_start.is_some_and(|start| start.distance(ipp.mouse.position) > DOUBLE_CLICK_ALLOWED_TRAVEL) {
|
||||
self.graph_middle_click_start = None;
|
||||
}
|
||||
|
||||
match self.navigation_operation {
|
||||
NavigationOperation::None => {}
|
||||
NavigationOperation::Pan { .. } => {
|
||||
|
||||
@@ -170,8 +170,6 @@ pub enum NodeGraphMessage {
|
||||
PointerOutsideViewport {
|
||||
shift: Key,
|
||||
},
|
||||
/// Sent when the middle button is released where it was pressed in the graph, rather than having panned it.
|
||||
MiddleClick,
|
||||
/// Sent every frame while a dragged wire hovers a node, to expand it once the hover delay passes.
|
||||
WireHoverTick,
|
||||
/// Sends where everything gliding into place is drawn, along with the wires that follow it.
|
||||
@@ -439,7 +437,6 @@ impl NodeGraphMessage {
|
||||
| Self::PointerMove { .. }
|
||||
| Self::PointerUp
|
||||
| Self::PointerOutsideViewport { .. }
|
||||
| Self::MiddleClick
|
||||
| Self::WireHoverTick
|
||||
| Self::SendGlide
|
||||
| Self::GlideTick
|
||||
|
||||
@@ -1752,20 +1752,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
self.auto_panning.stop(&messages, responses);
|
||||
}
|
||||
}
|
||||
// Middle-clicking a node toggles its visibility
|
||||
NodeGraphMessage::MiddleClick => {
|
||||
if !graph_view_overlay_open || network_interface.is_read_only(breadcrumb_network_path) {
|
||||
return;
|
||||
}
|
||||
let Some(node_id) = network_interface.node_from_click(ipp.mouse.position, breadcrumb_network_path) else {
|
||||
return;
|
||||
};
|
||||
|
||||
responses.add(NodeGraphMessage::ToggleVisibility {
|
||||
node_id,
|
||||
network_path: breadcrumb_network_path.to_vec(),
|
||||
});
|
||||
}
|
||||
NodeGraphMessage::WireHoverTick => {
|
||||
self.expand_wire_hovered_node_after_delay(ipp.time, ipp.mouse.position, network_interface, selection_network_path, responses);
|
||||
}
|
||||
|
||||
@@ -1337,7 +1337,7 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout
|
||||
return LayoutGroup::row(vec![]);
|
||||
};
|
||||
if let Some(&TaggedValue::BlendMode(blend_mode)) = input.as_non_exposed_value() {
|
||||
let entries = BlendMode::list()
|
||||
let entries = BlendMode::list_svg_subset()
|
||||
.iter()
|
||||
.map(|category| {
|
||||
category
|
||||
@@ -1354,7 +1354,9 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout
|
||||
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
DropdownInput::new(entries).selected_index(blend_mode.index_in_list().map(|index| index as u32)).widget_instance(),
|
||||
DropdownInput::new(entries)
|
||||
.selected_index(blend_mode.index_in_list_svg_subset().map(|index| index as u32))
|
||||
.widget_instance(),
|
||||
]);
|
||||
}
|
||||
LayoutGroup::row(widgets).with_tooltip_description("Formula used for blending.")
|
||||
|
||||
-57
@@ -3399,63 +3399,6 @@ async fn visibility_and_lock_toggles_made_in_an_open_transaction_undo_together()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn middle_clicking_a_node_in_the_graph_toggles_its_visibility_but_middle_dragging_only_pans() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
let layer = editor.get_selected_layer().await.expect("the drawn rectangle should be selected").to_node();
|
||||
editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await;
|
||||
|
||||
let is_visible = |editor: &EditorTestUtils| editor.active_document().network_interface.is_visible(&layer, &[]);
|
||||
let graph_pan = |editor: &EditorTestUtils| {
|
||||
editor
|
||||
.active_document()
|
||||
.network_interface
|
||||
.network_metadata(&[])
|
||||
.unwrap()
|
||||
.persistent_metadata
|
||||
.navigation_metadata
|
||||
.node_graph_ptz
|
||||
.pan
|
||||
};
|
||||
let layer_in_viewport = |editor: &EditorTestUtils| {
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
let [min, max] = network_interface.node_bounding_box(&layer, &[]).expect("the layer should have bounds");
|
||||
let node_graph_to_viewport = network_interface.network_metadata(&[]).unwrap().persistent_metadata.navigation_metadata.node_graph_to_viewport;
|
||||
|
||||
(0..=(max.x - min.x) as i32)
|
||||
.map(|x| node_graph_to_viewport.transform_point2(DVec2::new(min.x + x as f64, (min.y + max.y) / 2.)))
|
||||
.find(|&point| network_interface.node_from_click(point, &[]) == Some(layer))
|
||||
.expect("the layer should be pressable")
|
||||
};
|
||||
let pointer_state = |position: DVec2, mouse_keys: MouseKeys| EditorPointerState {
|
||||
editor_position: position,
|
||||
mouse_keys,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Pressed and released with a wobble too small to count as a drag
|
||||
let start = layer_in_viewport(&editor);
|
||||
editor.mousedown(pointer_state(start, MouseKeys::MIDDLE), ModifierKeys::empty()).await;
|
||||
assert!(is_visible(&editor), "pressing the middle button shouldn't toggle the layer yet");
|
||||
editor.mouseup(pointer_state(start + DVec2::new(2., 0.), MouseKeys::empty()), ModifierKeys::empty()).await;
|
||||
assert!(!is_visible(&editor), "a middle click on the layer should hide it");
|
||||
|
||||
// Dragged away and back before the release
|
||||
let start = layer_in_viewport(&editor);
|
||||
let pan_before = graph_pan(&editor);
|
||||
editor.mousedown(pointer_state(start, MouseKeys::MIDDLE), ModifierKeys::empty()).await;
|
||||
editor.move_mouse(start.x + 40., start.y, ModifierKeys::empty(), MouseKeys::MIDDLE).await;
|
||||
assert_ne!(graph_pan(&editor), pan_before, "a middle drag should pan the graph");
|
||||
editor.move_mouse(start.x, start.y, ModifierKeys::empty(), MouseKeys::MIDDLE).await;
|
||||
editor.mouseup(pointer_state(start, MouseKeys::empty()), ModifierKeys::empty()).await;
|
||||
assert!(!is_visible(&editor), "a middle drag shouldn't toggle the layer, even if released where it was pressed");
|
||||
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
assert!(is_visible(&editor), "one undo should revert the middle click");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shift_clicking_a_selected_node_in_the_graph_ends_its_press() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
import { getContext, onMount, onDestroy } from "svelte";
|
||||
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
|
||||
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
|
||||
import { createDragToggleManager, destroyDragToggleManager } from "/src/managers/drag-toggle";
|
||||
import type { DragToggleListener } from "/src/managers/drag-toggle";
|
||||
import { inspectorLayout } from "/src/stores/portfolio";
|
||||
import { createAutoScroller } from "/src/utility-functions/auto-scroll";
|
||||
import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
@@ -25,15 +23,7 @@
|
||||
let lastDragClientY = 0;
|
||||
const autoScroller = createAutoScroller(() => calculateInsertIndex(lastDragClientY));
|
||||
|
||||
// Everything one middle-button drag across the section headers paints is one history step
|
||||
const dragToggleListener: DragToggleListener = {
|
||||
groups: ["inspector-section-visibility"],
|
||||
engagedChanged: (engaged) => (engaged ? editor.startTransaction() : editor.endTransaction()),
|
||||
};
|
||||
|
||||
onMount(() => {
|
||||
createDragToggleManager(dragToggleListener);
|
||||
|
||||
addEventListener("pointermove", draggingPointerMove);
|
||||
addEventListener("pointerup", draggingPointerUp);
|
||||
// A drag cut short by the pointer being canceled or the window losing focus won't get the release that ends it
|
||||
@@ -46,8 +36,6 @@
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
destroyDragToggleManager(dragToggleListener);
|
||||
|
||||
removeEventListener("pointermove", draggingPointerMove);
|
||||
removeEventListener("pointerup", draggingPointerUp);
|
||||
removeEventListener("pointercancel", abortDrag);
|
||||
|
||||
@@ -331,7 +331,6 @@
|
||||
}
|
||||
|
||||
const dragToggleListener: DragToggleListener = {
|
||||
groups: ["layer-visibility", "layer-lock", "layer-chain-visibility"],
|
||||
activeGroupChanged: (group) => {
|
||||
activeDragToggleGroup = group;
|
||||
},
|
||||
@@ -343,15 +342,6 @@
|
||||
editor.toggleNodeVisibilityLayerPanel(id);
|
||||
}
|
||||
|
||||
// Middle-clicking one of the chain's node buttons toggles that node's visibility
|
||||
function chainIconsAuxClick(e: MouseEvent, listing: LayerListingInfo) {
|
||||
if (e.button !== 1) return;
|
||||
|
||||
const chainNodeButton = e.target instanceof Element ? e.target.closest("[data-chain-node]") : undefined;
|
||||
const chainNode = chainNodeButton ? listing.entry?.chainNodes[Number(chainNodeButton.getAttribute("data-chain-node"))] : undefined;
|
||||
if (chainNode) toggleNodeVisibilityLayerPanel(chainNode.id);
|
||||
}
|
||||
|
||||
function toggleLayerLock(id: bigint) {
|
||||
editor.toggleLayerLock(id);
|
||||
}
|
||||
@@ -1204,7 +1194,6 @@
|
||||
on:pointerdown={(e) => layerPointerDown(e, listing)}
|
||||
on:click={(e) => selectLayerWithModifiers(e, listing)}
|
||||
on:dblclick={(e) => chainIconsDoubleClick(e, listing)}
|
||||
on:auxclick={(e) => chainIconsAuxClick(e, listing)}
|
||||
on:pointerenter={() => hoverRow(index)}
|
||||
on:pointerleave={() => (hoveredRowIndex = undefined)}
|
||||
>
|
||||
@@ -1354,8 +1343,6 @@
|
||||
data-chain-node={slot.nodeIndex}
|
||||
data-chain-gap-before={slot.reorderablePosition}
|
||||
data-chain-gap-after={slot.reorderablePosition === undefined ? undefined : slot.reorderablePosition + 1}
|
||||
data-middle-drag-toggle-group="layer-chain-visibility"
|
||||
data-drag-toggle-state={chainNode.visible ? "visible" : "hidden"}
|
||||
/>
|
||||
{/if}
|
||||
{/if}
|
||||
@@ -1372,17 +1359,12 @@
|
||||
: entry.chainExpanded
|
||||
? "Stop listing this layer's chain one node per row."
|
||||
: "List this layer's chain one node per row, beneath the layer."}
|
||||
data-middle-drag-toggle-group="layer-chain-visibility"
|
||||
data-drag-toggle-state={entry.visible ? "visible" : "hidden"}
|
||||
on:click={(e) => {
|
||||
// Without a chain to expand, a click selects the layer as it does elsewhere in the row
|
||||
if (entry.chainNodes.length === 0) return;
|
||||
e.stopPropagation();
|
||||
editor.toggleLayerChainExpanded(listing.id);
|
||||
}}
|
||||
on:auxclick={(e) => {
|
||||
if (e.button === 1) toggleNodeVisibilityLayerPanel(listing.id);
|
||||
}}
|
||||
>
|
||||
<IconLabel
|
||||
icon={entry.iconName}
|
||||
@@ -1413,15 +1395,10 @@
|
||||
data-chain-row-node={slot.nodeIndex}
|
||||
data-chain-gap-before={slot.reorderablePosition}
|
||||
data-chain-gap-after={slot.reorderablePosition === undefined ? undefined : slot.reorderablePosition + 1}
|
||||
data-middle-drag-toggle-group="layer-chain-visibility"
|
||||
data-drag-toggle-state={chainNode.visible ? "visible" : "hidden"}
|
||||
on:pointerdown={(e) => {
|
||||
if (e.button === 0 && draggable) chainNodePointerDown(e, listing, chainNode);
|
||||
}}
|
||||
on:click={(e) => chainNodeClick(e, listing, chainNode.id)}
|
||||
on:auxclick={(e) => {
|
||||
if (e.button === 1) toggleNodeVisibilityLayerPanel(chainNode.id);
|
||||
}}
|
||||
on:dblclick={(e) => {
|
||||
// Only the node's icon opens it in the graph
|
||||
if (e.target instanceof Element && e.target.closest("[data-chain-node-row-icon]")) editor.showNodeInGraph(chainNode.id);
|
||||
|
||||
@@ -41,12 +41,6 @@
|
||||
const accel = operatingSystem() === "Mac" ? e.metaKey : e.ctrlKey;
|
||||
editor.toggleNodeInspectorSectionExpanded(widgetData.id, e.altKey || accel);
|
||||
}
|
||||
|
||||
function toggleVisibilityWithMiddleClick(e: MouseEvent) {
|
||||
if (e.button !== 1 || widgetData.disabled) return;
|
||||
|
||||
editor.toggleNodeVisibilityInspector(widgetData.id);
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- TODO: Implement collapsable sections with the Inspector system -->
|
||||
@@ -82,16 +76,7 @@
|
||||
{/if}
|
||||
{/each}
|
||||
{:else}
|
||||
<button
|
||||
class="header"
|
||||
class:expanded
|
||||
class:expandable
|
||||
data-inspector-reorder-handle={reorderable ? "" : undefined}
|
||||
data-middle-drag-toggle-group={widgetData.disabled ? undefined : "inspector-section-visibility"}
|
||||
data-drag-toggle-state={widgetData.visible ? "visible" : "hidden"}
|
||||
onclick={toggleExpandedWithModifiers}
|
||||
onauxclick={toggleVisibilityWithMiddleClick}
|
||||
>
|
||||
<button class="header" class:expanded class:expandable data-inspector-reorder-handle={reorderable ? "" : undefined} onclick={toggleExpandedWithModifiers}>
|
||||
<div
|
||||
class="icon-slot"
|
||||
data-tooltip-label={!expandable ? undefined : expanded ? "Collapse (All)" : "Expand (All)"}
|
||||
|
||||
@@ -8,30 +8,21 @@
|
||||
// The gesture only engages once the pointer crosses from the source into a different sibling, so plain
|
||||
// clicks still toggle as usual. When engaged, the source is clicked once (toggling it) and any sibling
|
||||
// the pointer enters whose state still matches the source's recorded starting state is also clicked.
|
||||
//
|
||||
// Peers toggled by the middle button declare data-middle-drag-toggle-group instead, and toggle on an `auxclick`
|
||||
// rather than a click. Their gesture engages on the press, which toggles the source at once.
|
||||
|
||||
export type DragToggleListener = {
|
||||
// The groups whose gestures this listener is told about
|
||||
groups: string[];
|
||||
// Given the group of the pressed button, and undefined once the press ends
|
||||
activeGroupChanged?: (activeGroup: string | undefined) => void;
|
||||
// Told when the gesture engages, before any of its clicks, and again when it ends, so its clicks can form one history step
|
||||
engagedChanged?: (engaged: boolean) => void;
|
||||
};
|
||||
|
||||
const MIDDLE_BUTTON = 1;
|
||||
|
||||
const listeners = new Set<DragToggleListener>();
|
||||
let activeGroup: string | undefined = undefined;
|
||||
let middleButtonGesture = false;
|
||||
let source: HTMLElement | undefined = undefined;
|
||||
let startingState: string | undefined = undefined;
|
||||
let visited = new WeakSet<Element>();
|
||||
let engaged = false;
|
||||
let suppressNextClickFromSource: HTMLElement | undefined = undefined;
|
||||
let suppressNextAuxClick = false;
|
||||
|
||||
export function createDragToggleManager(listener: DragToggleListener) {
|
||||
listeners.add(listener);
|
||||
@@ -47,13 +38,12 @@ export function createDragToggleManager(listener: DragToggleListener) {
|
||||
window.addEventListener("blur", onPointerUp);
|
||||
// Capture phase on click suppresses the natural source-click before the button's handler runs
|
||||
window.addEventListener("click", onClickCapture, true);
|
||||
window.addEventListener("auxclick", onAuxClickCapture, true);
|
||||
}
|
||||
}
|
||||
|
||||
export function destroyDragToggleManager(listener: DragToggleListener) {
|
||||
// A consumer leaving mid-gesture still hears it end
|
||||
if (engaged && activeGroup && listener.groups.includes(activeGroup)) listener.engagedChanged?.(false);
|
||||
if (engaged) listener.engagedChanged?.(false);
|
||||
listeners.delete(listener);
|
||||
|
||||
// Uninstall the window event listeners only once the last consumer leaves
|
||||
@@ -64,120 +54,83 @@ export function destroyDragToggleManager(listener: DragToggleListener) {
|
||||
window.removeEventListener("pointercancel", onPointerUp);
|
||||
window.removeEventListener("blur", onPointerUp);
|
||||
window.removeEventListener("click", onClickCapture, true);
|
||||
window.removeEventListener("auxclick", onAuxClickCapture, true);
|
||||
|
||||
activeGroup = undefined;
|
||||
middleButtonGesture = false;
|
||||
source = undefined;
|
||||
startingState = undefined;
|
||||
visited = new WeakSet();
|
||||
engaged = false;
|
||||
suppressNextClickFromSource = undefined;
|
||||
suppressNextAuxClick = false;
|
||||
}
|
||||
}
|
||||
|
||||
function listenersOfGroup(group: string): DragToggleListener[] {
|
||||
return Array.from(listeners).filter((listener) => listener.groups.includes(group));
|
||||
}
|
||||
|
||||
function notifyActiveGroupChange(group: string | undefined) {
|
||||
const previousGroup = activeGroup;
|
||||
activeGroup = group;
|
||||
|
||||
const notifiedGroup = group || previousGroup;
|
||||
if (notifiedGroup) listenersOfGroup(notifiedGroup).forEach((listener) => listener.activeGroupChanged?.(group));
|
||||
listeners.forEach((listener) => listener.activeGroupChanged?.(group));
|
||||
}
|
||||
|
||||
function groupAttribute(middleButton: boolean): string {
|
||||
return middleButton ? "data-middle-drag-toggle-group" : "data-drag-toggle-group";
|
||||
}
|
||||
|
||||
function findMember(target: EventTarget | undefined, middleButton: boolean): HTMLElement | undefined {
|
||||
function findMember(target: EventTarget | undefined): HTMLElement | undefined {
|
||||
if (!(target instanceof Element)) return undefined;
|
||||
const found = target.closest(`[${groupAttribute(middleButton)}]`);
|
||||
const found = target.closest("[data-drag-toggle-group]");
|
||||
return found instanceof HTMLElement ? found : undefined;
|
||||
}
|
||||
|
||||
function memberState(member: HTMLElement): string | undefined {
|
||||
return member.getAttribute("data-drag-toggle-state") || undefined;
|
||||
}
|
||||
|
||||
function toggle(member: HTMLElement) {
|
||||
if (middleButtonGesture) member.dispatchEvent(new MouseEvent("auxclick", { button: MIDDLE_BUTTON, bubbles: true }));
|
||||
else member.click();
|
||||
}
|
||||
|
||||
function engage() {
|
||||
if (!activeGroup || !source) return;
|
||||
|
||||
engaged = true;
|
||||
visited.add(source);
|
||||
listenersOfGroup(activeGroup).forEach((listener) => listener.engagedChanged?.(true));
|
||||
if (memberState(source) === startingState) toggle(source);
|
||||
}
|
||||
|
||||
function onPointerDown(e: PointerEvent) {
|
||||
if (e.button !== 0 && e.button !== MIDDLE_BUTTON) return;
|
||||
if (e.button !== 0) return;
|
||||
suppressNextClickFromSource = undefined;
|
||||
suppressNextAuxClick = false;
|
||||
|
||||
const middleButton = e.button === MIDDLE_BUTTON;
|
||||
const found = findMember(e.target || undefined, middleButton);
|
||||
const found = findMember(e.target || undefined);
|
||||
if (!found) return;
|
||||
|
||||
// Stop the event so sibling drag/select handlers on ancestors don't also engage
|
||||
e.stopPropagation();
|
||||
|
||||
middleButtonGesture = middleButton;
|
||||
source = found;
|
||||
startingState = memberState(found);
|
||||
startingState = found.getAttribute("data-drag-toggle-state") || undefined;
|
||||
visited = new WeakSet();
|
||||
engaged = false;
|
||||
|
||||
notifyActiveGroupChange(found.getAttribute(groupAttribute(middleButton)) || undefined);
|
||||
|
||||
if (middleButton) engage();
|
||||
notifyActiveGroupChange(found.getAttribute("data-drag-toggle-group") || undefined);
|
||||
}
|
||||
|
||||
function onPointerMove(e: PointerEvent) {
|
||||
if (!activeGroup || !source) return;
|
||||
|
||||
const member = findMember(e.target || undefined, middleButtonGesture);
|
||||
if (!member || member.getAttribute(groupAttribute(middleButtonGesture)) !== activeGroup) return;
|
||||
const member = findMember(e.target || undefined);
|
||||
if (!member || member.getAttribute("data-drag-toggle-group") !== activeGroup) return;
|
||||
|
||||
// Engages only when the cursor crosses from the source to a different peer, so tiny wobbles over the source don't trigger
|
||||
if (member === source || visited.has(member)) return;
|
||||
|
||||
// First crossing engages the drag and toggles the source as part of the operation
|
||||
if (!engaged) engage();
|
||||
if (!engaged) {
|
||||
engaged = true;
|
||||
visited.add(source);
|
||||
listeners.forEach((listener) => listener.engagedChanged?.(true));
|
||||
if ((source.getAttribute("data-drag-toggle-state") || undefined) === startingState) source.click();
|
||||
}
|
||||
|
||||
// Toggle only peers still in the starting state, so we don't flip ones already at the target state
|
||||
if (memberState(member) !== startingState) return;
|
||||
if ((member.getAttribute("data-drag-toggle-state") || undefined) !== startingState) return;
|
||||
|
||||
visited.add(member);
|
||||
toggle(member);
|
||||
member.click();
|
||||
}
|
||||
|
||||
function onPointerUp(e: Event) {
|
||||
if (!activeGroup) return;
|
||||
const endedGroup = activeGroup;
|
||||
|
||||
// An engaged drag already toggled the source, so its release's click won't toggle it again
|
||||
if (engaged && source && e.type === "pointerup") {
|
||||
if (middleButtonGesture) suppressNextAuxClick = true;
|
||||
else suppressNextClickFromSource = source;
|
||||
}
|
||||
// An engaged drag already clicked the source, so the click its release sends is suppressed rather than toggling it again
|
||||
if (engaged && source && e.type === "pointerup") suppressNextClickFromSource = source;
|
||||
const wasEngaged = engaged;
|
||||
|
||||
middleButtonGesture = false;
|
||||
source = undefined;
|
||||
startingState = undefined;
|
||||
visited = new WeakSet();
|
||||
engaged = false;
|
||||
|
||||
notifyActiveGroupChange(undefined);
|
||||
if (wasEngaged) listenersOfGroup(endedGroup).forEach((listener) => listener.engagedChanged?.(false));
|
||||
if (wasEngaged) listeners.forEach((listener) => listener.engagedChanged?.(false));
|
||||
}
|
||||
|
||||
function onClickCapture(e: Event) {
|
||||
@@ -188,15 +141,6 @@ function onClickCapture(e: Event) {
|
||||
suppressNextClickFromSource = undefined;
|
||||
}
|
||||
|
||||
// Unlike a click, this isn't limited to the source, since a drag's auxclick lands on the ancestor shared by its press and release
|
||||
function onAuxClickCapture(e: MouseEvent) {
|
||||
if (!suppressNextAuxClick || e.button !== MIDDLE_BUTTON) return;
|
||||
suppressNextAuxClick = false;
|
||||
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
}
|
||||
|
||||
// Self-accepting HMR: tear down the old instance and re-create with the new module's code
|
||||
import.meta.hot?.accept((newModule) => {
|
||||
const carried = Array.from(listeners);
|
||||
|
||||
@@ -360,11 +360,15 @@ impl NodeNetwork {
|
||||
};
|
||||
let value_node_id = gen_id();
|
||||
let merged_node_id = map_ids(id, value_node_id);
|
||||
let original_location = OriginalLocation {
|
||||
let mut original_location = OriginalLocation {
|
||||
path: Some(path.to_vec()),
|
||||
dependants: vec![vec![id]],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
if let Some(path) = &mut original_location.path {
|
||||
path.push(value_node_id);
|
||||
}
|
||||
collection.insert(
|
||||
merged_node_id,
|
||||
DocumentNode {
|
||||
|
||||
@@ -63,6 +63,7 @@ fn flatten_add_expected() -> NodeNetwork {
|
||||
inputs: vec![NodeInput::value(TaggedValue::Integer(2), false)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")),
|
||||
original_location: OriginalLocation {
|
||||
path: Some(vec![NodeId(4)]),
|
||||
dependants: vec![vec![NodeId(10)]],
|
||||
..Default::default()
|
||||
},
|
||||
|
||||
@@ -72,32 +72,31 @@ impl BlendMode {
|
||||
]
|
||||
}
|
||||
|
||||
/// The subset of [`BlendMode::list()`] that is supported by SVG.
|
||||
pub fn list_svg_subset() -> [&'static [BlendMode]; 6] {
|
||||
use BlendMode::*;
|
||||
[
|
||||
// Normal group
|
||||
&[Normal],
|
||||
// Darken group
|
||||
&[Darken, Multiply, ColorBurn],
|
||||
// Lighten group
|
||||
&[Lighten, Screen, ColorDodge],
|
||||
// Contrast group
|
||||
&[Overlay, SoftLight, HardLight],
|
||||
// Inversion group
|
||||
&[Difference, Exclusion],
|
||||
// Component group
|
||||
&[Hue, Saturation, Color, Luminosity],
|
||||
]
|
||||
}
|
||||
|
||||
pub fn index_in_list(&self) -> Option<usize> {
|
||||
Self::list().iter().flat_map(|x| x.iter()).position(|&blend_mode| blend_mode == *self)
|
||||
}
|
||||
|
||||
/// Whether a layer in this mode reads what lies beneath it to blend, since neither SVG's `mix-blend-mode` nor Vello's layers have the mode.
|
||||
/// The alpha-only utility modes, hidden from the list, draw layers normally.
|
||||
pub fn reads_backdrop(&self) -> bool {
|
||||
self.to_svg_style_name().is_none() && !matches!(self, BlendMode::Erase | BlendMode::Restore | BlendMode::MultiplyAlpha)
|
||||
}
|
||||
|
||||
/// Whether a paint's strength (an effect's opacity, or a layer's fill) moves its color toward the mode's neutral color, which then blends at full strength, rather than fading the blend, for PSD interop.
|
||||
pub fn strength_moves_toward_neutral(&self) -> bool {
|
||||
use BlendMode::*;
|
||||
matches!(self, ColorDodge | LinearDodge | ColorBurn | LinearBurn | VividLight | LinearLight | HardMix)
|
||||
}
|
||||
|
||||
/// Whether a layer's fill moves its content toward the mode's neutral color (see [`Self::strength_moves_toward_neutral`]) rather than fading it, for PSD interop.
|
||||
/// The layer then reads what lies beneath it to blend (see [`Self::layer_reads_backdrop`]).
|
||||
pub fn fill_moves_layer_toward_neutral(&self) -> bool {
|
||||
self.strength_moves_toward_neutral()
|
||||
}
|
||||
|
||||
/// Whether a layer in this mode at this `fill` reads what lies beneath it to blend: in a mode neither SVG's `mix-blend-mode` nor Vello's layers have,
|
||||
/// or below a full fill moving it toward the mode's neutral color, which Color Dodge and Color Burn layers otherwise blend natively without.
|
||||
pub fn layer_reads_backdrop(&self, fill: f32) -> bool {
|
||||
self.reads_backdrop() || (fill < 1. && self.fill_moves_layer_toward_neutral())
|
||||
pub fn index_in_list_svg_subset(&self) -> Option<usize> {
|
||||
Self::list_svg_subset().iter().flat_map(|x| x.iter()).position(|&blend_mode| blend_mode == *self)
|
||||
}
|
||||
|
||||
/// Convert the enum to the CSS string for the blend mode.
|
||||
@@ -131,14 +130,11 @@ impl BlendMode {
|
||||
}
|
||||
|
||||
/// Renders the blend mode CSS style declaration.
|
||||
/// A mode CSS lacks, which layers read what lies beneath to blend by, draws normally where nothing beneath can be read, as for content without bounds.
|
||||
pub fn render(&self) -> String {
|
||||
format!(
|
||||
r#" mix-blend-mode: {};"#,
|
||||
self.to_svg_style_name().unwrap_or_else(|| {
|
||||
if !self.reads_backdrop() {
|
||||
log::warn!("Unsupported blend mode {self:?}");
|
||||
}
|
||||
log::warn!("Unsupported blend mode {self:?}");
|
||||
"normal"
|
||||
})
|
||||
)
|
||||
@@ -160,7 +156,7 @@ impl Display for BlendMode {
|
||||
BlendMode::Lighten => write!(f, "Lighten"),
|
||||
BlendMode::Screen => write!(f, "Screen"),
|
||||
BlendMode::ColorDodge => write!(f, "Color Dodge"),
|
||||
BlendMode::LinearDodge => write!(f, "Linear Dodge (Add)"),
|
||||
BlendMode::LinearDodge => write!(f, "Linear Dodge"),
|
||||
BlendMode::LighterColor => write!(f, "Lighter Color"),
|
||||
// Contrast group
|
||||
BlendMode::Overlay => write!(f, "Overlay"),
|
||||
@@ -251,30 +247,6 @@ pub fn apply_blend_mode(foreground: Color, background: Color, blend_mode: BlendM
|
||||
}
|
||||
}
|
||||
|
||||
/// How strongly a layer whose fill moves it toward neutral (see [`BlendMode::fill_moves_layer_toward_neutral`]) shows over a backdrop of `backdrop_alpha`: fully over an opaque one,
|
||||
/// by its `fill` over nothing, and between, the harmonic mean of the two weighted by that alpha, which shows nothing at no fill.
|
||||
pub fn layer_fill_shown(backdrop_alpha: f32, fill: f32) -> f32 {
|
||||
let weighted = (1. - backdrop_alpha) + backdrop_alpha * fill;
|
||||
if weighted <= 0. { 0. } else { (fill / weighted).min(1.) }
|
||||
}
|
||||
|
||||
/// Like [`apply_blend_mode`], with the foreground at `strength` (from 0 to 1) moved toward the mode's neutral color where it does that (see [`BlendMode::strength_moves_toward_neutral`]),
|
||||
/// for the caller to composite at full strength. Other modes take the foreground as it is, for the caller to fade the blend by the strength.
|
||||
pub fn apply_blend_mode_at_strength(foreground: Color, background: Color, blend_mode: BlendMode, strength: f32) -> Color {
|
||||
let toward = |neutral: f32| {
|
||||
let moved = |channel: f32| neutral + strength * (channel - neutral);
|
||||
Color::from_rgbaf32_unchecked(moved(foreground.r()), moved(foreground.g()), moved(foreground.b()), foreground.a())
|
||||
};
|
||||
|
||||
match blend_mode {
|
||||
BlendMode::ColorDodge | BlendMode::LinearDodge => apply_blend_mode(toward(0.), background, blend_mode),
|
||||
BlendMode::ColorBurn | BlendMode::LinearBurn => apply_blend_mode(toward(1.), background, blend_mode),
|
||||
BlendMode::VividLight | BlendMode::LinearLight => apply_blend_mode(toward(0.5), background, blend_mode),
|
||||
BlendMode::HardMix => background.blend_rgb(foreground, |backdrop, source| Color::blend_hard_mix_at_strength(backdrop, source, strength)),
|
||||
_ => apply_blend_mode(foreground, background, blend_mode),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -289,13 +261,9 @@ mod tests {
|
||||
assert_eq!(Color::blend_color_burn(0.5, source), 0., "a source of {source}");
|
||||
}
|
||||
|
||||
// Color Dodge, like Divide, keeps a black backdrop black under any source, even white, and turns any other white under a white source.
|
||||
// Divide also turns any other white under a black source.
|
||||
for backdrop in [0., 1e-7, -1e-7] {
|
||||
assert_eq!(Color::blend_color_dodge(backdrop, 1.), 0., "a backdrop of {backdrop}");
|
||||
}
|
||||
// Color Dodge gives white for a white source, and Divide keeps a black backdrop black and turns any other white under a black source
|
||||
for source in [1., 1. - 1e-7, 1. + 2e-7] {
|
||||
assert_eq!(Color::blend_color_dodge(0.5, source), 1., "a source of {source}");
|
||||
assert_eq!(Color::blend_color_dodge(0., source), 1., "a source of {source}");
|
||||
}
|
||||
for backdrop in [0., 1e-7, -1e-7] {
|
||||
assert_eq!(Color::blend_divide(backdrop, 0.5), 0., "a backdrop of {backdrop}");
|
||||
@@ -371,65 +339,6 @@ mod tests {
|
||||
assert!((blended.a() - 1.).abs() < 1e-5, "alpha was {}", blended.a());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn darker_and_lighter_color_pick_the_whole_color_by_luma() {
|
||||
// Blue's luma (0.11) is below the gray's (0.3), though its mean channel (a third) is above it
|
||||
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
|
||||
let gray = Color::from_rgbaf32_unchecked(0.3, 0.3, 0.3, 1.);
|
||||
|
||||
assert_eq!(apply_blend_mode(gray, blue, BlendMode::DarkerColor), blue);
|
||||
assert_eq!(apply_blend_mode(gray, blue, BlendMode::LighterColor), gray);
|
||||
assert_eq!(apply_blend_mode(blue, gray, BlendMode::DarkerColor), blue);
|
||||
|
||||
// Where the lumas tie, the backdrop stays, with the paint's alpha
|
||||
let tied = Color::from_rgbaf32_unchecked(0.3, 0.3, 0.3, 0.5);
|
||||
assert_eq!(apply_blend_mode(tied, gray, BlendMode::DarkerColor), gray.with_alpha(0.5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hard_mix_ramps_steeper_with_strength_to_a_256th_wide_where_the_channels_sum_to_one() {
|
||||
let hard_mix = |backdrop: f32, source: f32, strength: f32| Color::blend_hard_mix_at_strength(backdrop, source, strength).clamp(0., 1.);
|
||||
|
||||
// At full strength, white past a sum of 1 and black short of it, even a level away
|
||||
assert_eq!(hard_mix(0.6, 0.5, 1.), 1.);
|
||||
assert_eq!(hard_mix(0.5, 0.49, 1.), 0.);
|
||||
assert_eq!(hard_mix(0.5, 0.51, 1.), 1.);
|
||||
|
||||
// For PSD interop, half a fill gives clamp(2b - 1 + s), and no strength leaves the backdrop as it is
|
||||
for (backdrop, source) in [(0.5, 0.3), (0.4, 0.4), (0.7, 0.1)] {
|
||||
let half = hard_mix(backdrop, source, 128. / 255.);
|
||||
assert!((half - (2. * backdrop - 1. + source).clamp(0., 1.)).abs() < 0.01, "{backdrop}, {source}: {half}");
|
||||
assert_eq!(hard_mix(backdrop, source, 0.), backdrop);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strength_moves_a_paint_toward_the_modes_neutral_color() {
|
||||
let backdrop = Color::from_rgbaf32_unchecked(0.4, 0.4, 0.4, 1.);
|
||||
let paint = Color::from_rgbaf32_unchecked(0.8, 0.8, 0.8, 1.);
|
||||
let at_half = |blend_mode: BlendMode| apply_blend_mode_at_strength(paint, backdrop, blend_mode, 0.5).r();
|
||||
|
||||
// Half the paint added, the paint halfway to white burned in, and the paint halfway to middle gray lighting
|
||||
assert!((at_half(BlendMode::LinearDodge) - 0.8).abs() < 1e-6, "{}", at_half(BlendMode::LinearDodge));
|
||||
assert!((at_half(BlendMode::LinearBurn) - 0.3).abs() < 1e-6, "{}", at_half(BlendMode::LinearBurn));
|
||||
assert!((at_half(BlendMode::LinearLight) - 0.7).abs() < 1e-6, "{}", at_half(BlendMode::LinearLight));
|
||||
|
||||
// The modes whose strength fades their blend take the paint as it is
|
||||
assert_eq!(at_half(BlendMode::Subtract), apply_blend_mode(paint, backdrop, BlendMode::Subtract).r());
|
||||
|
||||
// Layers read what lies beneath for the ten modes CSS lacks, of which five move their content toward neutral by their fill
|
||||
let reading: Vec<BlendMode> = BlendMode::list().into_iter().flatten().copied().filter(BlendMode::reads_backdrop).collect();
|
||||
assert_eq!(reading.len(), 10);
|
||||
assert_eq!(reading.iter().filter(|blend_mode| blend_mode.fill_moves_layer_toward_neutral()).count(), 5);
|
||||
assert!(!BlendMode::Erase.reads_backdrop());
|
||||
|
||||
// Color Dodge and Color Burn do too below a full fill, which they otherwise blend natively at
|
||||
for blend_mode in [BlendMode::ColorDodge, BlendMode::ColorBurn] {
|
||||
assert!(!blend_mode.reads_backdrop() && !blend_mode.layer_reads_backdrop(1.) && blend_mode.layer_reads_backdrop(0.5) && blend_mode.layer_reads_backdrop(0.));
|
||||
}
|
||||
assert!(!BlendMode::Multiply.layer_reads_backdrop(0.5) && BlendMode::LinearBurn.layer_reads_backdrop(1.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_over_weights_straight_colors_by_alpha() {
|
||||
let over = Color::from_rgbaf32_unchecked(1., 0., 0., 0.5);
|
||||
|
||||
@@ -633,20 +633,14 @@ impl Color {
|
||||
c_b + c_s - 1.
|
||||
}
|
||||
|
||||
/// Whole-color "Darker Color" blend: keeps whichever color has the lower luma (0.3 R + 0.59 G + 0.11 B), this one where they tie, with `other`'s alpha.
|
||||
/// Whole-color "Darker Color" blend: keeps whichever color has the lower mean RGB, with `other`'s alpha.
|
||||
#[inline(always)]
|
||||
pub fn blend_darker_color(&self, other: Color) -> Color {
|
||||
let darker = if self.blend_luma() <= other.blend_luma() { *self } else { other };
|
||||
let darker = if self.average_rgb_channels() <= other.average_rgb_channels() { *self } else { other };
|
||||
|
||||
darker.with_alpha(other.alpha)
|
||||
}
|
||||
|
||||
/// The luma that Darker Color and Lighter Color compare, as the component blend modes measure it.
|
||||
#[inline(always)]
|
||||
fn blend_luma(&self) -> f32 {
|
||||
luma_rec_601_rounded(self.red, self.green, self.blue)
|
||||
}
|
||||
|
||||
/// Per-channel "Screen" blend.
|
||||
#[inline(always)]
|
||||
pub fn blend_screen(c_b: f32, c_s: f32) -> f32 {
|
||||
@@ -659,16 +653,10 @@ impl Color {
|
||||
c_s.max(c_b)
|
||||
}
|
||||
|
||||
/// Per-channel "Color Dodge" blend, where a black backdrop stays black and any other turns white under a white source, as the W3C formula orders them.
|
||||
/// Per-channel "Color Dodge" blend.
|
||||
#[inline(always)]
|
||||
pub fn blend_color_dodge(c_b: f32, c_s: f32) -> f32 {
|
||||
if c_b.abs() <= BLEND_EDGE_TOLERANCE {
|
||||
0.
|
||||
} else if (c_s - 1.).abs() <= BLEND_EDGE_TOLERANCE {
|
||||
1.
|
||||
} else {
|
||||
(c_b / (1. - c_s)).min(1.)
|
||||
}
|
||||
if (c_s - 1.).abs() <= BLEND_EDGE_TOLERANCE { 1. } else { (c_b / (1. - c_s)).min(1.) }
|
||||
}
|
||||
|
||||
/// Per-channel "Linear Dodge" (Add) blend.
|
||||
@@ -677,10 +665,10 @@ impl Color {
|
||||
c_b + c_s
|
||||
}
|
||||
|
||||
/// Whole-color "Lighter Color" blend: keeps whichever color has the higher luma (0.3 R + 0.59 G + 0.11 B), this one where they tie, with `other`'s alpha.
|
||||
/// Whole-color "Lighter Color" blend: keeps whichever color has the higher mean RGB, with `other`'s alpha.
|
||||
#[inline(always)]
|
||||
pub fn blend_lighter_color(&self, other: Color) -> Color {
|
||||
let lighter = if self.blend_luma() >= other.blend_luma() { *self } else { other };
|
||||
let lighter = if self.average_rgb_channels() >= other.average_rgb_channels() { *self } else { other };
|
||||
|
||||
lighter.with_alpha(other.alpha)
|
||||
}
|
||||
@@ -736,15 +724,9 @@ impl Color {
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-channel "Hard Mix" blend: white where the channels sum to at least 1 and black below, along a ramp a 256th wide at full strength, for PSD interop.
|
||||
/// Per-channel "Hard Mix" blend: thresholds Linear Light at 0.5.
|
||||
pub fn blend_hard_mix(c_b: f32, c_s: f32) -> f32 {
|
||||
Color::blend_hard_mix_at_strength(c_b, c_s, 1.)
|
||||
}
|
||||
|
||||
/// Per-channel "Hard Mix" blend of a paint at `strength` (from 0 to 1), unclamped, whose ramp steepens from none (the backdrop as it is) to a 256th wide at full strength, for PSD interop.
|
||||
pub fn blend_hard_mix_at_strength(c_b: f32, c_s: f32, strength: f32) -> f32 {
|
||||
let steepness = 255. * strength / 256.;
|
||||
(c_b - steepness * (1. - c_s)) / (1. - steepness)
|
||||
if Color::blend_linear_light(c_b, c_s) < 0.5 { 0. } else { 1. }
|
||||
}
|
||||
|
||||
/// Per-channel "Difference" blend.
|
||||
|
||||
@@ -74,14 +74,10 @@ pub struct EffectLayers {
|
||||
|
||||
impl EffectLayers {
|
||||
/// The layers of content drawn with `blend_mode` and faded by `fill` through `effects`, or with every effect flattened if not `layered`, as for content clipped by a mask.
|
||||
/// Content in a mode CSS lacks reads what lies beneath to blend by it (see [`BlendMode::reads_backdrop`]), but the alpha-only utility modes are planned as normal.
|
||||
/// Content in a mode CSS lacks is drawn normally, so it's planned that way.
|
||||
pub fn plan(effects: &Effects, blend_mode: BlendMode, fill: f32, layered: bool) -> Self {
|
||||
let operations: Vec<EffectOperation> = effects.operations().collect();
|
||||
let blend_mode = if blend_mode.to_svg_style_name().is_some() || blend_mode.reads_backdrop() {
|
||||
blend_mode
|
||||
} else {
|
||||
BlendMode::Normal
|
||||
};
|
||||
let blend_mode = if blend_mode.to_svg_style_name().is_some() { blend_mode } else { BlendMode::Normal };
|
||||
|
||||
// Normal content at full fill hides what lies beneath its share, so its interior pieces blend with it alone, in any mode, within its own layer.
|
||||
// A Blend If fading the content by its colors acts as a fill below full wherever it hides any.
|
||||
@@ -230,20 +226,9 @@ impl EffectLayers {
|
||||
planned
|
||||
}
|
||||
|
||||
/// Whether a layered piece, a Blend If fading the layers, or a layer's blend mode reads what lies beneath the content.
|
||||
/// Whether a layered piece, or a Blend If fading the layers, reads what lies beneath the content.
|
||||
pub fn reads_backdrop(&self) -> bool {
|
||||
self.fades_by_underlying || self.reads_around_backdrop() || self.layers.iter().any(|layer| layer.blend_mode.reads_backdrop())
|
||||
}
|
||||
|
||||
/// Whether the content's layer reads what lies beneath it to blend at the content's `fill` (see [`BlendMode::layer_reads_backdrop`]).
|
||||
/// Color Dodge and Color Burn blend natively instead over a piece beneath the content it doesn't knock out, which what lies beneath the item leaves out.
|
||||
pub fn content_reads_backdrop(&self, fill: f32) -> bool {
|
||||
let Some(content_layer) = self.content_layer() else { return false };
|
||||
let blend_mode = self.layers[content_layer].blend_mode;
|
||||
|
||||
let shown_beneath = |part: &LayerPart| matches!(part, LayerPart::Piece(piece) if piece.place == PiecePlace::Beneath && !piece.knocks_out);
|
||||
let pieces_show_beneath = self.layers[..content_layer].iter().flat_map(|layer| &layer.parts).any(shown_beneath);
|
||||
blend_mode.reads_backdrop() || (blend_mode.layer_reads_backdrop(fill) && !pieces_show_beneath)
|
||||
self.fades_by_underlying || self.reads_around_backdrop()
|
||||
}
|
||||
|
||||
/// Whether a layered piece reads what lies around each pixel beneath the content, as a background blur does, where a Blend If reads only the pixel itself.
|
||||
@@ -313,30 +298,20 @@ impl EffectLayers {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether any of the effects reads what lies beneath the content, like a background blur, or may, like a shadow in a mode CSS lacks.
|
||||
/// Whether any of the effects reads what lies beneath the content, like a background blur.
|
||||
pub fn effects_read_backdrop(effects: &Effects) -> bool {
|
||||
effects.operations().any(|operation| match &operation {
|
||||
EffectOperation::BackgroundBlur { .. } => !operation.changes_nothing(),
|
||||
EffectOperation::BlendIf(ranges) => !ranges.underlying.show_everything(),
|
||||
_ => {
|
||||
!operation.changes_nothing()
|
||||
&& pieces(0, &operation)
|
||||
.iter()
|
||||
.any(|(piece, blend_mode)| piece.place == PiecePlace::Beneath && blend_mode.reads_backdrop())
|
||||
}
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether an effect row can draw as layered pieces, rather than being carried out within the content's image.
|
||||
/// Blurs, adjustments, masks, and feathers process the pixels of everything before them. A piece in a mode CSS lacks reads what lies beneath the item to blend, so only one beneath the content
|
||||
/// can, though interior pieces that `blend_into_content` blend with the content alone, which the renderers do themselves.
|
||||
/// Blurs, adjustments, masks, and feathers process the pixels of everything before them, and blend modes CSS lacks can't blend against the backdrop in SVG or a GPU layer,
|
||||
/// though interior pieces that `blend_into_content` blend with the content alone, which the renderers do themselves.
|
||||
fn can_be_layered(operation: &EffectOperation, blend_into_content: bool) -> bool {
|
||||
let layers_in = |(piece, blend_mode): (EffectPiece, BlendMode)| match piece.place {
|
||||
_ if blend_mode.to_svg_style_name().is_some() => true,
|
||||
PiecePlace::Beneath => blend_mode.reads_backdrop(),
|
||||
PiecePlace::Within => blend_into_content,
|
||||
_ => false,
|
||||
};
|
||||
let layers_in = |(piece, blend_mode): (EffectPiece, BlendMode)| blend_mode.to_svg_style_name().is_some() || (blend_into_content && piece.place == PiecePlace::Within);
|
||||
!is_pixel_filter(operation) && pieces(0, operation).into_iter().all(layers_in)
|
||||
}
|
||||
|
||||
@@ -492,7 +467,7 @@ fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendM
|
||||
| EffectOperation::MinimumMaximum { .. }
|
||||
| EffectOperation::Sharpen { .. }
|
||||
| EffectOperation::HighPass { .. }
|
||||
| EffectOperation::Speckle { .. }
|
||||
| EffectOperation::AddNoise { .. }
|
||||
| EffectOperation::Dissolve { .. }
|
||||
| EffectOperation::BlendIf(_)
|
||||
| EffectOperation::Adjustment(_) => Vec::new(),
|
||||
@@ -587,11 +562,9 @@ mod tests {
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Overlay, 1., true);
|
||||
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Overlay, BlendMode::Screen, BlendMode::Normal]);
|
||||
|
||||
// Content in a mode CSS lacks reads what lies beneath to blend by it, and an interior piece blending within the content's layer may take one too
|
||||
// A mode CSS lacks is drawn normally, so it's planned that way, and an interior piece blending within the content's layer may take one too
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::LinearBurn, 1., true);
|
||||
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::LinearBurn, BlendMode::Screen, BlendMode::Normal]);
|
||||
assert!(layers.reads_backdrop() && !layers.reads_around_backdrop());
|
||||
assert!(!EffectLayers::plan(&effects, BlendMode::Overlay, 1., true).reads_backdrop());
|
||||
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]);
|
||||
let linear_burn = Effects::from_operations([drop_shadow(red, BlendMode::Multiply), inner_shadow(red, BlendMode::LinearBurn)]);
|
||||
assert_eq!(EffectLayers::plan(&linear_burn, BlendMode::Normal, 1., true).flattened, 0);
|
||||
assert_eq!(EffectLayers::plan(&linear_burn, BlendMode::Normal, 0.5, true).flattened, 2);
|
||||
@@ -674,11 +647,14 @@ mod tests {
|
||||
let layers = EffectLayers::plan(&Effects::from_operations([with_knockout(true), inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(parts(&layers)[0], [Some((1, 0, PiecePlace::Through { over: false }))]);
|
||||
|
||||
// One flattened before an interior piece in a mode CSS lacks covers it too
|
||||
let flattening = [with_knockout(false), inner_shadow(red, BlendMode::LinearBurn), inner_shadow(red, BlendMode::Screen)];
|
||||
let layers = EffectLayers::plan(&Effects::from_operations(flattening), BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(layers.flattened, 2);
|
||||
assert_eq!(parts(&layers)[1], [Some((2, 0, through_over))]);
|
||||
// One flattened for a mode CSS lacks covers it too
|
||||
let mut flattened_shadow = with_knockout(false);
|
||||
if let EffectOperation::DropShadow { blend_mode, .. } = &mut flattened_shadow {
|
||||
*blend_mode = BlendMode::LinearBurn;
|
||||
}
|
||||
let layers = EffectLayers::plan(&Effects::from_operations([flattened_shadow, inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(layers.flattened, 1);
|
||||
assert_eq!(parts(&layers)[1], [Some((1, 0, through_over))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -785,14 +761,9 @@ mod tests {
|
||||
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (2, 2..2));
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false);
|
||||
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (5, 5..5));
|
||||
let unmerged = Effects::from_operations([
|
||||
drop_shadow(RED, BlendMode::Multiply),
|
||||
inner_shadow(RED, BlendMode::LinearBurn),
|
||||
drop_shadow(RED, BlendMode::Multiply),
|
||||
mask(),
|
||||
]);
|
||||
let layers = EffectLayers::plan(&unmerged, BlendMode::Normal, 0.5, true);
|
||||
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (4, 4..4));
|
||||
let unmerged = Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn), drop_shadow(RED, BlendMode::Multiply), mask()]);
|
||||
let layers = EffectLayers::plan(&unmerged, BlendMode::Normal, 1., true);
|
||||
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (3, 3..3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -809,23 +780,19 @@ mod tests {
|
||||
assert_eq!(layers.flattened, 2);
|
||||
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]);
|
||||
|
||||
// An interior piece in a mode CSS lacks, which would read the content beneath it, flattens what's before it, where one beneath the content takes a layer of its own
|
||||
let effects = Effects::from_operations([inner_shadow(RED, BlendMode::Screen), inner_shadow(RED, BlendMode::LinearBurn), inner_shadow(RED, BlendMode::Multiply)]);
|
||||
let effects = Effects::from_operations([inner_shadow(RED, BlendMode::Screen), drop_shadow(RED, BlendMode::LinearBurn), inner_shadow(RED, BlendMode::Multiply)]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(layers.flattened, 2);
|
||||
let layers = EffectLayers::plan(&Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn)]), BlendMode::Normal, 0.5, true);
|
||||
assert_eq!((layers.flattened, modes(&layers)), (0, vec![BlendMode::LinearBurn, BlendMode::Normal]));
|
||||
assert!(layers.reads_backdrop());
|
||||
|
||||
// A flattened shadow left unmerged by a blur would cover the layered shadow after it, so everything flattens
|
||||
let effects = Effects::from_operations([drop_shadow(RED, BlendMode::Multiply), inner_shadow(RED, BlendMode::LinearBurn), drop_shadow(RED, BlendMode::Multiply)]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(layers.flattened, 3);
|
||||
let effects = Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn), drop_shadow(RED, BlendMode::Multiply)]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true);
|
||||
assert_eq!(layers.flattened, 2);
|
||||
assert_eq!(modes(&layers), [BlendMode::Normal]);
|
||||
|
||||
// Clipped content flattens everything
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, false);
|
||||
assert_eq!(layers.flattened, 3);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false);
|
||||
assert_eq!(layers.flattened, 2);
|
||||
assert_eq!(parts(&layers), [[None]]);
|
||||
}
|
||||
|
||||
|
||||
@@ -65,7 +65,7 @@ pub enum EffectKind {
|
||||
/// Keeps how much each pixel differs from a blur of those around it, around middle gray.
|
||||
HighPass,
|
||||
/// Scatters random offsets across the colors, fixed in place on the content.
|
||||
Speckle,
|
||||
AddNoise,
|
||||
/// Shows a random scattering of the content fully opaque and hides the rest, more where it's more opaque.
|
||||
Dissolve,
|
||||
/// Smears the content along a line, as if it moved while being captured.
|
||||
@@ -139,7 +139,7 @@ impl std::fmt::Display for EffectKind {
|
||||
Self::MinimumMaximum => "Minimum/Maximum",
|
||||
Self::Sharpen => "Sharpen",
|
||||
Self::HighPass => "High Pass",
|
||||
Self::Speckle => "Speckle",
|
||||
Self::AddNoise => "Add Noise",
|
||||
Self::Dissolve => "Dissolve",
|
||||
Self::MotionBlur => "Motion Blur",
|
||||
Self::RadialBlur => "Radial Blur",
|
||||
@@ -1099,7 +1099,7 @@ pub enum EffectOperation {
|
||||
HighPass {
|
||||
radius: f64,
|
||||
},
|
||||
Speckle {
|
||||
AddNoise {
|
||||
/// Percent of full brightness.
|
||||
amount: f64,
|
||||
distribution: NoiseDistribution,
|
||||
@@ -1289,7 +1289,7 @@ impl EffectOperation {
|
||||
Self::MinimumMaximum { .. } => EffectKind::MinimumMaximum,
|
||||
Self::Sharpen { .. } => EffectKind::Sharpen,
|
||||
Self::HighPass { .. } => EffectKind::HighPass,
|
||||
Self::Speckle { .. } => EffectKind::Speckle,
|
||||
Self::AddNoise { .. } => EffectKind::AddNoise,
|
||||
Self::Dissolve { .. } => EffectKind::Dissolve,
|
||||
Self::MotionBlur { .. } => EffectKind::MotionBlur,
|
||||
Self::RadialBlur { .. } => EffectKind::RadialBlur,
|
||||
@@ -1383,7 +1383,7 @@ impl EffectOperation {
|
||||
Self::Feather { distance } => *distance <= 0.,
|
||||
Self::ConvolutionKernel { .. } => self.convolution().is_none(),
|
||||
Self::Emboss { .. } | Self::FindEdges | Self::HighPass { .. } | Self::Dissolve { .. } | Self::Adjustment(_) => false,
|
||||
Self::Speckle { amount, .. } => *amount <= 0.,
|
||||
Self::AddNoise { amount, .. } => *amount <= 0.,
|
||||
// The four neighbors lie a fixed distance away, so only the blur needs a radius
|
||||
Self::Sharpen { amount, radius, edges_only, .. } => *amount <= 0. || (!*edges_only && *radius <= 0.),
|
||||
Self::MinimumMaximum { radius, .. } => *radius <= 0.,
|
||||
@@ -1423,7 +1423,7 @@ impl EffectOperation {
|
||||
| Self::Outline { .. }
|
||||
| Self::BevelAndEmboss { .. }
|
||||
| Self::Feather { .. } => false,
|
||||
Self::PaintOverlay { .. } | Self::Mask { .. } | Self::BackgroundBlur { .. } | Self::Speckle { .. } | Self::Dissolve { .. } | Self::BlendIf(_) | Self::Adjustment(_) => false,
|
||||
Self::PaintOverlay { .. } | Self::Mask { .. } | Self::BackgroundBlur { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::BlendIf(_) | Self::Adjustment(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1491,7 +1491,7 @@ impl EffectOperation {
|
||||
Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } => self.displacement_reach() + 1.,
|
||||
// Within the frame they paint the content's own cells or dots, reading a cell's or a dot's area around each point there, which `Effects::source_region` finds
|
||||
Self::Pixelate { .. } | Self::ColorHalftone { .. } => 0.,
|
||||
Self::PaintOverlay { .. } | Self::Speckle { .. } | Self::Dissolve { .. } | Self::BlendIf(_) | Self::Adjustment(_) => 0.,
|
||||
Self::PaintOverlay { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::BlendIf(_) | Self::Adjustment(_) => 0.,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1578,7 +1578,7 @@ impl EffectOperation {
|
||||
Self::Emboss { angle, height, amount } => [angle, height, amount].into_iter().for_each(finite),
|
||||
Self::MinimumMaximum { radius, .. } | Self::HighPass { radius } => finite(radius),
|
||||
Self::Sharpen { amount, radius, threshold, .. } => [amount, radius, threshold].into_iter().for_each(finite),
|
||||
Self::Speckle { amount, .. } => finite(amount),
|
||||
Self::AddNoise { amount, .. } => finite(amount),
|
||||
Self::Dissolve { opacity, .. } => finite(opacity),
|
||||
Self::MotionBlur { angle, distance, .. } => [angle, distance].into_iter().for_each(finite),
|
||||
Self::RadialBlur { amount, transform, .. } => {
|
||||
@@ -1754,7 +1754,7 @@ impl EffectOperation {
|
||||
edges_only: false,
|
||||
},
|
||||
EffectKind::HighPass => Self::HighPass { radius: 0. },
|
||||
EffectKind::Speckle => Self::Speckle {
|
||||
EffectKind::AddNoise => Self::AddNoise {
|
||||
amount: 0.,
|
||||
distribution: NoiseDistribution::default(),
|
||||
monochromatic: false,
|
||||
@@ -2100,7 +2100,7 @@ impl EffectOperation {
|
||||
visitor.parameter("edges_only", edges_only, false);
|
||||
}
|
||||
Self::HighPass { radius } => visitor.parameter("radius", radius, 10.),
|
||||
Self::Speckle {
|
||||
Self::AddNoise {
|
||||
amount,
|
||||
distribution,
|
||||
monochromatic,
|
||||
@@ -2404,7 +2404,7 @@ mod tests {
|
||||
threshold: 0.,
|
||||
edges_only: true,
|
||||
},
|
||||
EffectOperation::Speckle {
|
||||
EffectOperation::AddNoise {
|
||||
amount: 40.,
|
||||
distribution: NoiseDistribution::Gaussian,
|
||||
monochromatic: true,
|
||||
|
||||
@@ -166,7 +166,7 @@ pub fn is_filter(operation: &EffectOperation) -> bool {
|
||||
| EffectOperation::MinimumMaximum { .. }
|
||||
| EffectOperation::Sharpen { .. }
|
||||
| EffectOperation::HighPass { .. }
|
||||
| EffectOperation::Speckle { .. }
|
||||
| EffectOperation::AddNoise { .. }
|
||||
| EffectOperation::Dissolve { .. }
|
||||
)
|
||||
}
|
||||
@@ -178,7 +178,7 @@ pub fn reads_neighbors(operation: &EffectOperation) -> bool {
|
||||
|
||||
/// Whether the operation is a pixel filter combining each pixel with a random field fixed to the content, which changes endless content as much as any other.
|
||||
pub fn is_random_field_filter(operation: &EffectOperation) -> bool {
|
||||
matches!(operation, EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. })
|
||||
matches!(operation, EffectOperation::AddNoise { .. } | EffectOperation::Dissolve { .. })
|
||||
}
|
||||
|
||||
/// Whether any of the effects is a pixel filter reading the pixels around each one that changes something, which reads endless content over the area in view.
|
||||
@@ -277,7 +277,7 @@ pub fn fill_shifts(reach: i32) -> Vec<[i32; 2]> {
|
||||
shifts
|
||||
}
|
||||
|
||||
/// How the random offsets Speckle gives the colors are spread.
|
||||
/// How the random offsets Add Noise gives the colors are spread.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
@@ -296,7 +296,7 @@ pub const GAUSSIAN_NOISE_LIMIT: f32 = 3.5;
|
||||
/// The random fields a seed gives, each hashed apart so the fields of one seed are unrelated.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum RandomField {
|
||||
/// Speckle's offset for each color, or for Gaussian noise its first uniform value.
|
||||
/// Add Noise's offset for each color, or for Gaussian noise its first uniform value.
|
||||
NoiseOffsets,
|
||||
/// Gaussian noise's second uniform value for each color, its angle.
|
||||
NoiseAngles,
|
||||
@@ -320,7 +320,7 @@ impl RandomField {
|
||||
}
|
||||
}
|
||||
|
||||
/// The largest offset Speckle of `amount` (a fraction) gives a color, as a fraction of full brightness, past which every color would be pushed to black or white anyway.
|
||||
/// The largest offset Add Noise of `amount` (a fraction) gives a color, as a fraction of full brightness, past which every color would be pushed to black or white anyway.
|
||||
pub fn noise_extent(amount: f64, distribution: NoiseDistribution) -> f64 {
|
||||
let deviations = match distribution {
|
||||
NoiseDistribution::Uniform => 1.,
|
||||
|
||||
@@ -1743,7 +1743,7 @@ impl EffectOperation {
|
||||
| Self::MinimumMaximum { .. }
|
||||
| Self::Sharpen { .. }
|
||||
| Self::HighPass { .. }
|
||||
| Self::Speckle { .. }
|
||||
| Self::AddNoise { .. }
|
||||
| Self::Dissolve { .. }
|
||||
| Self::BackgroundBlur { .. }
|
||||
| Self::BlendIf(_)
|
||||
|
||||
@@ -27,12 +27,12 @@ pub fn filter(plane: Plane<[f32; 4]>, full: Option<&Plane<[f32; 4]>>, operation:
|
||||
match *operation {
|
||||
EffectOperation::FindEdges => find_edges(&plane, document_to_pixels),
|
||||
EffectOperation::MinimumMaximum { radius, mode } => neighborhood_extreme(&plane, radius, mode == MinimumMaximumMode::Maximum, document_to_pixels),
|
||||
EffectOperation::Speckle {
|
||||
EffectOperation::AddNoise {
|
||||
amount,
|
||||
distribution,
|
||||
monochromatic,
|
||||
seed,
|
||||
} => speckle(&plane, amount / 100., distribution, monochromatic, seed, pixels_to_effect),
|
||||
} => add_noise(&plane, amount / 100., distribution, monochromatic, seed, pixels_to_effect),
|
||||
EffectOperation::Dissolve { opacity, seed } => dissolve(&plane, opacity / 100., seed, pixels_to_effect),
|
||||
_ => plane,
|
||||
}
|
||||
@@ -511,7 +511,7 @@ fn noise_at(sampling: &FieldSampling, pixel: [usize; 2], distribution: NoiseDist
|
||||
|
||||
/// For PSD interop, each straight color offset by noise of `amount` (a fraction of full brightness) with its `distribution`, the same for every color of a pixel if it's `monochromatic`, and clamped.
|
||||
/// The coverage is kept. The noise is fixed to the cells of the effect space, which `pixels_to_effect` places the plane's pixels among. O(width × height × samples per pixel).
|
||||
pub fn speckle(plane: &Plane<[f32; 4]>, amount: f64, distribution: NoiseDistribution, monochromatic: bool, seed: i64, pixels_to_effect: DAffine2) -> Plane<[f32; 4]> {
|
||||
pub fn add_noise(plane: &Plane<[f32; 4]>, amount: f64, distribution: NoiseDistribution, monochromatic: bool, seed: i64, pixels_to_effect: DAffine2) -> Plane<[f32; 4]> {
|
||||
let sampling = FieldSampling::new(pixels_to_effect);
|
||||
let extent = noise_extent(amount, distribution) as f32;
|
||||
let scale = (amount * sampling.deviation_scale) as f32;
|
||||
@@ -849,7 +849,7 @@ mod tests {
|
||||
let amount = 0.2;
|
||||
|
||||
// Uniform noise spreads evenly up to the amount, with a deviation of the amount over √3
|
||||
let uniform = speckle(&gray, amount, NoiseDistribution::Uniform, false, 0, DAffine2::IDENTITY);
|
||||
let uniform = add_noise(&gray, amount, NoiseDistribution::Uniform, false, 0, DAffine2::IDENTITY);
|
||||
let (mean, deviation, correlation) = offset_statistics(&uniform);
|
||||
for channel in 0..3 {
|
||||
assert!(
|
||||
@@ -861,21 +861,21 @@ mod tests {
|
||||
assert!(uniform.data.iter().all(|pixel| (pixel[0] - 0.5).abs() <= amount as f32 && pixel[3] == 1.));
|
||||
|
||||
// Gaussian noise deviates by the amount, cut off at its limit
|
||||
let gaussian = speckle(&gray, amount, NoiseDistribution::Gaussian, false, 0, DAffine2::IDENTITY);
|
||||
let gaussian = add_noise(&gray, amount, NoiseDistribution::Gaussian, false, 0, DAffine2::IDENTITY);
|
||||
let (_, deviation, _) = offset_statistics(&gaussian);
|
||||
assert!((deviation[0] / amount - 1.).abs() < 0.03, "{deviation:?}");
|
||||
|
||||
// Monochromatic noise shifts every color of a pixel together, and another seed gives other noise
|
||||
let monochromatic = speckle(&gray, amount, NoiseDistribution::Gaussian, true, 0, DAffine2::IDENTITY);
|
||||
let monochromatic = add_noise(&gray, amount, NoiseDistribution::Gaussian, true, 0, DAffine2::IDENTITY);
|
||||
assert!(monochromatic.data.iter().all(|pixel| pixel[0] == pixel[1] && pixel[1] == pixel[2]));
|
||||
let reseeded = speckle(&gray, amount, NoiseDistribution::Uniform, false, 1, DAffine2::IDENTITY);
|
||||
let reseeded = add_noise(&gray, amount, NoiseDistribution::Uniform, false, 1, DAffine2::IDENTITY);
|
||||
assert_ne!(reseeded.data[..64], uniform.data[..64]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_is_fixed_to_the_effect_spaces_cells_and_averages_where_pixels_span_several() {
|
||||
let gray = |size: usize| plane(size, size, vec![[0.5, 0.5, 0.5, 1.]; size * size]);
|
||||
let noise = |plane: &Plane<[f32; 4]>, pixels_to_effect| speckle(plane, 0.3, NoiseDistribution::Uniform, false, 4, pixels_to_effect);
|
||||
let noise = |plane: &Plane<[f32; 4]>, pixels_to_effect| add_noise(plane, 0.3, NoiseDistribution::Uniform, false, 4, pixels_to_effect);
|
||||
|
||||
// A plane placed three cells right and five down holds the same noise at the same cells
|
||||
let placed = noise(&gray(16), DAffine2::IDENTITY);
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
//! Blends a layer onto those beneath it by a blend mode, with the W3C Compositing and Blending formulas on gamma-encoded colors, as SVG and the GPU's layers blend.
|
||||
//! The modes CSS lacks, which layers read what lies beneath to blend by, take the formulas the effects share (see [`crate::blending::blend_gamma`]).
|
||||
//! The modes CSS lacks blend normally, since layers only ever take the others.
|
||||
|
||||
use crate::effect_kernels::Plane;
|
||||
use core_types::Color;
|
||||
use core_types::blending::{BlendMode, apply_blend_mode_at_strength, layer_fill_shown};
|
||||
use core_types::color::BLEND_EDGE_TOLERANCE;
|
||||
use core_types::blending::BlendMode;
|
||||
|
||||
/// The premultiplied gamma-encoded `layer` blended by the mode onto the layers `below` it. O(width × height).
|
||||
pub fn blend_layer(layer: &Plane<[f32; 4]>, below: &Plane<[f32; 4]>, blend_mode: BlendMode) -> Plane<[f32; 4]> {
|
||||
@@ -13,20 +11,6 @@ pub fn blend_layer(layer: &Plane<[f32; 4]>, below: &Plane<[f32; 4]>, blend_mode:
|
||||
|
||||
/// One premultiplied pixel blended onto another: its color mixes toward the blend of both as far as the backdrop covers it, and it then composites over the backdrop.
|
||||
pub fn blend_pixel(source: [f32; 4], backdrop: [f32; 4], blend_mode: BlendMode) -> [f32; 4] {
|
||||
blend_pixel_at_strength(source, backdrop, blend_mode, 1.)
|
||||
}
|
||||
|
||||
/// One premultiplied pixel of a layer's full-strength content blended onto another by the mode, faded by the layer's `fill`, or over the backdrop
|
||||
/// in a mode whose fill moves the content toward its neutral color (see [`BlendMode::fill_moves_layer_toward_neutral`]), moved there by it.
|
||||
pub fn blend_layer_pixel(content: [f32; 4], backdrop: [f32; 4], blend_mode: BlendMode, fill: f32) -> [f32; 4] {
|
||||
match blend_mode.fill_moves_layer_toward_neutral() {
|
||||
true => blend_pixel_at_strength(content, backdrop, blend_mode, fill),
|
||||
false => blend_pixel(content.map(|channel| channel * fill), backdrop, blend_mode),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`blend_pixel`] with the source at `strength`, which moves it toward the mode's neutral color where it blends, and shows it as strongly as [`layer_fill_shown`] gives.
|
||||
fn blend_pixel_at_strength(source: [f32; 4], backdrop: [f32; 4], blend_mode: BlendMode, strength: f32) -> [f32; 4] {
|
||||
let (source_alpha, backdrop_alpha) = (source[3], backdrop[3]);
|
||||
if source_alpha <= 0. {
|
||||
return backdrop;
|
||||
@@ -37,18 +21,14 @@ fn blend_pixel_at_strength(source: [f32; 4], backdrop: [f32; 4], blend_mode: Ble
|
||||
false => [0.; 3],
|
||||
};
|
||||
let (source_color, backdrop_color) = (straight(source), straight(backdrop));
|
||||
let blended = match strength < 1. {
|
||||
true => blend_at_strength(backdrop_color, source_color, blend_mode, strength),
|
||||
false => blend(backdrop_color, source_color, blend_mode),
|
||||
};
|
||||
let blended = blend(backdrop_color, source_color, blend_mode);
|
||||
|
||||
let shown = source_alpha * layer_fill_shown(backdrop_alpha, strength);
|
||||
let mut result = [0.; 4];
|
||||
for channel in 0..3 {
|
||||
let mixed = (1. - backdrop_alpha) * source_color[channel] + backdrop_alpha * blended[channel];
|
||||
result[channel] = shown * mixed + (1. - shown) * backdrop[channel];
|
||||
result[channel] = source_alpha * mixed + (1. - source_alpha) * backdrop[channel];
|
||||
}
|
||||
result[3] = shown + backdrop_alpha * (1. - shown);
|
||||
result[3] = source_alpha + backdrop_alpha * (1. - source_alpha);
|
||||
result
|
||||
}
|
||||
|
||||
@@ -59,22 +39,10 @@ fn blend(backdrop: [f32; 3], source: [f32; 3], blend_mode: BlendMode) -> [f32; 3
|
||||
BlendMode::Saturation => set_luminosity(set_saturation(backdrop, saturation(source)), luminosity(backdrop)),
|
||||
BlendMode::Color => set_luminosity(source, luminosity(backdrop)),
|
||||
BlendMode::Luminosity => set_luminosity(backdrop, luminosity(source)),
|
||||
blend_mode if blend_mode.reads_backdrop() => crate::blending::blend_gamma(backdrop, source, blend_mode),
|
||||
_ => [0, 1, 2].map(|channel| blend_channel(backdrop[channel], source[channel], blend_mode)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The blend of straight `backdrop` and `source` colors with the source at `strength`, moved toward the mode's neutral color (see [`apply_blend_mode_at_strength`]).
|
||||
fn blend_at_strength(backdrop: [f32; 3], source: [f32; 3], blend_mode: BlendMode, strength: f32) -> [f32; 3] {
|
||||
if !blend_mode.strength_moves_toward_neutral() {
|
||||
return blend(backdrop, source, blend_mode);
|
||||
}
|
||||
|
||||
let color = |[red, green, blue]: [f32; 3]| Color::from_rgbaf32_unchecked(red, green, blue, 1.);
|
||||
let blended = apply_blend_mode_at_strength(color(source), color(backdrop), blend_mode, strength);
|
||||
[blended.r(), blended.g(), blended.b()]
|
||||
}
|
||||
|
||||
/// The mode's blend of one channel of the backdrop and source, for the modes that blend each channel on its own.
|
||||
fn blend_channel(backdrop: f32, source: f32, blend_mode: BlendMode) -> f32 {
|
||||
let hard_light = |backdrop: f32, source: f32| match source <= 0.5 {
|
||||
@@ -88,8 +56,8 @@ fn blend_channel(backdrop: f32, source: f32, blend_mode: BlendMode) -> f32 {
|
||||
BlendMode::Overlay => hard_light(source, backdrop),
|
||||
BlendMode::Darken => backdrop.min(source),
|
||||
BlendMode::Lighten => backdrop.max(source),
|
||||
BlendMode::ColorDodge if backdrop <= BLEND_EDGE_TOLERANCE => 0.,
|
||||
BlendMode::ColorDodge if source >= 1. - BLEND_EDGE_TOLERANCE => 1.,
|
||||
BlendMode::ColorDodge if backdrop <= 0. => 0.,
|
||||
BlendMode::ColorDodge if source >= 1. => 1.,
|
||||
BlendMode::ColorDodge => (backdrop / (1. - source)).min(1.),
|
||||
BlendMode::ColorBurn if backdrop >= 1. => 1.,
|
||||
BlendMode::ColorBurn if source <= 0. => 0.,
|
||||
@@ -174,195 +142,6 @@ mod tests {
|
||||
assert!((screened[0] - (0.5 * 0.75 + 0.5 * 0.5)).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// The reference formulas, for PSD interop, for the modes CSS lacks and for Color Burn and Color Dodge, at full strength, on a channel of straight gamma-encoded `backdrop` and `source` colors.
|
||||
fn reference_formula(blend_mode: BlendMode, backdrop: [f32; 3], source: [f32; 3]) -> [f32; 3] {
|
||||
let luma = |color: [f32; 3]| 0.3 * color[0] + 0.59 * color[1] + 0.11 * color[2];
|
||||
let color_burn = |b: f32, s: f32| {
|
||||
if b >= 1. {
|
||||
1.
|
||||
} else if s <= 0. {
|
||||
0.
|
||||
} else {
|
||||
1. - ((1. - b) / s).min(1.)
|
||||
}
|
||||
};
|
||||
let color_dodge = |b: f32, s: f32| {
|
||||
if b <= 0. {
|
||||
0.
|
||||
} else if s >= 1. {
|
||||
1.
|
||||
} else {
|
||||
(b / (1. - s)).min(1.)
|
||||
}
|
||||
};
|
||||
let channels = |formula: &dyn Fn(f32, f32) -> f32| [0, 1, 2].map(|channel| formula(backdrop[channel], source[channel]).clamp(0., 1.));
|
||||
|
||||
match blend_mode {
|
||||
BlendMode::ColorBurn => channels(&color_burn),
|
||||
BlendMode::ColorDodge => channels(&color_dodge),
|
||||
BlendMode::LinearBurn => channels(&|b, s| b + s - 1.),
|
||||
BlendMode::LinearDodge => channels(&|b, s| b + s),
|
||||
BlendMode::VividLight => channels(&|b, s| if s <= 0.5 { color_burn(b, 2. * s) } else { color_dodge(b, 2. * s - 1.) }),
|
||||
BlendMode::LinearLight => channels(&|b, s| b + 2. * s - 1.),
|
||||
BlendMode::PinLight => channels(&|b, s| if s <= 0.5 { b.min(2. * s) } else { b.max(2. * s - 1.) }),
|
||||
BlendMode::HardMix => channels(&|b, s| 256. * b - 255. * (1. - s)),
|
||||
BlendMode::Subtract => channels(&|b, s| b - s),
|
||||
BlendMode::Divide => channels(&|b, s| {
|
||||
if b <= 0. {
|
||||
0.
|
||||
} else if s <= 0. {
|
||||
1.
|
||||
} else {
|
||||
b / s
|
||||
}
|
||||
}),
|
||||
BlendMode::DarkerColor => {
|
||||
if luma(source) < luma(backdrop) {
|
||||
source
|
||||
} else {
|
||||
backdrop
|
||||
}
|
||||
}
|
||||
BlendMode::LighterColor => {
|
||||
if luma(source) > luma(backdrop) {
|
||||
source
|
||||
} else {
|
||||
backdrop
|
||||
}
|
||||
}
|
||||
_ => panic!("{blend_mode} blends natively"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Pairs of a backdrop and a source color, away from Hard Mix's ramp and the lumas' ties.
|
||||
const PAIRS: [([f32; 3], [f32; 3]); 4] = [
|
||||
([0.2, 0.6, 0.45], [0.85, 0.3, 0.6]),
|
||||
([0.9, 0.1, 0.5], [0.3, 0.7, 0.2]),
|
||||
([0.55, 0.55, 0.55], [0.05, 0.95, 0.35]),
|
||||
([0., 1., 0.3], [0.6, 0.15, 0.8]),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn modes_css_lacks_take_the_reference_formulas_over_any_backdrop() {
|
||||
for blend_mode in BlendMode::list().into_iter().flatten().copied().filter(BlendMode::reads_backdrop) {
|
||||
for (backdrop, source) in PAIRS {
|
||||
let expected = reference_formula(blend_mode, backdrop, source);
|
||||
let opaque = |[red, green, blue]: [f32; 3]| [red, green, blue, 1.];
|
||||
|
||||
// Over an opaque backdrop, the source takes the formula
|
||||
let blended = blend_pixel(opaque(source), opaque(backdrop), blend_mode);
|
||||
assert!(
|
||||
(0..3).all(|channel| (blended[channel] - expected[channel]).abs() < 1e-5),
|
||||
"{blend_mode}: {blended:?} rather than {expected:?}"
|
||||
);
|
||||
|
||||
// Over one of half alpha, its color mixes halfway from its own to the formula's, as the 16 native modes do
|
||||
let half = [backdrop[0] * 0.5, backdrop[1] * 0.5, backdrop[2] * 0.5, 0.5];
|
||||
let blended = blend_pixel(opaque(source), half, blend_mode);
|
||||
for channel in 0..3 {
|
||||
let mixed = 0.5 * source[channel] + 0.5 * expected[channel];
|
||||
assert!((blended[channel] - mixed).abs() < 1e-5, "{blend_mode} over half alpha: {blended:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fills_move_the_content_toward_neutral_in_seven_modes_and_fade_it_in_the_others() {
|
||||
let fill = 0.5;
|
||||
let reading = BlendMode::list().into_iter().flatten().copied().filter(BlendMode::reads_backdrop);
|
||||
for blend_mode in reading.chain([BlendMode::ColorDodge, BlendMode::ColorBurn]) {
|
||||
for (backdrop, source) in PAIRS {
|
||||
let blended = blend_layer_pixel([source[0], source[1], source[2], 1.], [backdrop[0], backdrop[1], backdrop[2], 1.], blend_mode, fill);
|
||||
|
||||
let expected = match blend_mode {
|
||||
// The paint at full strength once moved halfway toward black, white, or middle gray
|
||||
BlendMode::ColorDodge | BlendMode::LinearDodge => reference_formula(blend_mode, backdrop, source.map(|channel| fill * channel)),
|
||||
BlendMode::ColorBurn | BlendMode::LinearBurn => reference_formula(blend_mode, backdrop, source.map(|channel| 1. - fill * (1. - channel))),
|
||||
BlendMode::VividLight | BlendMode::LinearLight => reference_formula(blend_mode, backdrop, source.map(|channel| 0.5 + fill * (channel - 0.5))),
|
||||
// A ramp a fill of half makes `clamp(2b - 1 + s)`
|
||||
BlendMode::HardMix => [0, 1, 2].map(|channel| Color::blend_hard_mix_at_strength(backdrop[channel], source[channel], fill).clamp(0., 1.)),
|
||||
// Halfway from the backdrop to the blend
|
||||
_ => {
|
||||
let full = reference_formula(blend_mode, backdrop, source);
|
||||
[0, 1, 2].map(|channel| backdrop[channel] + (full[channel] - backdrop[channel]) * fill)
|
||||
}
|
||||
};
|
||||
assert!(
|
||||
(0..3).all(|channel| (blended[channel] - expected[channel]).abs() < 1e-5),
|
||||
"{blend_mode}: {blended:?} rather than {expected:?}"
|
||||
);
|
||||
assert!((blended[3] - 1.).abs() < 1e-6, "{blend_mode} covers the opaque backdrop");
|
||||
}
|
||||
}
|
||||
|
||||
// Where nothing lies beneath, the fill fades the content as it is, as a fill fades content in the other modes
|
||||
let faded = blend_layer_pixel([0.8, 0.4, 0.2, 1.], [0.; 4], BlendMode::LinearDodge, fill);
|
||||
assert!(faded.iter().zip([0.4, 0.2, 0.1, 0.5]).all(|(channel, expected)| (channel - expected).abs() < 1e-6), "{faded:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fills_moving_layers_toward_neutral_blend_their_share_at_full_strength_over_opaque_backdrops_and_change_nothing_at_no_fill() {
|
||||
let close = |ours: [f32; 4], expected: [f32; 4]| ours.iter().zip(expected).all(|(ours, expected)| (ours - expected).abs() < 1e-5);
|
||||
let premultiplied = |[red, green, blue]: [f32; 3], alpha: f32| [red * alpha, green * alpha, blue * alpha, alpha];
|
||||
let pushed = |blend_mode: BlendMode, source: [f32; 3], fill: f32| {
|
||||
source.map(|channel| match blend_mode {
|
||||
BlendMode::ColorDodge | BlendMode::LinearDodge => fill * channel,
|
||||
BlendMode::ColorBurn | BlendMode::LinearBurn => 1. - fill * (1. - channel),
|
||||
_ => 0.5 + fill * (channel - 0.5),
|
||||
})
|
||||
};
|
||||
|
||||
let modes = [
|
||||
BlendMode::ColorDodge,
|
||||
BlendMode::ColorBurn,
|
||||
BlendMode::LinearDodge,
|
||||
BlendMode::LinearBurn,
|
||||
BlendMode::VividLight,
|
||||
BlendMode::LinearLight,
|
||||
];
|
||||
for blend_mode in modes {
|
||||
for (backdrop, source) in PAIRS {
|
||||
for alpha in [1., 0.5] {
|
||||
for fill in [0., 0.3, 1.] {
|
||||
// Over an opaque backdrop, the content's share blends the paint moved toward neutral at full strength, the rest showing the backdrop, for PSD interop
|
||||
let full = reference_formula(blend_mode, backdrop, pushed(blend_mode, source, fill));
|
||||
let expected = [0, 1, 2].map(|channel| alpha * full[channel] + (1. - alpha) * backdrop[channel]);
|
||||
let blended = blend_layer_pixel(premultiplied(source, alpha), premultiplied(backdrop, 1.), blend_mode, fill);
|
||||
assert!(close(blended, premultiplied(expected, 1.)), "{blend_mode} at fill {fill}, alpha {alpha}: {blended:?}");
|
||||
|
||||
// Over nothing, the fill fades the content as it is
|
||||
let blended = blend_layer_pixel(premultiplied(source, alpha), [0.; 4], blend_mode, fill);
|
||||
assert!(close(blended, premultiplied(source, alpha * fill)), "{blend_mode} at fill {fill} over nothing: {blended:?}");
|
||||
}
|
||||
|
||||
for backdrop_alpha in [0.25, 0.5, 0.75] {
|
||||
let beneath = premultiplied(backdrop, backdrop_alpha);
|
||||
|
||||
// No fill leaves a partly covering backdrop as it is, alpha included
|
||||
let unfilled = blend_layer_pixel(premultiplied(source, alpha), beneath, blend_mode, 0.);
|
||||
assert!(close(unfilled, beneath), "{blend_mode} at no fill over alpha {backdrop_alpha}: {unfilled:?}");
|
||||
|
||||
// A full fill blends by the W3C's general formula, mixing toward the blend as far as the backdrop covers
|
||||
let blend = reference_formula(blend_mode, backdrop, source);
|
||||
let mixed = [0, 1, 2].map(|channel| (1. - backdrop_alpha) * source[channel] + backdrop_alpha * blend[channel]);
|
||||
let expected = [0, 1, 2]
|
||||
.map(|channel| alpha * mixed[channel] + (1. - alpha) * beneath[channel])
|
||||
.into_iter()
|
||||
.chain([alpha + (1. - alpha) * backdrop_alpha])
|
||||
.collect::<Vec<f32>>();
|
||||
let filled = blend_layer_pixel(premultiplied(source, alpha), beneath, blend_mode, 1.);
|
||||
assert!(close(filled, expected.try_into().unwrap()), "{blend_mode} at full fill over alpha {backdrop_alpha}: {filled:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// An opaque layer at no fill over half alpha leaves that alpha
|
||||
let unfilled = blend_layer_pixel([0.8, 0.4, 0.2, 1.], [0.25, 0.25, 0.25, 0.5], BlendMode::LinearDodge, 0.);
|
||||
assert!((unfilled[3] - 0.5).abs() < 1e-6, "{unfilled:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_luminosity_of_black_over_any_gray_is_black() {
|
||||
for level in 0..=255 {
|
||||
|
||||
@@ -728,7 +728,7 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
| EffectOperation::MinimumMaximum { .. }
|
||||
| EffectOperation::Sharpen { .. }
|
||||
| EffectOperation::HighPass { .. }
|
||||
| EffectOperation::Speckle { .. }
|
||||
| EffectOperation::AddNoise { .. }
|
||||
| EffectOperation::Dissolve { .. } => {
|
||||
merge_beneath(&mut full, &mut filled, &mut beneath);
|
||||
// A filter sharpening the coverage fades the fill's result by the share of the full-strength coverage each pixel's fill left, as if the fill faded the result
|
||||
@@ -1727,7 +1727,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn random_fields_move_and_scale_with_the_content_after_them() {
|
||||
let noise = EffectOperation::Speckle {
|
||||
let noise = EffectOperation::AddNoise {
|
||||
amount: 30.,
|
||||
distribution: graphic_types::NoiseDistribution::Uniform,
|
||||
monochromatic: false,
|
||||
|
||||
@@ -4,7 +4,6 @@ pub mod render_ext;
|
||||
mod renderer;
|
||||
mod svg_backdrop;
|
||||
mod svg_blend_if;
|
||||
mod svg_layer_blend;
|
||||
pub mod to_peniko;
|
||||
pub mod vello_scene_builder;
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -96,10 +96,10 @@ impl SvgFilterPrimitives {
|
||||
match *operation {
|
||||
// The Euclidean length of the gradient loses too much precision through the 8-bit results between primitives
|
||||
EffectOperation::FindEdges => self.uncovered_map(image, capture, Surroundings::Matted(1.)),
|
||||
EffectOperation::MinimumMaximum { .. } | EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. } if forked => self.map_showing(capture, image),
|
||||
EffectOperation::MinimumMaximum { .. } | EffectOperation::AddNoise { .. } | EffectOperation::Dissolve { .. } if forked => self.map_showing(capture, image),
|
||||
EffectOperation::MinimumMaximum { radius, mode } => self.neighborhood_extreme(image, radius, mode == MinimumMaximumMode::Maximum),
|
||||
// Random fields come from the GPU, one map for both the content and the fill since they don't depend on either
|
||||
EffectOperation::Speckle { amount, distribution, .. } => self.speckle(image, noise_extent(amount / 100., distribution), EffectCapture { plane: 0, ..capture }),
|
||||
EffectOperation::AddNoise { amount, distribution, .. } => self.add_noise(image, noise_extent(amount / 100., distribution), EffectCapture { plane: 0, ..capture }),
|
||||
EffectOperation::Dissolve { .. } => self.dissolve(image, EffectCapture { plane: 0, ..capture }),
|
||||
_ => image.to_string(),
|
||||
}
|
||||
@@ -124,7 +124,7 @@ impl SvgFilterPrimitives {
|
||||
Some(convolution) => native && LatticeKernel::new(&convolution).is_some(),
|
||||
None => matches!(
|
||||
operation,
|
||||
EffectOperation::MinimumMaximum { .. } | EffectOperation::Sharpen { .. } | EffectOperation::HighPass { .. } | EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. }
|
||||
EffectOperation::MinimumMaximum { .. } | EffectOperation::Sharpen { .. } | EffectOperation::HighPass { .. } | EffectOperation::AddNoise { .. } | EffectOperation::Dissolve { .. }
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -275,9 +275,9 @@ impl SvgFilterPrimitives {
|
||||
self.push("feColorMatrix", &format!(r#"in="{image}" type="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 255 0""#), "")
|
||||
}
|
||||
|
||||
/// The image with each straight color offset by the noise in the GPU's map for `capture`, which holds offsets up to `extent` either way around middle gray, matching the GPU's `speckle`.
|
||||
/// The image with each straight color offset by the noise in the GPU's map for `capture`, which holds offsets up to `extent` either way around middle gray, matching the GPU's `add_noise`.
|
||||
/// Until the map is resolved, its middle gray offsets nothing.
|
||||
fn speckle(&mut self, image: &str, extent: f64, capture: EffectCapture) -> String {
|
||||
fn add_noise(&mut self, image: &str, extent: f64, capture: EffectCapture) -> String {
|
||||
let colors = self.opaque_colors(image);
|
||||
let noise = self.map_unresolved_as(capture, Color::from(SRGBA8::new(128, 128, 128, 255)));
|
||||
let attributes = format!(r#"in="{colors}" in2="{noise}" operator="arithmetic" k2="1" k3="{}" k4="{}""#, 2. * extent, -extent);
|
||||
@@ -719,8 +719,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn random_fields_come_from_the_gpu_combined_with_the_live_content() {
|
||||
// Speckle adds the map's offsets, scaled out from middle gray to their extent, to the opaque colors within the live coverage
|
||||
let noise = EffectOperation::Speckle {
|
||||
// Add Noise adds the map's offsets, scaled out from middle gray to their extent, to the opaque colors within the live coverage
|
||||
let noise = EffectOperation::AddNoise {
|
||||
amount: 40.,
|
||||
distribution: NoiseDistribution::Uniform,
|
||||
monochromatic: false,
|
||||
@@ -760,13 +760,13 @@ mod tests {
|
||||
use core_types::list::{ATTR_EFFECTS, List};
|
||||
use core_types::transform::Footprint;
|
||||
|
||||
// A color with Speckle after Levels draws through a filter over the view, with the noise's map and the Levels within it
|
||||
// A color with Add Noise after Levels draws through a filter over the view, with the noise's map and the Levels within it
|
||||
let levels = graphic_types::Adjustment::Exposure {
|
||||
exposure: 1.,
|
||||
offset: 0.,
|
||||
gamma_correction: 1.,
|
||||
};
|
||||
let noise = EffectOperation::Speckle {
|
||||
let noise = EffectOperation::AddNoise {
|
||||
amount: 20.,
|
||||
distribution: NoiseDistribution::Uniform,
|
||||
monochromatic: false,
|
||||
@@ -800,7 +800,7 @@ mod tests {
|
||||
|
||||
// A gradient mask without a transform lies across the color's own unit square, as on the GPU, rather than across the view
|
||||
let stops = [(0., core_types::Color::BLACK), (1., core_types::Color::WHITE)].map(|(position, color)| GradientStop { position, midpoint: 0.5, color });
|
||||
let noise = EffectOperation::Speckle {
|
||||
let noise = EffectOperation::AddNoise {
|
||||
amount: 20.,
|
||||
distribution: NoiseDistribution::Uniform,
|
||||
monochromatic: false,
|
||||
|
||||
@@ -134,9 +134,17 @@ impl SvgRender {
|
||||
|
||||
/// Markup showing what lies beneath the content drawn next, within the `region` of the current user space it reads, or `None` if nothing does.
|
||||
/// It copies the markup drawn since the backdrop root, or where that holds a copy already, stands for an image the GPU renders of it or else leaves held copies out.
|
||||
/// The image is embedded `for_mask`, since a mask can't render canvases.
|
||||
/// The image is embedded `for_mask`, which draws no canvas.
|
||||
pub(crate) fn backdrop_copy(&mut self, render_params: &RenderParams, region: [DVec2; 2], read_reach: f64, for_mask: bool) -> Option<BackdropCopy> {
|
||||
let root = self.backdrop_root()?;
|
||||
if self.drawing_deferred_markup || !self.transform.matrix2.determinant().is_normal() {
|
||||
return None;
|
||||
}
|
||||
let root = self.open_groups.groups.iter().rposition(|group| group.isolates)?;
|
||||
|
||||
// A clip's own stack lies over nothing, as in the GPU's layer for it, though a group isolated within it still reads what it drew
|
||||
if root == 0 && self.open_groups.clip {
|
||||
return None;
|
||||
}
|
||||
|
||||
// The backdrop root's own clip cuts every level's copy as it cuts the originals, from a group around them in the space of its content
|
||||
let root_group = &self.open_groups.groups[root];
|
||||
@@ -144,9 +152,8 @@ impl SvgRender {
|
||||
let clip = root_group.clip_path.clone().zip(root_group.user_to_document);
|
||||
let copies_to_document = clip.as_ref().map_or(self.transform, |(_, root_to_document)| *root_to_document);
|
||||
|
||||
// In the viewport, images draw to canvases in `<foreignObject>` elements, which a mask can't render, so a mask reads the GPU's image of what lies beneath instead, as later readers do
|
||||
let draws_canvases = self.draws_canvases_since(root, render_params);
|
||||
let images = holds_backdrop || (for_mask && draws_canvases);
|
||||
// A mask draws no canvas, so where one stands in for what lies beneath, the GPU's image of it shows what's displayed, as it does for later readers
|
||||
let images = holds_backdrop || (for_mask && self.draws_canvases_since(root, render_params));
|
||||
|
||||
// An image needs the outline of the root's clip, if it has one, to cut what it holds by
|
||||
let image_clip = match images && self.images_replace_markup(render_params) {
|
||||
@@ -160,7 +167,7 @@ impl SvgRender {
|
||||
// Elsewhere, copies leave out the blurred copies earlier content holds, so they never nest, losing only the blur of a blur where it overlaps
|
||||
let image = images && image_clip.is_some();
|
||||
let copies = match (images, image_clip) {
|
||||
(false, _) => self.backdrop_markup_copies(root, copies_to_document, render_params.to_canvas() || draws_canvases, false),
|
||||
(false, _) => self.backdrop_markup_copies(root, copies_to_document, render_params.to_canvas(), false),
|
||||
(true, Some(clip)) => {
|
||||
let image_params = RenderParams {
|
||||
embeds_images: render_params.embeds_images || for_mask,
|
||||
@@ -187,42 +194,11 @@ impl SvgRender {
|
||||
Some(BackdropCopy { markup, image })
|
||||
}
|
||||
|
||||
/// The group isolating the content drawn next from what lies beneath it, its backdrop root, as an index of the open groups, or `None` if it reads nothing beneath.
|
||||
fn backdrop_root(&self) -> Option<usize> {
|
||||
if self.drawing_deferred_markup || !self.transform.matrix2.determinant().is_normal() {
|
||||
return None;
|
||||
}
|
||||
let root = self.open_groups.groups.iter().rposition(|group| group.isolates)?;
|
||||
|
||||
// A clip's own stack lies over nothing, as in the GPU's layer for it, though a group isolated within it still reads what it drew
|
||||
(root > 0 || !self.open_groups.clip).then_some(root)
|
||||
}
|
||||
|
||||
/// Whether anything is drawn beneath the content drawn next for [`Self::backdrop_copy`] to show, as markup it copies or content it has the GPU draw again.
|
||||
/// O(segments drawn since the backdrop root).
|
||||
pub(crate) fn draws_beneath(&self) -> bool {
|
||||
let Some(root) = self.backdrop_root() else { return false };
|
||||
|
||||
(root..self.open_groups.groups.len()).any(|level| {
|
||||
let group = &self.open_groups.groups[level];
|
||||
let markup = &self.svg[group.content_start..self.level_content_end(level)];
|
||||
let copied = group.user_to_document.is_some() && markup.iter().any(|segment| segment.as_str().contains('<'));
|
||||
copied || group.drawn.iter().any(|drawn| drawn.count > 0)
|
||||
})
|
||||
}
|
||||
|
||||
/// Where the markup drawn directly inside the open group at `level` ends among the render's segments, at the tag of the group open inside it, if any.
|
||||
fn level_content_end(&self, level: usize) -> usize {
|
||||
self.open_groups.groups.get(level + 1).map_or(self.svg.len(), |inner| inner.tag_start)
|
||||
}
|
||||
|
||||
/// Whether the markup drawn since the backdrop `root` draws through canvases, as images and the GPU's images of content do in the viewport the `render_params` draw in,
|
||||
/// even where the content reading it embeds its own images. O(segments drawn since the root).
|
||||
/// Whether the markup drawn since the backdrop `root` draws through canvases, as images and the GPU's images of content do in the viewport. O(segments drawn since the root).
|
||||
fn draws_canvases_since(&self, root: usize, render_params: &RenderParams) -> bool {
|
||||
let in_viewport = !(render_params.for_export || render_params.thumbnail || render_params.for_mask || render_params.inside_pattern);
|
||||
let start = self.open_groups.groups[root].content_start;
|
||||
let draws_canvas = |segment: &SvgSegment| segment.as_str().contains("data-canvas-placeholder") || deferred_image::holds_image_markers(segment.as_str());
|
||||
in_viewport && self.svg[start..].iter().any(draws_canvas)
|
||||
render_params.to_canvas() && self.svg[start..].iter().any(draws_canvas)
|
||||
}
|
||||
|
||||
/// Copies of the content drawn at each level of the groups open since the backdrop `root`, in the space `copies_to_document` maps into the document, or `None` if there's none.
|
||||
@@ -236,7 +212,8 @@ impl SvgRender {
|
||||
let mut copies = Vec::new();
|
||||
for level in (root..=current).rev() {
|
||||
let group = &self.open_groups.groups[level];
|
||||
let (start, end) = (group.content_start, self.level_content_end(level));
|
||||
let start = group.content_start;
|
||||
let end = self.open_groups.groups.get(level + 1).map_or(self.svg.len(), |inner| inner.tag_start);
|
||||
let drawn = self.svg[start..end].iter().filter(kept).any(|segment| segment.as_str().contains('<'));
|
||||
let Some(user_to_document) = group.user_to_document.filter(|_| drawn) else { continue };
|
||||
|
||||
@@ -294,7 +271,6 @@ impl SvgRender {
|
||||
}
|
||||
|
||||
/// Markup showing what lies beneath content (see [`SvgRender::backdrop_copy`]).
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct BackdropCopy {
|
||||
pub markup: String,
|
||||
/// Whether the markup stands for an image the GPU renders of what lies beneath, rather than copying what's drawn.
|
||||
|
||||
@@ -49,7 +49,7 @@ pub(crate) fn weight(push: &mut impl FnMut(&str, &str, &str) -> String, image: &
|
||||
|
||||
/// The viewport's copy of what lies beneath as `markup`, with what a mask can't draw, so SVG can't read, covered by rectangles of the `key` color the ranges show in full.
|
||||
/// What's drawn over a cover still hides it, as it hides the image the cover stands in for.
|
||||
pub(crate) fn with_unreadable_covered(markup: &str, key: &str) -> String {
|
||||
fn with_unreadable_covered(markup: &str, key: &str) -> String {
|
||||
with_canvases_covered(&with_deferred_images_marked_for_covers(markup, key), key)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,571 +0,0 @@
|
||||
//! Layers in the blend modes `mix-blend-mode` lacks, or below a full fill moving them toward neutral in Color Dodge and Color Burn, built all natively from what SVG composites,
|
||||
//! over a copy of what lies beneath (see [`SvgRender::backdrop_copy`]).
|
||||
//! The layer's alpha, times [`layer_fill_shown`] where its fill moves it toward neutral, shows an opaque result: the layer made opaque, and over it the blend, shown by the alpha of what lies beneath,
|
||||
//! as the W3C's general formula mixes them. The blend draws the layer, recolored and made opaque, over an opaque copy of what lies beneath, where `s` is the layer moved toward neutral by its fill:
|
||||
//! - Linear Burn, Subtract: Lighten by `x`, then Difference by `x`, which leaves `max(0, b - x)` exactly, for `x` of `1 - s` or `s`.
|
||||
//! - Linear Dodge: that over the inverted copy, inverted back. Linear Light: Linear Burn by `2s`, then Linear Dodge by `2s - 1`.
|
||||
//! - Hard Mix: at full strength, the copy where it and the layer sum to white exactly, and white where they sum past it, each where Color Dodge reaches white.
|
||||
//! Below it, Linear Burn by `q (1 - s)`, stretched by `1 / (1 - q)`.
|
||||
//! - Divide: Color Dodge by the inverted layer. Pin Light: Darken by `2s`, then Lighten by `2s - 1`. Vivid Light: Color Burn by `2s`, then Color Dodge by `2s - 1`.
|
||||
//! - Darker Color, Lighter Color: the layer over the copy, masked to where Luminosity moves the copy's color down (or up) by a level or more.
|
||||
//! - Color Dodge, Color Burn: themselves by `s`.
|
||||
|
||||
use crate::renderer::{RenderParams, SvgRender, SvgSegment};
|
||||
use crate::svg_backdrop::BackdropCopy;
|
||||
use crate::svg_blend_if::with_unreadable_covered;
|
||||
use core_types::blending::{BlendMode, layer_fill_shown};
|
||||
use core_types::uuid::generate_uuid;
|
||||
use glam::DVec2;
|
||||
use std::fmt::Write;
|
||||
|
||||
/// A layer blending by a mode `mix-blend-mode` lacks, with what it reads to blend onto what lies beneath.
|
||||
pub(crate) struct SvgLayerBlend {
|
||||
blend_mode: BlendMode,
|
||||
/// The copy of what lies beneath, taken before any of the item is drawn, or `None` with nothing beneath.
|
||||
copy: Option<BackdropCopy>,
|
||||
/// The region of the current user space the layer covers, which the blend's filters and masks cover too.
|
||||
region: [DVec2; 2],
|
||||
/// The fill moving the layer toward the mode's neutral color (see [`BlendMode::fill_moves_layer_toward_neutral`]), or 1 where the layer is faded by its fill already.
|
||||
fill: f64,
|
||||
}
|
||||
|
||||
impl SvgLayerBlend {
|
||||
/// Copies what lies beneath the `region` of the current user space, before any of the layer is drawn, for it to blend onto by the mode.
|
||||
pub(crate) fn new(render: &mut SvgRender, render_params: &RenderParams, blend_mode: BlendMode, region: [DVec2; 2], fill: f64) -> Self {
|
||||
Self {
|
||||
blend_mode,
|
||||
copy: render.backdrop_copy(render_params, region, 0., true),
|
||||
region,
|
||||
fill,
|
||||
}
|
||||
}
|
||||
|
||||
/// The blend of another layer of the same item by its own `blend_mode` at full strength, onto the same copy of what lies beneath.
|
||||
pub(crate) fn with_mode(&self, blend_mode: BlendMode) -> Self {
|
||||
Self {
|
||||
blend_mode,
|
||||
copy: self.copy.clone(),
|
||||
region: self.region,
|
||||
fill: 1.,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the layer blends onto what lies beneath, rather than over nothing.
|
||||
pub(crate) fn blends(&self) -> bool {
|
||||
self.copy.is_some() && recipe(self.blend_mode, self.fill).is_some()
|
||||
}
|
||||
|
||||
/// Whether the blend moves the layer toward the mode's neutral color by a fill below full, which the layer itself then leaves out.
|
||||
pub(crate) fn moves_by_fill(&self) -> bool {
|
||||
self.fill < 1.
|
||||
}
|
||||
}
|
||||
|
||||
/// A map of each straight color channel, `scale × channel + offset`, clamped to 0 to 1.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct Recolor {
|
||||
scale: f64,
|
||||
offset: f64,
|
||||
}
|
||||
|
||||
impl Recolor {
|
||||
const IDENTITY: Self = Self { scale: 1., offset: 0. };
|
||||
const INVERT: Self = Self { scale: -1., offset: 1. };
|
||||
}
|
||||
|
||||
/// One step building a mode SVG lacks: the layer recolored and made opaque, then drawn by a native mode.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct BlendStep {
|
||||
recolor: Recolor,
|
||||
blend_mode: BlendMode,
|
||||
}
|
||||
|
||||
/// A stage of steps over its base (the copy of what lies beneath, or the stage before), recolored, whose result it then recolors by `stretch`.
|
||||
#[derive(Clone, Debug)]
|
||||
struct BlendStage {
|
||||
base: Recolor,
|
||||
steps: Vec<BlendStep>,
|
||||
stretch: Recolor,
|
||||
}
|
||||
|
||||
/// How SVG builds a mode it lacks over an opaque copy of what lies beneath.
|
||||
#[derive(Clone, Debug)]
|
||||
enum BlendRecipe {
|
||||
Stages(Vec<BlendStage>),
|
||||
/// Hard Mix at full strength: the copy where it and the layer sum to white exactly, and white where they sum past it.
|
||||
HardMixThreshold,
|
||||
/// The layer's whole color where its luma is lower than that of what lies beneath, or higher if `lighter`.
|
||||
Pick {
|
||||
lighter: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// The recipe for a mode SVG lacks at the `fill` moving the layer's color toward neutral where the mode does that, or `None` for a mode SVG has at it.
|
||||
fn recipe(blend_mode: BlendMode, fill: f64) -> Option<BlendRecipe> {
|
||||
use BlendMode::*;
|
||||
|
||||
let step = |scale: f64, offset: f64, blend_mode: BlendMode| BlendStep {
|
||||
recolor: Recolor { scale, offset },
|
||||
blend_mode,
|
||||
};
|
||||
// Lightening by `x`, then the difference from it, leaves `max(0, b - x)` in whole levels
|
||||
let burn_by = |scale: f64, offset: f64| vec![step(scale, offset, Lighten), step(scale, offset, Difference)];
|
||||
let stage = |base: Recolor, steps: Vec<BlendStep>, stretch: Recolor| BlendStage { base, steps, stretch };
|
||||
let (identity, invert) = (Recolor::IDENTITY, Recolor::INVERT);
|
||||
let steepness = 255. * fill / 256.;
|
||||
|
||||
let stages = match blend_mode {
|
||||
LinearBurn => vec![stage(identity, burn_by(-fill, fill), identity)],
|
||||
Subtract => vec![stage(identity, burn_by(1., 0.), identity)],
|
||||
LinearDodge => vec![stage(invert, burn_by(fill, 0.), invert)],
|
||||
LinearLight => vec![stage(identity, burn_by(-2. * fill, fill), identity), stage(invert, burn_by(2. * fill, -fill), invert)],
|
||||
HardMix if fill >= 1. => return Some(BlendRecipe::HardMixThreshold),
|
||||
HardMix => vec![stage(
|
||||
identity,
|
||||
burn_by(-steepness, steepness),
|
||||
Recolor {
|
||||
scale: 1. / (1. - steepness),
|
||||
offset: 0.,
|
||||
},
|
||||
)],
|
||||
Divide => vec![stage(identity, vec![step(-1., 1., ColorDodge)], identity)],
|
||||
ColorDodge if fill < 1. => vec![stage(identity, vec![step(fill, 0., ColorDodge)], identity)],
|
||||
ColorBurn if fill < 1. => vec![stage(identity, vec![step(fill, 1. - fill, ColorBurn)], identity)],
|
||||
PinLight => vec![stage(identity, vec![step(2., 0., Darken), step(2., -1., Lighten)], identity)],
|
||||
VividLight => vec![stage(identity, vec![step(2. * fill, 1. - fill, ColorBurn), step(2. * fill, -fill, ColorDodge)], identity)],
|
||||
DarkerColor => return Some(BlendRecipe::Pick { lighter: false }),
|
||||
LighterColor => return Some(BlendRecipe::Pick { lighter: true }),
|
||||
_ => return None,
|
||||
};
|
||||
Some(BlendRecipe::Stages(stages))
|
||||
}
|
||||
|
||||
/// The filters and masks one blended layer writes into the render's defs, each within the layer's region.
|
||||
struct BlendDefs<'a> {
|
||||
defs: &'a mut String,
|
||||
region: String,
|
||||
uuid: u64,
|
||||
recolors: Vec<(Recolor, String)>,
|
||||
}
|
||||
|
||||
impl BlendDefs<'_> {
|
||||
/// Writes a def named `name` with the `tag`, the `attributes` past its ID, and the `children`, returning a reference to it.
|
||||
fn write(&mut self, name: &str, tag: &str, attributes: &str, children: &str) -> String {
|
||||
let id = format!("layer-blend-{name}-{}", self.uuid);
|
||||
write!(self.defs, r#"<{tag} id="{id}" {attributes} {}>{children}</{tag}>"#, self.region).unwrap();
|
||||
format!("url(#{id})")
|
||||
}
|
||||
|
||||
/// A filter named `name` of the `primitives` on gamma-encoded colors.
|
||||
fn filter(&mut self, name: &str, primitives: &str) -> String {
|
||||
self.write(name, "filter", r#"filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB""#, primitives)
|
||||
}
|
||||
|
||||
/// A mask named `name` showing what the `markup` covers, by its alpha.
|
||||
fn mask(&mut self, name: &str, markup: &str) -> String {
|
||||
self.write(name, "mask", r#"mask-type="alpha" maskUnits="userSpaceOnUse""#, markup)
|
||||
}
|
||||
|
||||
/// A filter making what it draws opaque in its straight color, recolored, written once for each recoloring.
|
||||
fn recolor(&mut self, recolor: Recolor) -> String {
|
||||
if let Some((_, reference)) = self.recolors.iter().find(|(written, _)| *written == recolor) {
|
||||
return reference.clone();
|
||||
}
|
||||
|
||||
let Recolor { scale, offset } = recolor;
|
||||
let name = format!("recolor-{}", self.recolors.len());
|
||||
let reference = self.filter(
|
||||
&name,
|
||||
&format!(r#"<feColorMatrix type="matrix" values="{scale} 0 0 0 {offset} 0 {scale} 0 0 {offset} 0 0 {scale} 0 {offset} 0 0 0 0 1" />"#),
|
||||
);
|
||||
self.recolors.push((recolor, reference.clone()));
|
||||
reference
|
||||
}
|
||||
}
|
||||
|
||||
/// What a blended layer draws around it, with its defs written.
|
||||
struct BlendGroups {
|
||||
/// The attributes of each group around the layer made opaque and the blend over it, outermost first.
|
||||
around: Vec<Vec<(&'static str, String)>>,
|
||||
/// The filter making the layer opaque, beneath the blend.
|
||||
opaque: String,
|
||||
/// The ID the layer's own group takes, for copies of it to reference.
|
||||
layer_id: String,
|
||||
/// The blend's markup, drawn over the layer made opaque, which copies of what lies beneath leave out so they never nest.
|
||||
blended: String,
|
||||
}
|
||||
|
||||
/// Writes the defs of the `blend` of a layer at `opacity` and returns what it draws around the layer, or `None` with nothing beneath to blend onto.
|
||||
fn blend_groups(render: &mut SvgRender, blend: &SvgLayerBlend, opacity: f32) -> Option<BlendGroups> {
|
||||
let (Some(copy), Some(recipe)) = (&blend.copy, recipe(blend.blend_mode, blend.fill)) else {
|
||||
return None;
|
||||
};
|
||||
|
||||
let uuid = generate_uuid();
|
||||
let layer_id = format!("layer-blend-layer-{uuid}");
|
||||
let [min, max] = blend.region;
|
||||
let mut defs = BlendDefs {
|
||||
defs: &mut render.svg_defs,
|
||||
region: format!(r#"x="{}" y="{}" width="{}" height="{}""#, min.x, min.y, max.x - min.x, max.y - min.y),
|
||||
uuid,
|
||||
recolors: Vec::new(),
|
||||
};
|
||||
|
||||
// Copies of the layer reference it, and masks read what lies beneath from an image or a copy covering what they can't draw
|
||||
let layer = format!(r##"<use href="#{layer_id}" />"##);
|
||||
let beneath_in_mask = if copy.image { copy.markup.clone() } else { with_unreadable_covered(©.markup, "#000000") };
|
||||
let opaque = defs.recolor(Recolor::IDENTITY);
|
||||
let drawn = |filter: &str, blend_mode: BlendMode, markup: &str| format!(r#"<g filter="{filter}" style="{}">{markup}</g>"#, blend_mode.render().trim());
|
||||
|
||||
let blend_markup = match recipe {
|
||||
// Each stage's steps blend over its base alone, within a group recoloring what they leave
|
||||
BlendRecipe::Stages(stages) => {
|
||||
let mut result = copy.markup.clone();
|
||||
for stage in stages {
|
||||
let base = format!(r#"<g filter="{}">{result}</g>"#, defs.recolor(stage.base));
|
||||
let steps: String = stage.steps.iter().map(|step| drawn(&defs.recolor(step.recolor), step.blend_mode, &layer)).collect();
|
||||
result = format!(r#"<g filter="{}">{base}{steps}</g>"#, defs.recolor(stage.stretch));
|
||||
}
|
||||
result
|
||||
}
|
||||
// Color Dodge reaches white exactly where the layer and the copy sum to white or past it, or past it alone for the layer a level darker
|
||||
BlendRecipe::HardMixThreshold => {
|
||||
let white = defs.filter("white", r#"<feComponentTransfer><feFuncR type="linear" slope="255" intercept="-254" /><feFuncG type="linear" slope="255" intercept="-254" /><feFuncB type="linear" slope="255" intercept="-254" /></feComponentTransfer>"#);
|
||||
let mut reaches_white = |offset: f64| {
|
||||
format!(
|
||||
r#"<g filter="{opaque}">{}</g>{}"#,
|
||||
copy.markup,
|
||||
drawn(&defs.recolor(Recolor { scale: 1., offset }), BlendMode::ColorDodge, &layer)
|
||||
)
|
||||
};
|
||||
let (sums_to_white, sums_past_white) = (reaches_white(0.), reaches_white(-1. / 255.));
|
||||
format!(
|
||||
r#"<g filter="{opaque}">{}</g><g filter="{white}" style="mix-blend-mode: multiply;">{sums_to_white}</g><g filter="{white}" style="mix-blend-mode: lighten;">{sums_past_white}</g>"#,
|
||||
copy.markup
|
||||
)
|
||||
}
|
||||
// Luminosity moves the copy's color by the layer's luma less its own, which the change in any channel shows the direction of
|
||||
BlendRecipe::Pick { lighter } => {
|
||||
let any_channel = defs.filter("any-channel", r#"<feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 255 255 255 0 0" />"#);
|
||||
let toward = if lighter { BlendMode::Lighten } else { BlendMode::Darken };
|
||||
let moved = format!(
|
||||
r#"<g filter="{any_channel}"><g filter="{opaque}">{beneath_in_mask}</g>{}{}{}</g>"#,
|
||||
drawn(&opaque, BlendMode::Luminosity, &layer),
|
||||
drawn(&opaque, toward, &beneath_in_mask),
|
||||
drawn(&opaque, BlendMode::Difference, &beneath_in_mask)
|
||||
);
|
||||
let picked = defs.mask("picked", &moved);
|
||||
format!(r#"<g filter="{opaque}">{}</g><g filter="{opaque}" mask="{picked}">{layer}</g>"#, copy.markup)
|
||||
}
|
||||
};
|
||||
|
||||
// The blend shows by the alpha of what lies beneath, and the whole by the layer's own alpha, at its opacity
|
||||
let beneath = defs.mask("beneath", &beneath_in_mask);
|
||||
let blended = format!(r#"<g mask="{beneath}">{blend_markup}</g>"#);
|
||||
let mut outer = vec![("mask", defs.mask("shown", &layer))];
|
||||
if opacity < 1. {
|
||||
outer.push(("opacity", opacity.to_string()));
|
||||
}
|
||||
let mut around = vec![outer];
|
||||
|
||||
// A fill moving the layer toward neutral shows it by how much lies beneath, by a table of each level of alpha there
|
||||
if blend.fill < 1. {
|
||||
let table: Vec<String> = (0..=255).map(|level| format!("{:.5}", layer_fill_shown(level as f32 / 255., blend.fill as f32))).collect();
|
||||
let weight = defs.filter(
|
||||
"fill-weight",
|
||||
&format!(r#"<feComponentTransfer><feFuncA type="table" tableValues="{}" /></feComponentTransfer>"#, table.join(" ")),
|
||||
);
|
||||
around.push(vec![("mask", defs.mask("fill-shown", &format!(r#"<g filter="{weight}">{beneath_in_mask}</g>"#)))]);
|
||||
}
|
||||
|
||||
Some(BlendGroups { around, opaque, layer_id, blended })
|
||||
}
|
||||
|
||||
/// Draws the layer `draw_layer` draws, blended by the mode onto what lies beneath it and faded by `opacity`.
|
||||
pub(crate) fn draw_blended_layer(render: &mut SvgRender, blend: &SvgLayerBlend, opacity: f32, draw_layer: impl FnOnce(&mut SvgRender)) {
|
||||
let Some(BlendGroups { around, opaque, layer_id, blended }) = blend_groups(render, blend, opacity) else {
|
||||
// Over nothing, the layer shows as it is, faded by a fill it would otherwise move toward neutral
|
||||
let opacity = opacity as f64 * blend.fill;
|
||||
return render.parent_tag(
|
||||
"g",
|
||||
|attributes| {
|
||||
if opacity < 1. {
|
||||
attributes.push("opacity", opacity.to_string());
|
||||
}
|
||||
},
|
||||
draw_layer,
|
||||
);
|
||||
};
|
||||
|
||||
nest_groups(render, &around, |render| {
|
||||
render.parent_tag(
|
||||
"g",
|
||||
|attributes| attributes.push("filter", opaque),
|
||||
|render| render.parent_tag("g", |attributes| attributes.push("id", layer_id), draw_layer),
|
||||
);
|
||||
render.leaf_node(SvgSegment::Backdrop(blended));
|
||||
});
|
||||
}
|
||||
|
||||
/// Wraps the markup drawn since the segment at `start`, an image of the layer the GPU renders, in what [`draw_blended_layer`] draws around a layer. Returns whether it blends.
|
||||
pub(crate) fn wrap_blended_layer(render: &mut SvgRender, blend: &SvgLayerBlend, opacity: f32, start: usize) -> bool {
|
||||
let Some(BlendGroups { around, opaque, layer_id, blended }) = blend_groups(render, blend, opacity) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let opening = |attributes: &Vec<(&'static str, String)>| format!("<g{}>", attributes.iter().map(|(name, value)| format!(r#" {name}="{value}""#)).collect::<String>());
|
||||
let mut opened: String = around.iter().map(opening).collect();
|
||||
write!(opened, r#"<g filter="{opaque}"><g id="{layer_id}">"#).unwrap();
|
||||
render.svg.insert(start, opened.into());
|
||||
render.svg.push("</g></g>".into());
|
||||
render.svg.push(SvgSegment::Backdrop(blended));
|
||||
render.svg.push("</g>".repeat(around.len()).into());
|
||||
true
|
||||
}
|
||||
|
||||
/// Opens a group of each of the `groups`' attributes, outermost first, around what `inner` draws.
|
||||
fn nest_groups(render: &mut SvgRender, groups: &[Vec<(&'static str, String)>], inner: impl FnOnce(&mut SvgRender)) {
|
||||
let Some((attributes, nested)) = groups.split_first() else { return inner(render) };
|
||||
render.parent_tag(
|
||||
"g",
|
||||
|tag| attributes.iter().for_each(|(name, value)| tag.push(*name, value.clone())),
|
||||
|render| nest_groups(render, nested, inner),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use raster_kernels::layer_blending::{blend_layer_pixel, blend_pixel};
|
||||
|
||||
/// The modes SVG builds from native compositing.
|
||||
const MODES: [BlendMode; 10] = [
|
||||
BlendMode::LinearBurn,
|
||||
BlendMode::DarkerColor,
|
||||
BlendMode::LinearDodge,
|
||||
BlendMode::LighterColor,
|
||||
BlendMode::VividLight,
|
||||
BlendMode::LinearLight,
|
||||
BlendMode::PinLight,
|
||||
BlendMode::HardMix,
|
||||
BlendMode::Subtract,
|
||||
BlendMode::Divide,
|
||||
];
|
||||
|
||||
/// The modes SVG has, which it builds from native compositing too below a full fill moving the layer toward neutral.
|
||||
const BELOW_FULL_FILL: [BlendMode; 2] = [BlendMode::ColorDodge, BlendMode::ColorBurn];
|
||||
|
||||
/// A value as the 8-bit buffers browsers hold the results of filters and groups in keep it.
|
||||
fn quantized(value: f64) -> f64 {
|
||||
(value.clamp(0., 1.) * 255.).round() / 255.
|
||||
}
|
||||
|
||||
/// The opaque color an opaque `source` composites natively by the mode onto an opaque `backdrop`, by the W3C's formula, held in 8 bits.
|
||||
fn native(blend_mode: BlendMode, backdrop: [f64; 3], source: [f64; 3]) -> [f64; 3] {
|
||||
let opaque = |[red, green, blue]: [f64; 3]| [red as f32, green as f32, blue as f32, 1.];
|
||||
let blended = blend_pixel(opaque(source), opaque(backdrop), blend_mode);
|
||||
[0, 1, 2].map(|channel| quantized(blended[channel] as f64))
|
||||
}
|
||||
|
||||
/// A color recolored, held in 8 bits.
|
||||
fn recolored(recolor: Recolor, color: [f64; 3]) -> [f64; 3] {
|
||||
color.map(|channel| quantized(recolor.scale * channel + recolor.offset))
|
||||
}
|
||||
|
||||
/// The opaque color the `recipe` builds from an opaque `layer` over an opaque `backdrop`, compositing natively by the W3C's formulas, each result held in 8 bits.
|
||||
fn emulated(recipe: &BlendRecipe, backdrop: [f64; 3], layer: [f64; 3]) -> [f64; 3] {
|
||||
match recipe {
|
||||
BlendRecipe::Stages(stages) => {
|
||||
let mut result = backdrop;
|
||||
for stage in stages {
|
||||
result = recolored(stage.base, result);
|
||||
for step in &stage.steps {
|
||||
result = native(step.blend_mode, result, recolored(step.recolor, layer));
|
||||
}
|
||||
result = recolored(stage.stretch, result);
|
||||
}
|
||||
result
|
||||
}
|
||||
BlendRecipe::HardMixThreshold => {
|
||||
let reaches_white = |offset: f64| native(BlendMode::ColorDodge, backdrop, recolored(Recolor { scale: 1., offset }, layer)).map(|channel| quantized(255. * channel - 254.));
|
||||
let at_white = native(BlendMode::Multiply, backdrop, reaches_white(0.));
|
||||
native(BlendMode::Lighten, at_white, reaches_white(-1. / 255.))
|
||||
}
|
||||
BlendRecipe::Pick { lighter } => {
|
||||
let moved = native(BlendMode::Luminosity, backdrop, layer);
|
||||
let toward = native(if *lighter { BlendMode::Lighten } else { BlendMode::Darken }, moved, backdrop);
|
||||
let change = native(BlendMode::Difference, toward, backdrop);
|
||||
let layer_wins = change.iter().sum::<f64>() * 255. >= 1.;
|
||||
if layer_wins { layer } else { backdrop }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Colors on the 8-bit grid, which a render's inputs lie on.
|
||||
fn levels(colors: &[[u8; 3]]) -> Vec<[f64; 3]> {
|
||||
colors.iter().map(|color| color.map(|level| level as f64 / 255.)).collect()
|
||||
}
|
||||
|
||||
/// How many levels the recipe's result may stray from the CPU's at a `fill` below full, where the layer's recolored channels round to whole levels:
|
||||
/// none at full strength, which leaves them whole, a level otherwise, and on Hard Mix's ramp half a level stretched by `1 / (1 - steepness)`, more past a level.
|
||||
fn tolerance(blend_mode: BlendMode, fill: f64) -> f64 {
|
||||
match (fill < 1., blend_mode) {
|
||||
(false, _) => 0.5,
|
||||
(true, BlendMode::HardMix) => 1. + 0.5 / (1. - 255. * fill / 256.),
|
||||
// Burning and dodging by a nearly black or white layer stretch its rounding most, by up to a fifth across these colors
|
||||
(true, BlendMode::VividLight | BlendMode::ColorDodge | BlendMode::ColorBurn) => 3.,
|
||||
(true, _) => 1.,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recipes_build_each_mode_from_native_compositing_at_full_strength_exactly() {
|
||||
// Every level of a gray backdrop under every level of a gray layer, and a spread of colors
|
||||
let grays: Vec<[f64; 3]> = (0..=255).map(|level| [level as f64 / 255.; 3]).collect();
|
||||
let colors = levels(&[
|
||||
[0, 0, 0],
|
||||
[255, 255, 255],
|
||||
[204, 51, 128],
|
||||
[30, 200, 90],
|
||||
[128, 128, 128],
|
||||
[250, 180, 20],
|
||||
[64, 96, 230],
|
||||
[127, 129, 140],
|
||||
]);
|
||||
let opaque = |[red, green, blue]: [f64; 3]| [red as f32, green as f32, blue as f32, 1.];
|
||||
|
||||
for blend_mode in MODES.into_iter().filter(|blend_mode| !matches!(blend_mode, BlendMode::DarkerColor | BlendMode::LighterColor)) {
|
||||
let recipe = recipe(blend_mode, 1.).expect("SVG lacks the mode");
|
||||
for (backdrops, layers) in [(&grays, &grays), (&colors, &colors)] {
|
||||
for &backdrop in backdrops {
|
||||
for &layer in layers {
|
||||
let svg = emulated(&recipe, backdrop, layer);
|
||||
let cpu = blend_layer_pixel(opaque(layer), opaque(backdrop), blend_mode, 1.);
|
||||
for channel in 0..3 {
|
||||
assert!(
|
||||
(svg[channel] - cpu[channel] as f64).abs() * 255. <= 0.5 + 1e-4,
|
||||
"{blend_mode} of {layer:?} over {backdrop:?} gives {svg:?} in SVG and {cpu:?} on the CPU"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recipes_build_each_mode_from_native_compositing_below_full_strength_within_their_rounding() {
|
||||
let colors = levels(&[
|
||||
[0, 0, 0],
|
||||
[255, 255, 255],
|
||||
[204, 51, 128],
|
||||
[30, 200, 90],
|
||||
[128, 128, 128],
|
||||
[250, 180, 20],
|
||||
[64, 96, 230],
|
||||
[127, 129, 140],
|
||||
]);
|
||||
let opaque = |[red, green, blue]: [f64; 3]| [red as f32, green as f32, blue as f32, 1.];
|
||||
|
||||
for blend_mode in MODES.into_iter().filter(BlendMode::fill_moves_layer_toward_neutral).chain(BELOW_FULL_FILL) {
|
||||
for fill in [0.8, 0.6, 0.25, 0.] {
|
||||
let recipe = recipe(blend_mode, fill).expect("SVG lacks the mode");
|
||||
for &backdrop in &colors {
|
||||
for &layer in &colors {
|
||||
let svg = emulated(&recipe, backdrop, layer);
|
||||
let cpu = blend_layer_pixel(opaque(layer), opaque(backdrop), blend_mode, fill as f32);
|
||||
for channel in 0..3 {
|
||||
let difference = (svg[channel] - cpu[channel] as f64).abs() * 255.;
|
||||
assert!(
|
||||
difference <= tolerance(blend_mode, fill),
|
||||
"{blend_mode} at fill {fill} of {layer:?} over {backdrop:?} gives {svg:?} in SVG and {cpu:?} on the CPU"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn darker_and_lighter_color_pick_as_on_the_cpu_but_may_keep_the_backdrop_within_half_a_level_of_luma() {
|
||||
let opaque = |[red, green, blue]: [f64; 3]| [red as f32, green as f32, blue as f32, 1.];
|
||||
let luma = |color: [f64; 3]| 255. * (0.3 * color[0] + 0.59 * color[1] + 0.11 * color[2]);
|
||||
|
||||
// Pairs of colors around ties of luma, by a fraction of a level or a level or more, with channels at black and white where Luminosity clips
|
||||
let colors = levels(&[
|
||||
[0, 0, 255],
|
||||
[0, 48, 0],
|
||||
[0, 47, 0],
|
||||
[0, 49, 0],
|
||||
[255, 0, 0],
|
||||
[0, 130, 0],
|
||||
[10, 120, 40],
|
||||
[128, 128, 128],
|
||||
[100, 140, 140],
|
||||
[255, 255, 255],
|
||||
[0, 0, 0],
|
||||
[255, 254, 255],
|
||||
]);
|
||||
for lighter in [false, true] {
|
||||
let blend_mode = if lighter { BlendMode::LighterColor } else { BlendMode::DarkerColor };
|
||||
for &backdrop in &colors {
|
||||
for &layer in &colors {
|
||||
let svg = emulated(&BlendRecipe::Pick { lighter }, backdrop, layer);
|
||||
let difference = luma(layer) - luma(backdrop);
|
||||
let cpu = blend_layer_pixel(opaque(layer), opaque(backdrop), blend_mode, 1.);
|
||||
let cpu = [cpu[0] as f64, cpu[1] as f64, cpu[2] as f64];
|
||||
// It picks what the CPU picks, or within half a level of a tie, where Luminosity may move no channel a level, it may keep the backdrop, as at a tie
|
||||
let near_tie = difference.abs() < 0.5;
|
||||
assert!(svg == cpu.map(quantized) || (near_tie && svg == backdrop), "{blend_mode} of {layer:?} over {backdrop:?} picks {svg:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Blue's luma lies just under green's, so Darker Color keeps the blue backdrop
|
||||
let (blue, green) = ([0., 0., 1.], [0., 48. / 255., 0.]);
|
||||
assert_eq!(emulated(&BlendRecipe::Pick { lighter: false }, blue, green), blue);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_blend_by_the_alpha_beneath_and_their_own_as_on_the_cpu() {
|
||||
let (backdrop, layer) = ([0.2, 0.6, 0.45], [0.85, 0.3, 0.6]);
|
||||
|
||||
// Color Dodge and Color Burn blend so only below a full fill
|
||||
let cases = [(1., 0.5, 1., 1.), (0.5, 1., 0.6, 1.), (0.75, 0.25, 0.4, 0.7), (1., 0., 0.5, 1.), (1., 0.5, 0., 1.)];
|
||||
let modes_and_cases = MODES.into_iter().chain(BELOW_FULL_FILL).flat_map(|blend_mode| cases.map(|case| (blend_mode, case)));
|
||||
for (blend_mode, (layer_alpha, backdrop_alpha, fill, opacity)) in modes_and_cases.filter(|(blend_mode, (_, _, fill, _))| *fill < 1. || blend_mode.reads_backdrop()) {
|
||||
// Only a fill moving the layer toward neutral reaches the blend, which shows it by the alpha beneath, and the layer is otherwise already faded by it
|
||||
let moves = blend_mode.fill_moves_layer_toward_neutral();
|
||||
let blend_fill = if moves { fill } else { 1. };
|
||||
let drawn_alpha = if moves { layer_alpha } else { layer_alpha * fill };
|
||||
let blend = emulated(&recipe(blend_mode, blend_fill).unwrap(), backdrop, layer);
|
||||
|
||||
// The layer made opaque, the blend over it by the alpha beneath, all shown by the layer's alpha, its fill's weight, and its opacity over what lies beneath
|
||||
let shown = opacity * drawn_alpha * layer_fill_shown(backdrop_alpha as f32, blend_fill as f32) as f64;
|
||||
let svg: Vec<f64> = (0..3)
|
||||
.map(|channel| shown * (backdrop_alpha * blend[channel] + (1. - backdrop_alpha) * layer[channel]) + (1. - shown) * backdrop_alpha * backdrop[channel])
|
||||
.chain([shown + (1. - shown) * backdrop_alpha])
|
||||
.collect();
|
||||
|
||||
// The CPU blends the full-strength content by the fill, then the opacity mixes from what lies beneath to that
|
||||
let premultiplied = |color: [f64; 3], alpha: f64| [color[0] * alpha, color[1] * alpha, color[2] * alpha, alpha].map(|channel| channel as f32);
|
||||
let beneath = premultiplied(backdrop, backdrop_alpha);
|
||||
let blended = blend_layer_pixel(premultiplied(layer, layer_alpha), beneath, blend_mode, fill as f32);
|
||||
for channel in 0..4 {
|
||||
let cpu = beneath[channel] as f64 + (blended[channel] - beneath[channel]) as f64 * opacity;
|
||||
assert!(
|
||||
(svg[channel] - cpu).abs() * 255. <= 2.,
|
||||
"{blend_mode} at layer alpha {layer_alpha}, alpha beneath {backdrop_alpha}, fill {fill}, and opacity {opacity}: {svg:?} in SVG against {cpu} in channel {channel} on the CPU"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modes_svg_has_take_no_recipe() {
|
||||
for blend_mode in BlendMode::list().into_iter().flatten() {
|
||||
assert_eq!(recipe(*blend_mode, 1.).is_some(), blend_mode.reads_backdrop(), "{blend_mode}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -42,7 +42,7 @@ impl BlendModeExt for BlendMode {
|
||||
BlendMode::Saturation => peniko::Mix::Saturation,
|
||||
BlendMode::Color => peniko::Mix::Color,
|
||||
BlendMode::Luminosity => peniko::Mix::Luminosity,
|
||||
// Vello lacks the rest, so they draw normally, and layers in those reading what lies beneath blend in an effects group (see `BlendMode::reads_backdrop`)
|
||||
// Like SVG, the modes that layers can't blend by fall back to normal
|
||||
_ => peniko::Mix::Normal,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -612,7 +612,7 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
|
||||
// What lies beneath, for the effects that read it, where each of the effects texture's pixels lands in it.
|
||||
// Content without bounds reads nothing, as in SVG, and content reading past the scene's edges asks for the scene to be rendered grown by as much.
|
||||
let reads_backdrop = (layers.reads_backdrop() || layers.content_reads_backdrop(fill)) && capture.is_none() && bounds.is_some() && self.backdrop_readable();
|
||||
let reads_backdrop = layers.reads_backdrop() && capture.is_none() && bounds.is_some() && self.backdrop_readable();
|
||||
if reads_backdrop && layers.reads_around_backdrop() {
|
||||
// A box reaches as far along each axis of the view as its square turned into it does, and a Gaussian as far every way as its widest stretch
|
||||
let readers = (effects.operations()).filter(|operation| matches!(operation, graphic_types::EffectOperation::BackgroundBlur { .. }) && !operation.changes_nothing());
|
||||
|
||||
@@ -3,6 +3,7 @@ use crate::vector::flatten::WorkingVector;
|
||||
use crate::vector::misc::{BezierHandles, HandleId, HandleType};
|
||||
use crate::vector::path::{CurveType, Path, curve_types_of};
|
||||
use core_types::list::{ATTR_ID, List};
|
||||
use core_types::uuid::generate_uuid;
|
||||
use dyn_any::DynAny;
|
||||
use glam::DVec2;
|
||||
use rustc_hash::{FxHashMap, FxHashSet};
|
||||
@@ -1085,49 +1086,16 @@ impl VectorModification {
|
||||
}
|
||||
}
|
||||
|
||||
// Hash sets and maps are hashed in key order, so equal modifications hash equally regardless of iteration order
|
||||
impl graphene_hash::CacheHash for PointModification {
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
self.add.cache_hash(state);
|
||||
sorted_set(&self.remove).cache_hash(state);
|
||||
sorted_map(&self.delta).cache_hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl graphene_hash::CacheHash for SegmentModification {
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
self.add.cache_hash(state);
|
||||
sorted_set(&self.remove).cache_hash(state);
|
||||
sorted_map(&self.start_point).cache_hash(state);
|
||||
sorted_map(&self.end_point).cache_hash(state);
|
||||
sorted_map(&self.handle_primary).cache_hash(state);
|
||||
sorted_map(&self.handle_end).cache_hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
// Intentionally non-deterministic: fields contain HashMaps with non-deterministic iteration order,
|
||||
// so we use a UUID to always bust the cache and force re-evaluation when any modification is present.
|
||||
// This will not actually lead to a cache invalidation in most cases due to the
|
||||
// graph inputs being wrapped in a `MemoHash` wrapper.
|
||||
impl graphene_hash::CacheHash for VectorModification {
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
self.points.cache_hash(state);
|
||||
self.segments.cache_hash(state);
|
||||
sorted_set(&self.add_g1_continuous).cache_hash(state);
|
||||
sorted_set(&self.remove_g1_continuous).cache_hash(state);
|
||||
sorted_set(&self.path_breaks).cache_hash(state);
|
||||
sorted_set(&self.turned_on_load).cache_hash(state);
|
||||
core::hash::Hash::hash(&generate_uuid(), state);
|
||||
}
|
||||
}
|
||||
|
||||
fn sorted_set<T: Ord>(set: &HashSet<T>) -> Vec<&T> {
|
||||
let mut items: Vec<_> = set.iter().collect();
|
||||
items.sort_unstable();
|
||||
items
|
||||
}
|
||||
|
||||
fn sorted_map<K: Ord, V>(map: &HashMap<K, V>) -> Vec<(&K, &V)> {
|
||||
let mut entries: Vec<_> = map.iter().collect();
|
||||
entries.sort_unstable_by_key(|&(key, _)| key);
|
||||
entries
|
||||
}
|
||||
|
||||
// TODO: Do we want to enforce that all serialized/deserialized hashmaps are a vec of tuples?
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Serializes as sorted `[[key, value], ...]` (sequence of pairs)
|
||||
@@ -1295,23 +1263,6 @@ mod tests {
|
||||
format!("{anchors:?}\n{segments:?}\n{strokes:?}\n{pairs:?}")
|
||||
}
|
||||
|
||||
fn cache_hash(modification: &VectorModification) -> u64 {
|
||||
let mut hasher = std::hash::DefaultHasher::new();
|
||||
graphene_hash::CacheHash::cache_hash(modification, &mut hasher);
|
||||
std::hash::Hasher::finish(&hasher)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equal_modifications_hash_equally() {
|
||||
let (vector, paths) = mixed_geometry();
|
||||
|
||||
let first = VectorModification::create_from_vector(&vector, &paths);
|
||||
let second = VectorModification::create_from_vector(&vector, &paths);
|
||||
|
||||
assert_eq!(cache_hash(&first), cache_hash(&first));
|
||||
assert_eq!(cache_hash(&first), cache_hash(&second));
|
||||
}
|
||||
|
||||
/// Every curve type, a weld where they change, a smooth anchor, and a second subpath.
|
||||
fn mixed_geometry() -> (Vector, List<Path>) {
|
||||
let mut bezpath = BezPath::new();
|
||||
|
||||
@@ -84,9 +84,7 @@ impl WgpuExecutor {
|
||||
let view = vello_gpu::kurbo::Affine::new(view.to_cols_array());
|
||||
|
||||
let mut canvas = self.inner.document_canvas.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
self.inner
|
||||
.vello_renderer
|
||||
.render(&mut canvas, &self.context().device, &self.context().queue, draw, view, size, &texture)?;
|
||||
self.inner.vello_renderer.render(self, &mut canvas, draw, view, size, &texture)?;
|
||||
|
||||
Ok(texture)
|
||||
}
|
||||
@@ -95,7 +93,7 @@ impl WgpuExecutor {
|
||||
pub fn render_vello_scene_on_canvas(&self, canvas: &mut VelloCanvas, scene: VelloSceneBuilder) -> Result<Texture> {
|
||||
let texture = self.request_texture(UVec2::new(scene.width() as u32, scene.height() as u32));
|
||||
|
||||
self.inner.vello_renderer.render_scene(canvas, &self.context().device, &self.context().queue, scene, &texture);
|
||||
self.inner.vello_renderer.render_scene(self, canvas, scene, &texture);
|
||||
|
||||
Ok(texture)
|
||||
}
|
||||
@@ -165,7 +163,11 @@ impl WgpuExecutor {
|
||||
}
|
||||
|
||||
pub fn request_texture_with_format(&self, size: UVec2, format: wgpu::TextureFormat) -> Texture {
|
||||
self.inner.texture_cache.lock().unwrap().request_texture(&self.context().device, size, format)
|
||||
self.request_texture_with_mips(size, format, 1)
|
||||
}
|
||||
|
||||
pub fn request_texture_with_mips(&self, size: UVec2, format: wgpu::TextureFormat, mip_level_count: u32) -> Texture {
|
||||
self.inner.texture_cache.lock().unwrap().request_texture(self.context(), size, format, mip_level_count)
|
||||
}
|
||||
|
||||
pub fn create_buffer(&self, desc: &wgpu::BufferDescriptor) -> Buffer {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::WgpuContext;
|
||||
use glam::UVec2;
|
||||
use raster_types::Texture;
|
||||
use std::collections::VecDeque;
|
||||
@@ -16,24 +17,23 @@ impl TextureCache {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn request_texture(&mut self, device: &wgpu::Device, size: UVec2, format: wgpu::TextureFormat) -> Texture {
|
||||
pub fn request_texture(&mut self, context: &WgpuContext, size: UVec2, format: wgpu::TextureFormat, mip_level_count: u32) -> Texture {
|
||||
let size = size.max(UVec2::ONE);
|
||||
|
||||
if let Some(pos) = self
|
||||
.textures
|
||||
.iter()
|
||||
.position(|texture| UVec2::new(texture.width(), texture.height()) == size && texture.format() == format && !texture.is_shared() && !texture.is_weakly_shared())
|
||||
{
|
||||
if let Some(pos) = self.textures.iter().position(|texture| {
|
||||
UVec2::new(texture.width(), texture.height()) == size && texture.format() == format && texture.mip_level_count() == mip_level_count && !texture.is_shared() && !texture.is_weakly_shared()
|
||||
}) {
|
||||
let entry = self.textures.remove(pos).unwrap();
|
||||
let texture = entry.clone();
|
||||
self.textures.push_back(entry);
|
||||
return texture;
|
||||
}
|
||||
|
||||
let incoming_bytes = size.x as u64 * size.y as u64 * format.block_copy_size(None).unwrap_or(4) as u64;
|
||||
self.evict_until_fits(incoming_bytes);
|
||||
self.evict_until_fits(memory_size_estimate(size, format, mip_level_count));
|
||||
|
||||
let texture: Texture = device
|
||||
let usage = wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT;
|
||||
let texture: Texture = context
|
||||
.device
|
||||
.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some(&format!("cached_{}x{}", size.x, size.y)),
|
||||
size: wgpu::Extent3d {
|
||||
@@ -41,11 +41,11 @@ impl TextureCache {
|
||||
height: size.y,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
mip_level_count,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
usage: usage & context.adapter.get_texture_format_features(format).allowed_usages,
|
||||
view_formats: &[],
|
||||
})
|
||||
.into();
|
||||
@@ -83,12 +83,20 @@ impl TextureCache {
|
||||
}
|
||||
}
|
||||
|
||||
fn memory_size_estimate(size: UVec2, format: wgpu::TextureFormat, mip_level_count: u32) -> u64 {
|
||||
let texel_bytes = format.block_copy_size(None).unwrap_or(4) as u64;
|
||||
(0..mip_level_count)
|
||||
.map(|level| (size >> level).max(UVec2::ONE))
|
||||
.map(|level_size| level_size.x as u64 * level_size.y as u64 * texel_bytes)
|
||||
.sum()
|
||||
}
|
||||
|
||||
trait TextureMemoryCostEstimateExt {
|
||||
fn memory_size_estimate(&self) -> u64;
|
||||
}
|
||||
|
||||
impl TextureMemoryCostEstimateExt for wgpu::Texture {
|
||||
fn memory_size_estimate(&self) -> u64 {
|
||||
self.width() as u64 * self.height() as u64 * self.format().block_copy_size(None).unwrap_or(4) as u64
|
||||
memory_size_estimate(UVec2::new(self.width(), self.height()), self.format(), self.mip_level_count())
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,13 @@
|
||||
//! from `vello_adjustments.wgsl`, while the kinds that compilers struggle to build inside its loop each get a shader and pass of their own. Steps read their
|
||||
//! settings from a texture, so changing those recompiles nothing.
|
||||
|
||||
use crate::WgpuExecutor;
|
||||
use crate::vello_effects::{WORKING_FORMAT, pass_pipeline};
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use glam::UVec2;
|
||||
use graphic_types::Adjustment;
|
||||
use raster_kernels::adjustment_steps::{AdjustmentSteps, StepKind, shader_constants};
|
||||
use raster_types::{Texture, TextureWeakRef};
|
||||
use std::cmp::Reverse;
|
||||
use std::collections::HashMap;
|
||||
use std::ops::Range;
|
||||
@@ -22,11 +25,8 @@ const STANDALONE_KINDS: [StepKind; 2] = [StepKind::GradientMap, StepKind::ColorL
|
||||
/// How many runs of adjustments keep their encoded and uploaded steps past the render that last used them. Their tables are kept apart.
|
||||
const MAX_CACHED_RUNS: usize = 8;
|
||||
|
||||
/// How many bytes of tables stay uploaded past the render that last used them, the least recently used making way first.
|
||||
const TABLE_CACHE_BYTES: u64 = 256 << 20;
|
||||
|
||||
/// The most texels a run's tables span (128 MiB), past which they are resampled to fit. That's half of what the cache keeps and of the largest buffer
|
||||
/// wgpu allocates by default, which an upload passes through.
|
||||
/// The most texels a run's tables span (128 MiB), past which they are resampled to fit. That's half of the largest buffer wgpu allocates by default,
|
||||
/// which an upload passes through.
|
||||
const MAX_TABLE_TEXELS: usize = 1 << 23;
|
||||
|
||||
/// The format each pass of a run split across several hands its result on to the next in, where the GPU can render into it, so the split rounds nothing.
|
||||
@@ -344,15 +344,15 @@ fn texels_texture_descriptor(label: &'static str, width: u32, height: u32) -> wg
|
||||
}
|
||||
|
||||
/// A texture holding `texels` in rows as wide as the GPU allows, the last padded out, or `None` if they need more rows than it allows too.
|
||||
fn upload_texels(device: &wgpu::Device, queue: &wgpu::Queue, label: &'static str, texels: &[[f32; 4]]) -> Option<wgpu::Texture> {
|
||||
let max_dimension = device.limits().max_texture_dimension_2d as usize;
|
||||
fn upload_texels(executor: &WgpuExecutor, queue: &wgpu::Queue, texels: &[[f32; 4]]) -> Option<Texture> {
|
||||
let max_dimension = executor.context().device.limits().max_texture_dimension_2d as usize;
|
||||
let width = texels.len().clamp(1, max_dimension);
|
||||
let height = texels.len().div_ceil(width).max(1);
|
||||
if height > max_dimension {
|
||||
return None;
|
||||
}
|
||||
|
||||
let texture = device.create_texture(&texels_texture_descriptor(label, width as u32, height as u32));
|
||||
let texture = executor.request_texture_with_format(UVec2::new(width as u32, height as u32), wgpu::TextureFormat::Rgba32Float);
|
||||
let write_rows = |first_row: usize, rows: usize, data: &[[f32; 4]]| {
|
||||
let texture_rows = wgpu::TexelCopyTextureInfo {
|
||||
texture: &texture,
|
||||
@@ -397,12 +397,12 @@ pub(crate) struct PreparedPass {
|
||||
|
||||
/// The shader and the uploaded steps of each pass carrying out a run with these `steps`, each pass's texels starting with its step count,
|
||||
/// or `None` if any holds more than the GPU can read.
|
||||
fn upload_passes(device: &wgpu::Device, queue: &wgpu::Queue, steps: &AdjustmentSteps) -> Option<Vec<(AdjustmentShader, wgpu::Texture)>> {
|
||||
fn upload_passes(executor: &WgpuExecutor, queue: &wgpu::Queue, steps: &AdjustmentSteps) -> Option<Vec<(AdjustmentShader, Texture)>> {
|
||||
(pass_steps(steps.kinds()).into_iter())
|
||||
.map(|pass| {
|
||||
let shader = AdjustmentShader::for_pass(&steps.kinds()[pass.clone()]);
|
||||
let texels: Vec<[f32; 4]> = std::iter::once([pass.len() as f32, 0., 0., 0.]).chain(steps.step_texels(pass).iter().copied()).collect();
|
||||
upload_texels(device, queue, "vello_adjustments_steps", &texels).map(|texture| (shader, texture))
|
||||
upload_texels(executor, queue, &texels).map(|texture| (shader, texture))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -419,15 +419,14 @@ pub(crate) struct AdjustmentUploads {
|
||||
struct CachedRun {
|
||||
hash: u64,
|
||||
steps: AdjustmentSteps,
|
||||
passes: Option<Vec<(AdjustmentShader, wgpu::Texture)>>,
|
||||
passes: Option<Vec<(AdjustmentShader, TextureWeakRef)>>,
|
||||
last_used: u64,
|
||||
}
|
||||
|
||||
/// The tables of a run as uploaded, shared by every run reading the same ones, or `None` in place of the upload for tables too large for the GPU even resampled.
|
||||
struct CachedTables {
|
||||
key: u64,
|
||||
uploaded: Option<wgpu::Texture>,
|
||||
bytes: u64,
|
||||
uploaded: Option<TextureWeakRef>,
|
||||
last_used: u64,
|
||||
}
|
||||
|
||||
@@ -438,70 +437,95 @@ pub(crate) fn adjustment_run_hash(run: &[&Adjustment]) -> u64 {
|
||||
std::hash::Hasher::finish(&hasher)
|
||||
}
|
||||
|
||||
fn downgrade_passes(passes: &[(AdjustmentShader, Texture)]) -> Vec<(AdjustmentShader, TextureWeakRef)> {
|
||||
passes.iter().map(|(shader, texture)| (*shader, texture.downgrade())).collect()
|
||||
}
|
||||
|
||||
impl AdjustmentUploads {
|
||||
/// What each pass carrying out `run` reads in turn, encoding and uploading only what no recent render has. A run that changes no color
|
||||
/// or that holds more than the GPU can read takes no passes. Only the 64-bit hashes of the runs and of the tables' content tell them apart.
|
||||
pub(crate) fn prepare(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, run: &[&Adjustment], render_count: u64) -> Vec<PreparedPass> {
|
||||
/// What each pass carrying out `run` reads in turn, encoding and uploading only what no recent render has, with the uploads it reads added to `held`.
|
||||
/// A run that changes no color or that holds more than the GPU can read takes no passes. Only the 64-bit hashes of the runs and of the tables' content tell them apart.
|
||||
pub(crate) fn prepare(&mut self, executor: &WgpuExecutor, queue: &wgpu::Queue, run: &[&Adjustment], render_count: u64, held: &mut Vec<Texture>) -> Vec<PreparedPass> {
|
||||
let hash = adjustment_run_hash(run);
|
||||
let mut uploaded = None;
|
||||
let index = self.runs.iter().position(|cached| cached.hash == hash).unwrap_or_else(|| {
|
||||
let steps = AdjustmentSteps::encode(run);
|
||||
let passes = upload_passes(device, queue, &steps);
|
||||
if passes.is_none() {
|
||||
uploaded = upload_passes(executor, queue, &steps);
|
||||
if uploaded.is_none() {
|
||||
log::error!("Adjustments hold more settings than the GPU can read, so they're left out");
|
||||
}
|
||||
|
||||
self.runs.push(CachedRun {
|
||||
hash,
|
||||
steps,
|
||||
passes,
|
||||
passes: uploaded.as_deref().map(downgrade_passes),
|
||||
last_used: render_count,
|
||||
});
|
||||
self.runs.len() - 1
|
||||
});
|
||||
let cached_run = &mut self.runs[index];
|
||||
cached_run.last_used = render_count;
|
||||
let Some(passes) = cached_run.passes.clone() else { return Vec::new() };
|
||||
let Some(cached_passes) = &cached_run.passes else { return Vec::new() };
|
||||
let parked = cached_passes.iter().map(|(shader, texture)| Some((*shader, texture.upgrade()?))).collect();
|
||||
let passes = match uploaded.or(parked) {
|
||||
Some(passes) => passes,
|
||||
None => {
|
||||
let Some(passes) = upload_passes(executor, queue, &cached_run.steps) else { return Vec::new() };
|
||||
cached_run.passes = Some(downgrade_passes(&passes));
|
||||
passes
|
||||
}
|
||||
};
|
||||
if passes.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let tables = match cached_run.steps.table_key() {
|
||||
Some(key) => {
|
||||
let index = self.tables.iter().position(|cached| cached.key == key).unwrap_or_else(|| {
|
||||
// As many texels as one texture holds and one upload carries
|
||||
let limits = device.limits();
|
||||
let max_dimension = limits.max_texture_dimension_2d as usize;
|
||||
let max_uploaded = (limits.max_buffer_size / size_of::<[f32; 4]>() as u64) as usize;
|
||||
let texels = cached_run.steps.table_texels(MAX_TABLE_TEXELS.min(max_dimension * max_dimension).min(max_uploaded));
|
||||
let index = self.tables.iter().position(|cached| cached.key == key);
|
||||
let parked = index.map(|index| self.tables[index].uploaded.as_ref().map(TextureWeakRef::upgrade));
|
||||
let tables = match parked {
|
||||
// Failed to upload
|
||||
Some(None) => return Vec::new(),
|
||||
// Parked
|
||||
Some(Some(Some(tables))) => Some(tables),
|
||||
// Not parked
|
||||
Some(Some(None)) | None => {
|
||||
// As many texels as one texture holds and one upload carries
|
||||
let limits = executor.context().device.limits();
|
||||
let max_dimension = limits.max_texture_dimension_2d as usize;
|
||||
let max_uploaded = (limits.max_buffer_size / size_of::<[f32; 4]>() as u64) as usize;
|
||||
let texels = cached_run.steps.table_texels(MAX_TABLE_TEXELS.min(max_dimension * max_dimension).min(max_uploaded));
|
||||
|
||||
let uploaded = upload_texels(device, queue, "vello_adjustments_tables", &texels);
|
||||
if uploaded.is_none() {
|
||||
log::error!("Adjustments read lookup tables holding more data than the GPU can read, so they're left out");
|
||||
let uploaded = upload_texels(executor, queue, &texels);
|
||||
if uploaded.is_none() {
|
||||
log::error!("Adjustments read lookup tables holding more data than the GPU can read, so they're left out");
|
||||
}
|
||||
let cached = CachedTables {
|
||||
key,
|
||||
uploaded: uploaded.as_ref().map(Texture::downgrade),
|
||||
last_used: render_count,
|
||||
};
|
||||
match index {
|
||||
Some(index) => self.tables[index] = cached,
|
||||
None => self.tables.push(cached),
|
||||
}
|
||||
uploaded
|
||||
}
|
||||
|
||||
self.tables.push(CachedTables {
|
||||
key,
|
||||
bytes: uploaded
|
||||
.as_ref()
|
||||
.map_or(0, |texture| u64::from(texture.width()) * u64::from(texture.height()) * size_of::<[f32; 4]>() as u64),
|
||||
uploaded,
|
||||
last_used: render_count,
|
||||
});
|
||||
self.tables.len() - 1
|
||||
});
|
||||
let cached_tables = &mut self.tables[index];
|
||||
cached_tables.last_used = render_count;
|
||||
let Some(uploaded) = cached_tables.uploaded.clone() else { return Vec::new() };
|
||||
Some(uploaded)
|
||||
};
|
||||
let Some(tables) = tables else { return Vec::new() };
|
||||
if let Some(index) = index {
|
||||
self.tables[index].last_used = render_count;
|
||||
}
|
||||
Some(tables)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
held.extend(passes.iter().map(|(_, steps)| steps.clone()).chain(tables.clone()));
|
||||
(passes.into_iter())
|
||||
.map(|(shader, steps)| PreparedPass {
|
||||
shader,
|
||||
steps,
|
||||
tables: tables.clone(),
|
||||
steps: (*steps).clone(),
|
||||
tables: tables.as_ref().map(|tables| (**tables).clone()),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -513,13 +537,7 @@ impl AdjustmentUploads {
|
||||
let used_this_render = self.runs.iter().take_while(|cached| cached.last_used == render_count).count();
|
||||
self.runs.truncate(used_this_render.max(MAX_CACHED_RUNS));
|
||||
|
||||
// Tables are kept within a byte budget instead, since one can take up hundreds of megabytes
|
||||
self.tables.sort_by_key(|cached| Reverse(cached.last_used));
|
||||
let mut kept_bytes = 0;
|
||||
self.tables.retain(|cached| {
|
||||
kept_bytes += cached.bytes;
|
||||
cached.last_used == render_count || kept_bytes <= TABLE_CACHE_BYTES
|
||||
});
|
||||
self.tables.retain(|cached| cached.uploaded.as_ref().is_none_or(|tables| tables.upgrade().is_some()));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1630,11 +1630,7 @@ fn blend_lighten(c_b: f32, c_s: f32) -> f32 {
|
||||
return max(c_s, c_b);
|
||||
}
|
||||
|
||||
// A black backdrop stays black, and any other turns white under a white source, as the W3C formula orders them
|
||||
fn blend_color_dodge(c_b: f32, c_s: f32) -> f32 {
|
||||
if abs(c_b) <= BLEND_EDGE_TOLERANCE {
|
||||
return 0.;
|
||||
}
|
||||
if abs(c_s - 1.) <= BLEND_EDGE_TOLERANCE {
|
||||
return 1.;
|
||||
}
|
||||
@@ -1730,8 +1726,7 @@ fn blend_channel(mode: u32, c_b: f32, c_s: f32) -> f32 {
|
||||
return blend_pin_light(c_b, c_s);
|
||||
}
|
||||
case BLEND_HARD_MIX: {
|
||||
// A ramp a 256th wide around where the channels sum to 1, matching `blend_hard_mix`
|
||||
return (c_b - 255. / 256. * (1. - c_s)) * 256.;
|
||||
return select(1., 0., blend_linear_light(c_b, c_s) < 0.5);
|
||||
}
|
||||
case BLEND_DIFFERENCE: {
|
||||
return abs(c_b - c_s);
|
||||
@@ -1756,11 +1751,11 @@ fn blend_channel(mode: u32, c_b: f32, c_s: f32) -> f32 {
|
||||
fn apply_blend_mode(foreground: vec4<f32>, background: vec4<f32>, mode: u32) -> vec4<f32> {
|
||||
switch mode {
|
||||
case BLEND_DARKER_COLOR: {
|
||||
let background_is_darker = luma_rec_601_rounded(background.rgb) <= luma_rec_601_rounded(foreground.rgb);
|
||||
let background_is_darker = (background.r + background.g + background.b) / 3. <= (foreground.r + foreground.g + foreground.b) / 3.;
|
||||
return vec4<f32>(select(foreground.rgb, background.rgb, background_is_darker), foreground.a);
|
||||
}
|
||||
case BLEND_LIGHTER_COLOR: {
|
||||
let background_is_lighter = luma_rec_601_rounded(background.rgb) >= luma_rec_601_rounded(foreground.rgb);
|
||||
let background_is_lighter = (background.r + background.g + background.b) / 3. >= (foreground.r + foreground.g + foreground.b) / 3.;
|
||||
return vec4<f32>(select(foreground.rgb, background.rgb, background_is_lighter), foreground.a);
|
||||
}
|
||||
case BLEND_HUE, BLEND_SATURATION, BLEND_COLOR, BLEND_LUMINOSITY: {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! The GPU passes that carry out an item's effects on its content, between rendering the content offscreen and drawing the result back.
|
||||
|
||||
use crate::WgpuExecutor;
|
||||
use crate::vello_adjustments::{AdjustmentShaders, AdjustmentUploads, PassEncodings, PreparedPass};
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
use core_types::Color;
|
||||
@@ -14,6 +15,7 @@ use graphic_types::resampling::{DisplacementField, EffectFrame, FrameWarp, Halft
|
||||
use graphic_types::{Adjustment, BevelDirection, BevelStyle, BevelTechnique, EffectOperation, Effects, GlowSource, GlowTechnique};
|
||||
use raster_kernels::effect_kernels::{BlurKernel, MAX_DIRECT_BOX_RADIUS, NEGLIGIBLE_LENGTH, chamfer_passes};
|
||||
use raster_kernels::resample_kernels::MotionBlurShear;
|
||||
use raster_types::Texture;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
use vello_gpu::kurbo::Affine;
|
||||
@@ -21,7 +23,6 @@ use wgpu::util::DeviceExt;
|
||||
|
||||
mod blend_if;
|
||||
mod filters;
|
||||
mod layer_blend;
|
||||
mod masks;
|
||||
mod resample;
|
||||
mod styles;
|
||||
@@ -50,9 +51,6 @@ const GRADIENT_SAMPLES: u32 = GRADIENT_TABLE_SIZE as u32;
|
||||
const PARAMETER_TAPS: usize = 81;
|
||||
const _: () = assert!(PARAMETER_TAPS > 2 * raster_kernels::effect_kernels::MAX_KERNEL_REACH.div_ceil(2));
|
||||
|
||||
/// How many renders a pooled texture survives unused before it is freed.
|
||||
const UNUSED_TEXTURE_RENDER_LIMIT: u64 = 3;
|
||||
|
||||
/// The shader's parameters, laid out to match its `Parameters` struct.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Pod, Zeroable)]
|
||||
@@ -168,7 +166,7 @@ impl EffectPasses {
|
||||
log::warn!("This GPU can't render into the formats layer effects need, so content draws without its effects");
|
||||
}
|
||||
|
||||
// The filters', resampling, styles', masks', Blend If's, and layer blending's passes live in files of their own, sharing this one's bindings and helpers
|
||||
// The filters', resampling, styles', masks', and Blend If's passes live in files of their own, sharing this one's bindings and helpers
|
||||
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("vello_effects.wgsl"),
|
||||
source: wgpu::ShaderSource::Wgsl(
|
||||
@@ -180,8 +178,7 @@ impl EffectPasses {
|
||||
include_str!("vello_warp.wgsl"),
|
||||
include_str!("vello_styles.wgsl"),
|
||||
include_str!("vello_masks.wgsl"),
|
||||
include_str!("vello_blend_if.wgsl"),
|
||||
include_str!("vello_layer_blend.wgsl")
|
||||
include_str!("vello_blend_if.wgsl")
|
||||
)
|
||||
.into(),
|
||||
),
|
||||
@@ -265,8 +262,7 @@ impl EffectPasses {
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Carries out `effects` on `content`, a texture of premultiplied pixels, returning each of the `layers` they draw in a pooled texture of [`WORKING_FORMAT`] the same size, with the mode it blends by
|
||||
/// (normal for one in a mode Vello's layers lack, which comes back blended onto the `backdrop` already).
|
||||
/// Carries out `effects` on `content`, a texture of premultiplied pixels, returning each of the `layers` they draw in a pooled texture of [`WORKING_FORMAT`] the same size, with the mode it blends by.
|
||||
/// `effect_to_pixels` places the effects' space on the texture's pixels, `fill` fades the content but not the shadows and glows cast from it, and `opacity` fades the layers.
|
||||
/// The `frame`, in the texture's pixels, is the content's extent, which displacements take as their own.
|
||||
/// `paints` holds the effects' drawn paints in order, each rendered over the same pixels as the content.
|
||||
@@ -275,7 +271,7 @@ impl EffectPasses {
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub(crate) fn apply(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
executor: &WgpuExecutor,
|
||||
queue: &wgpu::Queue,
|
||||
textures: &mut EffectTextures,
|
||||
content: &wgpu::Texture,
|
||||
@@ -289,8 +285,10 @@ impl EffectPasses {
|
||||
backdrop: Option<(&wgpu::Texture, Affine)>,
|
||||
capture: Option<EffectCapture>,
|
||||
) -> Vec<(wgpu::Texture, BlendMode)> {
|
||||
let device = &executor.context().device;
|
||||
let mut recorder = PassRecorder {
|
||||
passes: self,
|
||||
executor,
|
||||
device,
|
||||
queue,
|
||||
encoder: device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_effects") }),
|
||||
@@ -300,16 +298,6 @@ impl EffectPasses {
|
||||
let lengths_to_pixels = effect_to_pixels.matrix2;
|
||||
let length_scale = lengths_to_pixels.determinant().abs().sqrt();
|
||||
|
||||
// A fill moving the content toward its layer mode's neutral color leaves the content at full strength, for its layer to blend by that fill.
|
||||
// Color Dodge and Color Burn layers blend so only where they read what lies beneath (see `EffectLayers::content_reads_backdrop`), and with nothing to read, natively.
|
||||
let content_mode = layers.content_layer().map(|layer| layers.layers[layer].blend_mode);
|
||||
let natively_otherwise = content_mode.is_some_and(|blend_mode| !blend_mode.reads_backdrop());
|
||||
let content_blends_onto_backdrop = layers.content_reads_backdrop(fill) && !(natively_otherwise && backdrop.is_none());
|
||||
let (fill, blend_fill) = match content_blends_onto_backdrop && content_mode.is_some_and(|blend_mode| blend_mode.fill_moves_layer_toward_neutral()) {
|
||||
true => (1., fill),
|
||||
false => (fill, 1.),
|
||||
};
|
||||
|
||||
// The content at full strength, which casts every silhouette, read from the content itself (whatever its format) until a pass replaces it
|
||||
let mut full: Option<wgpu::Texture> = None;
|
||||
// The content faded by the fill, which shows in the result
|
||||
@@ -845,7 +833,7 @@ impl EffectPasses {
|
||||
| EffectOperation::MinimumMaximum { .. }
|
||||
| EffectOperation::Sharpen { .. }
|
||||
| EffectOperation::HighPass { .. }
|
||||
| EffectOperation::Speckle { .. }
|
||||
| EffectOperation::AddNoise { .. }
|
||||
| EffectOperation::Dissolve { .. } => {
|
||||
recorder.merge_beneath(content, &mut full, &mut filled, beneath.take());
|
||||
let captured_plane = capture.filter(|capture| capture.index == index).map(|capture| capture.plane);
|
||||
@@ -1012,7 +1000,7 @@ impl EffectPasses {
|
||||
// The content at full strength is read only by an operation after the run, or shown as the result where no fill fades it
|
||||
let full_is_read = filled.is_none() || position + run.len() < operations.len();
|
||||
|
||||
let prepared_passes = recorder.textures.prepare_adjustments(device, queue, &run);
|
||||
let prepared_passes = recorder.textures.prepare_adjustments(recorder.executor, queue, &run);
|
||||
|
||||
// Each pass but the last hands its result on in the chained format, so splitting the run rounds nothing
|
||||
for (index, prepared) in prepared_passes.iter().enumerate() {
|
||||
@@ -1143,7 +1131,7 @@ impl EffectPasses {
|
||||
|
||||
// Each layer stacks its parts in order: what lies beneath the content, then the content with what lies within it
|
||||
let mut content_image = Some(content_image);
|
||||
let (mut results, mut content_result) = (Vec::new(), None);
|
||||
let mut results = Vec::new();
|
||||
for (index, layer) in layers.layers.iter().enumerate() {
|
||||
let holds_content = Some(index) == content_layer;
|
||||
let mut stack = if holds_content { beneath.take() } else { None };
|
||||
@@ -1212,16 +1200,9 @@ impl EffectPasses {
|
||||
let faded = recorder.run("apply_mask", WORKING_FORMAT, recorder.size, &result, Some(fade), None, Parameters::default());
|
||||
recorder.replace(&mut result, faded);
|
||||
}
|
||||
if holds_content {
|
||||
content_result = Some(results.len());
|
||||
}
|
||||
results.push((result, layer.blend_mode));
|
||||
}
|
||||
|
||||
// A layer in a mode Vello's layers lack blends onto what lies beneath here, before the Blend Ifs fade the blended layer
|
||||
let content_result = content_result.filter(|_| content_blends_onto_backdrop);
|
||||
recorder.blend_onto_backdrop(backdrop, blend_fill, content_result, &mut results);
|
||||
|
||||
// Blend If's ranges of what lies beneath fade every layer, like the opacity varying across them
|
||||
let underlying = underlying_ranges(&every_operation);
|
||||
if let Some(backdrop) = backdrop.filter(|_| !underlying.is_empty()) {
|
||||
@@ -1243,7 +1224,7 @@ impl EffectPasses {
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub(crate) fn adjust_image(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
executor: &WgpuExecutor,
|
||||
queue: &wgpu::Queue,
|
||||
textures: &mut EffectTextures,
|
||||
image: &wgpu::Texture,
|
||||
@@ -1252,8 +1233,10 @@ impl EffectPasses {
|
||||
target: &wgpu::Texture,
|
||||
) {
|
||||
let size = UVec2::new(image.width(), image.height());
|
||||
let device = &executor.context().device;
|
||||
let mut recorder = PassRecorder {
|
||||
passes: self,
|
||||
executor,
|
||||
device,
|
||||
queue,
|
||||
encoder: device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
@@ -1285,19 +1268,20 @@ impl EffectPasses {
|
||||
}
|
||||
chained.into_iter().for_each(|texture| recorder.textures.release(texture));
|
||||
|
||||
self.record_mipmaps(device, &mut recorder.encoder, recorder.textures, target);
|
||||
self.record_mipmaps(executor, &mut recorder.encoder, recorder.textures, target);
|
||||
queue.submit([recorder.encoder.finish()]);
|
||||
}
|
||||
|
||||
/// Records the averaging of each of `texture`'s smaller mip levels from the one above it, like the levels of an uploaded image.
|
||||
/// Each is halved into a pooled texture and copied into place, since WebGL sets the levels read for a whole texture, so none is drawn into while another is read.
|
||||
pub(crate) fn record_mipmaps(&self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, textures: &mut EffectTextures, texture: &wgpu::Texture) {
|
||||
pub(crate) fn record_mipmaps(&self, executor: &WgpuExecutor, encoder: &mut wgpu::CommandEncoder, textures: &mut EffectTextures, texture: &wgpu::Texture) {
|
||||
let device = &executor.context().device;
|
||||
let format = texture.format();
|
||||
let mut above: Option<wgpu::Texture> = None;
|
||||
|
||||
for index in 1..texture.mip_level_count() {
|
||||
let level_size = UVec2::new(texture.width() >> index, texture.height() >> index).max(UVec2::ONE);
|
||||
let level = textures.acquire(device, level_size, format);
|
||||
let level = textures.acquire(executor, level_size, format);
|
||||
|
||||
// The first level reads the top one through a view of every level
|
||||
let source = above.as_ref().unwrap_or(texture).create_view(&wgpu::TextureViewDescriptor::default());
|
||||
@@ -1450,6 +1434,7 @@ fn premultiplied_gamma_channels(color: Color) -> [f32; 4] {
|
||||
/// Records the passes of one effects group, whose images all share one size.
|
||||
struct PassRecorder<'a> {
|
||||
passes: &'a EffectPasses,
|
||||
executor: &'a WgpuExecutor,
|
||||
device: &'a wgpu::Device,
|
||||
queue: &'a wgpu::Queue,
|
||||
encoder: wgpu::CommandEncoder,
|
||||
@@ -1470,7 +1455,7 @@ impl PassRecorder<'_> {
|
||||
content: Option<&wgpu::Texture>,
|
||||
parameters: Parameters,
|
||||
) -> wgpu::Texture {
|
||||
let target = self.textures.acquire(self.device, size, format);
|
||||
let target = self.textures.acquire(self.executor, size, format);
|
||||
|
||||
let view = |texture: &wgpu::Texture| texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let (source, secondary, content) = (view(source), secondary.map(view), content.map(view));
|
||||
@@ -1618,7 +1603,7 @@ impl PassRecorder<'_> {
|
||||
fn gradient_glow_tint(&mut self, paint: &GlowFill, strength: &wgpu::Texture, content: &wgpu::Texture, fades: bool, grain: Option<&styles::GlowGrain>) -> Option<wgpu::Texture> {
|
||||
let (samples, opacity) = paint.gradient_samples(GRADIENT_SAMPLES as usize)?;
|
||||
let samples: Vec<half::f16> = samples.into_iter().flatten().map(half::f16::from_f32).collect();
|
||||
let samples = self.row_texture("vello_effects_gradient", wgpu::TextureFormat::Rgba16Float, GRADIENT_SAMPLES, bytemuck::cast_slice(&samples));
|
||||
let samples = self.row_texture(wgpu::TextureFormat::Rgba16Float, GRADIENT_SAMPLES, bytemuck::cast_slice(&samples));
|
||||
|
||||
let parameters = Parameters {
|
||||
values: [if fades { 1. } else { 0. }, GRADIENT_GLOW_FADE as f32, opacity, grain.map_or(0., |grain| grain.amounts[0] as f32)],
|
||||
@@ -1673,27 +1658,17 @@ impl PassRecorder<'_> {
|
||||
let samples: Vec<half::f16> = (0..CONTOUR_SAMPLES)
|
||||
.map(|index| half::f16::from_f64(contour.evaluate(index as f64 / (CONTOUR_SAMPLES - 1) as f64).clamp(0., 1.)))
|
||||
.collect();
|
||||
self.row_texture("vello_effects_contour", COVERAGE_FORMAT, CONTOUR_SAMPLES, bytemuck::cast_slice(&samples))
|
||||
self.row_texture(COVERAGE_FORMAT, CONTOUR_SAMPLES, bytemuck::cast_slice(&samples))
|
||||
}
|
||||
|
||||
/// A texture one row of `width` texels tall holding `data` in the `format`, for shaders to interpolate between its samples.
|
||||
/// It's made fresh rather than pooled, since its upload runs ahead of the passes recorded before it that a pooled texture may still serve.
|
||||
fn row_texture(&mut self, label: &str, format: wgpu::TextureFormat, width: u32, data: &[u8]) -> wgpu::Texture {
|
||||
fn row_texture(&mut self, format: wgpu::TextureFormat, width: u32, data: &[u8]) -> wgpu::Texture {
|
||||
let extent = wgpu::Extent3d {
|
||||
width,
|
||||
height: 1,
|
||||
depth_or_array_layers: 1,
|
||||
};
|
||||
let texture = self.device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some(label),
|
||||
size: extent,
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
let texture = self.executor.request_texture_with_format(UVec2::new(width, 1), format);
|
||||
self.queue.write_texture(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: &texture,
|
||||
@@ -1709,7 +1684,9 @@ impl PassRecorder<'_> {
|
||||
},
|
||||
extent,
|
||||
);
|
||||
texture
|
||||
let row = (*texture).clone();
|
||||
self.textures.held.push(texture);
|
||||
row
|
||||
}
|
||||
|
||||
/// The coverage (or tinted image) of what lies beneath, hidden behind the full-strength content where a `fill` below 1 (times the Blend If weight if any) fades the content that shows over it.
|
||||
@@ -1918,7 +1895,7 @@ impl PassRecorder<'_> {
|
||||
/// The image (of any format a shader can load from) with a pass of adjustments carried out on it into a texture of `format`, reading what was `prepared` for the pass,
|
||||
/// in the `encodings` of its source and result.
|
||||
fn adjust(&mut self, image: &wgpu::Texture, prepared: &PreparedPass, format: wgpu::TextureFormat, encodings: PassEncodings) -> wgpu::Texture {
|
||||
let target = self.textures.acquire(self.device, self.size, format);
|
||||
let target = self.textures.acquire(self.executor, self.size, format);
|
||||
|
||||
let view = |texture: &wgpu::Texture| texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
self.adjust_into(&view(&target), format, &view(image), prepared, encodings);
|
||||
@@ -2014,11 +1991,11 @@ impl PassRecorder<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Textures for the effect passes and the content they work on, kept between renders for reuse at the same sizes.
|
||||
/// Textures for the effect passes and the content they work on, taken from the texture pool and held until the render ends.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct EffectTextures {
|
||||
/// Each unused texture with the render it was last used in.
|
||||
free: Vec<(wgpu::Texture, u64)>,
|
||||
held: Vec<Texture>,
|
||||
released: Vec<wgpu::Texture>,
|
||||
/// The uploads of recent runs of adjustments.
|
||||
adjustments: AdjustmentUploads,
|
||||
render_count: u64,
|
||||
@@ -2029,43 +2006,32 @@ pub(crate) struct EffectTextures {
|
||||
|
||||
impl EffectTextures {
|
||||
/// What each pass carrying out a run of adjustments reads, as [`AdjustmentUploads::prepare`] gives it.
|
||||
pub(crate) fn prepare_adjustments(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, run: &[&Adjustment]) -> Vec<PreparedPass> {
|
||||
self.adjustments.prepare(device, queue, run, self.render_count)
|
||||
pub(crate) fn prepare_adjustments(&mut self, executor: &WgpuExecutor, queue: &wgpu::Queue, run: &[&Adjustment]) -> Vec<PreparedPass> {
|
||||
self.adjustments.prepare(executor, queue, run, self.render_count, &mut self.held)
|
||||
}
|
||||
|
||||
pub(crate) fn acquire(&mut self, device: &wgpu::Device, size: UVec2, format: wgpu::TextureFormat) -> wgpu::Texture {
|
||||
pub(crate) fn acquire(&mut self, executor: &WgpuExecutor, size: UVec2, format: wgpu::TextureFormat) -> wgpu::Texture {
|
||||
let size = size.max(UVec2::ONE);
|
||||
let matches = |texture: &wgpu::Texture| texture.width() == size.x && texture.height() == size.y && texture.format() == format;
|
||||
if let Some(index) = self.free.iter().position(|(texture, _)| matches(texture)) {
|
||||
return self.free.swap_remove(index).0;
|
||||
if let Some(index) = self.released.iter().position(matches) {
|
||||
return self.released.swap_remove(index);
|
||||
}
|
||||
|
||||
device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("vello_effects_texture"),
|
||||
size: wgpu::Extent3d {
|
||||
width: size.x,
|
||||
height: size.y,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
})
|
||||
let texture = executor.request_texture_with_format(size, format);
|
||||
let acquired = (*texture).clone();
|
||||
self.held.push(texture);
|
||||
acquired
|
||||
}
|
||||
|
||||
/// Returns a texture to the pool once the passes recorded so far are done with it, since later passes are recorded and submitted after them.
|
||||
pub(crate) fn release(&mut self, texture: wgpu::Texture) {
|
||||
self.free.push((texture, self.render_count));
|
||||
self.released.push(texture);
|
||||
}
|
||||
|
||||
/// Frees the textures no recent render has used.
|
||||
pub(crate) fn finish_render(&mut self) {
|
||||
let render_count = self.render_count;
|
||||
self.free.retain(|(_, last_used)| render_count - last_used < UNUSED_TEXTURE_RENDER_LIMIT);
|
||||
self.adjustments.finish_render(render_count);
|
||||
self.released.clear();
|
||||
self.held.clear();
|
||||
self.adjustments.finish_render(self.render_count);
|
||||
|
||||
self.render_count += 1;
|
||||
}
|
||||
@@ -2108,7 +2074,10 @@ mod tests {
|
||||
use core_types::list::Item;
|
||||
use graphic_types::vector_types::Gradient;
|
||||
|
||||
let Some(context) = futures::executor::block_on(crate::WgpuContext::for_tests()) else { return };
|
||||
let Some(executor) = futures::executor::block_on(crate::WgpuContext::for_tests()).and_then(crate::WgpuExecutor::with_context) else {
|
||||
return;
|
||||
};
|
||||
let context = executor.context();
|
||||
let passes = EffectPasses::new(&context.device, &context.adapter);
|
||||
if !passes.renders_working_formats {
|
||||
return;
|
||||
@@ -2146,12 +2115,12 @@ mod tests {
|
||||
let effects = Effects::from_operations(operations);
|
||||
|
||||
let mut textures = EffectTextures::default();
|
||||
let content = textures.acquire(&context.device, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm);
|
||||
let content = textures.acquire(&executor, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm);
|
||||
let queue = context.queue.lock();
|
||||
let apply = |textures: &mut EffectTextures, effects: &Effects| {
|
||||
textures.drawn_passes.clear();
|
||||
let layers = EffectLayers::plan(effects, BlendMode::Normal, 1., false);
|
||||
let results = passes.apply(&context.device, &queue, textures, &content, effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None);
|
||||
let results = passes.apply(&executor, &queue, textures, &content, effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None);
|
||||
results.into_iter().for_each(|(result, _)| textures.release(result));
|
||||
};
|
||||
let draw = |textures: &mut EffectTextures| {
|
||||
@@ -2173,7 +2142,7 @@ mod tests {
|
||||
textures.drawn_passes.clear();
|
||||
let effects = Effects::from_operations(operations);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, fill, false);
|
||||
let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, fill, 1., DAffine2::IDENTITY, None, &[], None, None);
|
||||
let results = passes.apply(&executor, &queue, &mut textures, &content, &effects, &layers, fill, 1., DAffine2::IDENTITY, None, &[], None, None);
|
||||
results.into_iter().for_each(|(result, _)| textures.release(result));
|
||||
textures.drawn_passes.clone()
|
||||
};
|
||||
@@ -2204,7 +2173,10 @@ mod tests {
|
||||
fn effects_blending_normally_at_a_full_fill_take_no_more_passes_when_layered() {
|
||||
use graphic_types::effects::EffectKind;
|
||||
|
||||
let Some(context) = futures::executor::block_on(crate::WgpuContext::for_tests()) else { return };
|
||||
let Some(executor) = futures::executor::block_on(crate::WgpuContext::for_tests()).and_then(crate::WgpuExecutor::with_context) else {
|
||||
return;
|
||||
};
|
||||
let context = executor.context();
|
||||
let passes = EffectPasses::new(&context.device, &context.adapter);
|
||||
if !passes.renders_working_formats {
|
||||
return;
|
||||
@@ -2212,12 +2184,12 @@ mod tests {
|
||||
|
||||
let effects = Effects::from_operations([EffectOperation::default_for(EffectKind::DropShadow), EffectOperation::default_for(EffectKind::InnerShadow)]);
|
||||
let mut textures = EffectTextures::default();
|
||||
let content = textures.acquire(&context.device, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm);
|
||||
let content = textures.acquire(&executor, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm);
|
||||
let queue = context.queue.lock();
|
||||
let mut drawn = |layered: bool| {
|
||||
textures.drawn_passes.clear();
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., layered);
|
||||
let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None);
|
||||
let results = passes.apply(&executor, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None);
|
||||
results.into_iter().for_each(|(result, _)| textures.release(result));
|
||||
textures.drawn_passes.clone()
|
||||
};
|
||||
@@ -2228,7 +2200,10 @@ mod tests {
|
||||
fn a_bevel_without_a_gloss_contour_or_texture_lights_its_highlight_and_shadow_directly() {
|
||||
use graphic_types::effects::EffectKind;
|
||||
|
||||
let Some(context) = futures::executor::block_on(crate::WgpuContext::for_tests()) else { return };
|
||||
let Some(executor) = futures::executor::block_on(crate::WgpuContext::for_tests()).and_then(crate::WgpuExecutor::with_context) else {
|
||||
return;
|
||||
};
|
||||
let context = executor.context();
|
||||
let passes = EffectPasses::new(&context.device, &context.adapter);
|
||||
if !passes.renders_working_formats {
|
||||
return;
|
||||
@@ -2236,10 +2211,10 @@ mod tests {
|
||||
|
||||
let effects = Effects::from_operations([EffectOperation::default_for(EffectKind::BevelAndEmboss)]);
|
||||
let mut textures = EffectTextures::default();
|
||||
let content = textures.acquire(&context.device, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm);
|
||||
let content = textures.acquire(&executor, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm);
|
||||
let queue = context.queue.lock();
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false);
|
||||
let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None);
|
||||
let results = passes.apply(&executor, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None);
|
||||
results.into_iter().for_each(|(result, _)| textures.release(result));
|
||||
|
||||
let drawn = |label: &str| textures.drawn_passes.iter().filter(|&&drawn| drawn == label).count();
|
||||
@@ -2248,7 +2223,10 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_table_stays_uploaded_while_the_settings_beside_it_change() {
|
||||
let Some(context) = futures::executor::block_on(crate::WgpuContext::for_tests()) else { return };
|
||||
let Some(executor) = futures::executor::block_on(crate::WgpuContext::for_tests()).and_then(crate::WgpuExecutor::with_context) else {
|
||||
return;
|
||||
};
|
||||
let context = executor.context();
|
||||
let queue = context.queue.lock();
|
||||
|
||||
let lookup = Adjustment::ColorLookup {
|
||||
@@ -2258,7 +2236,7 @@ mod tests {
|
||||
let prepare = |textures: &mut EffectTextures, posterize_levels| {
|
||||
let posterize = Adjustment::Posterize { levels: posterize_levels };
|
||||
// Color Lookup's pass and then Posterize's, which share the run's tables
|
||||
let mut prepared = textures.prepare_adjustments(&context.device, &queue, &[&lookup, &posterize]);
|
||||
let mut prepared = textures.prepare_adjustments(&executor, &queue, &[&lookup, &posterize]);
|
||||
prepared.pop().map(|prepared| (prepared.steps, prepared.tables))
|
||||
};
|
||||
|
||||
@@ -2270,11 +2248,13 @@ mod tests {
|
||||
panic!("The run reads its table")
|
||||
};
|
||||
assert!(first_steps == again_steps && first_table == again_table);
|
||||
let Some((other_steps, _)) = prepare(&mut textures, 5) else { panic!("The run reads its table") };
|
||||
assert!(other_steps != first_steps);
|
||||
for levels in 5..20 {
|
||||
let Some((steps, Some(table))) = prepare(&mut textures, levels) else {
|
||||
let Some((_, Some(table))) = prepare(&mut textures, levels) else {
|
||||
panic!("The run reads its table")
|
||||
};
|
||||
assert!(steps != first_steps && table == first_table);
|
||||
assert!(table == first_table);
|
||||
textures.finish_render();
|
||||
}
|
||||
|
||||
|
||||
@@ -431,13 +431,14 @@ fn composite_beneath(@builtin(position) position: vec4<f32>) -> @location(0) vec
|
||||
|
||||
// The paint mixed with the backdrop by a blend mode besides the component ones, numbered in the order `BlendMode` declares them
|
||||
fn blend(backdrop: vec3<f32>, paint: vec3<f32>, mode: u32) -> vec3<f32> {
|
||||
let average = vec3<f32>(1. / 3.);
|
||||
switch mode {
|
||||
// Darker Color and Lighter Color keep whichever whole color has the lower or higher luma, the backdrop where they tie
|
||||
// Darker Color and Lighter Color keep whichever whole color has the lower or higher mean
|
||||
case 5u: {
|
||||
return select(paint, backdrop, luma(backdrop) <= luma(paint));
|
||||
return select(paint, backdrop, dot(backdrop, average) <= dot(paint, average));
|
||||
}
|
||||
case 10u: {
|
||||
return select(paint, backdrop, luma(backdrop) >= luma(paint));
|
||||
return select(paint, backdrop, dot(backdrop, average) >= dot(paint, average));
|
||||
}
|
||||
default: {
|
||||
return vec3<f32>(blend_channel(backdrop.r, paint.r, mode), blend_channel(backdrop.g, paint.g, mode), blend_channel(backdrop.b, paint.b, mode));
|
||||
@@ -503,7 +504,7 @@ fn blend_channel(backdrop: f32, paint: f32, mode: u32) -> f32 {
|
||||
result = select(max(2. * paint - 1., backdrop), min(2. * paint, backdrop), paint <= 0.5);
|
||||
}
|
||||
case 17u: {
|
||||
result = hard_mix(backdrop, paint, 1.);
|
||||
result = select(1., 0., linear_light(backdrop, paint) < 0.5);
|
||||
}
|
||||
// Difference, Exclusion, Subtract, Divide
|
||||
case 18u: {
|
||||
@@ -544,11 +545,7 @@ fn color_burn(backdrop: f32, paint: f32) -> f32 {
|
||||
return 1. - min((1. - backdrop) / paint, 1.);
|
||||
}
|
||||
|
||||
// A black backdrop stays black, and any other turns white under white paint, as the W3C formula orders them
|
||||
fn color_dodge(backdrop: f32, paint: f32) -> f32 {
|
||||
if abs(backdrop) <= BLEND_EDGE_TOLERANCE {
|
||||
return 0.;
|
||||
}
|
||||
if abs(paint - 1.) <= BLEND_EDGE_TOLERANCE {
|
||||
return 1.;
|
||||
}
|
||||
@@ -571,12 +568,6 @@ fn linear_light(backdrop: f32, paint: f32) -> f32 {
|
||||
return select(2. * paint - 1. + backdrop, 2. * paint + backdrop - 1., paint <= 0.5);
|
||||
}
|
||||
|
||||
// Hard Mix of a paint at `strength`, unclamped, whose ramp steepens to a 256th wide at full strength, matching the CPU's `blend_hard_mix_at_strength`
|
||||
fn hard_mix(backdrop: f32, paint: f32, strength: f32) -> f32 {
|
||||
let steepness = 255. * strength / 256.;
|
||||
return (backdrop - steepness * (1. - paint)) / (1. - steepness);
|
||||
}
|
||||
|
||||
// Hue, Saturation, Color, and Luminosity on gamma-encoded channels, as the compositing specification constructs them
|
||||
fn blend_components(backdrop: vec3<f32>, paint: vec3<f32>, mode: u32) -> vec3<f32> {
|
||||
switch mode {
|
||||
|
||||
@@ -50,7 +50,7 @@ pub(super) fn field_parameters(sampling: &FieldSampling, first_seed: u32, second
|
||||
fn field_passes(operation: &EffectOperation, effect_to_pixels: DAffine2) -> Option<(&'static str, &'static str, Parameters)> {
|
||||
let sampling = FieldSampling::new(effect_to_pixels.inverse());
|
||||
match *operation {
|
||||
EffectOperation::Speckle {
|
||||
EffectOperation::AddNoise {
|
||||
amount,
|
||||
distribution,
|
||||
monochromatic,
|
||||
@@ -67,7 +67,7 @@ fn field_passes(operation: &EffectOperation, effect_to_pixels: DAffine2) -> Opti
|
||||
],
|
||||
..field_parameters(&sampling, RandomField::NoiseOffsets.seed(seed), RandomField::NoiseAngles.seed(seed))
|
||||
};
|
||||
Some(("speckle_map", "speckle", parameters))
|
||||
Some(("noise_map", "add_noise", parameters))
|
||||
}
|
||||
EffectOperation::Dissolve { opacity, seed } => {
|
||||
let parameters = Parameters {
|
||||
|
||||
@@ -412,7 +412,7 @@ fn sample_offset(column: u32, row: u32) -> vec2<f32> {
|
||||
return ((vec2<f32>(f32(column), f32(row)) + 0.5) / parameters.taps[2].xy - 0.5) * parameters.taps[2].zw;
|
||||
}
|
||||
|
||||
// The offsets Speckle gives a texel's colors, matching the CPU's `speckle`: its noise averaged over its samples (Gaussian with `values.z` 1), the same for every color with `values.w` 1,
|
||||
// The offsets Add Noise gives a texel's colors, matching the CPU's `add_noise`: its noise averaged over its samples (Gaussian with `values.z` 1), the same for every color with `values.w` 1,
|
||||
// scaled by `values.x` and kept within `values.y` either way
|
||||
fn noise_offsets(position: vec2<f32>) -> vec3<f32> {
|
||||
let counts = sample_counts();
|
||||
@@ -439,15 +439,15 @@ fn noise_offsets(position: vec2<f32>) -> vec3<f32> {
|
||||
return clamp(noise * parameters.values.x, vec3<f32>(-parameters.values.y), vec3<f32>(parameters.values.y));
|
||||
}
|
||||
|
||||
// The offsets Speckle gives each color, around middle gray and scaled to fill the range, which an SVG adds to the colors
|
||||
// The offsets Add Noise gives each color, around middle gray and scaled to fill the range, which an SVG adds to the colors
|
||||
@fragment
|
||||
fn speckle_map(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
fn noise_map(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
return vec4<f32>(0.5 + noise_offsets(position.xy) / (2. * parameters.values.y), 1.);
|
||||
}
|
||||
|
||||
// Each straight color offset by noise and clamped, with the coverage kept
|
||||
@fragment
|
||||
fn speckle(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
fn add_noise(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let color = textureLoad(source, vec2<i32>(position.xy), 0);
|
||||
if color.a <= 0. {
|
||||
return vec4<f32>(0.);
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
//! The GPU pass blending a layer by a mode Vello's layers lack, onto what lies beneath it, matching the CPU's `blend_layer_pixel` and SVG's layers built from native compositing.
|
||||
|
||||
use super::{Parameters, PassRecorder, WORKING_FORMAT};
|
||||
use core_types::blending::BlendMode;
|
||||
use vello_gpu::kurbo::Affine;
|
||||
|
||||
impl PassRecorder<'_> {
|
||||
/// Blends onto the scene's `backdrop` each layer's image in `results` whose mode reads what lies beneath (see [`BlendMode::reads_backdrop`]), and the `content` one if it reads it at its fill,
|
||||
/// leaving what it then draws normally. The `fill` moves only the content toward its mode's neutral color (see [`BlendMode::fill_moves_layer_toward_neutral`]). Without a backdrop, nothing lies beneath.
|
||||
pub(super) fn blend_onto_backdrop(&mut self, backdrop: Option<(&wgpu::Texture, Affine)>, fill: f32, content: Option<usize>, results: &mut [(wgpu::Texture, BlendMode)]) {
|
||||
for (index, (image, blend_mode)) in results.iter_mut().enumerate() {
|
||||
let holds_content = Some(index) == content;
|
||||
if !holds_content && !blend_mode.reads_backdrop() {
|
||||
continue;
|
||||
}
|
||||
let strength = if holds_content && blend_mode.fill_moves_layer_toward_neutral() { fill } else { 1. };
|
||||
|
||||
match backdrop {
|
||||
Some((backdrop, placement)) => {
|
||||
let placed = Parameters::placed_in_backdrop(placement);
|
||||
let [x, y, ..] = placed.values;
|
||||
let parameters = Parameters {
|
||||
values: [x, y, *blend_mode as u32 as f32, strength],
|
||||
..placed
|
||||
};
|
||||
let blended = self.run("blend_onto_backdrop", WORKING_FORMAT, self.size, backdrop, Some(image), None, parameters);
|
||||
self.replace(image, blended);
|
||||
}
|
||||
// Over nothing, the layer shows as it is, faded by a fill it would otherwise move toward neutral
|
||||
None if strength < 1. => {
|
||||
let faded = self.scale(image, strength);
|
||||
self.replace(image, faded);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
|
||||
*blend_mode = BlendMode::Normal;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -86,7 +86,7 @@ impl PassRecorder<'_> {
|
||||
})
|
||||
.map(half::f16::from_f32)
|
||||
.collect();
|
||||
let table = self.row_texture("vello_effects_masked_radius_blur", wgpu::TextureFormat::Rgba16Float, 256, bytemuck::cast_slice(&blends));
|
||||
let table = self.row_texture(wgpu::TextureFormat::Rgba16Float, 256, bytemuck::cast_slice(&blends));
|
||||
let interpolation = self.run("masked_radius_blur_interpolation", WORKING_FORMAT, self.size, luminance, Some(&table), None, Parameters::default());
|
||||
|
||||
if full_is_read && let Some(blurred) = self.masked_radius_blur_image(full.as_ref().unwrap_or(content), &interpolation, levels, linear) {
|
||||
|
||||
@@ -74,7 +74,7 @@ impl PassRecorder<'_> {
|
||||
return band;
|
||||
};
|
||||
let samples: Vec<half::f16> = samples.into_iter().flatten().map(half::f16::from_f32).collect();
|
||||
let samples = self.row_texture("vello_effects_gradient", wgpu::TextureFormat::Rgba16Float, GRADIENT_SAMPLES, bytemuck::cast_slice(&samples));
|
||||
let samples = self.row_texture(wgpu::TextureFormat::Rgba16Float, GRADIENT_SAMPLES, bytemuck::cast_slice(&samples));
|
||||
|
||||
let parameters = Parameters {
|
||||
amount: opacity,
|
||||
|
||||
@@ -40,7 +40,7 @@ impl PassRecorder<'_> {
|
||||
let vertices = 12 * (columns + rows) + 24 + 6 * columns * rows;
|
||||
|
||||
let format = texture.format();
|
||||
let warped = self.textures.acquire(self.device, self.size, format);
|
||||
let warped = self.textures.acquire(self.executor, self.size, format);
|
||||
let view = |texture: &wgpu::Texture| texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let reading = self.passes.bind_group(self.device, self.size, &view(&texture), None, None, parameters);
|
||||
let mesh = (self.passes).pipeline_with(self.device, "warp_vertex", "warp_effect", format, Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING));
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
//! The GPU pass that renders tiles of generators' patterns, matching the CPU's renders of them.
|
||||
|
||||
use crate::WgpuExecutor;
|
||||
use crate::vello_render::TEXTURE_FORMAT;
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
use glam::DVec2;
|
||||
use glam::{DVec2, UVec2};
|
||||
use graphic_types::generator::{
|
||||
CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, MandelbrotExterior, MandelbrotFractal, MandelbrotInterior, NoiseSettings, NoiseType,
|
||||
};
|
||||
use raster_kernels::mandelbrot::{MandelbrotSetup, ReferenceOrbit, resolves_in_32_bits};
|
||||
use raster_types::Texture;
|
||||
use std::iter::zip;
|
||||
use std::sync::OnceLock;
|
||||
use wgpu::util::DeviceExt;
|
||||
@@ -270,7 +272,7 @@ impl Tile {
|
||||
}
|
||||
|
||||
/// The texture holding a reference orbit's values and their raisings for the Mandelbrot shader, in rows of `REFERENCE_ROW_LENGTH`, or one empty texel without one.
|
||||
fn reference_texture(device: &wgpu::Device, queue: &wgpu::Queue, reference: Option<&ReferenceOrbit>) -> wgpu::Texture {
|
||||
fn reference_texture(executor: &WgpuExecutor, queue: &wgpu::Queue, reference: Option<&ReferenceOrbit>) -> Texture {
|
||||
let (values, raised_values) = reference.map_or((&[][..], &[][..]), |reference| (&reference.values[..], &reference.raised_values[..]));
|
||||
let (width, height) = (values.len().clamp(1, REFERENCE_ROW_LENGTH), values.len().div_ceil(REFERENCE_ROW_LENGTH).max(1));
|
||||
|
||||
@@ -279,25 +281,18 @@ fn reference_texture(device: &wgpu::Device, queue: &wgpu::Queue, reference: Opti
|
||||
*texel = [value.x, value.y, raised.x, raised.y];
|
||||
}
|
||||
|
||||
device.create_texture_with_data(
|
||||
queue,
|
||||
&wgpu::TextureDescriptor {
|
||||
label: Some("vello_generator_reference_orbit"),
|
||||
size: wgpu::Extent3d {
|
||||
width: width as u32,
|
||||
height: height as u32,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba32Float,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
view_formats: &[],
|
||||
},
|
||||
wgpu::util::TextureDataOrder::LayerMajor,
|
||||
let texture = executor.request_texture_with_format(UVec2::new(width as u32, height as u32), wgpu::TextureFormat::Rgba32Float);
|
||||
queue.write_texture(
|
||||
texture.as_image_copy(),
|
||||
bytemuck::cast_slice(&texels),
|
||||
)
|
||||
wgpu::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(width as u32 * size_of::<[f32; 4]>() as u32),
|
||||
rows_per_image: Some(height as u32),
|
||||
},
|
||||
texture.size(),
|
||||
);
|
||||
texture
|
||||
}
|
||||
|
||||
/// The pipelines of the pass, one for each shader.
|
||||
@@ -386,26 +381,24 @@ impl GeneratorPasses {
|
||||
}
|
||||
|
||||
/// A texture for square tiles `pixels` across to be rendered into, with the mip levels they're drawn from.
|
||||
pub(crate) fn tile_texture(device: &wgpu::Device, pixels: u32) -> wgpu::Texture {
|
||||
device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("vello_generator_tile"),
|
||||
size: wgpu::Extent3d {
|
||||
width: pixels,
|
||||
height: pixels,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: TILE_MIP_LEVELS,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: TEXTURE_FORMAT,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
})
|
||||
pub(crate) fn tile_texture(executor: &WgpuExecutor, pixels: u32) -> Texture {
|
||||
executor.request_texture_with_mips(UVec2::splat(pixels), TEXTURE_FORMAT, TILE_MIP_LEVELS)
|
||||
}
|
||||
|
||||
/// Records the rendering of a square tile of `pattern` into the top mip level of `texture`, with its top left corner at `corner` of the pattern's space and pixels `texel` units across.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn render_tile(&self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, texture: &wgpu::Texture, pattern: &GeneratorPattern, corner: DVec2, texel: f64) {
|
||||
pub(crate) fn render_tile(
|
||||
&self,
|
||||
executor: &WgpuExecutor,
|
||||
queue: &wgpu::Queue,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
held: &mut Vec<Texture>,
|
||||
texture: &wgpu::Texture,
|
||||
pattern: &GeneratorPattern,
|
||||
corner: DVec2,
|
||||
texel: f64,
|
||||
) {
|
||||
let device = &executor.context().device;
|
||||
let tile = Tile::new(pattern, corner, texel, texture.width());
|
||||
let (pipeline, bind_group_layout) = self.pipeline(device, tile.shader);
|
||||
|
||||
@@ -414,7 +407,12 @@ impl GeneratorPasses {
|
||||
contents: &tile.parameters,
|
||||
usage: wgpu::BufferUsages::UNIFORM,
|
||||
});
|
||||
let reference_view = (tile.shader == Shader::Mandelbrot).then(|| reference_texture(device, queue, tile.reference.as_ref()).create_view(&wgpu::TextureViewDescriptor::default()));
|
||||
let reference_view = (tile.shader == Shader::Mandelbrot).then(|| {
|
||||
let reference = reference_texture(executor, queue, tile.reference.as_ref());
|
||||
let view = reference.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
held.push(reference);
|
||||
view
|
||||
});
|
||||
let mut entries = vec![wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: buffer.as_entire_binding(),
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
// The pass blending a layer by a mode that reads what lies beneath, appended to the effect passes, matching the CPU's `blend_layer_pixel`
|
||||
|
||||
// A paint at `strength` blended by the mode, moved toward the mode's neutral color where its strength does that, matching `apply_blend_mode_at_strength`
|
||||
fn blend_gamma_at_strength(backdrop: vec3<f32>, paint: vec3<f32>, mode: u32, strength: f32) -> vec3<f32> {
|
||||
// Hard Mix steepens its ramp with the strength instead
|
||||
if mode == 17u {
|
||||
let mixed = vec3<f32>(hard_mix(backdrop.r, paint.r, strength), hard_mix(backdrop.g, paint.g, strength), hard_mix(backdrop.b, paint.b, strength));
|
||||
return clamp(mixed, vec3<f32>(0.), vec3<f32>(1.));
|
||||
}
|
||||
|
||||
// Color Dodge and Linear Dodge move toward black, Color Burn and Linear Burn toward white, and Vivid Light and Linear Light toward middle gray
|
||||
var moved = paint;
|
||||
if mode == 8u || mode == 9u {
|
||||
moved = strength * paint;
|
||||
} else if mode == 3u || mode == 4u {
|
||||
moved = 1. - strength * (1. - paint);
|
||||
} else if mode == 14u || mode == 15u {
|
||||
moved = 0.5 + strength * (paint - 0.5);
|
||||
}
|
||||
return blend_gamma(backdrop, moved, mode);
|
||||
}
|
||||
|
||||
// How strongly a layer whose fill `strength` moves it toward neutral shows over a backdrop of `backdrop_alpha`, matching the CPU's `layer_fill_shown`
|
||||
fn layer_fill_shown(backdrop_alpha: f32, strength: f32) -> f32 {
|
||||
return min(strength / max((1. - backdrop_alpha) + backdrop_alpha * strength, 1e-6), 1.);
|
||||
}
|
||||
|
||||
// A layer's image (`secondary`) blended by the mode in `values.z` onto what lies beneath it, sampled from the scene's backdrop (`source`) where each pixel lands as `sample_backdrop` places it.
|
||||
// It's what the layer then draws normally: its color mixed toward the blend as far as the backdrop covers it, shown as strongly as a fill `values.w` moving it toward neutral leaves it.
|
||||
@fragment
|
||||
fn blend_onto_backdrop(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let layer = textureLoad(secondary, vec2<i32>(position.xy), 0);
|
||||
let backdrop = textureSampleLevel(source, linear_sampler, backdrop_point(position.xy) / vec2<f32>(textureDimensions(source)), 0.);
|
||||
if layer.a <= 0. {
|
||||
return vec4<f32>(0.);
|
||||
}
|
||||
|
||||
let paint = clamp(layer.rgb / layer.a, vec3<f32>(0.), vec3<f32>(1.));
|
||||
var beneath = vec3<f32>(0.);
|
||||
if backdrop.a > 0. {
|
||||
beneath = clamp(backdrop.rgb / backdrop.a, vec3<f32>(0.), vec3<f32>(1.));
|
||||
}
|
||||
let strength = parameters.values.w;
|
||||
let blended = blend_gamma_at_strength(beneath, paint, u32(parameters.values.z), strength);
|
||||
|
||||
let shown = layer.a * layer_fill_shown(backdrop.a, strength);
|
||||
return vec4<f32>(shown * ((1. - backdrop.a) * paint + backdrop.a * blended), shown);
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::WgpuExecutor;
|
||||
use crate::vello_adjustments::adjustment_run_hash;
|
||||
use crate::vello_effects::{EffectPasses, EffectTextures};
|
||||
use crate::vello_generators::GeneratorPasses;
|
||||
@@ -5,7 +6,7 @@ use core_types::blending::BlendMode;
|
||||
use glam::{DAffine2, UVec2};
|
||||
use graphic_types::effect_layers::EffectLayers;
|
||||
use graphic_types::effects::EffectCapture;
|
||||
use graphic_types::raster_types::{CPU, Image, Raster, WeakCPU};
|
||||
use graphic_types::raster_types::{CPU, Image, Raster, Texture, TextureWeakRef, WeakCPU};
|
||||
use graphic_types::{Adjustment, Effects};
|
||||
use rendering::vello_scene_builder::{EffectsRenderer, GeneratorTile, SceneImage, VelloSceneBuilder, image_downscale_factor, image_texture_size};
|
||||
use std::collections::HashMap;
|
||||
@@ -25,12 +26,6 @@ pub(crate) const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba
|
||||
/// 16-bit unorm comes first for holding every 8-bit level exactly, unlike half floats.
|
||||
const PRECISE_FORMATS: &[wgpu::TextureFormat] = &[wgpu::TextureFormat::Rgba16Unorm, wgpu::TextureFormat::Rgba16Float];
|
||||
|
||||
/// How many renders a GPU texture's premultiplied copy survives without being drawn before it is freed.
|
||||
const UNUSED_IMAGE_RENDER_LIMIT: u64 = 60;
|
||||
|
||||
/// About the most tiles of generators kept between renders, past which the least recently drawn are freed. Tiles drawn in the same render are kept or freed together.
|
||||
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;
|
||||
|
||||
@@ -54,8 +49,6 @@ pub(crate) struct VelloRenderer {
|
||||
pub struct VelloCanvas {
|
||||
/// Scenes to draw into, one for each depth of effects groups nested in a render, reused between renders to keep their allocations.
|
||||
spare_scenes: Vec<vello_gpu::Scene>,
|
||||
/// The premultiplied texture Vello GPU renders into before conversion to straight alpha, kept while the render size stays the same.
|
||||
premultiplied_target: Option<wgpu::Texture>,
|
||||
images: ImageTextures,
|
||||
effect_textures: EffectTextures,
|
||||
}
|
||||
@@ -71,8 +64,7 @@ enum TargetAlpha {
|
||||
struct RenderContext<'a> {
|
||||
renderer: &'a VelloRenderer,
|
||||
canvas: &'a mut VelloCanvas,
|
||||
device: &'a wgpu::Device,
|
||||
queue: &'a Queue,
|
||||
executor: &'a WgpuExecutor,
|
||||
}
|
||||
|
||||
impl VelloRenderer {
|
||||
@@ -121,12 +113,10 @@ impl VelloRenderer {
|
||||
|
||||
/// Renders the scene `draw` draws on `canvas`, with its content placed by `view`, into `target` (an `Rgba8Unorm` texture of `size` with straight alpha).
|
||||
/// A render with more content than Vello GPU can hold calls `draw` again for each part it splits into.
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub(crate) fn render(
|
||||
&self,
|
||||
executor: &WgpuExecutor,
|
||||
canvas: &mut VelloCanvas,
|
||||
device: &wgpu::Device,
|
||||
queue: &Queue,
|
||||
draw: &mut dyn FnMut(&mut VelloSceneBuilder),
|
||||
view: Affine,
|
||||
size: UVec2,
|
||||
@@ -137,12 +127,7 @@ impl VelloRenderer {
|
||||
}
|
||||
|
||||
canvas.images.render_count += 1;
|
||||
let mut context = RenderContext {
|
||||
renderer: self,
|
||||
canvas,
|
||||
device,
|
||||
queue,
|
||||
};
|
||||
let mut context = RenderContext { renderer: self, canvas, executor };
|
||||
context.render_area(draw, view, size, target, TargetAlpha::Straight);
|
||||
canvas.images.free_unused();
|
||||
canvas.effect_textures.finish_render();
|
||||
@@ -152,25 +137,30 @@ impl VelloRenderer {
|
||||
|
||||
/// Renders a `scene` drawn beforehand on `canvas` into `target` (an `Rgba8Unorm` texture of the scene's size with straight alpha).
|
||||
/// Unlike [`Self::render`], it can't split the scene, so one with more content than Vello GPU can hold renders transparent.
|
||||
pub(crate) fn render_scene(&self, canvas: &mut VelloCanvas, device: &wgpu::Device, queue: &Queue, scene: VelloSceneBuilder, target: &wgpu::Texture) {
|
||||
pub(crate) fn render_scene(&self, executor: &WgpuExecutor, canvas: &mut VelloCanvas, scene: VelloSceneBuilder, target: &wgpu::Texture) {
|
||||
canvas.images.render_count += 1;
|
||||
let max_texture_size = scene.max_texture_size();
|
||||
let mut context = RenderContext {
|
||||
renderer: self,
|
||||
canvas,
|
||||
device,
|
||||
queue,
|
||||
};
|
||||
let mut context = RenderContext { renderer: self, canvas, executor };
|
||||
let (scene, images) = scene.finish();
|
||||
if let Err(error) = context.submit(&scene, images, max_texture_size, target, TargetAlpha::Straight, true) {
|
||||
log::error!("Vello GPU failed to render: {error}");
|
||||
clear(device, queue, target);
|
||||
clear(&executor.context().device, &executor.context().queue, target);
|
||||
}
|
||||
canvas.images.free_unused();
|
||||
canvas.effect_textures.finish_render();
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> RenderContext<'a> {
|
||||
fn device(&self) -> &'a wgpu::Device {
|
||||
&self.executor.context().device
|
||||
}
|
||||
|
||||
fn queue(&self) -> &'a Queue {
|
||||
&self.executor.context().queue
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderContext<'_> {
|
||||
/// Renders the scene `draw` draws into `target`, a texture of `size`, splitting its area into halves while it holds more content than one render can.
|
||||
fn render_area(&mut self, draw: &mut dyn FnMut(&mut VelloSceneBuilder), view: Affine, size: UVec2, target: &wgpu::Texture, target_alpha: TargetAlpha) {
|
||||
@@ -182,7 +172,7 @@ impl RenderContext<'_> {
|
||||
/// Renders each half of the area of `target`, a texture of `size`, after rendering it whole failed with `error`, splitting again each half that still holds too much.
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
fn render_halves(&mut self, draw: &mut dyn FnMut(&mut VelloSceneBuilder), view: Affine, size: UVec2, target: &wgpu::Texture, target_alpha: TargetAlpha, error: RenderError, split_depth: u32) {
|
||||
let (device, queue) = (self.device, self.queue);
|
||||
let (device, queue) = (self.device(), self.queue());
|
||||
|
||||
// Each half covers less of the scene, so it has less content and smaller layers to hold
|
||||
let too_much_to_hold = matches!(
|
||||
@@ -203,14 +193,9 @@ impl RenderContext<'_> {
|
||||
let top = size.y / 2;
|
||||
[(UVec2::ZERO, UVec2::new(size.x, top)), (UVec2::new(0, top), UVec2::new(size.x, size.y - top))]
|
||||
};
|
||||
let executor = self.executor;
|
||||
let halves = halves.map(|(offset, half_size)| {
|
||||
let half_target = create_texture(
|
||||
device,
|
||||
"vello_gpu_split_target",
|
||||
half_size,
|
||||
target.format(),
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST,
|
||||
);
|
||||
let half_target = executor.request_texture_with_format(half_size, target.format());
|
||||
let half_view = Affine::translate((-(offset.x as f64), -(offset.y as f64))) * view;
|
||||
let rendered = self.render_once(draw, half_view, half_size, &half_target, target_alpha);
|
||||
(offset, half_size, half_view, half_target, rendered)
|
||||
@@ -254,7 +239,7 @@ impl RenderContext<'_> {
|
||||
|
||||
/// Renders the scene `draw` draws into `target`, a texture of `size`, in a single Vello GPU render.
|
||||
fn render_once(&mut self, draw: &mut dyn FnMut(&mut VelloSceneBuilder), view: Affine, size: UVec2, target: &wgpu::Texture, target_alpha: TargetAlpha) -> Result<(), RenderError> {
|
||||
let max_texture_size = self.device.limits().max_texture_dimension_2d;
|
||||
let max_texture_size = self.device().limits().max_texture_dimension_2d;
|
||||
let max_size = max_texture_size.min(u16::MAX as u32);
|
||||
let (mut scene, mut images, apron) = self.draw_scene(draw, view, size, max_texture_size, largest_apron(size, max_size));
|
||||
|
||||
@@ -266,17 +251,11 @@ impl RenderContext<'_> {
|
||||
let grown_view = Affine::translate((apron as f64, apron as f64)) * view;
|
||||
let (scene, images, _) = self.draw_scene(draw, grown_view, grown_size, max_texture_size, 0);
|
||||
|
||||
let grown_target = create_texture(
|
||||
self.device,
|
||||
"vello_gpu_grown_target",
|
||||
grown_size,
|
||||
target.format(),
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC,
|
||||
);
|
||||
let grown_target = self.executor.request_texture_with_format(grown_size, target.format());
|
||||
let rendered = self.submit(&scene, images, max_texture_size, &grown_target, target_alpha, true);
|
||||
self.canvas.spare_scenes.push(scene);
|
||||
|
||||
let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_gpu_grown_copy") });
|
||||
let mut encoder = self.device().create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_gpu_grown_copy") });
|
||||
encoder.copy_texture_to_texture(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
origin: wgpu::Origin3d { x: apron, y: apron, z: 0 },
|
||||
@@ -289,7 +268,7 @@ impl RenderContext<'_> {
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
);
|
||||
self.queue.submit([encoder.finish()]);
|
||||
self.queue().submit([encoder.finish()]);
|
||||
return rendered;
|
||||
}
|
||||
|
||||
@@ -334,23 +313,34 @@ impl RenderContext<'_> {
|
||||
/// Renders a drawn scene, with the images it draws, into `target`, a texture of the scene's size, in a single Vello GPU render.
|
||||
/// The effects results it draws are freed for reuse after it, even if it fails when `release_failed`.
|
||||
fn submit(&mut self, scene: &vello_gpu::Scene, images: Vec<SceneImage>, max_texture_size: u32, target: &wgpu::Texture, target_alpha: TargetAlpha, release_failed: bool) -> Result<(), RenderError> {
|
||||
let device = self.device;
|
||||
let device = self.device();
|
||||
let (width, height) = (scene.width(), scene.height());
|
||||
let size = UVec2::new(width as u32, height as u32);
|
||||
|
||||
// Locked from here to the submission, so drawing a scene doesn't hold up other uses of the queue
|
||||
let queue = self.queue.lock();
|
||||
let queue = self.queue().lock();
|
||||
|
||||
// Each render submits its own encoder, since Vello GPU stages its uploads for the next submission
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_gpu_render") });
|
||||
|
||||
// Supply the textures of the images the scene draws, under the IDs it drew them with
|
||||
let mut texture_bindings = TextureBindings::new();
|
||||
let mut held = Vec::new();
|
||||
for (id, image) in images.iter().enumerate() {
|
||||
let view = self
|
||||
.canvas
|
||||
.images
|
||||
.prepare(device, &queue, &mut encoder, &mut self.canvas.effect_textures, self.renderer, image, max_texture_size);
|
||||
let view = match image {
|
||||
SceneImage::Texture(source) => {
|
||||
let premultiplied = self.executor.request_texture(UVec2::new(source.width(), source.height()));
|
||||
let view = premultiplied.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let source_view = source.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
self.renderer.alpha_conversion.premultiply(device, &mut encoder, &source_view, source.format().is_srgb(), &view);
|
||||
held.push(premultiplied);
|
||||
Some(view)
|
||||
}
|
||||
_ => self
|
||||
.canvas
|
||||
.images
|
||||
.prepare(self.executor, &queue, &mut encoder, &mut self.canvas.effect_textures, self.renderer, image, max_texture_size, &mut held),
|
||||
};
|
||||
|
||||
// Adjustments draw a copy of the texture they're carried out on
|
||||
let view = match image {
|
||||
@@ -358,7 +348,7 @@ impl RenderContext<'_> {
|
||||
let effects = (&self.renderer.effect_passes, &mut self.canvas.effect_textures);
|
||||
self.canvas
|
||||
.images
|
||||
.prepare_adjusted(device, &queue, effects, raster, adjustments, max_texture_size, self.renderer.precise_format)
|
||||
.prepare_adjusted(self.executor, &queue, effects, raster, adjustments, max_texture_size, self.renderer.precise_format, &mut held)
|
||||
}),
|
||||
_ => view,
|
||||
};
|
||||
@@ -370,21 +360,10 @@ impl RenderContext<'_> {
|
||||
|
||||
// Vello GPU renders premultiplied, which is converted to straight alpha unless the target wants it premultiplied
|
||||
let target_view = target.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let premultiplied_view = match (target_alpha, &self.canvas.premultiplied_target) {
|
||||
(TargetAlpha::Premultiplied, _) => target_view.clone(),
|
||||
(TargetAlpha::Straight, Some(texture)) if texture.width() == size.x && texture.height() == size.y => texture.create_view(&wgpu::TextureViewDescriptor::default()),
|
||||
(TargetAlpha::Straight, _) => {
|
||||
let texture = create_texture(
|
||||
device,
|
||||
"vello_gpu_premultiplied_target",
|
||||
size,
|
||||
TEXTURE_FORMAT,
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
);
|
||||
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
self.canvas.premultiplied_target = Some(texture);
|
||||
view
|
||||
}
|
||||
let premultiplied_target = (target_alpha == TargetAlpha::Straight).then(|| self.executor.request_texture(size));
|
||||
let premultiplied_view = match &premultiplied_target {
|
||||
Some(texture) => texture.create_view(&wgpu::TextureViewDescriptor::default()),
|
||||
None => target_view.clone(),
|
||||
};
|
||||
let target_init = TargetInit::Clear(ClearSettings::Viewport { color: peniko::Color::TRANSPARENT });
|
||||
|
||||
@@ -445,24 +424,24 @@ impl EffectsRenderer for RenderContext<'_> {
|
||||
draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder),
|
||||
draw: &mut dyn FnMut(&mut VelloSceneBuilder),
|
||||
) -> Vec<(wgpu::Texture, BlendMode)> {
|
||||
let content_texture = self.canvas.effect_textures.acquire(self.device, size, self.renderer.precise_format);
|
||||
let content_texture = self.canvas.effect_textures.acquire(self.executor, size, self.renderer.precise_format);
|
||||
self.render_area(draw, view, size, &content_texture, TargetAlpha::Premultiplied);
|
||||
|
||||
// The effects' drawn paints, each rendered over the same pixels as the content
|
||||
let paint_count = effects.operations().map(|operation| operation.drawn_paints().count()).sum();
|
||||
let paint_textures: Vec<wgpu::Texture> = (0..paint_count)
|
||||
.map(|index| {
|
||||
let paint_texture = self.canvas.effect_textures.acquire(self.device, size, self.renderer.precise_format);
|
||||
let paint_texture = self.canvas.effect_textures.acquire(self.executor, size, self.renderer.precise_format);
|
||||
self.render_area(&mut |scene| draw_paint(index, scene), view, size, &paint_texture, TargetAlpha::Premultiplied);
|
||||
paint_texture
|
||||
})
|
||||
.collect();
|
||||
|
||||
let queue = self.queue().lock();
|
||||
let effect_textures = &mut self.canvas.effect_textures;
|
||||
let queue = self.queue.lock();
|
||||
let effect_passes = &self.renderer.effect_passes;
|
||||
let results = effect_passes.apply(
|
||||
self.device,
|
||||
self.executor,
|
||||
&queue,
|
||||
effect_textures,
|
||||
&content_texture,
|
||||
@@ -484,7 +463,7 @@ impl EffectsRenderer for RenderContext<'_> {
|
||||
|
||||
fn render_backdrop(&mut self, scene: &vello_gpu::Scene, images: &[SceneImage], max_texture_size: u32) -> Option<wgpu::Texture> {
|
||||
let size = UVec2::new(scene.width() as u32, scene.height() as u32);
|
||||
let backdrop = self.canvas.effect_textures.acquire(self.device, size, self.renderer.precise_format);
|
||||
let backdrop = self.canvas.effect_textures.acquire(self.executor, size, self.renderer.precise_format);
|
||||
|
||||
// A failed render leaves the scene to go on drawing what it drew, so the results it draws stay in use
|
||||
match self.submit(scene, images.to_vec(), max_texture_size, &backdrop, TargetAlpha::Premultiplied, false) {
|
||||
@@ -515,122 +494,117 @@ 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, a GPU texture, or a tile of a generator's pattern.
|
||||
/// Identifies the pixels behind an image texture: a blob of CPU pixels or a CPU raster.
|
||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||
enum ImageKey {
|
||||
Blob(u64),
|
||||
Raster(u64),
|
||||
Texture(wgpu::Texture),
|
||||
GeneratorTile(GeneratorTile),
|
||||
}
|
||||
|
||||
/// A premultiplied copy of an image's pixels that Vello GPU samples as an external texture.
|
||||
struct ImageTexture {
|
||||
texture: wgpu::Texture,
|
||||
texture: TextureWeakRef,
|
||||
last_used: u64,
|
||||
/// The CPU raster pixels copied into the texture, which is freed once they're gone since they can't be drawn again.
|
||||
raster: Option<WeakCPU>,
|
||||
/// Copies with runs of adjustments carried out on them, one for each run the image is drawn with.
|
||||
adjusted: Vec<AdjustedTexture>,
|
||||
/// The raster's straight linear colors in 32-bit floats that adjustments are carried out from, kept while any adjusted copy is.
|
||||
adjustment_source: Option<wgpu::Texture>,
|
||||
adjustment_source: Option<TextureWeakRef>,
|
||||
}
|
||||
|
||||
/// A copy of an image's texture with a run of adjustments carried out on it, made over in place for another run.
|
||||
/// A copy of an image's texture with a run of adjustments carried out on it, made over for another run.
|
||||
struct AdjustedTexture {
|
||||
texture: wgpu::Texture,
|
||||
/// The hash of the run carried out on it, or `None` until one is.
|
||||
run_hash: Option<u64>,
|
||||
texture: TextureWeakRef,
|
||||
run_hash: u64,
|
||||
last_used: u64,
|
||||
}
|
||||
|
||||
/// The textures of the images recent renders drew, each freed once it goes unused for long enough.
|
||||
/// The textures of the images recent renders drew, parked in the texture pool between renders.
|
||||
#[derive(Default)]
|
||||
struct ImageTextures {
|
||||
textures: HashMap<ImageKey, ImageTexture>,
|
||||
/// The textures of the generator tiles the last render freed, for its next render's new tiles to take over, as when changing a generator's settings replaces every tile.
|
||||
spare_generator_tiles: Vec<wgpu::Texture>,
|
||||
generator_tiles: HashMap<GeneratorTile, TextureWeakRef>,
|
||||
render_count: u64,
|
||||
}
|
||||
|
||||
impl ImageTextures {
|
||||
/// A view of the premultiplied texture for `image`, uploading CPU pixels or rendering a generator's tile the first time they're drawn.
|
||||
/// GPU textures are converted again at every render since the texture cache hands their textures out again with new contents.
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
fn prepare(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
executor: &WgpuExecutor,
|
||||
queue: &wgpu::Queue,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
effect_textures: &mut EffectTextures,
|
||||
renderer: &VelloRenderer,
|
||||
image: &SceneImage,
|
||||
max_texture_size: u32,
|
||||
held: &mut Vec<Texture>,
|
||||
) -> Option<wgpu::TextureView> {
|
||||
let key = match image {
|
||||
SceneImage::Pixels(data) => ImageKey::Blob(data.data.id()),
|
||||
SceneImage::Raster { raster, .. } => ImageKey::Raster(raster.buffer_id()),
|
||||
SceneImage::Texture(texture) => ImageKey::Texture((**texture).clone()),
|
||||
SceneImage::GeneratorTile { tile, .. } => ImageKey::GeneratorTile(*tile),
|
||||
SceneImage::GeneratorTile { pattern, tile } => {
|
||||
let texture = match self.generator_tiles.get(tile).and_then(TextureWeakRef::upgrade) {
|
||||
Some(texture) => texture,
|
||||
None => {
|
||||
let texture = GeneratorPasses::tile_texture(executor, GeneratorTile::SAMPLES);
|
||||
let (corner, texel) = tile.corner_and_texel();
|
||||
renderer.generator_passes.render_tile(executor, queue, encoder, held, &texture, pattern, corner, texel);
|
||||
renderer.effect_passes.record_mipmaps(executor, encoder, effect_textures, &texture);
|
||||
self.generator_tiles.insert(*tile, texture.downgrade());
|
||||
texture
|
||||
}
|
||||
};
|
||||
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
held.push(texture);
|
||||
return Some(view);
|
||||
}
|
||||
// Effects results are premultiplied already
|
||||
SceneImage::Rendered(texture) => return Some(texture.create_view(&wgpu::TextureViewDescriptor::default())),
|
||||
SceneImage::Texture(_) => return None,
|
||||
};
|
||||
|
||||
if !self.textures.contains_key(&key) {
|
||||
let texture = match image {
|
||||
SceneImage::Pixels(data) => {
|
||||
if data.format != peniko::ImageFormat::Rgba8 {
|
||||
log::error!("Unsupported image format {:?}", data.format);
|
||||
return None;
|
||||
let texture = match self.textures.get(&key).and_then(|image_texture| image_texture.texture.upgrade()) {
|
||||
Some(texture) => texture,
|
||||
None => {
|
||||
let texture = match image {
|
||||
SceneImage::Pixels(data) => {
|
||||
if data.format != peniko::ImageFormat::Rgba8 {
|
||||
log::error!("Unsupported image format {:?}", data.format);
|
||||
return None;
|
||||
}
|
||||
|
||||
upload_pixels(executor, queue, data.data.data(), data.width, data.height, data.alpha_type, max_texture_size)?
|
||||
}
|
||||
SceneImage::Raster { raster, .. } => {
|
||||
let (pixels, width, height) = raster.to_flat_u8();
|
||||
upload_pixels(executor, queue, &pixels, width, height, peniko::ImageAlphaType::Alpha, max_texture_size)?
|
||||
}
|
||||
SceneImage::Rendered(_) | SceneImage::Texture(_) | SceneImage::GeneratorTile { .. } => return None,
|
||||
};
|
||||
let raster = match image {
|
||||
SceneImage::Raster { raster, .. } => Some(raster.downgrade()),
|
||||
SceneImage::Pixels(_) | SceneImage::Texture(_) | SceneImage::Rendered(_) | SceneImage::GeneratorTile { .. } => None,
|
||||
};
|
||||
self.textures.insert(
|
||||
key.clone(),
|
||||
ImageTexture {
|
||||
texture: texture.downgrade(),
|
||||
last_used: 0,
|
||||
raster,
|
||||
adjusted: Vec::new(),
|
||||
adjustment_source: None,
|
||||
},
|
||||
);
|
||||
texture
|
||||
}
|
||||
};
|
||||
|
||||
upload_pixels(device, queue, data.data.data(), data.width, data.height, data.alpha_type, max_texture_size)?
|
||||
}
|
||||
SceneImage::Raster { raster, .. } => {
|
||||
let (pixels, width, height) = raster.to_flat_u8();
|
||||
upload_pixels(device, queue, &pixels, width, height, peniko::ImageAlphaType::Alpha, max_texture_size)?
|
||||
}
|
||||
SceneImage::GeneratorTile { pattern, tile } => {
|
||||
let texture = (self.spare_generator_tiles.pop()).unwrap_or_else(|| GeneratorPasses::tile_texture(device, GeneratorTile::SAMPLES));
|
||||
let (corner, texel) = tile.corner_and_texel();
|
||||
renderer.generator_passes.render_tile(device, queue, encoder, &texture, pattern, corner, texel);
|
||||
renderer.effect_passes.record_mipmaps(device, encoder, effect_textures, &texture);
|
||||
texture
|
||||
}
|
||||
SceneImage::Rendered(_) => return None,
|
||||
SceneImage::Texture(texture) => create_texture(
|
||||
device,
|
||||
"vello_gpu_premultiplied_image",
|
||||
UVec2::new(texture.width(), texture.height()),
|
||||
TEXTURE_FORMAT,
|
||||
wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
),
|
||||
};
|
||||
let raster = match image {
|
||||
SceneImage::Raster { raster, .. } => Some(raster.downgrade()),
|
||||
SceneImage::Pixels(_) | SceneImage::Texture(_) | SceneImage::Rendered(_) | SceneImage::GeneratorTile { .. } => None,
|
||||
};
|
||||
self.textures.insert(
|
||||
key.clone(),
|
||||
ImageTexture {
|
||||
texture,
|
||||
last_used: 0,
|
||||
raster,
|
||||
adjusted: Vec::new(),
|
||||
adjustment_source: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let image_texture = self.textures.get_mut(&key)?;
|
||||
image_texture.last_used = self.render_count;
|
||||
let view = image_texture.texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
|
||||
if let SceneImage::Texture(source) = image {
|
||||
let source_view = source.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
renderer.alpha_conversion.premultiply(device, encoder, &source_view, source.format().is_srgb(), &view);
|
||||
}
|
||||
|
||||
self.textures.get_mut(&key)?.last_used = self.render_count;
|
||||
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
held.push(texture);
|
||||
Some(view)
|
||||
}
|
||||
|
||||
@@ -638,30 +612,38 @@ impl ImageTextures {
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
fn prepare_adjusted(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
executor: &WgpuExecutor,
|
||||
queue: &wgpu::Queue,
|
||||
effects: (&EffectPasses, &mut EffectTextures),
|
||||
raster: &Raster<CPU>,
|
||||
run: &[Adjustment],
|
||||
max_texture_size: u32,
|
||||
precise_format: wgpu::TextureFormat,
|
||||
held: &mut Vec<Texture>,
|
||||
) -> Option<wgpu::TextureView> {
|
||||
let (effect_passes, effect_textures) = effects;
|
||||
let run: Vec<&Adjustment> = run.iter().collect();
|
||||
let run_hash = adjustment_run_hash(&run);
|
||||
let render_count = self.render_count;
|
||||
let image_texture = self.textures.get_mut(&ImageKey::Raster(raster.buffer_id()))?;
|
||||
let image = image_texture.texture.upgrade()?;
|
||||
|
||||
// A run seen before has its copy
|
||||
if let Some(copy) = image_texture.adjusted.iter_mut().find(|copy| copy.run_hash == Some(run_hash)) {
|
||||
let seen = (image_texture.adjusted.iter_mut()).find(|copy| copy.run_hash == run_hash).and_then(|copy| {
|
||||
copy.last_used = render_count;
|
||||
return Some(copy.texture.create_view(&wgpu::TextureViewDescriptor::default()));
|
||||
copy.texture.upgrade()
|
||||
});
|
||||
if let Some(copy) = seen {
|
||||
let view = copy.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
held.push(copy);
|
||||
return Some(view);
|
||||
}
|
||||
image_texture.adjusted.retain(|copy| copy.run_hash != run_hash);
|
||||
|
||||
// A run that changes no color draws the texture itself
|
||||
let prepared = effect_textures.prepare_adjustments(device, queue, &run);
|
||||
let prepared = effect_textures.prepare_adjustments(executor, queue, &run);
|
||||
if prepared.is_empty() {
|
||||
return Some(image_texture.texture.create_view(&wgpu::TextureViewDescriptor::default()));
|
||||
return Some(image.create_view(&wgpu::TextureViewDescriptor::default()));
|
||||
}
|
||||
|
||||
// A new run takes over the copy longest unused, as when dragging a slider makes a new run every render
|
||||
@@ -669,85 +651,59 @@ impl ImageTextures {
|
||||
.filter(|(_, copy)| copy.last_used < render_count)
|
||||
.min_by_key(|(_, copy)| copy.last_used)
|
||||
.map(|(index, _)| index);
|
||||
let index = match reusable {
|
||||
Some(index) => index,
|
||||
None => {
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("vello_gpu_adjusted_image"),
|
||||
size: image_texture.texture.size(),
|
||||
mip_level_count: image_texture.texture.mip_level_count(),
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: precise_format,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
image_texture.adjusted.push(AdjustedTexture {
|
||||
texture,
|
||||
run_hash: None,
|
||||
last_used: render_count,
|
||||
});
|
||||
image_texture.adjusted.len() - 1
|
||||
}
|
||||
};
|
||||
if let Some(index) = reusable {
|
||||
image_texture.adjusted.swap_remove(index);
|
||||
}
|
||||
let copy = executor.request_texture_with_mips(UVec2::new(image.width(), image.height()), precise_format, image.mip_level_count());
|
||||
|
||||
// Adjusting the raster's own colors, rather than its 8-bit premultiplied texture, keeps faint colors from banding and steps landing as on the CPU
|
||||
if image_texture.adjustment_source.is_none() {
|
||||
image_texture.adjustment_source = upload_adjustment_source(device, queue, raster.data(), max_texture_size);
|
||||
}
|
||||
let (source, straight_linear) = match &image_texture.adjustment_source {
|
||||
let source = match image_texture.adjustment_source.as_ref().and_then(TextureWeakRef::upgrade) {
|
||||
Some(source) => Some(source),
|
||||
None => {
|
||||
let source = upload_adjustment_source(executor, queue, raster.data(), max_texture_size);
|
||||
image_texture.adjustment_source = source.as_ref().map(Texture::downgrade);
|
||||
source
|
||||
}
|
||||
};
|
||||
let (source, straight_linear) = match &source {
|
||||
Some(source) => (source, true),
|
||||
None => (&image_texture.texture, false),
|
||||
None => (&image, false),
|
||||
};
|
||||
|
||||
let copy = &mut image_texture.adjusted[index];
|
||||
effect_passes.adjust_image(device, queue, effect_textures, source, straight_linear, &prepared, ©.texture);
|
||||
copy.run_hash = Some(run_hash);
|
||||
copy.last_used = render_count;
|
||||
effect_passes.adjust_image(executor, queue, effect_textures, source, straight_linear, &prepared, ©);
|
||||
image_texture.adjusted.push(AdjustedTexture {
|
||||
texture: copy.downgrade(),
|
||||
run_hash,
|
||||
last_used: render_count,
|
||||
});
|
||||
|
||||
Some(copy.texture.create_view(&wgpu::TextureViewDescriptor::default()))
|
||||
let view = copy.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
held.push(copy);
|
||||
Some(view)
|
||||
}
|
||||
|
||||
fn free_unused(&mut self) {
|
||||
let render_count = self.render_count;
|
||||
let in_use = |last_used: u64| render_count - last_used < UNUSED_IMAGE_RENDER_LIMIT;
|
||||
|
||||
let kept = |key: &ImageKey, image_texture: &ImageTexture| match key {
|
||||
// CPU pixels get a new blob ID at every render, so a blob this render didn't draw is unlikely to return
|
||||
ImageKey::Blob(_) => image_texture.last_used == render_count,
|
||||
ImageKey::Raster(_) => image_texture.last_used == render_count || (in_use(image_texture.last_used) && image_texture.raster.as_ref().is_some_and(WeakCPU::is_alive)),
|
||||
ImageKey::Texture(_) | ImageKey::GeneratorTile(_) => in_use(image_texture.last_used),
|
||||
ImageKey::Raster(_) => image_texture.last_used == render_count || image_texture.raster.as_ref().is_some_and(WeakCPU::is_alive),
|
||||
};
|
||||
|
||||
// Spares this render didn't take over are freed, and the tiles it freed become the next render's spares
|
||||
self.spare_generator_tiles.clear();
|
||||
let unused = self.textures.extract_if(|key, image_texture| !kept(key, image_texture));
|
||||
let unused_tiles = unused.filter(|(key, _)| matches!(key, ImageKey::GeneratorTile(_))).map(|(_, image_texture)| image_texture.texture);
|
||||
self.spare_generator_tiles.extend(unused_tiles);
|
||||
self.textures.retain(|key, image_texture| kept(key, image_texture) && image_texture.texture.upgrade().is_some());
|
||||
self.generator_tiles.retain(|_, texture| texture.upgrade().is_some());
|
||||
|
||||
self.textures.values_mut().for_each(|image_texture| {
|
||||
image_texture.adjusted.retain(|copy| in_use(copy.last_used));
|
||||
image_texture.adjusted.retain(|copy| copy.texture.upgrade().is_some());
|
||||
if image_texture.adjusted.is_empty() {
|
||||
image_texture.adjustment_source = None;
|
||||
}
|
||||
});
|
||||
|
||||
// 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);
|
||||
let least_recent = (self.textures).extract_if(|key, image_texture| matches!(key, ImageKey::GeneratorTile(_)) && image_texture.last_used < oldest_kept);
|
||||
self.spare_generator_tiles.extend(least_recent.map(|(_, image_texture)| image_texture.texture));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Uploads CPU pixels as a premultiplied texture, downscaling them by a whole factor if they exceed `max_texture_size`.
|
||||
fn upload_pixels(device: &wgpu::Device, queue: &wgpu::Queue, pixels: &[u8], width: u32, height: u32, alpha_type: peniko::ImageAlphaType, max_texture_size: u32) -> Option<wgpu::Texture> {
|
||||
fn upload_pixels(executor: &WgpuExecutor, queue: &wgpu::Queue, pixels: &[u8], width: u32, height: u32, alpha_type: peniko::ImageAlphaType, max_texture_size: u32) -> Option<Texture> {
|
||||
if width == 0 || height == 0 {
|
||||
return None;
|
||||
}
|
||||
@@ -776,20 +732,7 @@ fn upload_pixels(device: &wgpu::Device, queue: &wgpu::Queue, pixels: &[u8], widt
|
||||
|
||||
// Each mipmap level halves the one before it, so a minified image averages its pixels rather than skipping over them
|
||||
let level_count = texture_width.max(texture_height).ilog2() + 1;
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("vello_gpu_image"),
|
||||
size: wgpu::Extent3d {
|
||||
width: texture_width,
|
||||
height: texture_height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: level_count,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: TEXTURE_FORMAT,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
let texture = executor.request_texture_with_mips(UVec2::new(texture_width, texture_height), TEXTURE_FORMAT, level_count);
|
||||
|
||||
let (mut level_pixels, mut level_width, mut level_height) = (pixels, texture_width, texture_height);
|
||||
for level in 0..level_count {
|
||||
@@ -880,7 +823,7 @@ fn box_downscale<Channel: Copy + Into<f32>>(pixels: &[Channel], width: u32, heig
|
||||
|
||||
/// Uploads a raster's straight linear colors as one level of 32-bit floats, the size [`upload_pixels`] makes them, so adjustments read the CPU's exact values.
|
||||
/// A raster too large for one texture is averaged down to fit on premultiplied gamma-encoded channels, as [`upload_pixels`] averages them.
|
||||
fn upload_adjustment_source(device: &wgpu::Device, queue: &wgpu::Queue, image: &Image<core_types::Color>, max_texture_size: u32) -> Option<wgpu::Texture> {
|
||||
fn upload_adjustment_source(executor: &WgpuExecutor, queue: &wgpu::Queue, image: &Image<core_types::Color>, max_texture_size: u32) -> Option<Texture> {
|
||||
let (width, height) = (image.width, image.height);
|
||||
if width == 0 || height == 0 {
|
||||
return None;
|
||||
@@ -917,16 +860,7 @@ fn upload_adjustment_source(device: &wgpu::Device, queue: &wgpu::Queue, image: &
|
||||
height: texture_height,
|
||||
depth_or_array_layers: 1,
|
||||
};
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("vello_gpu_adjustment_source"),
|
||||
size,
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
let texture = executor.request_texture_with_format(UVec2::new(texture_width, texture_height), format);
|
||||
queue.write_texture(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: &texture,
|
||||
@@ -965,23 +899,6 @@ fn clear_texture(encoder: &mut wgpu::CommandEncoder, view: &wgpu::TextureView) {
|
||||
});
|
||||
}
|
||||
|
||||
fn create_texture(device: &wgpu::Device, label: &str, size: UVec2, format: wgpu::TextureFormat, usage: wgpu::TextureUsages) -> wgpu::Texture {
|
||||
device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some(label),
|
||||
size: wgpu::Extent3d {
|
||||
width: size.x.max(1),
|
||||
height: size.y.max(1),
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage,
|
||||
view_formats: &[],
|
||||
})
|
||||
}
|
||||
|
||||
/// Full-target passes converting between straight and premultiplied alpha.
|
||||
struct AlphaConversion {
|
||||
bind_group_layout: wgpu::BindGroupLayout,
|
||||
|
||||
@@ -908,7 +908,7 @@ fn random_fields_match_the_cpu_zoomed_out_and_away_from_the_origin() {
|
||||
let (width, origin) = (32, glam::DVec2::new(-1000., -600.));
|
||||
let placement = DAffine2::from_translation(origin) * DAffine2::from_scale(glam::DVec2::splat(2. * width as f64));
|
||||
let view = DAffine2::from_scale(glam::DVec2::splat(0.5)) * DAffine2::from_translation(-origin);
|
||||
let noise = |amount, distribution, monochromatic| EffectOperation::Speckle {
|
||||
let noise = |amount, distribution, monochromatic| EffectOperation::AddNoise {
|
||||
amount,
|
||||
distribution,
|
||||
monochromatic,
|
||||
@@ -959,7 +959,7 @@ fn random_fields_stay_in_place_far_from_the_origin() {
|
||||
|
||||
// Noise over an endless color whose cells lie past where 32-bit floats hold every integer, rendered there and a pixel further right
|
||||
let size = UVec2::splat(16);
|
||||
let noise = EffectOperation::Speckle {
|
||||
let noise = EffectOperation::AddNoise {
|
||||
amount: 40.,
|
||||
distribution: NoiseDistribution::Uniform,
|
||||
monochromatic: false,
|
||||
@@ -1376,46 +1376,6 @@ fn a_clipping_base_clips_by_its_blur_but_not_by_its_shadow() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn endless_layers_clip_to_the_shape_beneath_them() {
|
||||
use core_types::list::{ATTR_APPEARANCE, Item, List};
|
||||
use core_types::{ATTR_CLIPPING_MASK, Color as GraphicColor};
|
||||
use graphic_types::generator::Generator;
|
||||
use graphic_types::vector_types::gradient::Gradient;
|
||||
use graphic_types::{Appearance, Coverage, Graphic, Vector};
|
||||
use rendering::{Render, RenderParams};
|
||||
use vello_gpu::kurbo::Shape;
|
||||
|
||||
let size = UVec2::new(128, 128);
|
||||
let mut square = Vector::item_from_bezpath(&Rect::new(30., 30., 80., 80.).to_path(0.1));
|
||||
square.set_attribute(
|
||||
ATTR_APPEARANCE,
|
||||
Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(GraphicColor::WHITE))),
|
||||
);
|
||||
let base = Item::new_from_element(Graphic::VectorList(List::new_from_item(square)));
|
||||
|
||||
// Layers of a color, a gradient, and noise, each clipped to a square beneath it
|
||||
let layers = [
|
||||
("color", Graphic::from(Item::new_from_element(GraphicColor::RED).with_attribute(ATTR_CLIPPING_MASK, true))),
|
||||
(
|
||||
"gradient",
|
||||
Graphic::from(Item::new_from_element(Gradient::from(vec![GraphicColor::RED, GraphicColor::BLUE])).with_attribute(ATTR_CLIPPING_MASK, true)),
|
||||
),
|
||||
("noise", Graphic::from(Item::new_from_element(Generator::Noise).with_attribute(ATTR_CLIPPING_MASK, true))),
|
||||
];
|
||||
for (name, layer) in layers {
|
||||
let graphic = Graphic::GraphicList([base.clone(), Item::new_from_element(layer)].into_iter().collect());
|
||||
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||||
return;
|
||||
};
|
||||
|
||||
assert_eq!(pixel(&pixels, size, 55, 55)[3], 255, "{name}: the layer shows within the square");
|
||||
for (x, y) in [(10, 10), (100, 55), (55, 100), (120, 120)] {
|
||||
assert_eq!(pixel(&pixels, size, x, y)[3], 0, "{name}: the layer is clipped away at ({x}, {y}), past the square");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feathers_fade_the_content_to_nothing_at_its_edges() {
|
||||
use graphic_types::EffectOperation;
|
||||
@@ -1647,7 +1607,7 @@ fn gpu_effect_texels(effects: &graphic_types::Effects, texels: &[[half::f16; 4]]
|
||||
|
||||
let mut textures = crate::vello_effects::EffectTextures::default();
|
||||
let layers = graphic_types::effect_layers::EffectLayers::plan(effects, BlendMode::Normal, 1., false);
|
||||
let results = effect_passes.apply(device, &queue, &mut textures, &content, effects, &layers, 1., 1., DAffine2::IDENTITY, None, &paints, None, None);
|
||||
let results = effect_passes.apply(executor, &queue, &mut textures, &content, effects, &layers, 1., 1., DAffine2::IDENTITY, None, &paints, None, None);
|
||||
let (result, _) = results.into_iter().next()?;
|
||||
drop(queue);
|
||||
|
||||
@@ -4155,7 +4115,7 @@ fn cpu_evaluated_effects_match_the_gpu_passes() {
|
||||
vec![blur(2., false, false), edges_only(200., 0.)],
|
||||
vec![blur(2., false, false), unsharp(150., 0., 0.)],
|
||||
]);
|
||||
let noise = |amount, distribution, monochromatic| EffectOperation::Speckle {
|
||||
let noise = |amount, distribution, monochromatic| EffectOperation::AddNoise {
|
||||
amount,
|
||||
distribution,
|
||||
monochromatic,
|
||||
@@ -4369,7 +4329,7 @@ fn gpu_adjusted_texels(run: &[graphic_types::Adjustment], texels: &[[half::f16;
|
||||
let effects = Effects::from_operations(run.iter().cloned().map(EffectOperation::Adjustment));
|
||||
let mut textures = crate::vello_effects::EffectTextures::default();
|
||||
let layers = graphic_types::effect_layers::EffectLayers::plan(&effects, core_types::blending::BlendMode::Normal, fill, false);
|
||||
let results = effect_passes.apply(device, &queue, &mut textures, &content, &effects, &layers, fill, 1., DAffine2::IDENTITY, None, &[], None, None);
|
||||
let results = effect_passes.apply(executor, &queue, &mut textures, &content, &effects, &layers, fill, 1., DAffine2::IDENTITY, None, &[], None, None);
|
||||
let (adjusted, _) = results.into_iter().next().expect("the adjustments draw one layer");
|
||||
drop(queue);
|
||||
|
||||
@@ -4721,10 +4681,10 @@ fn gpu_color_adjustments_match_the_cpu_kernels() {
|
||||
];
|
||||
let mut runs: Vec<(String, Vec<Adjustment>)> = runs.into_iter().map(|(name, adjustment)| (name.to_string(), vec![adjustment])).collect();
|
||||
|
||||
// Every blend mode, overlaying an opaque color and a translucent one, each with a luma apart from every test color's, which Darker Color and Lighter Color compare, and off Hard Mix's steep ramp over them
|
||||
// Every blend mode, overlaying an opaque color and a translucent one, each with channels summing to what no test color's do, which Darker Color and Lighter Color compare
|
||||
for blend_mode in BlendMode::list().into_iter().flatten().chain(&[BlendMode::Erase, BlendMode::Restore, BlendMode::MultiplyAlpha]) {
|
||||
for (color, opacity) in [
|
||||
(Color::from_gamma_srgb_channels(0.9, 0.462, 0.239, 1.), 70.),
|
||||
(Color::from_gamma_srgb_channels(0.9, 0.453, 0.2, 1.), 70.),
|
||||
(Color::from_gamma_srgb_channels(0.1, 0.6, 0.853, 0.4), 100.),
|
||||
] {
|
||||
let overlay = Adjustment::ColorOverlay {
|
||||
@@ -6366,8 +6326,10 @@ fn generator_tile_pixels(pattern: &graphic_types::generator::GeneratorPattern, c
|
||||
|
||||
let queue = executor.context().queue.lock();
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("generator_tile_test") });
|
||||
(executor.inner.vello_renderer.generator_passes).render_tile(device, &queue, &mut encoder, &texture, pattern, corner, texel);
|
||||
let mut held = Vec::new();
|
||||
(executor.inner.vello_renderer.generator_passes).render_tile(executor, &queue, &mut encoder, &mut held, &texture, pattern, corner, texel);
|
||||
queue.submit([encoder.finish()]);
|
||||
drop(held);
|
||||
drop(queue);
|
||||
|
||||
let bytes = executor.read_texture_pixels(&texture).expect("Failed to read back the tile");
|
||||
@@ -6423,7 +6385,7 @@ fn generator_tiles_are_reused_across_a_pan() {
|
||||
let Some(executor) = executor() else { return };
|
||||
let _turn = take_turn();
|
||||
let max_texture_size = executor.context().device.limits().max_texture_dimension_2d;
|
||||
let tiles = |canvas: &crate::VelloCanvas| canvas.images.textures.len();
|
||||
let tiles = |canvas: &crate::VelloCanvas| canvas.images.generator_tiles.len();
|
||||
|
||||
// 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();
|
||||
@@ -6442,44 +6404,6 @@ fn generator_tiles_are_reused_across_a_pan() {
|
||||
assert!(panned < first, "panning renders only the tiles newly in view, not all {first} again (rendered {panned})");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_generator_tiles_take_over_the_textures_of_freed_ones() {
|
||||
use graphic_types::generator::{GeneratorPattern, NoiseSettings};
|
||||
|
||||
let Some(executor) = executor() else { return };
|
||||
let _turn = take_turn();
|
||||
let max_texture_size = executor.context().device.limits().max_texture_dimension_2d;
|
||||
let tile_textures = |canvas: &crate::VelloCanvas| -> Vec<wgpu::Texture> {
|
||||
(canvas.images.textures.iter())
|
||||
.filter(|(key, _)| matches!(key, super::ImageKey::GeneratorTile(_)))
|
||||
.map(|(_, image_texture)| image_texture.texture.clone())
|
||||
.collect()
|
||||
};
|
||||
|
||||
let mut canvas = crate::VelloCanvas::default();
|
||||
let draw = |canvas: &mut crate::VelloCanvas, seed: i64| {
|
||||
let mut scene = VelloSceneBuilder::new(512, 512, Affine::IDENTITY, max_texture_size);
|
||||
scene.draw_generator(&GeneratorPattern::Noise(NoiseSettings { seed, ..noise_settings() }), Affine::scale(2.));
|
||||
executor.render_vello_scene_on_canvas(canvas, scene).unwrap();
|
||||
};
|
||||
|
||||
// The first pattern's tiles, freed once another is drawn for long enough
|
||||
draw(&mut canvas, 1);
|
||||
let freed = tile_textures(&canvas);
|
||||
for _ in 0..super::UNUSED_IMAGE_RENDER_LIMIT {
|
||||
draw(&mut canvas, 2);
|
||||
}
|
||||
|
||||
// The textures in use since the first pattern was freed are the second's and the third's, which takes over the first's
|
||||
let second = tile_textures(&canvas);
|
||||
draw(&mut canvas, 3);
|
||||
let third: Vec<_> = tile_textures(&canvas).into_iter().filter(|texture| !second.contains(texture)).collect();
|
||||
assert!(
|
||||
third.len() == freed.len() && third.iter().all(|texture| freed.contains(texture)),
|
||||
"the third pattern's tiles render into the textures of the first's"
|
||||
);
|
||||
}
|
||||
|
||||
/// An effect stamped on content at `placement` the way its node stamps it, with displacement maps lined up with the content where it lies.
|
||||
fn stamped_at(operation: &graphic_types::EffectOperation, placement: DAffine2) -> graphic_types::Effect {
|
||||
let mut operation = operation.clone();
|
||||
@@ -11549,474 +11473,3 @@ fn endless_layers_fade_by_blend_ifs_reading_each_effect_run_as_the_runs_before_i
|
||||
};
|
||||
assert!(worst <= 3, "the half-filled color mask differs between the CPU and GPU by up to {worst} levels");
|
||||
}
|
||||
|
||||
/// A raster of `size` texels placed a texel to each of the render's pixels from `corner`, each of the straight 8-bit color `level` gives at its column and row.
|
||||
fn leveled_image(corner: UVec2, size: UVec2, level: impl Fn(u32, u32) -> [u8; 4]) -> core_types::list::Item<graphic_types::raster_types::Raster<graphic_types::raster_types::CPU>> {
|
||||
use core_types::color::SRGBA8;
|
||||
use graphic_types::raster_types::{Image, Raster};
|
||||
|
||||
let data = (0..size.x * size.y)
|
||||
.map(|index| {
|
||||
let [red, green, blue, alpha] = level(index % size.x, index / size.x);
|
||||
core_types::Color::from(SRGBA8::new(red, green, blue, alpha))
|
||||
})
|
||||
.collect();
|
||||
let placement = DAffine2::from_translation(corner.as_dvec2()) * DAffine2::from_scale(size.as_dvec2());
|
||||
core_types::list::Item::new_from_element(Raster::new_cpu(Image { width: size.x, height: size.y, data })).with_attribute(core_types::ATTR_TRANSFORM, placement)
|
||||
}
|
||||
|
||||
/// The premultiplied gamma-encoded channels of a straight 8-bit color, from 0 to 1.
|
||||
fn premultiplied_gamma([red, green, blue, alpha]: [u8; 4]) -> [f32; 4] {
|
||||
let alpha = alpha as f32 / 255.;
|
||||
[red, green, blue]
|
||||
.map(|channel| channel as f32 / 255. * alpha)
|
||||
.into_iter()
|
||||
.chain([alpha])
|
||||
.collect::<Vec<_>>()
|
||||
.try_into()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// What lies beneath layers blending by the modes Vello's layers lack: red rising across and green rising down over a constant blue, opaque in the top half and fading across the bottom half to a quarter.
|
||||
fn blend_backdrop_level(x: u32, y: u32) -> [u8; 4] {
|
||||
let alpha = if y < 48 { 255 } else { 255 - x * 191 / 95 };
|
||||
[(x * 255 / 95) as u8, (y * 255 / 95) as u8, 140, alpha as u8]
|
||||
}
|
||||
|
||||
/// The layer blending onto it, 80 texels across from the corner at 8: red falling down, green rising across, and blue rising across both, with a band of half alpha.
|
||||
fn blend_content_level(x: u32, y: u32) -> [u8; 4] {
|
||||
let alpha = if (50..62).contains(&y) { 128 } else { 255 };
|
||||
[(230 - 2 * y) as u8, (20 + 2 * x) as u8, ((x + 2 * y) * 255 / 237) as u8, alpha]
|
||||
}
|
||||
|
||||
/// Whether a blend is ill-conditioned for the colors, where it stretches the rounding of what lies beneath far: on or near Hard Mix's steep ramp,
|
||||
/// where a burn or dodge (Vivid Light's too) is by a paint dark or light enough to stretch each level more than fourfold, and near a tie of luma for Darker or Lighter Color.
|
||||
fn blend_ill_conditioned(blend_mode: BlendMode, content: [f32; 4], backdrop: [f32; 4], fill: f32) -> bool {
|
||||
let straight = |pixel: [f32; 4]| [0, 1, 2].map(|channel| if pixel[3] > 0. { pixel[channel] / pixel[3] } else { 0. });
|
||||
let (source, beneath) = (straight(content), straight(backdrop));
|
||||
let luma = |color: [f32; 3]| 0.3 * color[0] + 0.59 * color[1] + 0.11 * color[2];
|
||||
let strength = if blend_mode.fill_moves_layer_toward_neutral() { fill } else { 1. };
|
||||
let steepness = 255. * strength / 256.;
|
||||
|
||||
match blend_mode {
|
||||
BlendMode::HardMix => (0..3).any(|channel| (-0.01..1. - steepness + 0.01).contains(&(beneath[channel] - steepness * (1. - source[channel])))),
|
||||
BlendMode::VividLight => source.iter().any(|&channel| (2. * (0.5 + strength * (channel - 0.5)) - 1.).abs() > 0.75),
|
||||
BlendMode::ColorDodge => source.iter().any(|&channel| strength * channel > 0.75),
|
||||
BlendMode::ColorBurn => source.iter().any(|&channel| 1. - strength * (1. - channel) < 0.25),
|
||||
BlendMode::DarkerColor | BlendMode::LighterColor => (luma(source) - luma(beneath)).abs() < 2. / 255.,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The reference formula, for PSD interop, for one opaque channel of a layer in a mode Vello's layers lack, or in Color Dodge or Color Burn, with its fill, over an opaque backdrop channel.
|
||||
fn reference_blend(blend_mode: BlendMode, backdrop: f32, source: f32, fill: f32) -> f32 {
|
||||
let color_burn = |backdrop: f32, source: f32| {
|
||||
if backdrop >= 1. {
|
||||
1.
|
||||
} else if source <= 0. {
|
||||
0.
|
||||
} else {
|
||||
1. - ((1. - backdrop) / source).min(1.)
|
||||
}
|
||||
};
|
||||
let color_dodge = |backdrop: f32, source: f32| {
|
||||
if backdrop <= 0. {
|
||||
0.
|
||||
} else if source >= 1. {
|
||||
1.
|
||||
} else {
|
||||
(backdrop / (1. - source)).min(1.)
|
||||
}
|
||||
};
|
||||
let mix = |blended: f32| backdrop + (blended.clamp(0., 1.) - backdrop) * fill;
|
||||
|
||||
match blend_mode {
|
||||
BlendMode::ColorDodge => color_dodge(backdrop, fill * source),
|
||||
BlendMode::ColorBurn => color_burn(backdrop, 1. - fill * (1. - source)),
|
||||
BlendMode::LinearBurn => (backdrop + (1. - fill * (1. - source)) - 1.).clamp(0., 1.),
|
||||
BlendMode::LinearDodge => (backdrop + fill * source).clamp(0., 1.),
|
||||
BlendMode::VividLight => {
|
||||
let source = 0.5 + fill * (source - 0.5);
|
||||
if source <= 0.5 {
|
||||
color_burn(backdrop, 2. * source)
|
||||
} else {
|
||||
color_dodge(backdrop, 2. * source - 1.)
|
||||
}
|
||||
}
|
||||
BlendMode::LinearLight => (backdrop + 2. * (0.5 + fill * (source - 0.5)) - 1.).clamp(0., 1.),
|
||||
BlendMode::HardMix => {
|
||||
let steepness = 255. * fill / 256.;
|
||||
((backdrop - steepness * (1. - source)) / (1. - steepness)).clamp(0., 1.)
|
||||
}
|
||||
BlendMode::PinLight => mix(if source <= 0.5 { backdrop.min(2. * source) } else { backdrop.max(2. * source - 1.) }),
|
||||
BlendMode::Subtract => mix(backdrop - source),
|
||||
BlendMode::Divide => mix(if backdrop <= 0. {
|
||||
0.
|
||||
} else if source <= 0. {
|
||||
1.
|
||||
} else {
|
||||
backdrop / source
|
||||
}),
|
||||
_ => panic!("{blend_mode} picks whole colors or blends natively"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_in_modes_vello_lacks_blend_onto_partly_covering_backdrops_as_on_the_cpu_and_by_the_reference_formulas() {
|
||||
use core_types::list::List;
|
||||
use core_types::{ATTR_BLEND_MODE, ATTR_OPACITY, ATTR_OPACITY_FILL};
|
||||
use graphic_types::Graphic;
|
||||
use raster_kernels::layer_blending::blend_layer_pixel;
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
let size = UVec2::splat(96);
|
||||
let (corner, content_size) = (UVec2::splat(8), UVec2::splat(80));
|
||||
let modes = BlendMode::list().into_iter().flatten().copied().filter(BlendMode::reads_backdrop);
|
||||
|
||||
for blend_mode in modes.chain([BlendMode::ColorDodge, BlendMode::ColorBurn]) {
|
||||
for (fill, opacity) in [(1., 1.), (0.5, 1.), (0.7, 0.6)] {
|
||||
let content = leveled_image(corner, content_size, blend_content_level)
|
||||
.with_attribute(ATTR_BLEND_MODE, blend_mode)
|
||||
.with_attribute(ATTR_OPACITY_FILL, fill as f64)
|
||||
.with_attribute(ATTR_OPACITY, opacity as f64);
|
||||
let mut list = List::new_from_item(leveled_image(UVec2::ZERO, size, blend_backdrop_level));
|
||||
list.push(content);
|
||||
let graphic = Graphic::RasterCPUList(list);
|
||||
let Some(gpu) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let (mut worst, mut worst_at) = (0., UVec2::ZERO);
|
||||
for y in 0..size.y {
|
||||
for x in 0..size.x {
|
||||
let backdrop = premultiplied_gamma(blend_backdrop_level(x, y));
|
||||
let inside = (corner.x..corner.x + content_size.x).contains(&x) && (corner.y..corner.y + content_size.y).contains(&y);
|
||||
let content = if inside { premultiplied_gamma(blend_content_level(x - corner.x, y - corner.y)) } else { [0.; 4] };
|
||||
if blend_ill_conditioned(blend_mode, content, backdrop, fill) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// The CPU blends the content by its fill, then its opacity mixes from what lies beneath to that
|
||||
let blended = blend_layer_pixel(content, backdrop, blend_mode, fill);
|
||||
let gpu = premultiplied_gamma(pixel(&gpu, size, x, y));
|
||||
for channel in 0..4 {
|
||||
let cpu = backdrop[channel] + (blended[channel] - backdrop[channel]) * opacity;
|
||||
let difference = (cpu - gpu[channel]).abs() * 255.;
|
||||
if difference > worst {
|
||||
(worst, worst_at) = (difference, UVec2::new(x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
worst <= 3.,
|
||||
"{blend_mode} at fill {fill} and opacity {opacity} differs from the CPU by up to {worst} levels at {worst_at}"
|
||||
);
|
||||
|
||||
// Over the opaque top half, the opaque layer takes the reference formula
|
||||
if opacity < 1. || matches!(blend_mode, BlendMode::DarkerColor | BlendMode::LighterColor) {
|
||||
continue;
|
||||
}
|
||||
for (x, y) in [(20, 12), (50, 30), (80, 44), (14, 40)] {
|
||||
let backdrop = premultiplied_gamma(blend_backdrop_level(x, y));
|
||||
let content = premultiplied_gamma(blend_content_level(x - corner.x, y - corner.y));
|
||||
if blend_ill_conditioned(blend_mode, content, backdrop, fill) {
|
||||
continue;
|
||||
}
|
||||
let gpu = premultiplied_gamma(pixel(&gpu, size, x, y));
|
||||
for channel in 0..3 {
|
||||
let expected = reference_blend(blend_mode, backdrop[channel], content[channel], fill);
|
||||
assert!(
|
||||
(expected - gpu[channel]).abs() * 255. <= 3.,
|
||||
"{blend_mode} at fill {fill} gives {gpu:?} at ({x}, {y}) rather than {expected} in channel {channel}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn darker_and_lighter_color_layers_pick_whole_colors_by_luma_on_the_gpu() {
|
||||
use core_types::ATTR_BLEND_MODE;
|
||||
use core_types::list::List;
|
||||
use graphic_types::Graphic;
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
// Blue's luma (0.11) is below the gray's (0.3), though its mean channel (a third) is above it
|
||||
let size = UVec2::splat(32);
|
||||
let gray = |_: u32, _: u32| [77, 77, 77, 255];
|
||||
let blue = |_: u32, _: u32| [0, 0, 255, 255];
|
||||
for (blend_mode, expected) in [(BlendMode::DarkerColor, [0, 0, 255, 255]), (BlendMode::LighterColor, [77, 77, 77, 255])] {
|
||||
let mut list = List::new_from_item(leveled_image(UVec2::ZERO, size, blue));
|
||||
list.push(leveled_image(UVec2::splat(8), UVec2::splat(16), gray).with_attribute(ATTR_BLEND_MODE, blend_mode));
|
||||
let graphic = Graphic::RasterCPUList(list);
|
||||
let Some(gpu) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||||
return;
|
||||
};
|
||||
let picked = pixel(&gpu, size, 16, 16);
|
||||
assert!(picked.iter().zip(expected).all(|(gpu, expected)| gpu.abs_diff(expected) <= 1), "{blend_mode} picks {picked:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effect_pieces_beneath_the_content_blend_by_their_own_modes_unmoved_by_its_fill() {
|
||||
use core_types::Color as GraphicColor;
|
||||
use glam::DVec2;
|
||||
use graphic_types::EffectOperation;
|
||||
use raster_kernels::layer_blending::blend_layer_pixel;
|
||||
|
||||
let size = UVec2::new(128, 128);
|
||||
let (backdrop, content, shadow, glow) = ([153, 128, 102], [204, 153, 77], [179, 77, 230], [102, 51, 128]);
|
||||
let levels = |color: [u8; 3]| color.map(|level| level as f32 / 255.);
|
||||
let piece_color = |color: [u8; 3]| GraphicColor::from_gamma_srgb_channels(levels(color)[0], levels(color)[1], levels(color)[2], 1.);
|
||||
let shadow_in = |mode: BlendMode| {
|
||||
let mut operation = drop_shadow(piece_color(shadow), DVec2::splat(10.), 0., 0.);
|
||||
if let EffectOperation::DropShadow { blend_mode, .. } = &mut operation {
|
||||
*blend_mode = mode;
|
||||
}
|
||||
operation
|
||||
};
|
||||
let dodging_glow = EffectOperation::OuterGlow {
|
||||
color: piece_color(glow).into(),
|
||||
blend_mode: BlendMode::ColorDodge,
|
||||
technique: Default::default(),
|
||||
spread: 100.,
|
||||
size: 5.,
|
||||
range: 50.,
|
||||
contour: Default::default(),
|
||||
noise: 0.,
|
||||
jitter: 0.,
|
||||
seed: 0,
|
||||
};
|
||||
|
||||
// Each piece, outside the content, and the content, over a piece it knocks out, at a fill moving only the content toward neutral
|
||||
let cases = [
|
||||
("a Linear Burn shadow under normal content", shadow_in(BlendMode::LinearBurn), shadow, (85, 85), BlendMode::Normal, 1.),
|
||||
(
|
||||
"a normal shadow under Linear Burn content at half fill",
|
||||
shadow_in(BlendMode::Normal),
|
||||
shadow,
|
||||
(85, 85),
|
||||
BlendMode::LinearBurn,
|
||||
0.5,
|
||||
),
|
||||
("a Color Dodge glow under Color Dodge content at half fill", dodging_glow, glow, (82, 55), BlendMode::ColorDodge, 0.5),
|
||||
(
|
||||
"a Linear Burn shadow under Linear Burn content at half fill",
|
||||
shadow_in(BlendMode::LinearBurn),
|
||||
shadow,
|
||||
(85, 85),
|
||||
BlendMode::LinearBurn,
|
||||
0.5,
|
||||
),
|
||||
];
|
||||
for (case, piece, piece_level, piece_at, content_mode, fill) in cases {
|
||||
let piece_mode = match &piece {
|
||||
EffectOperation::DropShadow { blend_mode, .. } | EffectOperation::OuterGlow { blend_mode, .. } => *blend_mode,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let [red, green, blue] = backdrop;
|
||||
let backdrop_color = Color::from_rgb8(red, green, blue);
|
||||
let [red, green, blue] = content;
|
||||
let Some(gpu) = render_square_over_backdrop(vec![piece], fill, 1., content_mode, Some(backdrop_color), Color::from_rgb8(red, green, blue), 30., 80., size) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// The reference formula, which the CPU blends by, for an opaque layer at a fill over the opaque backdrop
|
||||
let opaque = |color: [f32; 3]| [color[0], color[1], color[2], 1.];
|
||||
for (blend_mode, source, fill, (x, y)) in [(piece_mode, levels(piece_level), 1., piece_at), (content_mode, levels(content), fill, (50, 50))] {
|
||||
let expected = match blend_mode {
|
||||
BlendMode::Normal => source,
|
||||
_ => [0, 1, 2].map(|channel| reference_blend(blend_mode, levels(backdrop)[channel], source[channel], fill)),
|
||||
};
|
||||
let cpu = blend_layer_pixel(opaque(source), opaque(levels(backdrop)), blend_mode, fill);
|
||||
let gpu = premultiplied_gamma(pixel(&gpu, size, x, y));
|
||||
for channel in 0..3 {
|
||||
assert!(
|
||||
(cpu[channel] - expected[channel]).abs() * 255. <= 0.5,
|
||||
"{case}: the CPU gives {cpu:?} at ({x}, {y}) rather than {expected:?}"
|
||||
);
|
||||
assert!(
|
||||
(gpu[channel] - expected[channel]).abs() * 255. <= 3.,
|
||||
"{case}: the GPU gives {gpu:?} at ({x}, {y}) rather than {expected:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_dodge_and_burn_layers_blend_natively_over_a_shadow_beneath_them_not_knocked_out() {
|
||||
use core_types::Color as GraphicColor;
|
||||
use glam::DVec2;
|
||||
use graphic_types::EffectOperation;
|
||||
use graphic_types::effect_layers::EffectLayers;
|
||||
use graphic_types::effects::{EffectCapture, Effects};
|
||||
use raster_kernels::layer_blending::blend_pixel;
|
||||
|
||||
let size = UVec2::new(128, 128);
|
||||
let (backdrop, content, shadow, fill) = ([153, 128, 102], [102, 179, 77], [51, 77, 128], 0.5);
|
||||
let levels = |color: [u8; 3]| color.map(|level| level as f32 / 255.);
|
||||
let mut shadow_not_knocked_out = drop_shadow(
|
||||
GraphicColor::from_gamma_srgb_channels(levels(shadow)[0], levels(shadow)[1], levels(shadow)[2], 1.),
|
||||
DVec2::splat(10.),
|
||||
0.,
|
||||
0.,
|
||||
);
|
||||
if let EffectOperation::DropShadow { knockout, .. } = &mut shadow_not_knocked_out {
|
||||
*knockout = false;
|
||||
}
|
||||
|
||||
for blend_mode in [BlendMode::ColorDodge, BlendMode::ColorBurn] {
|
||||
// What lies beneath the item leaves out the shadow the content blends onto, so the layer blends natively, faded by its fill
|
||||
let layers = EffectLayers::plan(&Effects::from_operations([shadow_not_knocked_out.clone()]), blend_mode, fill, true);
|
||||
assert!(!layers.content_reads_backdrop(fill) && layers.layer_of(EffectCapture { index: 0, plane: 0 }).is_some(), "{blend_mode}");
|
||||
|
||||
let [red, green, blue] = backdrop;
|
||||
let backdrop_color = Color::from_rgb8(red, green, blue);
|
||||
let [red, green, blue] = content;
|
||||
let Some(gpu) = render_square_over_backdrop(
|
||||
vec![shadow_not_knocked_out.clone()],
|
||||
fill,
|
||||
1.,
|
||||
blend_mode,
|
||||
Some(backdrop_color),
|
||||
Color::from_rgb8(red, green, blue),
|
||||
30.,
|
||||
80.,
|
||||
size,
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Over the shadow, and past it over what lies beneath the item, the content faded by its fill blends natively, as the CPU blends it
|
||||
let opaque = |color: [f32; 3]| [color[0], color[1], color[2], 1.];
|
||||
let faded = [levels(content)[0] * fill, levels(content)[1] * fill, levels(content)[2] * fill, fill];
|
||||
for (beneath, (x, y)) in [(levels(shadow), (60, 60)), (levels(backdrop), (35, 35))] {
|
||||
let expected = blend_pixel(faded, opaque(beneath), blend_mode);
|
||||
let gpu = premultiplied_gamma(pixel(&gpu, size, x, y));
|
||||
for channel in 0..3 {
|
||||
assert!(
|
||||
(gpu[channel] - expected[channel]).abs() * 255. <= 3.,
|
||||
"{blend_mode} gives {gpu:?} at ({x}, {y}) rather than {expected:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_dodge_layers_blending_natively_fade_by_their_fill_in_their_first_effect_run() {
|
||||
use core_types::list::List;
|
||||
use core_types::{ATTR_BLEND_MODE, ATTR_OPACITY_FILL, ATTR_TRANSFORM};
|
||||
use glam::DVec2;
|
||||
use graphic_types::adjustment::Adjustment;
|
||||
use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect};
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
// Opaque 0.4 gray in Color Dodge at half fill, made opaque, then scaled, then casting a normal shadow it doesn't knock out, over opaque 0.3 gray
|
||||
let size = UVec2::splat(128);
|
||||
let mut content = leveled_image(UVec2::splat(20), UVec2::splat(40), |_, _| [102, 102, 102, 255])
|
||||
.with_attribute(ATTR_BLEND_MODE, BlendMode::ColorDodge)
|
||||
.with_attribute(ATTR_OPACITY_FILL, 0.5);
|
||||
stamp_effect(&mut content, Effect::new(&EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 100. })));
|
||||
content.set_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(20.)) * DAffine2::from_scale(DVec2::splat(60.)));
|
||||
let mut shadow = drop_shadow(core_types::Color::from_gamma_srgb_channels(0.2, 0.2, 0.2, 1.), DVec2::splat(10.), 0., 0.);
|
||||
if let EffectOperation::DropShadow { knockout, .. } = &mut shadow {
|
||||
*knockout = false;
|
||||
}
|
||||
stamp_effect(&mut content, Effect::new(&shadow));
|
||||
let mut list = List::new_from_item(leveled_image(UVec2::ZERO, size, |_, _| [77, 77, 77, 255]));
|
||||
list.push(content);
|
||||
let graphic = Graphic::RasterCPUList(list);
|
||||
let Some(gpu) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// As in SVG, the fill fades the content before Make Opaque restores its alpha, so past the shadow it dodges at full strength: 0.3 / (1 - 0.4)
|
||||
let dodged = pixel(&gpu, size, 25, 25);
|
||||
assert!(dodged[..3].iter().all(|&channel| channel.abs_diff(128) <= 3), "{dodged:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_in_modes_vello_lacks_blend_only_onto_what_their_faded_group_drew() {
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::{ATTR_BLEND_MODE, ATTR_OPACITY};
|
||||
use graphic_types::Graphic;
|
||||
use raster_kernels::layer_blending::blend_layer_pixel;
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
// White beneath a faded group of dark blue and a layer adding a gray over it, which over the white would add up to white
|
||||
let size = UVec2::splat(48);
|
||||
let white = |_: u32, _: u32| [255, 255, 255, 255];
|
||||
let dark_blue = |_: u32, _: u32| [20, 30, 120, 255];
|
||||
let gray = |_: u32, _: u32| [100, 100, 100, 255];
|
||||
let mut inner = List::new_from_item(leveled_image(UVec2::splat(4), UVec2::splat(40), dark_blue));
|
||||
inner.push(leveled_image(UVec2::splat(12), UVec2::splat(24), gray).with_attribute(ATTR_BLEND_MODE, BlendMode::LinearDodge));
|
||||
let group = Item::new_from_element(Graphic::RasterCPUList(inner)).with_attribute(ATTR_OPACITY, 0.5_f64);
|
||||
let mut list = List::new_from_item(Item::new_from_element(Graphic::RasterCPUList(List::new_from_item(leveled_image(UVec2::ZERO, size, white)))));
|
||||
list.push(group);
|
||||
let graphic = Graphic::GraphicList(list);
|
||||
let Some(gpu) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// The layer adds onto the dark blue alone, and the group then fades over the white
|
||||
let added = blend_layer_pixel(premultiplied_gamma(gray(0, 0)), premultiplied_gamma(dark_blue(0, 0)), BlendMode::LinearDodge, 1.);
|
||||
let expected: Vec<f32> = (0..3).map(|channel| 1. + (added[channel] - 1.) * 0.5).collect();
|
||||
let shown = premultiplied_gamma(pixel(&gpu, size, 24, 24));
|
||||
for channel in 0..3 {
|
||||
assert!((shown[channel] - expected[channel]).abs() * 255. <= 2., "{shown:?} rather than {expected:?}");
|
||||
}
|
||||
|
||||
// A group in the mode adds all it draws onto what lies beneath it
|
||||
let mut list = List::new_from_item(Item::new_from_element(Graphic::RasterCPUList(List::new_from_item(leveled_image(UVec2::ZERO, size, dark_blue)))));
|
||||
list.push(Item::new_from_element(Graphic::RasterCPUList(List::new_from_item(leveled_image(UVec2::splat(12), UVec2::splat(24), gray)))).with_attribute(ATTR_BLEND_MODE, BlendMode::LinearDodge));
|
||||
let graphic = Graphic::GraphicList(list);
|
||||
let Some(gpu) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||||
return;
|
||||
};
|
||||
let shown = premultiplied_gamma(pixel(&gpu, size, 24, 24));
|
||||
assert!((0..3).all(|channel| (shown[channel] - added[channel]).abs() * 255. <= 2.), "{shown:?} rather than {added:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_ifs_fade_a_layer_once_it_blends_by_a_mode_vello_lacks() {
|
||||
use core_types::ATTR_BLEND_MODE;
|
||||
use core_types::list::List;
|
||||
use graphic_types::blend_if::BlendIfRanges;
|
||||
use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect};
|
||||
use raster_kernels::layer_blending::blend_layer_pixel;
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
// Shown over grays from a quarter up, fully from a half, with columns of gray beneath from dark to light
|
||||
let mut ranges = BlendIfRanges::default();
|
||||
ranges.underlying.gray = blend_range([64., 128., 255., 255.]);
|
||||
let size = UVec2::new(64, 16);
|
||||
let columns = |x: u32, _: u32| {
|
||||
let level = (x * 4) as u8;
|
||||
[level, level, level, 255]
|
||||
};
|
||||
let orange = |_: u32, _: u32| [230, 140, 60, 255];
|
||||
let mut content = leveled_image(UVec2::ZERO, size, orange).with_attribute(ATTR_BLEND_MODE, BlendMode::LinearBurn);
|
||||
stamp_effect(&mut content, Effect::new(&EffectOperation::BlendIf(Box::new(ranges))));
|
||||
let mut list = List::new_from_item(leveled_image(UVec2::ZERO, size, columns));
|
||||
list.push(content);
|
||||
let graphic = Graphic::RasterCPUList(list);
|
||||
let Some(gpu) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Each column shows the blend as strongly as Blend If shows the gray beneath it
|
||||
for x in 0..size.x {
|
||||
let beneath = premultiplied_gamma(columns(x, 0));
|
||||
let blended = blend_layer_pixel(premultiplied_gamma(orange(0, 0)), beneath, BlendMode::LinearBurn, 1.);
|
||||
let weight = ranges.underlying.weight([beneath[0], beneath[1], beneath[2]].map(f64::from)) as f32;
|
||||
let shown = premultiplied_gamma(pixel(&gpu, size, x, 8));
|
||||
for channel in 0..3 {
|
||||
let expected = beneath[channel] + (blended[channel] - beneath[channel]) * weight;
|
||||
assert!((shown[channel] - expected).abs() * 255. <= 3., "column {x} shows {shown:?} rather than {expected} in channel {channel}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -197,10 +197,10 @@ fn high_pass<T>(
|
||||
}
|
||||
|
||||
/// Scatters random offsets across the colors of the input graphics, like film grain, fixed in place on the content.
|
||||
#[node_macro::node(category("Raster: Filter"), version(2))]
|
||||
fn speckle<T>(
|
||||
#[node_macro::node(category("Raster: Filter"))]
|
||||
fn add_noise<T>(
|
||||
_: impl Ctx,
|
||||
/// The content to speckle.
|
||||
/// The content to add noise to.
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// How strong the noise is, as a percentage of full brightness: the most a color shifts for uniform noise, or the standard deviation of its shifts for Gaussian noise.
|
||||
@@ -221,7 +221,7 @@ fn speckle<T>(
|
||||
let mut content = content;
|
||||
stamp_effect(
|
||||
&mut content,
|
||||
Effect::new(&EffectOperation::Speckle {
|
||||
Effect::new(&EffectOperation::AddNoise {
|
||||
amount: *amount.element(),
|
||||
distribution: *distribution.element(),
|
||||
monochromatic: *monochromatic.element(),
|
||||
|
||||
@@ -68,9 +68,9 @@ Marrying vector and raster under one roof enables both art forms to complement e
|
||||
|
||||
<div class="roadmap">
|
||||
<div class="feature-icons">
|
||||
<!-- Inception -->
|
||||
<!-- Formulation -->
|
||||
<div class="feature-icon complete heading" data-year="2020">
|
||||
<h3>— Inception —</h3>
|
||||
<h3>— Formulation —</h3>
|
||||
</div>
|
||||
<div class="feature-icon complete" title="Development Complete">
|
||||
<img class="atlas" style="--atlas-index: 40" src="https://static.graphite.art/icons/icon-atlas-roadmap__6.png" alt="" />
|
||||
|
||||
Reference in new issue
Block a user