Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-image

Source of release 0.45.0

0.45.0 / src / liquify.lucb

#==============================================================================================
#
#   liquify - Liquify's push: a stroke on the displacement grid, and its cells on the GPU
#
#   DESCRIPTION:
#       A push stroke walks its path as before — a dab every 2.5% of the brush, each moving
#       what is under the tip along the step by the strength — but a dab moves the grid's
#       points (liquify_grid.lucb), not pixels. The pixels are made by liquify.frag a cell at
#       a time from the layer as the stroke began: at the level a view draws while the
#       stroke goes (canvas/liquifying.lucb shows the layer through a stand-in), and once at
#       full size for the cells it moved when the stroke is kept.
#
#==============================================================================================

from luce_gpu import gpu
from luce_std import math
import memory
from luce_canvas.tiles import Tiles, tile_size, tile_texture
from luce_canvas.pyramid import Pyramid
from transform_window import Footprint, gather, gather_layer, level_for, Window
from liquify_grid import Grid, Reach, step_for
from shaders import liquify_frag_words, liquify_frag_msl
from luce_raster.errors import invalid

## Push steps finely whatever the brush: each step moves pixels by its length.
let push_spacing: f64 = 0.025

## The widest window a kept cell reads at full size, in pixels a side; one
## reaching farther (a cell torn across a huge move) reads a coarser level.
let full_window: f64 = 4096.0

## Draws pushed cells: liquify.frag's pipeline.
pub struct Liquifier:
    var owner: gpu.Device
    var shader: gpu.Shader
    var pipeline: gpu.Pipeline
    ## Whether samples mix as sRGB-encoded values: the document's blending, set
    ## for each push (it cannot change while one is under way).
    pub var srgb: bool = false

    pub static func create(device: gpu.Device) -> Liquifier!:
        var shader = try gpu.Shader.create(device, liquify_frag_words, liquify_frag_msl)
        errdefer shader.destroy()
        var pipeline = try gpu.Pipeline.create(device, shader, gpu.Blend.replace, gpu.Format.rgba16_float)
        return Liquifier(owner = device, shader = shader, pipeline = pipeline)

    pub func destroy():
        self.pipeline.destroy()
        self.shader.destroy()

    ## liquify.frag with `params` over `window` and `field`, into a tile of its own.
    func shade(params: f32[16]*, window: gpu.Texture, field: gpu.Texture) -> gpu.Texture!:
        var fresh = try tile_texture(self.owner)
        errdefer fresh.destroy()
        let frame = try fresh.frame()
        defer frame.release()
        let area = try frame.value().target()
        defer area.release()
        try gpu.shade(area.value(), self.pipeline, gpu.Rect(width = (f64)tile_size, height = (f64)tile_size), u8[]((u8*)&(*params)[0], 64), [window, field], gpu.Filter.nearest)
        _ = try frame.value().present(gpu.Color(0.0, 0.0, 0.0, 0.0))
        return fresh

    ## Cell (`column`, `row`) of pyramid `level` of the layer `grid` pushes,
    ## made from `tiles` as the stroke began (`pyramid` their levels). `original` when nothing moves over the cell; none where
    ## nothing lands. At level 0 it is the kept pixels.
    pub func cell(grid: const Grid*, tiles: const Tiles*, pyramid: Pyramid*, column: u32, row: u32, level: u32, original: bool*) -> gpu.Texture?!:
        *original = false
        let scale = (f64)(1u32 << level)
        let side = (f64)tile_size * scale
        let x0 = (f64)column * side
        let y0 = (f64)row * side
        if not grid.touches(x0 - 1.0, y0 - 1.0, x0 + side + 1.0, y0 + side + 1.0):
            *original = true
            return none
        # The field no finer than the grid or the level's texels: at level 0,
        # a point to a sample.
        let spacing = math.max(grid.step, scale)
        let n = (i64)(side / spacing) + 1
        let bytes = try new u8[(usize)(n * n) * 8] --- in memory.heap
        defer free(bytes) in memory.heap
        let reach = grid.field(x0, y0, spacing, n, bytes)
        if not reach.moved:
            *original = true
            return none
        # The window: every place a pixel of the cell reads, a texel of its
        # level around it for the bilinear tap, within the layer.
        var at = level
        if level == 0:
            while at < 12 and math.max(reach.right - reach.left, reach.bottom - reach.top) / (f64)(1u32 << at) > full_window:
                at += 1
        else:
            let coarsest = level_for(source_box(reach, tiles, scale) else return none)
            at = coarsest if coarsest > level else level
        let box = source_box(reach, tiles, (f64)(1u32 << at)) else return none
        let clear = gpu.Color(0.0, 0.0, 0.0, 0.0)
        var window: Window = ---
        if at == 0:
            window = try gather_layer(self.owner, tiles, box, clear)
        else:
            window = try gather(self.owner, tiles, pyramid, box, at, false, clear)
        defer window.destroy()
        var field = try gpu.Texture.create(self.owner, (u32)n, (u32)n, gpu.Format.rgba16_float)
        defer field.destroy()
        try field.upload(bytes)
        var params: f32[16] = [(f32)x0, (f32)y0, (f32)scale, 0.0, (f32)window.left, (f32)window.top, (f32)(try window.texture.width()), (f32)(try window.texture.height()),
                               (f32)(1u32 << at), (f32)spacing, (f32)n, 0.0, 1.0 if self.srgb else 0.0, 0.0, 0.0, 0.0]
        return try self.shade(&params, window.texture, field)

## Where a cell's pixels read (`reach`), two texels of `scale` pixels around
## for the tap, within `tiles`' layer; none when that is past it.
func source_box(reach: Reach, tiles: const Tiles*, scale: f64) -> Footprint?:
    let box = Footprint(left = math.max(0.0, math.floor(reach.left) - 2.0 * scale), top = math.max(0.0, math.floor(reach.top) - 2.0 * scale),
                        right = math.min((f64)tiles.width(), math.ceil(reach.right) + 2.0 * scale), bottom = math.min((f64)tiles.height(), math.ceil(reach.bottom) + 2.0 * scale))
    if box.right <= box.left or box.bottom <= box.top:
        return none
    return box

## A push stroke: its grid, and where along its path it is.
pub struct LiquifyStroke:
    pub var grid: Grid
    var radius: f64
    var hardness: f64
    var strength: f64
    var last_x: f64
    var last_y: f64
    var debt: f64
    ## Whether the grid moved since the last frame showed it.
    pub var changed: bool

    ## Begin a push on a `width` by `height` layer at (`x`, `y`): `diameter`,
    ## `hardness` (at most 0.98) and `strength` (0.01..1).
    pub static func begin(width: u32, height: u32, x: f64, y: f64, diameter: f64, hardness: f64, strength: f64) -> LiquifyStroke!:
        if not math.is_finite(x) or not math.is_finite(y) or not (diameter >= 1.0 and diameter <= 5000.0):
            error(invalid, "a push needs a finite point and a diameter of 1..5000")
        let grid = try Grid.create(width, height, step_for(diameter))
        return LiquifyStroke(grid = grid, radius = math.max(1.0, diameter * 0.5), hardness = math.clamp(hardness, 0.0, 0.98), strength = math.clamp(strength, 0.01, 1.0),
                             last_x = x, last_y = y, debt = 0.0, changed = false)

    ## Continue to (`x`, `y`), a dab every step along the way.
    pub func extend(x: f64, y: f64) -> !:
        if not math.is_finite(x) or not math.is_finite(y):
            error(invalid, "stroke coordinates must be finite")
        let dx = x - self.last_x
        let dy = y - self.last_y
        let length = math.sqrt(dx * dx + dy * dy)
        let step = math.max(1.0, self.radius * 2.0 * push_spacing)
        var along = step - self.debt
        var from_x = self.last_x
        var from_y = self.last_y
        while along <= length:
            let t = along / length
            let to_x = self.last_x + dx * t
            let to_y = self.last_y + dy * t
            try self.grid.push(to_x, to_y, (to_x - from_x) * self.strength, (to_y - from_y) * self.strength, self.radius, self.hardness)
            self.changed = true
            from_x = to_x
            from_y = to_y
            along += step
        self.debt = length - (along - step)
        self.last_x = x
        self.last_y = y

    pub func destroy():
        self.grid.destroy()