dymokomi/luce-image
Source of release 0.45.1
0.45.1 / src / canvas / module.lucb
#==============================================================================================
#
# canvas - The editor's document
#
# DESCRIPTION:
# The Canvas is the one Luce-facing object an editor drives: the layer stack, the
# brush, selections, adjustments, previews, history, files and drawing. Its methods
# live in the fragment of their concern, under `extend Canvas:`, and delegate to the
# engine (Document, Composer, luce-painting's Painter, Adjuster, Filters,
# Transformer, luce-vector). This fragment holds its fields, the per-layer Record
# and its lifecycle. Getters that read a layer take its stack index; setters take
# its id. Fragments, in ORDER, by concern:
#
# layers, layer_masks, layer_clip the stack, masks, clipping, styles, layers copied
# painting, adjusting, sizing strokes and fills, adjustments, canvas and image size
# drawing, bands, histograms the view, 8-bit bands for export and copy, Levels
# files, opening*, package_*, raw_tiles pictures, Photoshop files and .l2d documents
# clipboard, mask_fill copy and paste; masks made a cell at a time
# retouch*, liquifying, mesh_warping retouching tools, Liquify, Warp and Puppet Warp
# transforming, *_previews transforms and live previews
# type_layers, shape_layers, vector_*, text, shapes and vector layers (drawn by
# graph_layers luce-vector)
# ranging, selecting, selection_preview, selections: Color Range, shapes, the wand,
# refining, magnetic, masking, quick_mask Transform Selection, Magnetic Lasso, Select
# and Mask, Quick Mask
# channels, package_channels alpha channels
# history, memory, support, warp_trace undo, the memory governor, binding, tracing
# *_tests, test_support the canvas tests, by concern
#
#==============================================================================================
## The editor's document as one Luce-owned object: layers with names,
## visibility and opacity, pixels loaded from files, a flattened save, and
## drawing at any zoom and offset onto a render target. GPU storage is bound to
## the device of the first target it is drawn on; until then layers and their
## pictures wait on the CPU, so a document can be built before it is shown.
import c as c_api
from luce_std import files
from luce_jpeg import jpeg
from luce_png import png
from luce_compress import flate
from luce_raw import raw
from luce_gpu import gpu
import interop
from luce_std import math
import memory
from luce_canvas import pool
import ownership
from luce_std import paths
from luce_prism import prism
import strings
from luce_svg import svg
import os
import time
from luce_color import transfer
import thread
import sync
from image import Image, Pixel
from streaming import encoded_tables
from luce_svg.render import is_svg
from luce_vector.vector import SvgVectors, svg_vectors, VectorElement, kind_name, made_element, copied_element, release_element, copied_list, free_list, list_with, list_without, spec_drawing, spec_hit, draw_elements, cell_edge, cell_inside, CellPlan, shape_reach, CellMask, write_elements, read_elements, ShapeSpec, shape_values, shape_from_values, shape_svg, anchor_values, copy_spec_path, release_spec_path, owned_path, drawable
from luce_vector.graph import Graph, GraphCache, ShapeList, copied_graph, free_graph, graph_with_node, graph_without_nodes, graph_with_link, graph_without_link, graph_with_value, graph_with_position, default_graph, replace_graph, evaluate_graph, drawn_elements, free_view, mark_changed_shapes, compose, spec_mapped, same_spec, write_graph, read_graph, node_info, node_kinds, node_slots, node_output, node_rectangle, node_ellipse, node_polygon, node_star, node_path, node_grid, node_circle, node_line, node_scatter, node_outline, node_clone, node_transform, node_merge, node_number, node_random, node_gradient, slot_x, slot_y, slot_width, slot_height, slot_fill, slot_special
from luce_canvas.tiles import pack_band, pack_band_coded, packed_band_bytes, Cell, CellRange, read_cells, transient_mark, release_transients, Tiles, Bounds, tile_size, tile_columns, min_u32, max_u32, min_i64, flatten, tiles_alive, tile_texture, residency_configure, residency_budgets, residency_advance, residency_frame, residency_over_budget, residency_begin_marking, residency_mark_live, residency_settle, residency_report, set_scratch_directory, residency_codec, clear_residency_codec, Gathering, prefetch_collect, prefetch_pending, prefetch_had_failure, prefetch_wait, release_scratch, TileSource, open_tile_source, release_tile_source, back_cell, detach_tile_source, tile_source_is
from luce_canvas.pyramid import covered_at
from luce_painting.heal import heal
from color_range import RangeSample, range_sample, range_coverage, range_labs
from luce_painting.warp import WarpStroke, default_smudge_spacing, upload_budget_ns
from liquify import Liquifier, LiquifyStroke
from mesh_map import MeshMap
from mesh_render import Mesher
from warp_patch import identity_patch, bend_patch, patch_mesh, patch_points
from puppet import Puppet
from document import Style, Document, Layer, TreeState, release_snapshot, box_document, unbox_document, blend_mode_count, style_field_count, style_field_names
from composite import Composer, box_composer, unbox_composer
from luce_painting.paint import Brush, Painter, gradient_tile
from luce_painting.stroke import Stroke, PaintTarget, EffectSource, begin_boxed, finish_boxed
from fill import fill_selection, fill_gradient
from luce_painting.brush_images import BrushImages
from luce_painting.dynamics import Dynamic, Control, Pen, dynamic_count
from adjust import Adjuster, adjustment_count, parameter_count, curves, levels, replace_color
from curves import Curves, lut_size
from filter import Filters
import filter as filtering
import light_filters
from transform import translate, Transformer, Landed, landing, sampling_nearest, sampling_smooth, sampling_high
from projective import Warp, affine_warp, quad_warp, multiply
import live_wire
from selection_refine import Refinement, CellBox, RefineWork, pending_cells, needed_cells
from background import Background, start_background, background_done, join_background
from luce_canvas.wake import wake_frames
from extent import full_bounds, pieces, relocate, Pieces, land_rows, landing_cells, flatten_all
from transform_window import Footprint
from transform_preview import warp_preview_cell, lifted_preview_cell
from filter_preview import resample_level_cell, blur_level_cell
from stand_in import StandIn, Made, made_texture, made_nothing, made_original, next_generation
from luce_canvas.pyramid import Pyramid
from selection_passes import SelectionPasses
from luce_psd import psd
from luce_fonts import fonts
from geometry import resize_canvas, resize_image
from selection import Selection
from selection_cells import Mode, Cells, block_bytes
import selection_sources
from batched_reads import Piece, read_pieces, no_piece
from shaders import ants_frag_words, ants_frag_msl, quickmask_frag_words, quickmask_frag_msl, encode_frag_words, encode_frag_msl, channels_frag_words, channels_frag_msl
from luce_canvas.half import from_half, to_half
from luce_raster.binary import Buffer
from luce_raster.errors import invalid, limit
struct Record:
var id: u64
var name: str
## A group holds layers and has no pixels; `parent` is the group holding
## this one, 0 at the top level.
var group: bool = false
var parent: u64 = 0
## A disabled mask is kept but hides nothing.
var mask_enabled: bool = true
## A linked mask moves and transforms with the pixels; an unlinked one stays.
var mask_linked: bool = true
## An adjustment layer's kind and parameters (no pixels), or -1.
var adjustment: i64 = -1
var adjustment_values: f64[23]
## A Curves adjustment layer's curves.
var curves: Curves
var visible: bool
var opacity: f64
var blend: i64
var masked: bool
var clipped: bool
var style: Style = Style()
## A text layer's words and how they are set (type_layers.lucb).
var typed: bool = false
var typeset: TypeSpec = TypeSpec()
## A vector layer's elements, bottom first, and the one edits act on
## alone, -1 for none (vector_elements.lucb).
var shaped: bool = false
var elements: VectorElement[]
var active: i64 = -1
## A vector layer's node graph, drawn over its elements; the values its
## nodes last made, the shapes it last put out (stale when not
## `generated_fresh`), and how many nodes that evaluation computed
## (graph_layers.lucb).
var graph: Graph
var graph_cache: GraphCache
var generated: ShapeList
var generated_fresh: bool = false
var graph_evaluated: usize = 0
## A picture waiting to become tiles once a device is bound, and a mask
## likewise, each with the document pixel its top-left goes at (a picture
## may reach past the canvas).
var picture: interop.Reference[Image]?
var mask_picture: interop.Reference[Image]?
var picture_x: i64 = 0
var picture_y: i64 = 0
var mask_x: i64 = 0
var mask_y: i64 = 0
## The layer's place in the .l2d file its tiles wait in (package_open.lucb); -1 for none.
var stored: i64 = -1
pub struct Canvas:
## An opened .l2d file's tables, until the bind loads its tiles.
var package: PackageSource*? = none
## The .l2d file its tiles are backed by (opened from, or last saved to):
## the governor lets them leave the GPU and RAM without writing them, and
## reads them back from it. The canvas holds one reference.
var backing: TileSource*? = none
## The layer the application had selected when the document was saved or
## opened (a stack index), for it to select again; -1 when not known.
var selected_layer_index: i64 = -1
var extent_x: u32
var extent_y: u32
var records: Record[]
var count: usize
var next_id: u64
var device: gpu.Device?
var document: Document*?
var composer: Composer*?
var painter: Painter?
var adjuster: Adjuster?
var filters: Filters?
var transformer: Transformer?
var passes: SelectionPasses?
var brush: Brush
## A fill's tile seam (`fill_selection`'s `fault`): the tests fail a fill part way through.
var fill_fault: (func(usize) -> unit!)? = none
## The brush's sampled tip and texture image (set_brush_tip, set_brush_texture_image).
var brush_images: BrushImages
var stroke: Stroke*?
## The layer the stroke paints: the stroke knows tiles, found again for each call.
var stroke_layer: u64
var preview: Snapshot?
var curves: Curves
var table: gpu.Texture?
## The last color the eyedropper read, straight alpha, linear light.
var picked: f64[4]
var mask_editing: bool
## The selection lives on the CPU here and is copied into the GPU document at bind.
var selection: Selection
var polygon: f64[]
var polygon_count: usize
## The last element outline asked for (`element_outline`): x, y and whether
## the point starts a run, three values a point.
var outline: f64[]
var outline_count: usize
## Color Range's sampled colors (`add_range_sample`).
var range_samples: RangeSample[32]
var range_count: usize
## The Color Range dialog's session while it is up (ranging.lucb).
var range_session: RangeSession*?
var ants_shader: gpu.Shader?
var ants: gpu.Pipeline?
## Quick Mask's overlay, made when first drawn.
var quick_shader: gpu.Shader?
var quick_overlay: gpu.Pipeline?
## channels.frag, for the Channels panel's view (channels.lucb).
var channels_shader: gpu.Shader?
var channels_view: gpu.Pipeline?
## What the view's own pipelines (Quick Mask's tint, the channel view)
## draw into: none for a window's surface; tests draw into textures.
var view_format: gpu.Format?
## Liquify's push pipeline, made for the first push.
var liquifier: Liquifier?
## Warp and Puppet Warp's pipeline, made for the first warp.
var mesher: Mesher?
var history: Snapshot[]
var history_count: usize
var future: Snapshot[]
var future_count: usize
## Bytes of GPU tiles the history may hold beyond the document's own.
var history_budget: u64
var closed: bool
## Pixels per inch, for print sizes and rulers in physical units.
var dpi: f64
## The color profile the pixels are in, by luce-color's space name.
var profile_name: u8[64]
var profile_length: usize
## What `measure_content` found last: a layer's painted box.
var content: Bounds
## The next edit joins the one before it in the history (`join_next_edit`).
var joining: bool
## The next typing step starts afresh rather than continuing the last one
## (`separate_next_step`).
var separating: bool
## The parameters the next adjustment takes (`set_adjustment`).
var adjustment: f64[23]
## The retouching tool strokes use (`set_retouch`), the clone stamp's
## source and offset (whole pixels) and options, a smudge under
## way and its layer, and a spot healing stroke's opacity.
var retouch: i64
var clone_x: f64
var clone_y: f64
var clone_set: bool
var clone_offset_x: i64
var clone_offset_y: i64
var clone_offset_set: bool
var clone_aligned: bool
var clone_all: bool
## Dodge and Burn's range and exposure (`set_tone`).
var tone_range: i64
var tone_exposure: f64
## The last Clone Stamp preview's bytes (`clone_preview`), kept for reuse.
var preview_bytes: u8[]
var warp: WarpStroke*?
var warped: u64
## The smudge stroke has ended and its worker walks the rest of
## its path; the next frame after it is done keeps it (`settle_warp`).
var warp_finishing: bool
## Whether smudge walks on a worker (the default), and smudge's
## dab spacing as a fraction of the diameter.
var warp_async: bool
var smudge_spacing: f64
## A Liquify push under way (canvas/liquifying.lucb).
var liquify: Liquifying*?
## A Warp or Puppet Warp under way (canvas/mesh_warping.lucb).
var mesh_warp: MeshWarping*?
## Cells the last kept warp made at full size (tests hold it to its box).
var mesh_cells_made: usize
var heal_opacity: f64
## Inside `begin_edit`: changes record nothing more, the edit's first snapshot covers them.
var edit_depth: i64
## What a kept preview is called in the history.
var preview_name: str
## The last step's serial handed out, and the step the document was saved at (0: none).
var serial: u64
var saved_version: u64
## Whether the edit under way (`begin_edit`) recorded the whole document.
var edit_captured: bool
## How the next marquee, lasso or wand shape is made: feathered by this
## many pixels, and with hard edges when not anti-aliased.
var shape_feather: i64
var shape_hard: bool
## The guides, dragged out of the rulers.
var guides: Guides
## The alpha channels (channels.lucb), and which of red, green and blue
## the view shows: the Channels panel's eyes, never saved.
var channels: Channels
var view_channels: bool[3]
## The installed font families, listed when first asked for.
var families: fonts.Names*?
## The free transform under way, if any.
var transform_session: TransformSession*?
## Select › Transform Selection under way (refining.lucb).
var selection_warping: SelectionWarping*?
## The Magnetic Lasso under way (magnetic.lucb).
var magnetic: Magnetic*?
## Select and Mask while open (masking.lucb).
var select_mask: SelectMask*?
## A filter dialog's preview, shown through the compositor until kept or dropped.
var filter_stand_in: FilterPreview*?
## A gradient being dragged, shown through the compositor until kept or dropped.
var gradient_stand_in: GradientPreview*?
## The last frame drew some cell from a coarser level while its tiles
## come back in the background (canvas/drawing).
var coarse_shown: bool
## What `measure_histogram` counted: luminosity, red, green and blue, 256
## bins each of the encoded values.
var histogram_counts: u64[1024]
## A picture opened as the document loads in the background once bound
## (canvas/opening), and while it does, `opening` is its load.
var open_in_background: bool = false
var opening: Opening*? = none
## Why the load failed, kept for the error that reports it.
var open_failure: u8[256]
## "Blend RGB Colors Using Gamma 1.0" until the document is bound, which
## then keeps it (`Document.linear_blend`).
var cold_linear_blend: bool = false
## The view's checkerboard under transparent pixels (`set_checker`): its
## squares in points (0: the caller draws its own), their linear greys.
var checker_cell: f64 = 0.0
var checker_light: f32 = 0.0
var checker_dark: f32 = 0.0
## Whether the last `draw` tinted what Quick Mask masks itself.
var quick_drawn: bool = false
# mark: Lifecycle and document settings ===========================================================
## An empty `width` by `height` document with no layers.
pub func init(width: i64, height: i64) -> !:
if width < 1 or height < 1 or width > 65536 or height > 65536:
error(invalid, "document dimensions must be in 1..65536")
self.package = none
self.extent_x = (u32)width
self.extent_y = (u32)height
var empty: Record[]
self.records = empty
self.count = 0
self.next_id = 1
self.device = none
self.document = none
self.composer = none
self.painter = none
self.adjuster = none
self.filters = none
self.transformer = none
self.passes = none
self.brush = Brush()
self.fill_fault = none
self.brush_images = BrushImages()
self.stroke = none
self.stroke_layer = 0
self.preview = none
self.curves = Curves.identity()
self.table = none
var nothing: f64[4]
self.picked = nothing
self.mask_editing = false
self.selection = try Selection.create((u32)width, (u32)height)
var no_points: f64[]
self.polygon = no_points
self.polygon_count = 0
self.outline = no_points
self.outline_count = 0
var no_samples: RangeSample[32]
self.range_samples = no_samples
self.range_count = 0
self.range_session = none
self.ants_shader = none
self.liquifier = none
self.mesher = none
self.ants = none
self.quick_shader = none
self.quick_overlay = none
self.channels_shader = none
self.channels_view = none
self.view_format = none
var no_history: Snapshot[]
self.history = no_history
self.history_count = 0
self.future = no_history
self.future_count = 0
self.history_budget = default_history_budget
self.closed = false
self.dpi = 72.0
var no_name: u8[64]
self.profile_name = no_name
self.profile_length = 0
self.content = Bounds(left = 0, top = 0, right = 0, bottom = 0)
self.joining = false
self.separating = false
self.retouch = 0
self.clone_x = 0.0
self.clone_y = 0.0
self.clone_set = false
self.clone_offset_x = 0
self.clone_offset_y = 0
self.clone_offset_set = false
self.clone_aligned = true
self.clone_all = false
self.tone_range = 1
self.tone_exposure = 0.5
var no_bytes: u8[]
self.preview_bytes = no_bytes
self.warp = none
self.warped = 0
self.warp_finishing = false
self.warp_async = true
self.liquify = none
self.mesh_warp = none
self.mesh_cells_made = 0
self.smudge_spacing = default_smudge_spacing
self.transform_session = none
self.selection_warping = none
self.magnetic = none
self.select_mask = none
self.filter_stand_in = none
self.gradient_stand_in = none
self.coarse_shown = false
self.heal_opacity = 1.0
self.edit_depth = 0
self.edit_captured = false
self.shape_feather = 0
self.shape_hard = false
self.guides = Guides()
self.channels = Channels(count = 0)
self.view_channels = [true, true, true]
self.families = none
self.preview_name = "Adjustment"
self.serial = 0
self.saved_version = 0
self.backing = none
self.selected_layer_index = -1
var no_values: f64[23]
self.adjustment = no_values
var no_counts: u64[1024]
self.histogram_counts = no_counts
self.clear_adjustments()
self.set_profile("sRGB")
## Pixels per inch: how big the document prints, and what a ruler in
## millimeters or inches measures. 72 unless set.
pub func resolution() -> f64:
return self.dpi
pub func set_resolution(dpi: f64) -> !:
if not math.is_finite(dpi) or dpi < 1.0 or dpi > 100000.0:
error(invalid, "a resolution must be 1..100000 pixels per inch")
self.dpi = dpi
## Photoshop's Color Settings › "Blend RGB Colors Using Gamma 1.0": whether
## colors mix in linear light. Off by default: they mix as sRGB-encoded
## values wherever they mix, as Photoshop's 8- and 16-bit documents do.
pub func linear_blend() -> bool:
if let document = self.document:
return document.linear_blend
return self.cold_linear_blend
## Turn linear blending on or off for the whole document, one undo step.
pub func set_linear_blend(on: bool) -> !:
if on == self.linear_blend():
return
if let document = self.document:
try self.require_idle()
try self.remember_state("Blend RGB Colors Using Gamma 1.0")
document.linear_blend = on
document.revision += 1
return
self.cold_linear_blend = on
## Draw the view's checkerboard under transparent pixels with the picture,
## in squares of `cell` points of linear greys `light_grey` and `dark_grey`,
## aligned to the document's corner: the picture mixes with it as its
## colors mix. A `cell` of 0 leaves it to the caller, who draws it first.
pub func set_checker(cell: f64, light_grey: f64, dark_grey: f64) -> !:
if not math.is_finite(cell) or cell < 0.0 or not math.is_finite(light_grey) or not math.is_finite(dark_grey):
error(invalid, "a checkerboard needs a square size of 0 or more and finite greys")
self.checker_cell = cell
self.checker_light = (f32)math.clamp(light_grey, 0.0, 1.0)
self.checker_dark = (f32)math.clamp(dark_grey, 0.0, 1.0)
## The color profile the document's pixels are in, as luce-color names spaces
## ("sRGB", "Display P3", "Adobe RGB (1998)", …). sRGB unless set.
pub func profile() -> interop.Owned[str]!:
return try interop.copy_text((str)self.profile_name[..<self.profile_length])
pub func set_profile(name: str):
let length = name.length if name.length < self.profile_name.length else self.profile_name.length
for index in 0..<length:
self.profile_name[index] = name.bytes[index]
self.profile_length = length
## A document from `path`: an `.l2d` package with its layers, or a picture
## of any supported format as one layer.
pub static func open(path: str) -> interop.Reference[Canvas]!:
return try open_canvas(path)
pub func width() -> i64:
return (i64)self.extent_x
pub func height() -> i64:
return (i64)self.extent_y
## The selection being edited: the document's once bound, the cold one before.
func live() -> Selection*:
if let document = self.document:
return &document.selection
return &self.selection
func current() -> const Selection*:
if let document = self.document:
return &document.selection
return &self.selection
## No stroke and no preview may be in progress for edits and history; a
## smudge still finishing on its worker is waited for.
func require_idle() -> !:
try require_loaded(&self)
try self.wait_idle()
if self.stroke != none or self.warp != none or self.liquify != none:
error(invalid, "finish the stroke first")
if self.transform_session != none or self.mesh_warp != none:
error(invalid, "finish the transform first")
if self.preview != none:
error(invalid, "finish the preview first")
## Create the GPU document on the target's device and move waiting pictures in.
func bind(target: const gpu.RenderTarget*) -> !:
if self.document != none:
return
let acquired = gpu.device_of(target) catch failure:
if failure.code == gpu.unavailable:
return
error(failure.code, failure.message)
try self.bind_device(acquired)
# An .l2d's layers load their tiles from the file once the document is bound.
try load_package(&self)
# mark: Memory ====================================================================================
## Whether the canvas is on a GPU device yet (drawn once, or bound headless):
## what reads pixels back needs it.
## The layer (stack index) to select after opening, as the application
## had it when the document was saved; -1 when the file does not say.
pub func selected_layer() -> i64:
return self.selected_layer_index
## The application's selected layer (stack index), saved with the document.
pub func set_selected_layer(index: i64):
self.selected_layer_index = index
pub let canvas_type: interop.Type[Canvas] = interop.Type[Canvas]("Canvas", Canvas.close, Canvas.trace, closeable = true, main_thread = true)