Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-image

Source of release 0.45.1

0.45.1 / src / canvas / transforming.lucb

#==============================================================================================
#
#   canvas/transforming - Free transform and distort, live
#
#   DESCRIPTION:
#       A transform session, as Photoshop's Free Transform: one or more layers (each with
#       its linked mask) shown through the box as it is dragged, then kept as one undo
#       step or dropped. With a selection the selected pixels of one layer float instead:
#       they move over what the selection leaves behind, and the selection's outline
#       follows them when kept. The map is a free transform (scale, turn, move about a
#       pivot) or a distortion (the box's corners moved freely, in perspective).
#
#       While the box moves nothing is made at full size: each new map is a new generation
#       of a stand-in the compositor draws the session's layers through, a cell at a time at
#       the level the view shows (transform_preview.lucb). The layers keep their pixels as the
#       session began; applying makes the transform once, at full size.
#
#==============================================================================================

extend Canvas:
    ## Begin a free transform of layer `id` and its linked mask (while editing
    ## a mask, the mask alone); `add_to_transform` brings more layers. With a
    ## selection the selected pixels float instead. Shown live by
    ## `preview_transform` or `preview_distort`, kept or dropped by `end_transform`.
    pub func begin_transform(id: i64) -> !:
        try begin_transform_session(&self, (u64)id, true)

    pub func add_to_transform(id: i64) -> !:
        let session = self.transform_session else error(invalid, "no transform is in progress")
        let document = self.document else trap("transform without a document")
        try add_to_session(&self, document, session, (u64)id)

    pub func transforming() -> bool:
        return self.transform_session != none

    ## Whether the transform under way moves floating selected pixels.
    pub func transform_floats() -> bool:
        let session = self.transform_session else return false
        return session.floating

    ## Show the transform's layers scaled by (`scale_x`, `scale_y`) — negative
    ## flips — and turned `angle` degrees about (`pivot_x`, `pivot_y`), then
    ## moved by (`dx`, `dy`).
    ## `name` is the step's (Edit › Transform's Skew, say), kept as History names it.
    pub func preview_transform(scale_x: f64, scale_y: f64, angle: f64, dx: f64, dy: f64, pivot_x: f64, pivot_y: f64, name: str = "Free Transform") -> !:
        try show_session(&self, try affine_warp(scale_x, scale_y, angle * math.pi / 180.0, dx, dy, pivot_x, pivot_y), transform_step_name(name))

    ## Show the transform's layers distorted: the box at (`left`, `top`),
    ## `width` by `height`, with its corners (top-left, top-right,
    ## bottom-right, bottom-left) taken to the points given, in perspective.
    pub func preview_distort(left: f64, top: f64, width: f64, height: f64, x0: f64, y0: f64, x1: f64, y1: f64,
                             x2: f64, y2: f64, x3: f64, y3: f64, name: str = "Distort") -> !:
        let corners: f64[8] = [x0, y0, x1, y1, x2, y2, x3, y3]
        let box = Landed(left = left, top = top, right = left + width, bottom = top + height)
        try show_session(&self, try quad_warp(left, top, width, height, corners[..<8]), transform_step_name(name), box)

    ## How the transform resamples from now on: 0 nearest, 1 smooth
    ## (bilinear), 2 high quality (bicubic). `preview_*` again to show it.
    pub func set_transform_sampling(sampling: i64) -> !:
        let session = self.transform_session else error(invalid, "no transform is in progress")
        if sampling < sampling_nearest or sampling > sampling_high:
            error(invalid, "sampling is 0 nearest, 1 smooth or 2 high quality")
        session.sampling = sampling

    ## Keep what the transform shows as one undo step, or put it all back.
    pub func end_transform(keep: bool) -> !:
        let session = self.transform_session else error(invalid, "no transform is in progress")
        self.transform_session = none
        if let composer = self.composer:
            composer.drop_stand_ins()
        defer drop_session(session)
        let document = self.document else trap("transform without a document")
        let transformer = self.transformer else trap("transform without a transformer")
        try restore_session(document, session)
        if not keep or not session.shown:
            return
        # From the pixels as they began, so the step undoes to them.
        try self.begin_edit(session.name)
        defer self.end_edit()
        try warp_session(&self, document, transformer, session)
        # Transformed text is pixels; vector elements follow an affine map and are
        # drawn again, crisp, or else are pixels too.
        for at in 0..<session.count:
            let id = session.entries[at].id
            rasterize_type(&self, id)
            let index = self.index(id) catch _:
                continue
            if not self.records[index].shaped:
                continue
            let forward = session.warp.forward((f64)self.extent_x * 0.5, (f64)self.extent_y * 0.5) catch _:
                recover session.warp
            if session.floating or not (try transform_all_elements(&self, index, forward)):
                rasterize_shape(&self, id)
        if session.floating:
            try self.live().warp(session.warp)

    ## Free transform (as `preview_transform`) of layer `id` at once, one undo step.
    pub func transform_layer(id: i64, scale_x: f64, scale_y: f64, angle: f64, dx: f64, dy: f64, pivot_x: f64, pivot_y: f64) -> !:
        try transform_now(&self, (u64)id, try affine_warp(scale_x, scale_y, angle * math.pi / 180.0, dx, dy, pivot_x, pivot_y), "Free Transform", true)

    ## Mirror a layer's pixels (and linked mask) left to right, or top to
    ## bottom, about the middle of what it has painted. Undoable.
    pub func flip_layer(id: i64, horizontal: bool) -> !:
        if not try self.measure_content(id):
            return
        let pivot_x = (f64)(self.content.left + self.content.right) * 0.5
        let pivot_y = (f64)(self.content.top + self.content.bottom) * 0.5
        let warp = try affine_warp(-1.0 if horizontal else 1.0, 1.0 if horizontal else -1.0, 0.0, 0.0, 0.0, pivot_x, pivot_y)
        try transform_now(&self, (u64)id, warp, "Flip Horizontal" if horizontal else "Flip Vertical", false)

    ## Mirror the whole image — every layer and mask — about the canvas's
    ## middle. Undoable in one step.
    pub func flip_canvas(horizontal: bool) -> !:
        let document = self.document else error(invalid, "draw the document once before flipping")
        let warp = try affine_warp(-1.0 if horizontal else 1.0, 1.0 if horizontal else -1.0, 0.0, 0.0, 0.0, (f64)self.extent_x * 0.5, (f64)self.extent_y * 0.5)
        var begun = false
        for index in 0..<self.count:
            let layer = document.find(self.records[index].id) else continue
            if layer.tiles() == none:
                continue
            if begun:
                try self.add_to_transform((i64)self.records[index].id)
            else:
                try begin_transform_session(&self, self.records[index].id, false)
                begun = true
        let session = self.transform_session else return
        session.warp = warp
        session.shown = true
        session.name = "Flip Canvas"
        try self.end_transform(true)
        # The step just taken holds the channels as they were.
        try warp_channels(&self, warp)

## One layer in the session: its pixels and mask as the session began.
struct Transformed:
    var id: u64
    var pixels: Tiles
    var mask: Tiles
    var masked: bool
    ## Where the pixels (and the mask) have anything, past the canvas too; none when nothing.
    var pixels_limit: Footprint?
    var mask_limit: Footprint?

struct TransformSession:
    var entries: Transformed[]
    var count: usize
    ## Only the selected pixels move, on the one layer.
    var floating: bool
    ## The map shown now, and whether one is shown at all.
    var warp: Warp
    var shown: bool
    var name: str
    ## A distortion's box, which bounds where its pixels come from.
    var box: Landed?
    ## Nearest, smooth or high quality (transform.lucb's `sampling_*`).
    var sampling: i64
    ## What the previews read and draw with, and which map they show.
    var document: Document*
    var transformer: Transformer
    var generation: u64

## The most layers one transform takes.
let transform_limit: usize = 64

## The step a transform is kept as, one of Edit › Transform's names: the history
## holds the name past the call, so it is always one of these, never the caller's text.
func transform_step_name(name: str) -> str:
    if name == "Skew":
        return "Skew"
    if name == "Perspective":
        return "Perspective"
    if name == "Distort":
        return "Distort"
    if name == "Scale":
        return "Scale"
    if name == "Rotate":
        return "Rotate"
    return "Free Transform"

## `Canvas.begin_transform`: a session on layer `id`; with `float_selection`
## and a selection (not while editing a mask), only its selected pixels move.
func begin_transform_session(canvas: Canvas*, id: u64, float_selection: bool) -> !:
    try canvas.require_open()
    try canvas.require_idle()
    let document = canvas.document else error(invalid, "draw the document once before transforming")
    let floating = float_selection and canvas.has_selection() and not canvas.mask_editing
    let transformer = canvas.transformer else error(invalid, "draw the document once before transforming")
    let entries = try new Transformed[transform_limit] --- in memory.heap
    errdefer free(entries) in memory.heap
    let session = try new TransformSession(entries = entries, count = 0, floating = floating,
                                           warp = Warp(m = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]), shown = false, name = "Free Transform", box = none,
                                           sampling = sampling_smooth, document = document, transformer = transformer, generation = 0) in memory.heap
    canvas.transform_session = session
    add_to_session(canvas, document, session, id) catch failure:
        canvas.transform_session = none
        drop_session(session)
        error(failure.code, failure.message)

## `Canvas.add_to_transform`: another layer, when nothing floats.
func add_to_session(canvas: Canvas*, document: Document*, session: TransformSession*, id: u64) -> !:
    let index = try canvas.index(id)
    for at in 0..<session.count:
        if session.entries[at].id == id:
            return
    if session.floating and session.count > 0:
        error(invalid, "a floating selection moves the pixels of one layer")
    if session.count == transform_limit:
        error(limit, "a transform takes at most 64 layers")
    let layer = document.find(id) else error(invalid, "no such layer")
    let tiles = layer.tiles() else error(invalid, "a group has no pixels to transform")
    var entry = Transformed(id = id, pixels = try tiles.clone(), mask = Tiles(), masked = false, pixels_limit = occupied_limit(tiles), mask_limit = none)
    errdefer entry.pixels.destroy()
    # A linked mask goes with the pixels; while editing a mask, the mask alone
    # moves; an unlinked mask stays unless it is the one being edited.
    if canvas.records[index].masked and not session.floating and (canvas.records[index].mask_linked or canvas.mask_editing):
        if let mask = layer.mask_tiles():
            entry.mask = try mask.clone()
            entry.masked = true
            entry.mask_limit = occupied_limit(mask)
    session.entries[session.count] = entry
    session.count += 1

## Show the session's layers through `warp`, from their pixels as it began:
## only a new generation of their stand-ins, made when a view draws them.
func show_session(canvas: Canvas*, warp: Warp, name: str, box: Landed? = none) -> !:
    let session = canvas.transform_session else error(invalid, "no transform is in progress")
    let composer = canvas.composer else trap("transform without a compositor")
    # A map that cannot be drawn fails here, as applying it would.
    if session.count > 0:
        _ = try preview_box(session, &session.entries[0], false, warp, box)
    session.warp = warp
    session.shown = true
    session.name = name
    session.box = box
    session.generation = next_generation()
    for at in 0..<session.count:
        let entry = session.entries[at]
        let on_mask = canvas.mask_editing and entry.masked
        if session.floating or not on_mask:
            try composer.stand_in(StandIn(layer = entry.id, mask = false, generation = session.generation, context = (void*)session, make = session_cell))
        if entry.masked and not session.floating:
            try composer.stand_in(StandIn(layer = entry.id, mask = true, generation = session.generation, context = (void*)session, make = session_cell))

## A stand-in's cell (`column`, `row`) of `level` for layer `layer` (its mask
## when `mask`) of the session `context`, through the session's map.
func session_cell(context: void*?, layer_levels: Pyramid*, layer: u64, mask: bool, column: u32, row: u32, level: u32) -> Made!:
    let session = (TransformSession*)(context else return made_original())
    var found: Transformed*? = none
    for at in 0..<session.count:
        if session.entries[at].id == layer:
            found = &session.entries[at]
    let entry = found else return made_original()
    let transformer = &session.transformer
    if session.floating:
        let selection = try session.document.selection_tiles() else return made_original()
        let outline = session.document.selection
        let lifted = Footprint(left = (f64)outline.left, top = (f64)outline.top, right = (f64)outline.right, bottom = (f64)outline.bottom)
        if lifted.right <= lifted.left or lifted.bottom <= lifted.top:
            return made_original()
        var original = false
        let texture = try lifted_preview_cell(transformer, &entry.pixels, selection, layer_levels, session.warp, lifted,
                                              column, row, level, session.sampling, session.document.mixes_encoded(), &original)
        if original:
            return made_original()
        return made_texture(texture else return made_nothing())
    let box = try preview_box(session, entry, mask, session.warp, session.box) else return made_nothing()
    let reach = (entry.mask_limit if mask else entry.pixels_limit) else return made_nothing()
    let tiles = &entry.mask if mask else &entry.pixels
    let texture = try warp_preview_cell(transformer, tiles, layer_levels, session.warp, box, reach, column, row, level, mask, session.sampling,
                                        session.document.mixes_encoded(mask))
    return made_texture(texture else return made_nothing())

## The box a preview's pixels come from: a distortion's, or where the layer
## (its mask) has anything; none when it has nothing. Fails as `landing`
## does when `warp` pulls it past its horizon.
func preview_box(session: TransformSession*, entry: const Transformed*, mask: bool, warp: Warp, box: Landed?) -> Landed?!:
    let painted = (entry.mask_limit if mask else entry.pixels_limit) else return none
    let found = box else Landed(left = painted.left, top = painted.top, right = painted.right, bottom = painted.bottom)
    _ = try landing(warp, found.left, found.top, found.right, found.bottom)
    return found

## Where `tiles` has anything, by whole cells, past the canvas too.
func occupied_limit(tiles: const Tiles*) -> Footprint?:
    let occupied = tiles.occupied() else return none
    return Footprint(left = (f64)(occupied.left * (i64)tile_size), top = (f64)(occupied.top * (i64)tile_size),
                     right = (f64)(occupied.right * (i64)tile_size), bottom = (f64)(occupied.bottom * (i64)tile_size))

## Every layer of the session (and its mask) through its warp; the floating
## pixels over what the selection leaves.
func warp_session(canvas: Canvas*, document: Document*, transformer: Transformer, session: TransformSession*) -> !:
    for at in 0..<session.count:
        let entry = session.entries[at]
        if session.floating:
            let selection = try document.selection_tiles() else error(invalid, "the selection is gone")
            let outline = document.selection
            try transformer.apply_selected(document, entry.id, session.warp, selection, outline.left, outline.top, outline.right, outline.bottom, session.sampling)
            continue
        let on_mask = canvas.mask_editing and entry.masked
        if not on_mask:
            try transformer.apply(document, entry.id, session.warp, source = session.box, sampling = session.sampling)
        if entry.masked:
            try transformer.apply(document, entry.id, session.warp, on_mask = true, source = session.box, sampling = session.sampling)

## Put every layer of the session back as it began.
func restore_session(document: Document*, session: TransformSession*) -> !:
    for at in 0..<session.count:
        let entry = session.entries[at]
        try document.set_tiles(entry.id, try entry.pixels.clone())
        if entry.masked:
            var shown = try document.take_mask(entry.id, try entry.mask.clone())
            shown.destroy()

func drop_session(session: TransformSession*):
    for at in 0..<session.count:
        session.entries[at].pixels.destroy()
        if session.entries[at].masked:
            session.entries[at].mask.destroy()
    free(session.entries) in memory.heap
    free(session) in memory.heap

## `Canvas.transform_layer`: layer `id` through `warp` at once, one undo step.
func transform_now(canvas: Canvas*, id: u64, warp: Warp, name: str, float_selection: bool) -> !:
    try begin_transform_session(canvas, id, float_selection)
    let session = canvas.transform_session else trap("begun")
    session.warp = warp
    session.shown = true
    session.name = name
    try canvas.end_transform(true)