Compare commits

..
28 changed files with 89 additions and 180 deletions

No files matched your search

Generated
+9 -9
View File
@@ -648,17 +648,17 @@ dependencies = [
[[package]]
name = "cargo-gpu"
version = "0.1.0"
source = "git+https://github.com/rust-gpu/cargo-gpu?rev=3952a22d16edbd38689f3a876e417899f21e1fe7#3952a22d16edbd38689f3a876e417899f21e1fe7"
source = "git+https://github.com/rust-gpu/cargo-gpu?rev=f969528e87baa17a7d48eecf4a6fcfdcaaf30566#f969528e87baa17a7d48eecf4a6fcfdcaaf30566"
dependencies = [
"anyhow",
"cargo_metadata",
"clap",
"crossterm",
"directories",
"dunce",
"env_logger",
"log",
"relative-path",
"rustc_codegen_spirv-target-specs 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)",
"semver",
"serde",
"serde_json",
@@ -1322,12 +1322,6 @@ dependencies = [
"serde",
]
[[package]]
name = "dunce"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
[[package]]
name = "dyn-any"
version = "0.3.1"
@@ -4790,6 +4784,12 @@ version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d"
[[package]]
name = "rustc_codegen_spirv-target-specs"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c89eaf493b3dfc730cda42a77014aad65e03213992c7afe0dff60a9f7d3dd94"
[[package]]
name = "rustc_codegen_spirv-target-specs"
version = "0.9.0"
@@ -5335,7 +5335,7 @@ dependencies = [
"memchr",
"notify",
"raw-string",
"rustc_codegen_spirv-target-specs",
"rustc_codegen_spirv-target-specs 0.9.0 (git+https://github.com/rust-gpu/rust-gpu?rev=c12f216121820580731440ee79ebc7403d6ea04f)",
"rustc_codegen_spirv-types",
"semver",
"serde",
+1 -1
View File
@@ -196,7 +196,7 @@ poly-cool = "0.3"
spin = "0.10"
clap = "4.5"
spirv-std = { git = "https://github.com/rust-gpu/rust-gpu", rev = "c12f216121820580731440ee79ebc7403d6ea04f", features = ["bytemuck"] }
cargo-gpu = { git = "https://github.com/rust-gpu/cargo-gpu", rev = "3952a22d16edbd38689f3a876e417899f21e1fe7", default-features = false }
cargo-gpu = { git = "https://github.com/rust-gpu/cargo-gpu", rev = "f969528e87baa17a7d48eecf4a6fcfdcaaf30566" }
[workspace.lints.rust]
unexpected_cfgs = { level = "allow", check-cfg = ['cfg(target_arch, values("spirv"))'] }
+7 -11
View File
@@ -82,7 +82,7 @@ impl App {
}
}
fn handle_desktop_frontend_message(&mut self, message: DesktopFrontendMessage, responses: &mut Vec<DesktopWrapperMessage>) {
fn handle_desktop_frontend_message(&mut self, message: DesktopFrontendMessage) {
match message {
DesktopFrontendMessage::ToWeb(messages) => {
let Some(bytes) = serialize_frontend_messages(messages) else {
@@ -205,7 +205,7 @@ impl App {
to_front: false,
select_after_open: true,
};
responses.push(message);
self.dispatch_desktop_wrapper_message(message);
}
}
DesktopFrontendMessage::PersistenceLoadRemainingDocuments => {
@@ -216,7 +216,7 @@ impl App {
to_front: true,
select_after_open: false,
};
responses.push(message);
self.dispatch_desktop_wrapper_message(message);
}
for (id, document) in self.persistent_data.documents_after_current() {
let message = DesktopWrapperMessage::LoadDocument {
@@ -225,11 +225,11 @@ impl App {
to_front: false,
select_after_open: false,
};
responses.push(message);
self.dispatch_desktop_wrapper_message(message);
}
if let Some(id) = self.persistent_data.current_document_id() {
let message = DesktopWrapperMessage::SelectDocument { id };
responses.push(message);
self.dispatch_desktop_wrapper_message(message);
}
}
DesktopFrontendMessage::PersistenceWritePreferences { preferences } => {
@@ -238,18 +238,14 @@ impl App {
DesktopFrontendMessage::PersistenceLoadPreferences => {
let preferences = self.persistent_data.load_preferences();
let message = DesktopWrapperMessage::LoadPreferences { preferences };
responses.push(message);
self.dispatch_desktop_wrapper_message(message);
}
}
}
fn handle_desktop_frontend_messages(&mut self, messages: Vec<DesktopFrontendMessage>) {
let mut responses = Vec::new();
for message in messages {
self.handle_desktop_frontend_message(message, &mut responses);
}
for message in responses {
self.dispatch_desktop_wrapper_message(message);
self.handle_desktop_frontend_message(message);
}
}
+4 -5
View File
@@ -246,8 +246,7 @@ impl ClickTracker {
return ClickCount::Single;
};
let prev_time = record.time;
let prev_position = record.position;
let previous = record.time;
let now = Instant::now();
record.time = now;
@@ -271,10 +270,10 @@ impl ClickTracker {
_ => {}
}
let dx = position.x.abs_diff(prev_position.x);
let dy = position.y.abs_diff(prev_position.y);
let dx = position.x.abs_diff(record.position.x);
let dy = position.y.abs_diff(record.position.y);
let within_dist = dx <= MULTICLICK_ALLOWED_TRAVEL && dy <= MULTICLICK_ALLOWED_TRAVEL;
let within_time = now.saturating_duration_since(prev_time) <= MULTICLICK_TIMEOUT;
let within_time = now.saturating_duration_since(previous) <= MULTICLICK_TIMEOUT;
let count = if within_time && within_dist { ClickCount::Double } else { ClickCount::Single };
+4 -3
View File
@@ -6,13 +6,14 @@ pub(crate) struct PersistentData {
current_document: Option<DocumentId>,
#[serde(skip)]
document_order: Option<Vec<DocumentId>>,
preferences: Option<Preferences>,
}
impl PersistentData {
pub(crate) fn write_document(&mut self, id: DocumentId, document: Document) {
self.documents.write(id, document);
if let Some(order) = &self.document_order {
self.documents.force_order(order);
self.documents.force_order(order.clone());
}
self.flush();
}
@@ -170,10 +171,10 @@ impl DocumentStore {
})
}
fn force_order(&mut self, desired_order: &Vec<DocumentId>) {
fn force_order(&mut self, desired_order: Vec<DocumentId>) {
let mut ordered_prefix_len = 0;
for id in desired_order {
if let Some(offset) = self.0[ordered_prefix_len..].iter().position(|meta| meta.id == *id) {
if let Some(offset) = self.0[ordered_prefix_len..].iter().position(|meta| meta.id == id) {
let found_index = ordered_prefix_len + offset;
if found_index != ordered_prefix_len {
self.0[ordered_prefix_len..=found_index].rotate_right(1);
@@ -81,7 +81,7 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
id: document_id,
document: Document {
name: details.name,
path: details.path,
path: None,
content: document,
is_saved: details.is_saved,
},
+1 -3
View File
@@ -71,8 +71,6 @@ impl<'a> DesktopWrapperMessageDispatcher<'a> {
frontend_messages.extend(current_frontend_messages);
}
if !frontend_messages.is_empty() {
self.respond(DesktopFrontendMessage::ToWeb(frontend_messages));
}
self.respond(DesktopFrontendMessage::ToWeb(frontend_messages));
}
}
@@ -1,5 +1,3 @@
use std::path::PathBuf;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::prelude::*;
@@ -12,13 +10,10 @@ pub struct OpenDocument {
#[derive(PartialEq, Eq, Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
pub struct DocumentDetails {
pub name: String,
pub path: Option<PathBuf>,
#[serde(rename = "isSaved")]
pub is_saved: bool,
#[serde(rename = "isAutoSaved")]
pub is_auto_saved: bool,
#[serde(rename = "exportPath")]
pub export_path: Option<PathBuf>,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, specta::Type)]
@@ -123,9 +123,6 @@ pub enum DocumentMessage {
path: Option<PathBuf>,
},
MarkAsSaved,
ExportedDocument {
path: Option<PathBuf>,
},
SelectParentLayer,
SelectAllLayers,
SelectedLayersLower,
@@ -118,8 +118,6 @@ pub struct DocumentMessageHandler {
/// The path of the to the document file.
#[serde(skip)]
pub(crate) path: Option<PathBuf>,
/// The path to which the document was most recently exported to.
pub(crate) export_path: Option<PathBuf>,
/// Path to network currently viewed in the node graph overlay. This will eventually be stored in each panel, so that multiple panels can refer to different networks
#[serde(skip)]
breadcrumb_network_path: Vec<NodeId>,
@@ -1049,8 +1047,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
DocumentMessage::SavedDocument { path } => {
self.path = path;
responses.add(PortfolioMessage::AutoSaveActiveDocument);
// Update the name to match the file stem
let document_name_from_path = self.path.as_ref().and_then(|path| {
if path.extension().is_some_and(|e| e == FILE_EXTENSION) {
@@ -1070,10 +1066,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
self.set_save_state(true);
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
}
DocumentMessage::ExportedDocument { path } => {
self.export_path = path;
responses.add(PortfolioMessage::AutoSaveActiveDocument);
}
DocumentMessage::SelectParentLayer => {
let selected_nodes = self.network_interface.selected_nodes();
let selected_layers = selected_nodes.selected_layers(self.metadata());
@@ -741,7 +741,6 @@ impl NodeNetworkInterface {
(concrete!(()), TypeSource::Error("Could not type from network"))
}
NodeInput::Scope(_) => todo!(),
NodeInput::Inline(_) => todo!(),
NodeInput::Reflection(_) => todo!(),
}
}
@@ -4403,17 +4402,17 @@ impl NodeNetworkInterface {
self.try_set_upstream_to_chain(input_connector, network_path);
}
// If a connection is made to the imports
(NodeInput::Value { .. } | NodeInput::Scope { .. } | NodeInput::Inline { .. }, NodeInput::Import { .. }) => {
(NodeInput::Value { .. } | NodeInput::Scope { .. }, NodeInput::Import { .. }) => {
self.unload_outward_wires(network_path);
self.unload_wire(input_connector, network_path);
}
// If a connection to the imports is disconnected
(NodeInput::Import { .. }, NodeInput::Value { .. } | NodeInput::Scope { .. } | NodeInput::Inline { .. }) => {
(NodeInput::Import { .. }, NodeInput::Value { .. } | NodeInput::Scope { .. }) => {
self.unload_outward_wires(network_path);
self.unload_wire(input_connector, network_path);
}
// If a node is disconnected.
(NodeInput::Node { .. }, NodeInput::Value { .. } | NodeInput::Scope { .. } | NodeInput::Inline { .. }) => {
(NodeInput::Node { .. }, NodeInput::Value { .. } | NodeInput::Scope { .. }) => {
self.unload_outward_wires(network_path);
self.unload_wire(input_connector, network_path);
@@ -5990,7 +5989,7 @@ impl NodeNetworkInterface {
if !inserting_into_stack {
match post_node_input {
// Create a new stack
NodeInput::Value { .. } | NodeInput::Scope(_) | NodeInput::Inline(_) | NodeInput::Reflection(_) => {
NodeInput::Value { .. } | NodeInput::Scope(_) | NodeInput::Reflection(_) => {
self.create_wire(&OutputConnector::node(layer.to_node(), 0), &post_node, network_path);
let final_layer_position = after_move_post_layer_position + IVec2::new(-8, 3);
@@ -6016,7 +6015,7 @@ impl NodeNetworkInterface {
} else {
match post_node_input {
// Move to the bottom of the stack
NodeInput::Value { .. } | NodeInput::Scope(_) | NodeInput::Inline(_) | NodeInput::Reflection(_) => {
NodeInput::Value { .. } | NodeInput::Scope(_) | NodeInput::Reflection(_) => {
let offset = after_move_post_layer_position - previous_layer_position + IVec2::new(0, 3 + height_above_layer);
self.shift_absolute_node_position(&layer.to_node(), offset, network_path);
self.create_wire(&OutputConnector::node(layer.to_node(), 0), &post_node, network_path);
@@ -136,11 +136,9 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
// Messages
PortfolioMessage::Init => {
// Tell frontend to load persistent preferences
responses.add(FrontendMessage::TriggerLoadPreferences);
// Tell frontend to load the current document
// Load persistent data from the browser database
responses.add(FrontendMessage::TriggerLoadFirstAutoSaveDocument);
responses.add(FrontendMessage::TriggerLoadPreferences);
// Display the menu bar at the top of the window
responses.add(MenuBarMessage::SendLayout);
@@ -151,7 +149,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
node_types: document_node_definitions::collect_node_types(),
});
// Tell frontend to finish loading persistent documents
// Finish loading persistent data from the browser database
responses.add(FrontendMessage::TriggerLoadRestAutoSaveDocuments);
}
PortfolioMessage::DocumentPassMessage { document_id, message } => {
@@ -194,10 +192,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
document: document.serialize_document(),
details: DocumentDetails {
name: document.name.clone(),
path: document.path.clone(),
is_saved: document.is_saved(),
is_auto_saved: document.is_auto_saved(),
export_path: None,
},
})
}
@@ -1054,11 +1050,9 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
self.documents.get(id).map(|document| OpenDocument {
id: *id,
details: DocumentDetails {
name: document.name.clone(),
path: document.path.clone(),
is_saved: document.is_saved(),
is_auto_saved: document.is_auto_saved(),
export_path: None,
is_saved: document.is_saved(),
name: document.name.clone(),
},
})
})
+3 -3
View File
@@ -146,7 +146,7 @@ impl NodeGraphExecutor {
},
time,
#[cfg(any(feature = "resvg", feature = "vello"))]
export_format: graphene_std::application_io::ExportFormat::Canvas,
export_format: graphene_std::application_io::ExportFormat::Raster,
#[cfg(not(any(feature = "resvg", feature = "vello")))]
export_format: graphene_std::application_io::ExportFormat::Svg,
render_mode: document.render_mode,
@@ -190,10 +190,10 @@ impl NodeGraphExecutor {
let size = bounds[1] - bounds[0];
let transform = DAffine2::from_translation(bounds[0]).inverse();
let export_format = if export_config.file_type == FileType::Svg || cfg!(not(feature = "gpu")) {
let export_format = if export_config.file_type == FileType::Svg {
graphene_std::application_io::ExportFormat::Svg
} else {
graphene_std::application_io::ExportFormat::Texture
graphene_std::application_io::ExportFormat::Raster
};
let render_config = RenderConfig {
+21 -2
View File
@@ -7,7 +7,7 @@ use graph_craft::graphene_compiler::Compiler;
use graph_craft::proto::GraphErrors;
use graph_craft::wasm_application_io::EditorPreferences;
use graph_craft::{ProtoNodeIdentifier, concrete};
use graphene_std::application_io::{ApplicationIo, ImageTexture, NodeGraphUpdateMessage, NodeGraphUpdateSender, RenderConfig};
use graphene_std::application_io::{ApplicationIo, ExportFormat, ImageTexture, NodeGraphUpdateMessage, NodeGraphUpdateSender, RenderConfig};
use graphene_std::bounds::RenderBoundingBox;
use graphene_std::memo::IORecord;
use graphene_std::ops::Convert;
@@ -212,7 +212,26 @@ impl NodeRuntime {
self.sender.send_generation_response(CompilationResponse { result, node_graph_errors });
}
GraphRuntimeRequest::ExecutionRequest(ExecutionRequest { execution_id, render_config, .. }) => {
GraphRuntimeRequest::ExecutionRequest(ExecutionRequest { execution_id, mut render_config, .. }) => {
// There are cases where we want to export via the svg pipeline eventhough raster whas requested.
// On desktop when the user has disabled vello rendering in the preferences and we are not exporting.
// On web when the user has disabled vello rendering in the preferences or we are exporting.
if matches!(render_config.export_format, ExportFormat::Raster) {
let allow_raster_export = {
#[cfg(target_family = "wasm")]
{
self.editor_api.editor_preferences.use_vello() && !render_config.for_export
}
#[cfg(not(target_family = "wasm"))]
{
self.editor_api.editor_preferences.use_vello() || render_config.for_export
}
};
if !allow_raster_export || self.editor_api.application_io.as_ref().unwrap().gpu_executor().is_some() {
render_config.export_format = ExportFormat::Svg;
}
}
let result = self.execute_network(render_config).await;
let mut responses = VecDeque::new();
// TODO: Only process monitor nodes if the graph has changed, not when only the Footprint changes
+1 -2
View File
@@ -222,8 +222,7 @@ pub trait GetEditorPreferences {
pub enum ExportFormat {
#[default]
Svg,
Canvas,
Texture,
Raster,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny, serde::Serialize, serde::Deserialize)]
-2
View File
@@ -20,7 +20,6 @@ pub enum AnimationTimeMode {
FrameNumber,
}
/// Produces a chosen representation of the current real time and date (in UTC) based on the system clock.
#[node_macro::node(category("Animation"))]
fn real_time(ctx: impl Ctx + ExtractRealTime, _primary: (), mode: RealTimeMode) -> f64 {
let real_time = ctx.try_real_time().unwrap_or_default();
@@ -36,7 +35,6 @@ fn real_time(ctx: impl Ctx + ExtractRealTime, _primary: (), mode: RealTimeMode)
}
}
/// Produces the time, in seconds on the timeline, since the beginning of animation playback.
#[node_macro::node(category("Animation"))]
fn animation_time(ctx: impl Ctx + ExtractAnimationTime) -> f64 {
ctx.try_animation_time().unwrap_or_default()
-1
View File
@@ -110,7 +110,6 @@ pub fn migrate_artboard<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Re
})
}
/// Constructs a new single artboard table with the chosen properties.
#[node_macro::node(category(""))]
async fn create_artboard<T: Into<Table<Graphic>> + 'n>(
ctx: impl ExtractAll + CloneVarArgs + Ctx,
-3
View File
@@ -174,7 +174,6 @@ impl SetClip for Table<GradientStops> {
}
}
/// Applies the blend mode to the input graphics. Setting this allows for customizing how overlapping content is composited together.
#[node_macro::node(category("Style"))]
fn blend_mode<T: SetBlendMode>(
_: impl Ctx,
@@ -193,7 +192,6 @@ fn blend_mode<T: SetBlendMode>(
value
}
/// Modifies the opacity of the input graphics by multiplying the existing opacity by this percentage. This affects the transparency of the content (together with any above which is clipped to it).
#[node_macro::node(category("Style"))]
fn opacity<T: MultiplyAlpha>(
_: impl Ctx,
@@ -212,7 +210,6 @@ fn opacity<T: MultiplyAlpha>(
value
}
/// Sets each of the blending properties at once. The blend mode determines how overlapping content is composited together. The opacity affects the transparency of the content (together with any above which is clipped to it). The fill affects the transparency of the content itself, without affecting that of content clipped to it. The clip property determines whether the content inherits the alpha of the content beneath it.
#[node_macro::node(category("Style"))]
fn blending<T: SetBlendMode + MultiplyAlpha + MultiplyFill + SetClip>(
_: impl Ctx,
+2 -2
View File
@@ -11,8 +11,8 @@ use core::f64;
use glam::{DAffine2, DVec2};
use graphene_core_shaders::color::Color;
/// Node for filtering components of the context based on the specified requirements.
/// This node is inserted by the compiler to "zero out" unused context components.
/// Node for filtering context features based on requirements
/// This node is inserted by the compiler to "zero out" unused context parts
#[node_macro::node(category("Internal"))]
async fn context_modification<T>(
ctx: impl Ctx + CloneVarArgs + ExtractAll,
-1
View File
@@ -3,7 +3,6 @@ use crate::raster_types::{CPU, Raster};
use crate::table::Table;
use glam::{DAffine2, DVec2};
/// Meant for debugging purposes, not general use. Logs the input value to the console and passes it through unchanged.
#[node_macro::node(category("Debug"), name("Log to Console"))]
fn log_to_console<T: std::fmt::Debug>(_: impl Ctx, #[implementations(bool, f64, u32, u64, DVec2, DAffine2, String)] value: T) -> T {
// KEEP THIS `debug!()` - It acts as the output for the debug node itself
-2
View File
@@ -354,7 +354,6 @@ async fn to_graphic<T: Into<Table<Graphic>> + 'n>(
content.into()
}
/// Removes a level of nesting from a graphic table, or all nesting if "Fully Flatten" is enabled.
#[node_macro::node(category("General"))]
async fn flatten_graphic(_: impl Ctx, content: Table<Graphic>, fully_flatten: bool) -> Table<Graphic> {
// TODO: Avoid mutable reference, instead return a new Table<Graphic>?
@@ -394,7 +393,6 @@ async fn flatten_graphic(_: impl Ctx, content: Table<Graphic>, fully_flatten: bo
output
}
/// Converts a graphic table into a vector table by deeply flattening any vector content it contains, and discarding any non-vector content.
#[node_macro::node(category("Vector"))]
async fn flatten_vector(_: impl Ctx, content: Table<Graphic>) -> Table<Vector> {
// TODO: Avoid mutable reference, instead return a new Table<Graphic>?
-9
View File
@@ -9,13 +9,11 @@ use crate::vector::Vector;
use crate::{Context, Ctx};
use glam::{DAffine2, DVec2};
/// Type-asserts a value to be a string, so the automatic type conversion system can convert another type to a string.
#[node_macro::node(category("Debug"))]
fn to_string(_: impl Ctx, value: String) -> String {
value
}
/// Converts a value to a JSON string representation.
#[node_macro::node(category("Text"))]
fn serialize<T: serde::Serialize>(
_: impl Ctx,
@@ -24,21 +22,16 @@ fn serialize<T: serde::Serialize>(
serde_json::to_string(&value).unwrap_or_else(|_| "Serialization Error".to_string())
}
/// Joins two strings together.
#[node_macro::node(category("Text"))]
fn string_concatenate(_: impl Ctx, #[implementations(String)] first: String, second: TextArea) -> String {
first.clone() + &second
}
/// Replaces all occurrences of "From" with "To" in the input string.
#[node_macro::node(category("Text"))]
fn string_replace(_: impl Ctx, string: String, from: TextArea, to: TextArea) -> String {
string.replace(&from, &to)
}
/// Extracts a substring from the input string, starting at "Start" and ending before "End".
/// Negative indices count from the end of the string.
/// If "Start" equals or exceeds "End", the result is an empty string.
#[node_macro::node(category("Text"))]
fn string_slice(_: impl Ctx, string: String, start: f64, end: f64) -> String {
let total_chars = string.chars().count();
@@ -63,13 +56,11 @@ fn string_slice(_: impl Ctx, string: String, start: f64, end: f64) -> String {
// TODO: Return u32, u64, or usize instead of f64 after #1621 is resolved and has allowed us to implement automatic type conversion in the node graph for nodes with generic type inputs.
// TODO: (Currently automatic type conversion only works for concrete types, via the Graphene preprocessor and not the full Graphene type system.)
/// Counts the number of characters in a string.
#[node_macro::node(category("Text"))]
fn string_length(_: impl Ctx, string: String) -> f64 {
string.chars().count() as f64
}
/// Evaluates either the "If True" or "If False" input branch based on whether the input condition is true or false.
#[node_macro::node(category("Math: Logic"))]
async fn switch<T, C: Send + 'n + Clone>(
#[implementations(Context)] ctx: C,
+1 -9
View File
@@ -8,7 +8,6 @@ use core::f64;
use glam::{DAffine2, DVec2};
use graphene_core_shaders::color::Color;
/// Applies the specified transform to the input value, which may be a graphic type or another transform.
#[node_macro::node(category(""))]
async fn transform<T: ApplyTransform + 'n + 'static>(
ctx: impl Ctx + CloneVarArgs + ExtractAll + ModifyFootprint,
@@ -47,7 +46,6 @@ async fn transform<T: ApplyTransform + 'n + 'static>(
transform_target
}
/// Overwrites the transform of each element in the input table with the specified transform.
#[node_macro::node(category(""))]
fn replace_transform<Data, TransformInput: Transform>(
_: impl Ctx + InjectFootprint,
@@ -60,8 +58,6 @@ fn replace_transform<Data, TransformInput: Transform>(
data
}
// TODO: Figure out how this node should behave once #2982 is implemented.
/// Obtains the transform of the first element in the input table, if present.
#[node_macro::node(category("Math: Transform"), path(graphene_core::vector))]
async fn extract_transform<T>(
_: impl Ctx,
@@ -78,25 +74,21 @@ async fn extract_transform<T>(
vector.iter().next().map(|row| *row.transform).unwrap_or_default()
}
/// Produces the inverse of the input transform, which is the transform that undoes the effect of the original transform.
#[node_macro::node(category("Math: Transform"))]
fn invert_transform(_: impl Ctx, transform: DAffine2) -> DAffine2 {
transform.inverse()
}
/// Extracts the translation component from the input transform.
#[node_macro::node(category("Math: Transform"))]
fn decompose_translation(_: impl Ctx, transform: DAffine2) -> DVec2 {
transform.translation
}
/// Extracts the rotation component (in degrees) from the input transform. This, together with the "Decompose Scale" node, also may jointly represent any shear component in the original transform.
#[node_macro::node(category("Math: Transform"))]
fn decompose_rotation(_: impl Ctx, transform: DAffine2) -> f64 {
transform.decompose_rotation().to_degrees()
transform.decompose_rotation()
}
/// Extracts the scale component from the input transform. This, together with the "Decompose Rotation" node, also may jointly represent any shear component in the original transform.
#[node_macro::node(category("Math: Transform"))]
fn decompose_scale(_: impl Ctx, transform: DAffine2) -> DVec2 {
transform.decompose_scale()
-23
View File
@@ -143,10 +143,6 @@ impl DocumentNode {
let mut construction_args = ConstructionArgs::Nodes(vec![]);
// If we have one input of the type inline, set it as the construction args
if let &[NodeInput::Inline(ref inline)] = self.inputs.as_slice() {
construction_args = ConstructionArgs::Inline(inline.clone());
}
// If we have one input of the type inline, set it as the construction args
if let &[NodeInput::Value { ref tagged_value, .. }] = self.inputs.as_slice() {
construction_args = ConstructionArgs::Value(tagged_value.clone());
@@ -188,22 +184,6 @@ pub enum NodeInput {
/// Input that is extracted from the parent scopes the node resides in. The string argument is the key.
Reflection(DocumentNodeMetadata),
/// A Rust source code string. Allows us to insert literal Rust code. Only used for GPU compilation.
/// We can use this whenever we spin up Rustc. Sort of like inline assembly, but because our language is Rust, it acts as inline Rust.
Inline(InlineRust),
}
#[derive(Debug, Clone, PartialEq, Hash, DynAny, serde::Serialize, serde::Deserialize)]
pub struct InlineRust {
pub expr: String,
pub ty: Type,
}
impl InlineRust {
pub fn new(expr: String, ty: Type) -> Self {
Self { expr, ty }
}
}
#[derive(Debug, Clone, PartialEq, Hash, DynAny, serde::Serialize, serde::Deserialize)]
@@ -240,7 +220,6 @@ impl NodeInput {
NodeInput::Node { .. } => true,
NodeInput::Value { exposed, .. } => *exposed,
NodeInput::Import { .. } => true,
NodeInput::Inline(_) => false,
NodeInput::Scope(_) => false,
NodeInput::Reflection(_) => false,
}
@@ -251,7 +230,6 @@ impl NodeInput {
NodeInput::Node { .. } => unreachable!("ty() called on NodeInput::Node"),
NodeInput::Value { tagged_value, .. } => tagged_value.ty(),
NodeInput::Import { import_type, .. } => import_type.clone(),
NodeInput::Inline(_) => panic!("ty() called on NodeInput::Inline"),
NodeInput::Scope(_) => panic!("ty() called on NodeInput::Scope"),
NodeInput::Reflection(_) => concrete!(Metadata),
}
@@ -846,7 +824,6 @@ impl NodeNetwork {
*import_index = parent_input_index;
}
NodeInput::Value { .. } => unreachable!("Value inputs should have been replaced with value nodes"),
NodeInput::Inline(_) => (),
NodeInput::Scope(ref key) => {
let (import_id, _ty) = self.scope_injections.get(key.as_ref()).expect("Tried to import a non existent key from scope");
// TODO use correct output index
+1 -11
View File
@@ -1,5 +1,5 @@
use crate::document::value;
use crate::document::value::TaggedValue;
use crate::document::{InlineRust, value};
use crate::document::{NodeId, OriginalLocation};
pub use graphene_core::registry::*;
use graphene_core::*;
@@ -51,10 +51,6 @@ impl core::fmt::Display for ProtoNetwork {
write_node(f, network, *id, indent + 1)?;
}
}
ConstructionArgs::Inline(inline) => {
f.write_str(&"\t".repeat(indent + 1))?;
f.write_fmt(format_args!("Inline construction argument: {inline:?}"))?
}
}
f.write_str(&"\t".repeat(indent))?;
f.write_str("}\n")?;
@@ -75,8 +71,6 @@ pub enum ConstructionArgs {
/// The bool indicates whether to treat the node as lambda node.
// TODO: use a struct for clearer naming.
Nodes(Vec<NodeId>),
/// Used for GPU computation to work around the limitations of rust-gpu.
Inline(InlineRust),
}
impl Eq for ConstructionArgs {}
@@ -109,7 +103,6 @@ impl Hash for ConstructionArgs {
}
}
Self::Value(value) => value.hash(state),
Self::Inline(inline) => inline.hash(state),
}
}
}
@@ -119,7 +112,6 @@ impl ConstructionArgs {
match self {
ConstructionArgs::Nodes(nodes) => nodes.iter().map(|n| format!("n{:0x}", n.0)).collect(),
ConstructionArgs::Value(value) => vec![value.to_primitive_string()],
ConstructionArgs::Inline(inline) => vec![inline.expr.clone()],
}
}
}
@@ -376,7 +368,6 @@ impl ProtoNetwork {
// We pretend like we have already placed context modification nodes after ourselves because value nodes don't need to be cached
ConstructionArgs::Value(_) => return (context_features.extract, Some(id)),
ConstructionArgs::Nodes(items) => items.clone(),
ConstructionArgs::Inline(_) => return (context_features.extract, Some(id)),
};
// Compute the dependencies for each branch and combine all of them
@@ -686,7 +677,6 @@ impl TypingContext {
.map(|node| node.ty())
})
.collect::<Result<Vec<Type>, GraphErrors>>()?,
ConstructionArgs::Inline(ref inline) => vec![inline.ty.clone()],
};
// Get the node input type from the proto node declaration
+22 -39
View File
@@ -42,7 +42,6 @@ async fn render_intermediate<'a: 'n, T: 'static + Render + WasmNotSend + Send +
Context -> Table<GradientStops>,
)]
data: impl Node<Context<'static>, Output = T>,
editor_api: impl Node<Context<'static>, Output = &'a WasmEditorApi>,
) -> RenderIntermediate {
let render_params = ctx
.vararg(0)
@@ -58,39 +57,29 @@ async fn render_intermediate<'a: 'n, T: 'static + Render + WasmNotSend + Send +
data.collect_metadata(&mut metadata, footprint, None);
let contains_artboard = data.contains_artboard();
let use_vello = {
#[cfg(target_family = "wasm")]
{
let editor_api = editor_api.eval(None).await;
!render_params.for_export && editor_api.editor_preferences.use_vello() && matches!(render_params.render_output_type, graphene_svg_renderer::RenderOutputType::Vello)
match &render_params.render_output_type {
RenderOutputTypeRequest::Vello => {
let mut scene = vello::Scene::new();
let mut context = wgpu_executor::RenderContext::default();
data.render_to_vello(&mut scene, Default::default(), &mut context, render_params);
RenderIntermediate {
ty: RenderIntermediateType::Vello(Arc::new((scene, context))),
metadata,
contains_artboard,
}
}
#[cfg(not(target_family = "wasm"))]
{
let _ = editor_api;
matches!(render_params.render_output_type, graphene_svg_renderer::RenderOutputType::Vello)
}
};
RenderOutputTypeRequest::Svg => {
let mut render = SvgRender::new();
if use_vello {
let mut scene = vello::Scene::new();
data.render_svg(&mut render, render_params);
let mut context = wgpu_executor::RenderContext::default();
data.render_to_vello(&mut scene, Default::default(), &mut context, render_params);
RenderIntermediate {
ty: RenderIntermediateType::Vello(Arc::new((scene, context))),
metadata,
contains_artboard,
}
} else {
let mut render = SvgRender::new();
data.render_svg(&mut render, render_params);
RenderIntermediate {
ty: RenderIntermediateType::Svg(Arc::new((render.svg.to_svg_string(), render.image_data, render.svg_defs.clone()))),
metadata,
contains_artboard,
RenderIntermediate {
ty: RenderIntermediateType::Svg(Arc::new((render.svg.to_svg_string(), render.image_data, render.svg_defs.clone()))),
metadata,
contains_artboard,
}
}
}
}
@@ -105,8 +94,7 @@ async fn create_context<'a: 'n>(
let render_output_type = match render_config.export_format {
ExportFormat::Svg => RenderOutputTypeRequest::Svg,
ExportFormat::Texture => RenderOutputTypeRequest::Vello,
ExportFormat::Canvas => RenderOutputTypeRequest::Vello,
ExportFormat::Raster => RenderOutputTypeRequest::Vello,
};
let render_params = RenderParams {
@@ -154,12 +142,7 @@ async fn render<'a: 'n>(
None
};
let mut output_format = render_params.render_output_type;
// TODO: Actually request the right thing upfront
if let RenderIntermediateType::Svg(_) = ty {
output_format = RenderOutputTypeRequest::Svg;
}
let data = match (output_format, &ty) {
let data = match (render_params.render_output_type, &ty) {
(RenderOutputTypeRequest::Svg, RenderIntermediateType::Svg(svg_data)) => {
let mut svg_renderer = SvgRender::new();
if !contains_artboard && !render_params.hide_artboards {
@@ -391,7 +391,6 @@ impl BorrowTree {
};
self.store_node(node, id, path.into());
}
ConstructionArgs::Inline(_) => unimplemented!("Inline nodes are not supported yet"),
ConstructionArgs::Nodes(ids) => {
let ids = ids.to_vec();
let construction_nodes = self.node_deps(&ids);
+1 -4
View File
@@ -43,10 +43,7 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<WasmEdito
},
DocumentNode {
call_argument: concrete!(Context),
inputs: vec![
NodeInput::import(graphene_core::Type::Fn(Box::new(concrete!(Context)), Box::new(generic!(T))), 0),
NodeInput::scope("editor-api"),
],
inputs: vec![NodeInput::import(graphene_core::Type::Fn(Box::new(concrete!(Context)), Box::new(generic!(T))), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render_intermediate::IDENTIFIER),
context_features: graphene_std::ContextDependencies {
extract: ContextFeatures::VARARGS,