blit-ui 0.1.0

an experimental immediate-mode ui library
Documentation
use crate::*;

/// context resources and temporary storage for painting
pub struct PaintCx<'a, C: Context> {
    bump: &'a BumpArena,
    context: &'a mut C,
}

impl<'a, C: Context> PaintCx<'a, C> {
    pub fn context(&self) -> &C {
        self.context
    }

    pub fn context_mut(&mut self) -> &mut C {
        self.context
    }

    pub fn scratch(&self) -> &'a ScratchBuffer {
        &self.bump.storage
    }
}

//
// internals
//

pub fn insert_measure<C: Context, R, F>(tree: &mut Tree<C>, node: NodeId, measure: F)
where
    R: Into<Fit<Size<C::Scalar>>>,
    F: Fn(&mut C, Constraints<C::Scalar>) -> R + 'static,
{
    fn run<C: Context, R, F>(
        bump: &BumpArena,
        id: BumpId,
        context: &mut C,
        bounds: Constraints<C::Scalar>,
    ) -> Fit<Size<C::Scalar>>
    where
        R: Into<Fit<Size<C::Scalar>>>,
        F: Fn(&mut C, Constraints<C::Scalar>) -> R + 'static,
    {
        (bump.load::<F>(id))(context, bounds).into()
    }

    let id = StoredMeasureId::new(tree.measures.len());
    let node = &mut tree.nodes[node.index()];
    // prepended because measurement combines sizes with max
    tree.measures.push(StoredMeasure {
        run: run::<C, R, F>,
        bump_id: tree.bump.store(measure),
        next: node.first_measure,
    });
    node.first_measure = id;
}

pub fn insert_paint<C: Context, F>(tree: &mut Tree<C>, node: NodeId, paint: F)
where
    F: Fn(&mut PaintCx<'_, C>, Rect<C::Scalar>) + 'static,
{
    fn run<C: Context, F>(bump: &BumpArena, id: BumpId, context: &mut C, area: Rect<C::Scalar>)
    where
        F: Fn(&mut PaintCx<'_, C>, Rect<C::Scalar>) + 'static,
    {
        (bump.load::<F>(id))(&mut PaintCx { bump, context }, area);
    }

    let id = StoredPaintId::new(tree.paints.len());
    let bump_id = tree.bump.store(paint);
    let node = &mut tree.nodes[node.index()];
    // circular list where last_paint.next points to the first paint
    let next = if let Some(last) = node.last_paint.index() {
        let first = tree.paints[last].next;
        tree.paints[last].next = id;
        first
    } else {
        id
    };
    tree.paints.push(StoredPaint {
        run: run::<C, F>,
        bump_id,
        next,
    });
    node.last_paint = id;
}

pub fn resolve_order<C: Context>(tree: &mut Tree<C>, bump: &BumpArena) {
    tree.paint_order.clear();
    if !tree.has_custom_order {
        return;
    }
    let count = tree.nodes.len();
    let z_indices = &tree.z_indices;
    let z_index = |index: usize| z_indices.get(index).copied().unwrap_or(0);
    if !tree
        .nodes
        .iter()
        .enumerate()
        .any(|(index, node)| z_index(index) != 0 || visual_parent(&tree.aux, node) != node.parent)
    {
        return;
    }

    let mut scratch = bump.storage.alloc(count);
    scratch.resize(count, PaintLinks::default());
    let links = &mut scratch[..count];
    // zero marks the end of a child list since the root has no parent
    for index in 1..count {
        let parent = visual_parent(&tree.aux, &tree.nodes[index]).index();
        links[index].next_sibling = links[parent].first_child;
        links[parent].first_child = index as u32;
    }

    // completed nodes fill the front while pending nodes form a stack at the back
    tree.paint_order.resize(count, NodeId::new(0));
    let order = &mut tree.paint_order[..count];
    let mut pending = count - 1;
    for output in 0..count {
        debug_assert!(pending >= output && pending < count);
        let parent = order[pending];
        pending += 1;
        order[output] = parent;
        let start = pending;
        let mut child = links[parent.index()].first_child;
        let mut needs_sort = false;
        while child != 0 {
            let index = child as usize;
            child = links[index].next_sibling;
            needs_sort = needs_sort || z_index(index) != 0;
            pending -= 1;
            debug_assert!(pending > output);
            order[pending] = NodeId::new(index);
        }
        let children = &mut order[pending..start];
        if needs_sort {
            children.sort_unstable_by_key(|id| (z_index(id.index()), id.index()));
        }
    }
    debug_assert_eq!(pending, count);
}

pub fn resolve_clips<C: Context>(tree: &mut Tree<C>) {
    tree.interaction.clips.clear();
    tree.resolved_clips.clear();
    if !tree.has_clips {
        return;
    }
    let count = tree.nodes.len();
    let nodes = &tree.nodes[..count];
    let placements = &tree.placements[..count];
    let aux = &tree.aux;
    tree.resolved_clips.reserve(count);
    for index in 0..count {
        let parent = if index == 0 {
            ResolvedClipId::NONE
        } else {
            tree.resolved_clips[visual_parent(aux, &nodes[index]).index()]
        };
        let Some(radius) = nodes[index].aux.index().and_then(|index| aux[index].clip) else {
            tree.resolved_clips.push(parent);
            continue;
        };
        let area = placements[index];
        let bounds = parent
            .index()
            .map_or(tree.screen, |clip| tree.interaction.clips[clip].bounds)
            .intersection(area)
            .unwrap_or_default();
        let id = ResolvedClipId::new(tree.interaction.clips.len());
        let depth = parent
            .index()
            .map_or(1, |parent| tree.interaction.clips[parent].depth + 1);
        tree.interaction.clips.push(ResolvedClip {
            parent,
            depth,
            area,
            radius,
            bounds,
        });
        tree.resolved_clips.push(id);
    }
}

pub fn paint<C: Context>(
    tree: &Tree<C>,
    bump: &BumpArena,
    context: &mut C,
    mut push_clip: impl FnMut(&mut C, Rect<C::Scalar>, Corners<C::Scalar>),
    mut pop_clip: impl FnMut(&mut C),
) {
    // the clips applied to the context, at most every clip deep
    let mut active = bump.storage.alloc::<ResolvedClipId>(tree.interaction.clips.len());
    let mut set = |context: &mut C, target: ResolvedClipId| {
        if active.last().map_or(u32::MAX, |clip| clip.0) == target.0 {
            return;
        }
        let mut common = target;
        while let Some(index) = common.index() {
            let depth = tree.interaction.clips[index].depth as usize;
            if depth <= active.len() && active[depth - 1].0 == common.0 {
                break;
            }
            common = tree.interaction.clips[index].parent;
        }
        while active.last().map_or(u32::MAX, |clip| clip.0) != common.0 {
            active.pop();
            pop_clip(context);
        }
        let start = active.len();
        let mut clip = target;
        while clip.0 != common.0 {
            active.push(clip);
            clip = tree.interaction.clips[clip.index().unwrap()].parent;
        }
        active[start..].reverse();
        for &clip in &active[start..] {
            let stored = tree.interaction.clips[clip.index().unwrap()];
            push_clip(context, stored.area, stored.radius);
        }
    };
    let count = if tree.paint_order.is_empty() {
        tree.nodes.len()
    } else {
        tree.paint_order.len()
    };
    for index in 0..count {
        let node = if tree.paint_order.is_empty() {
            index
        } else {
            tree.paint_order[index].index()
        };
        let Some(last) = tree.nodes[node].last_paint.index() else {
            continue;
        };
        let area = tree.placements[node];
        let resolved_clip = if tree.resolved_clips.is_empty() {
            ResolvedClipId::NONE
        } else {
            tree.resolved_clips[node]
        };
        // painters may draw past their area so renderers cull by what they draw
        let bounds = resolved_clip
            .index()
            .map_or(tree.screen, |clip| tree.interaction.clips[clip].bounds);
        if bounds.width <= C::Scalar::ZERO || bounds.height <= C::Scalar::ZERO {
            continue;
        }
        set(context, resolved_clip);
        let mut index = tree.paints[last].next.0 as usize;
        loop {
            let stored = tree.paints[index];
            (stored.run)(bump, stored.bump_id, context, area);
            if index == last {
                break;
            }
            index = stored.next.0 as usize;
        }
    }
    set(context, ResolvedClipId::NONE);
}

#[derive(Clone, Copy, Default)]
struct PaintLinks {
    first_child: u32,
    next_sibling: u32,
}