A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.
TypeScript animationcartoonclip-studio-paintcollaborativedesktop-appdigital-paintingdrawing-appillustrationmangamultiplayeropen-sourcerusttaurithreejswebglwebtoon
//! Layer tree construction, clipping-mask chain grouping, pass-through folder flattening,
//! and 3-slice (`below` / `active` / `above`) stack partitioning for the GPU compositor.
//!
//! Direct Rust port of `src/utils/compositor/layerTree.ts` with animation cel visibility
//! override support and index-based tree nodes.
use super::parse_layer_styles;
use crate::document::{BlendMode, LayerNode, LayerType};
use std::collections::{HashMap, HashSet};
/// Hierarchical tree node referencing a layer by its index in `Document::layers`.
#[derive(Debug, Clone)]
pub struct LayerTreeNode {
pub layer_index: usize,
pub children: Vec<LayerTreeNode>,
}
/// Base layer node together with consecutive sibling nodes clipped (`clipped == true`) to it.
#[derive(Debug, Clone)]
pub struct TreeNodeRenderGroup {
pub base_node: LayerTreeNode,
pub clipped_nodes: Vec<LayerTreeNode>,
}
/// Atomic compositing unit produced after flattening `pass-through` folders.
#[derive(Debug, Clone)]
pub struct CompositingUnit {
/// Base node and its clipped siblings at this compositing level.
pub group: TreeNodeRenderGroup,
/// Accumulated opacity from enclosing `pass-through` folders.
pub inherited_opacity: f32,
/// All layer IDs contained in this unit (base, clipped siblings, and folder descendants).
pub contained_layer_ids: HashSet<String>,
}
/// Caching strategy for the slice of layers strictly above the active unit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AboveSliceStrategy {
/// No visible units above active.
Empty,
/// All units above active are strictly source-over associative -> baked into `above_active_cache` with `Normal`.
BakedNormal,
/// Exactly one non-associative unit above active that can bake onto transparent and composite with one blend pass.
BakedSingleBlend,
/// Mixed: non-associative prefix renders dynamically (`above_dynamic_units`), associative suffix bakes into `above_active_cache`.
Mixed,
}
/// Partition of a flattened bottom-to-top compositing unit stack around `active_layer_id`.
#[derive(Debug, Clone)]
pub struct LayerStackPartition {
/// Units strictly below the active unit (always safe to bake into `below_active_cache`).
pub below_units: Vec<CompositingUnit>,
/// The active unit containing `active_layer_id`, or `None` if absent/hidden.
pub active_unit: Option<CompositingUnit>,
/// Non-associative upper units (e.g. Multiply/Adjustment) that must render dynamically over `active_unit`.
pub above_dynamic_units: Vec<CompositingUnit>,
/// Upper units that can be pre-baked into `above_active_cache`.
pub above_cached_units: Vec<CompositingUnit>,
/// Strategy controlling how `above_active_cache` composites over `(below + active + above_dynamic)`.
pub above_strategy: AboveSliceStrategy,
/// Blend mode applied when `above_strategy == AboveSliceStrategy::BakedSingleBlend`.
pub above_cache_blend_mode: BlendMode,
}
/// Resolves effective visibility of a single layer node respecting optional animation cel overrides.
#[inline]
pub fn is_node_visible(
layer: &LayerNode,
cel_overrides: &HashMap<String, bool>,
) -> bool {
if !layer.meta.visible {
return false;
}
if let Some(&override_vis) = cel_overrides.get(&layer.meta.id) {
return override_vis;
}
true
}
/// Returns true if a layer has an active non-destructive 8-bit layer mask.
#[inline]
pub fn layer_has_active_mask(layer: &LayerNode) -> bool {
(layer.grid.has_mask || layer.meta.has_mask) && layer.meta.mask_enabled.unwrap_or(true)
}
/// Returns true ONLY when a folder-like node truly composites as non-isolated `PassThrough`
/// (unmasked, unstyled, `opacity == 1.0`, and `blend_mode == PassThrough`).
/// Any folder with a mask, active styles, or `opacity < 1.0` MUST be isolated so its children
/// composite as a group and then blend onto the backdrop with `Normal`.
#[inline]
pub fn folder_is_true_pass_through(layer: &LayerNode) -> bool {
layer.meta.layer_type.is_folder_like()
&& layer.meta.blend_mode == BlendMode::PassThrough
&& layer.meta.opacity >= 0.999
&& !layer_has_active_mask(layer)
&& !parse_layer_styles(layer.meta.styles.as_ref()).has_active()
}
/// Builds a hierarchical top-to-bottom tree from InkStudio's flat top-to-bottom `layers` slice.
pub fn build_layer_tree(layers: &[LayerNode]) -> Vec<LayerTreeNode> {
let id_to_idx: HashMap<&str, usize> = layers
.iter()
.enumerate()
.map(|(i, l)| (l.meta.id.as_str(), i))
.collect();
let mut children_by_parent: HashMap<usize, Vec<usize>> = HashMap::new();
let mut root_indices: Vec<usize> = Vec::new();
for (idx, layer) in layers.iter().enumerate() {
if let Some(pid) = layer.meta.parent_id.as_deref() {
if let Some(&pidx) = id_to_idx.get(pid) {
if pidx != idx {
children_by_parent.entry(pidx).or_default().push(idx);
continue;
}
}
}
root_indices.push(idx);
}
fn build_subtree(
idx: usize,
children_by_parent: &HashMap<usize, Vec<usize>>,
visited: &mut HashSet<usize>,
) -> LayerTreeNode {
visited.insert(idx);
let mut children = Vec::new();
if let Some(c_indices) = children_by_parent.get(&idx) {
for &cidx in c_indices {
if !visited.contains(&cidx) {
children.push(build_subtree(cidx, children_by_parent, visited));
}
}
}
LayerTreeNode {
layer_index: idx,
children,
}
}
let mut visited = HashSet::with_capacity(layers.len());
let mut roots = Vec::with_capacity(root_indices.len());
for idx in root_indices {
if !visited.contains(&idx) {
roots.push(build_subtree(idx, &children_by_parent, &mut visited));
}
}
roots
}
/// Groups consecutive clipped (`clipped == true`) sibling nodes under their immediate
/// non-clipped base node underneath. Expects `nodes_bottom_to_top` in bottom-to-top render order.
pub fn group_tree_nodes_for_compositing(
nodes_bottom_to_top: Vec<LayerTreeNode>,
layers: &[LayerNode],
) -> Vec<TreeNodeRenderGroup> {
let mut groups: Vec<TreeNodeRenderGroup> = Vec::new();
for node in nodes_bottom_to_top {
let is_clipped = layers
.get(node.layer_index)
.and_then(|l| l.meta.clipped)
.unwrap_or(false);
if is_clipped {
if let Some(last) = groups.last_mut() {
last.clipped_nodes.push(node);
continue;
}
}
groups.push(TreeNodeRenderGroup {
base_node: node,
clipped_nodes: Vec::new(),
});
}
groups
}
fn collect_node_layer_ids(node: &LayerTreeNode, layers: &[LayerNode], out: &mut HashSet<String>) {
if let Some(l) = layers.get(node.layer_index) {
out.insert(l.meta.id.clone());
}
for child in &node.children {
collect_node_layer_ids(child, layers, out);
}
}
/// Flattens unmasked `pass-through` folders into a bottom-to-top sequence of atomic
/// [`CompositingUnit`]s while keeping isolated folders, comic `frame-folder`s, masked folders,
/// and clipping-mask groups atomic.
pub fn flatten_layer_tree_to_units(
nodes_top_to_bottom: &[LayerTreeNode],
layers: &[LayerNode],
cel_overrides: &HashMap<String, bool>,
inherited_opacity: f32,
) -> Vec<CompositingUnit> {
let mut units = Vec::new();
let siblings_bottom_to_top: Vec<LayerTreeNode> =
nodes_top_to_bottom.iter().rev().cloned().collect();
let groups = group_tree_nodes_for_compositing(siblings_bottom_to_top, layers);
for group in groups {
let Some(base_layer) = layers.get(group.base_node.layer_index) else {
continue;
};
if !is_node_visible(base_layer, cel_overrides) || base_layer.meta.opacity <= 0.001 {
continue;
}
if base_layer.meta.layer_type == LayerType::Folder
&& folder_is_true_pass_through(base_layer)
&& group.clipped_nodes.is_empty()
{
let nested = flatten_layer_tree_to_units(
&group.base_node.children,
layers,
cel_overrides,
inherited_opacity * base_layer.meta.opacity,
);
units.extend(nested);
continue;
}
let mut contained_layer_ids = HashSet::new();
collect_node_layer_ids(&group.base_node, layers, &mut contained_layer_ids);
for cn in &group.clipped_nodes {
collect_node_layer_ids(cn, layers, &mut contained_layer_ids);
}
units.push(CompositingUnit {
group,
inherited_opacity,
contained_layer_ids,
});
}
units
}
/// Returns true if a compositing unit is strictly Porter-Duff source-over associative with
/// respect to the backdrop below it (safe to pre-bake onto transparent target and composite
/// with `Normal` blend mode).
fn subtree_is_normal_associative(
node: &LayerTreeNode,
layers: &[LayerNode],
cel_overrides: &HashMap<String, bool>,
) -> bool {
let Some(layer) = layers.get(node.layer_index) else {
return true;
};
if !is_node_visible(layer, cel_overrides) || layer.meta.opacity <= 0.001 {
return true;
}
if layer.meta.layer_type == LayerType::Adjustment {
return false;
}
if !matches!(
layer.meta.blend_mode,
BlendMode::Normal | BlendMode::PassThrough
) {
return false;
}
// Only true non-isolated PassThrough folders allow inner blend modes / adjustments
// to interact with the backdrop below. Masked, styled, or translucent PassThrough
// folders are isolated and composite with Normal -> strictly associative!
if folder_is_true_pass_through(layer) {
for child in &node.children {
if !subtree_is_normal_associative(child, layers, cel_overrides) {
return false;
}
}
}
true
}
pub fn is_unit_normal_associative(
unit: &CompositingUnit,
layers: &[LayerNode],
cel_overrides: &HashMap<String, bool>,
) -> bool {
let Some(base_layer) = layers.get(unit.group.base_node.layer_index) else {
return true;
};
if base_layer.meta.layer_type == LayerType::Adjustment {
return false;
}
if !matches!(
base_layer.meta.blend_mode,
BlendMode::Normal | BlendMode::PassThrough
) {
return false;
}
if folder_is_true_pass_through(base_layer) {
for child in &unit.group.base_node.children {
if !subtree_is_normal_associative(child, layers, cel_overrides) {
return false;
}
}
}
// Because clipped children are composited onto an isolated clip group containing `base`
// using `source-atop` and then composited onto `dst` once with `base`'s blend mode,
// a clipping chain with Normal/PassThrough base is associative even when clipped children
// use non-Normal blend modes or Adjustment layers!
true
}
/// Returns `Some(blend_mode)` if a single non-associative unit can be baked onto transparent
/// with `Normal` and composited over `(below + active)` via one ping-pong blend pass.
pub fn can_single_unit_bake_with_blend_mode(
unit: &CompositingUnit,
layers: &[LayerNode],
cel_overrides: &HashMap<String, bool>,
) -> Option<BlendMode> {
let base_layer = layers.get(unit.group.base_node.layer_index)?;
if base_layer.meta.layer_type == LayerType::Adjustment {
return None;
}
let has_visible_clipped = unit.group.clipped_nodes.iter().any(|cn| {
layers.get(cn.layer_index).is_some_and(|cl| {
is_node_visible(cl, cel_overrides)
&& cl.meta.opacity > 0.001
&& !cl.meta.layer_type.is_folder_like()
})
});
if has_visible_clipped {
return None;
}
if base_layer.meta.layer_type.is_folder_like() {
if !matches!(
base_layer.meta.blend_mode,
BlendMode::Normal | BlendMode::PassThrough
) {
return Some(base_layer.meta.blend_mode);
}
return None;
}
if !matches!(
base_layer.meta.blend_mode,
BlendMode::Normal | BlendMode::PassThrough
) {
return Some(base_layer.meta.blend_mode);
}
None
}
/// Partitions an already-flattened bottom-to-top [`CompositingUnit`] sequence into
/// `below`, `active`, `above_dynamic`, and `above_cached` slices relative to `active_layer_id`.
pub fn partition_units_for_active_layer(
units: Vec<CompositingUnit>,
layers: &[LayerNode],
cel_overrides: &HashMap<String, bool>,
active_layer_id: Option<&str>,
) -> LayerStackPartition {
let active_idx = active_layer_id.and_then(|aid| {
units
.iter()
.position(|u| u.contained_layer_ids.contains(aid))
});
let Some(idx) = active_idx else {
return LayerStackPartition {
below_units: units,
active_unit: None,
above_dynamic_units: Vec::new(),
above_cached_units: Vec::new(),
above_strategy: AboveSliceStrategy::Empty,
above_cache_blend_mode: BlendMode::Normal,
};
};
let mut iter = units.into_iter();
let below_units: Vec<CompositingUnit> = iter.by_ref().take(idx).collect();
let active_unit = iter.next();
let above_all: Vec<CompositingUnit> = iter.collect();
if above_all.is_empty() {
return LayerStackPartition {
below_units,
active_unit,
above_dynamic_units: Vec::new(),
above_cached_units: Vec::new(),
above_strategy: AboveSliceStrategy::Empty,
above_cache_blend_mode: BlendMode::Normal,
};
}
let mut last_non_assoc: Option<usize> = None;
for (i, u) in above_all.iter().enumerate() {
if !is_unit_normal_associative(u, layers, cel_overrides) {
last_non_assoc = Some(i);
}
}
let Some(split_idx) = last_non_assoc else {
return LayerStackPartition {
below_units,
active_unit,
above_dynamic_units: Vec::new(),
above_cached_units: above_all,
above_strategy: AboveSliceStrategy::BakedNormal,
above_cache_blend_mode: BlendMode::Normal,
};
};
if above_all.len() == 1 {
if let Some(single_blend) =
can_single_unit_bake_with_blend_mode(&above_all[0], layers, cel_overrides)
{
return LayerStackPartition {
below_units,
active_unit,
above_dynamic_units: Vec::new(),
above_cached_units: above_all,
above_strategy: AboveSliceStrategy::BakedSingleBlend,
above_cache_blend_mode: single_blend,
};
}
}
let mut above_iter = above_all.into_iter();
let above_dynamic_units: Vec<CompositingUnit> = above_iter.by_ref().take(split_idx + 1).collect();
let above_cached_units: Vec<CompositingUnit> = above_iter.collect();
LayerStackPartition {
below_units,
active_unit,
above_dynamic_units,
above_cached_units,
above_strategy: AboveSliceStrategy::Mixed,
above_cache_blend_mode: BlendMode::Normal,
}
}
/// Full layer-stack partitioning helper: builds tree, flattens pass-through folders,
/// and partitions around `active_layer_id`.
pub fn partition_layer_stack(
layers: &[LayerNode],
cel_overrides: &HashMap<String, bool>,
active_layer_id: Option<&str>,
) -> LayerStackPartition {
let tree = build_layer_tree(layers);
let units = flatten_layer_tree_to_units(&tree, layers, cel_overrides, 1.0);
partition_units_for_active_layer(units, layers, cel_overrides, active_layer_id)
}