Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-image

Source of release 0.45.1

0.45.1 / src / transform_window.lucb

#==============================================================================================
#
#   transform_window - The part of a layer one output tile of a transform reads
#
#   DESCRIPTION:
#       A free transform or distort makes each output tile from the source pixels its map
#       reaches: the output tile's corners taken back through the map, a margin for the
#       resampling around them. Those pixels are gathered into a small window texture — at
#       the pyramid level where the window is at most `window_side` texels, so a heavy
#       shrink reads a properly reduced copy — and the tile is drawn from it. No texture is
#       ever the size of the layer, so a 24000-pixel layer transforms like a small one.
#
#==============================================================================================

from luce_gpu import gpu
from luce_std import math
from luce_canvas.tiles import Tiles, tile_size, min_i64, max_i64
from luce_canvas.pyramid import Pyramid, covered_at, cell_exists
from projective import Warp, multiply
from luce_raster.errors import invalid

## The longest side a window has, in texels of its level.
let window_side: f64 = 1024.0

## Pixels of margin around what a tile reads: bicubic sampling reaches two
## texels out, and a texel either way for rounding.
pub let reach: f64 = 3.0

## A box of document pixels, fractional (see transform.lucb's Landed).
pub struct Footprint:
    pub var left: f64
    pub var top: f64
    pub var right: f64
    pub var bottom: f64

## Source pixels gathered for one output tile: `texture`'s texel (0, 0) is
## texel (`left`, `top`) of pyramid `level` (document pixels at level 0).
pub struct Window:
    pub var texture: gpu.Texture
    pub var left: i64
    pub var top: i64
    pub var level: u32

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

## What output cell (`column`, `row`) reads through `warp` (a backwards map,
## output to source), a margin around it, within `limit` (where the source has
## pixels); none when it reads nothing there. Behind a distortion's horizon the
## corners do not map, and the whole `limit` is taken.
pub func footprint(warp: Warp, column: i64, row: i64, limit: Footprint) -> Footprint?:
    return footprint_at(warp, (f64)(column * (i64)tile_size), (f64)(row * (i64)tile_size), (f64)tile_size, reach, limit)

## As `footprint`, for the square of document pixels `side` wide at (`x0`, `y0`)
## (a cell of a coarser level), `margin` pixels around what it reads.
pub func footprint_at(warp: Warp, x0: f64, y0: f64, side: f64, margin: f64, limit: Footprint) -> Footprint?:
    var box = Footprint(left = 1.0e18, top = 1.0e18, right = -1.0e18, bottom = -1.0e18)
    for corner in 0..<(usize)4:
        var x = 0.0
        var y = 0.0
        if not warp.map(x0 + (0.0 if corner % 2 == 0 else side), y0 + (0.0 if corner < 2 else side), &x, &y):
            box = limit
            break
        box.left = math.min(box.left, x - margin)
        box.top = math.min(box.top, y - margin)
        box.right = math.max(box.right, x + margin)
        box.bottom = math.max(box.bottom, y + margin)
    box.left = math.max(box.left, limit.left)
    box.top = math.max(box.top, limit.top)
    box.right = math.min(box.right, limit.right)
    box.bottom = math.min(box.bottom, limit.bottom)
    if box.right <= box.left or box.bottom <= box.top:
        return none
    return box

## The pyramid level at which `box` fits a window.
pub func level_for(box: Footprint) -> u32:
    var level: u32 = 0
    let side = math.max(box.right - box.left, box.bottom - box.top)
    while level < 12 and side / (f64)(1u32 << level) > window_side:
        level += 1
    return level

## `box` of `tiles` gathered at `level` into a window texture, `empty` where
## the layer has nothing (a mask's white). Level 0 takes the layer's cells,
## past the canvas too; coarser levels the canvas's pyramid.
pub func gather(device: gpu.Device, tiles: const Tiles*, pyramid: Pyramid*, box: Footprint, level: u32, mask: bool, empty: gpu.Color) -> Window!:
    if level == 0:
        return try gather_layer(device, tiles, box, empty)
    return try gather_level(device, tiles, pyramid, box, level, mask, empty)

## As `gather`, reading full-size pixels from the canvas's grid only.
pub func gather_tiles(device: gpu.Device, tiles: const Tiles*, pyramid: Pyramid*, box: Footprint, level: u32, mask: bool, empty: gpu.Color) -> Window!:
    if level == 0:
        return try gather_cells(device, tiles, box, empty)
    return try gather_level(device, tiles, pyramid, box, level, mask, empty)

## `box` of `tiles` at pyramid `level` (above 0) into a window texture.
func gather_level(device: gpu.Device, tiles: const Tiles*, pyramid: Pyramid*, box: Footprint, level: u32, mask: bool, empty: gpu.Color) -> Window!:
    let scale = (f64)(1u32 << level)
    let left = (i64)math.floor(box.left / scale)
    let top = (i64)math.floor(box.top / scale)
    let right = (i64)math.ceil(box.right / scale)
    let bottom = (i64)math.ceil(box.bottom / scale)
    if right - left > 16384 or bottom - top > 16384:
        error(invalid, "a transform window cannot exceed 16384 texels")
    var texture = try gpu.Texture.create(device, (u32)(right - left), (u32)(bottom - top), gpu.Format.rgba16_float)
    errdefer texture.destroy()
    let frame = try texture.frame()
    defer frame.release()
    let whole = try frame.value().target()
    defer whole.release()
    let span = (i64)tile_size
    for row in max_i64(0, top // span)..<(bottom + span - 1) // span:
        for column in max_i64(0, left // span)..<(right + span - 1) // span:
            if not cell_exists(tiles, (u32)column, (u32)row, level):
                continue
            let cell = (try pyramid.texture(tiles, (u32)column, (u32)row, level, mask)) else continue
            let width = covered_at(tiles.width(), (u32)column, level)
            let height = covered_at(tiles.height(), (u32)row, level)
            try gpu.copy_image(whole.value(), cell, gpu.Rect((f64)(column * span - left), (f64)(row * span - top), (f64)width, (f64)height), gpu.Region(0, 0, width, height))
    _ = try frame.value().present(empty)
    return Window(texture = texture, left = left, top = top, level = level)

## `box` of `tiles` on the canvas gathered at full size into a window texture,
## `empty` where the layer has nothing.
pub func gather_cells(device: gpu.Device, tiles: const Tiles*, box: Footprint, empty: gpu.Color) -> Window!:
    return try gather_full(device, tiles, box, empty, false)

## `box` of `tiles` (past the canvas too) gathered at full size into a window
## texture, `empty` where the layer has nothing.
pub func gather_layer(device: gpu.Device, tiles: const Tiles*, box: Footprint, empty: gpu.Color) -> Window!:
    return try gather_full(device, tiles, box, empty, true)

## `gather_cells`, and with `outside` `gather_layer`. Every texture is asked
## for as it is copied, never kept from an earlier frame: the memory tiers may
## have moved a tile off the GPU since, releasing the texture it had then.
func gather_full(device: gpu.Device, tiles: const Tiles*, box: Footprint, empty: gpu.Color, outside: bool) -> Window!:
    let left = (i64)math.floor(box.left)
    let top = (i64)math.floor(box.top)
    let right = (i64)math.ceil(box.right)
    let bottom = (i64)math.ceil(box.bottom)
    if right - left > 16384 or bottom - top > 16384:
        error(invalid, "a transform window cannot exceed 16384 texels")
    var texture = try gpu.Texture.create(device, (u32)(right - left), (u32)(bottom - top), gpu.Format.rgba16_float)
    errdefer texture.destroy()
    let frame = try texture.frame()
    defer frame.release()
    let whole = try frame.value().target()
    defer whole.release()
    let span = (i64)tile_size
    for row in max_i64(0, top // span)..<min_i64((i64)tiles.rows(), (bottom + span - 1) // span):
        for column in max_i64(0, left // span)..<min_i64((i64)tiles.columns(), (right + span - 1) // span):
            let cell = (try tiles.texture((u32)column, (u32)row)) else continue
            let area = tiles.region((u32)column, (u32)row)
            try gpu.copy_image(whole.value(), cell, gpu.Rect((f64)(column * span - left), (f64)(row * span - top), (f64)area.width, (f64)area.height), area)
    if outside:
        if let range = tiles.outside_range():
            for row in max_i64(range.top, floor_div(top, span))..<min_i64(range.bottom, floor_div(bottom + span - 1, span)):
                for column in max_i64(range.left, floor_div(left, span))..<min_i64(range.right, floor_div(right + span - 1, span)):
                    try copy_outside(whole.value(), tiles, column, row, left, top)
    _ = try frame.value().present(empty)
    return Window(texture = texture, left = left, top = top, level = 0)

## The part of outside cell (`column`, `row`) of `tiles` past the canvas into
## `whole`, a window whose texel (0, 0) is document pixel (`left`, `top`).
func copy_outside(whole: const gpu.RenderTarget*, tiles: const Tiles*, column: i64, row: i64, left: i64, top: i64) -> !:
    let texture = (try tiles.outside_texture(column, row)) else return
    let span = (i64)tile_size
    let x = column * span - left
    let y = row * span - top
    if not tiles.on_canvas(column, row):
        try gpu.copy_image(whole, texture, gpu.Rect((f64)x, (f64)y, (f64)span, (f64)span), gpu.Region(0, 0, tile_size, tile_size))
        return
    # On the canvas's edge: only the strips the canvas does not reach.
    let area = tiles.region((u32)column, (u32)row)
    if area.width < tile_size:
        try gpu.copy_image(whole, texture, gpu.Rect((f64)(x + (i64)area.width), (f64)y, (f64)(tile_size - area.width), (f64)span),
                           gpu.Region(area.width, 0, tile_size - area.width, tile_size))
    if area.height < tile_size:
        try gpu.copy_image(whole, texture, gpu.Rect((f64)x, (f64)(y + (i64)area.height), (f64)area.width, (f64)(tile_size - area.height)),
                           gpu.Region(0, area.height, area.width, tile_size - area.height))

## `value` divided by `span`, rounded down (cells past the canvas are negative).
func floor_div(value: i64, span: i64) -> i64:
    if value >= 0:
        return value // span
    return -((-value + span - 1) // span)

## `warp` read into `window`'s texels: document pixels scaled to its level and
## moved to its corner.
pub func window_map(warp: Warp, window: const Window*) -> Warp:
    let scale = 1.0 / (f64)(1u32 << window.level)
    let shift = Warp(m = [scale, 0.0, (f64)-window.left, 0.0, scale, (f64)-window.top, 0.0, 0.0, 1.0])
    return multiply(shift, warp)