dymokomi/luce-develop
Source of release 0.1.0
## The renderer: a viewer's photo developed on the GPU every frame, so a slider
## moves the picture as it moves. A scene loads on a thread of the renderer's
## own (the newest asked for wins), its pixels go up once, and each draw is one
## pass of shaders/develop.frag with the settings in its uniforms and two
## textures: the develop's tables (tables.lucb), rebuilt when the settings change,
## and the ACES view's table, baked once.
##
## Comparing, the photo before its film (settings.before_film: the camera's
## light, white balance and exposure, unfilmed) shows left of a split and the
## develop right of it; having no film, it is prepared on the window's thread.
##
## What the settings make on the CPU (the tables, the film's atlas: its model,
## its development, and for the stochastic render its grains, the better part
## of a second) is made on a second thread, so the window never waits for it:
## until it is done the last develop stays shown, `busy` says so, and the
## thread wakes the window (`tell`) when it is.
import interop
import memory
import time
import ownership
import strings
import sync
import thread
from luce_gpu import gpu
from luce_std import math
from settings import Settings, View, Look, defaults, compile, before_film
from scene import Scene
import scene
import tables
import geometry
import view
import film_print
import lens
from parameters import Parameter
import film
import film_exposure
from film import Film
from film_gpu import FilmPasses
from shaders import develop_frag_words, develop_frag_msl
import codes
pub let invalid: ErrorCode = codes.invalid
## Who the loading thread tells when a scene is ready (or failed): `call` with
## `context`, from the loading thread. The window passes its loop's wake-up
## (luced-photo: a luce-ui notifier), so it takes the scene with `poll` at once
## instead of polling for it.
pub struct Wake:
pub var call: func(void*) -> unit
pub var context: void*
## What the window and the loading thread share, guarded by `lock`.
struct Loading:
var lock: sync.Mutex
var wake: sync.Condition
## The file asked for (a strings.copy, or empty) and the size it loads at.
var wanted: str
var edge: usize
var serial: u64
## The newest scene loaded and the request it answers; or why it failed.
var done: Scene
var done_serial: u64
var failure: u8[256]
var failure_length: usize
var stopping: bool
var told: Wake?
func load(context: void*?):
let loading = (Loading*)(context else return)
var served: u64 = 0
while true:
loading.lock.lock()
while loading.serial == served and not loading.stopping:
loading.wake.wait(&loading.lock)
if loading.stopping:
loading.lock.unlock()
return
served = loading.serial
let path = strings.copy(loading.wanted) catch failure:
loading.lock.unlock()
continue
let edge = loading.edge
loading.lock.unlock()
defer strings.release(path)
var opened: Scene
# The failure's message lives only as long as its handler; keep a copy.
var held: u8[256]
var message = ""
opened = scene.open(path, edge) catch failure:
message = strings.copy_into(held, failure.message)
recover Scene()
loading.lock.lock()
if served == loading.serial:
loading.done.close()
loading.done = opened
loading.done_serial = served
let length = message.length if message.length < 256 else 256
memory.copy(loading.failure[..<length], message.bytes[..<length], length)
loading.failure_length = length
else:
opened.close()
let told = loading.told
loading.lock.unlock()
if let hook = told:
hook.call(hook.context)
## A preparation asked for: its settings, what the film needs of the
## scene, whether the stochastic render's grains are wanted too, and its serial
## (0: nothing asked).
struct Asked:
var settings: Settings
var input: film_exposure.Input
var grains: bool
var serial: u64
## The view the window has up (`view_key`): baked again only when it differs.
var view_known: i64
## A preparation done: the tables as half floats (heap, the window
## takes them), its film ready in `Preparing.films`, and the serial it answers.
struct Prepared:
var tables: f16[]
var settings: Settings
var grains: bool
var serial: u64
var ready: bool
## The view's table or the print and paper views' data (heap; empty when
## the window's is still right), and the view they are of.
var view_table: f16[]
var print_data: f32[]
var view_key: i64
func discard():
if self.tables.length > 0:
free(self.tables) in memory.heap
if self.view_table.length > 0:
free(self.view_table) in memory.heap
if self.print_data.length > 0:
free(self.print_data) in memory.heap
self.tables = no_tables()
self.view_table = no_tables()
self.print_data = no_data()
self.ready = false
## What the window and the preparing thread share, guarded by `lock`: the
## newest preparation asked for, the last one done, and the film the thread
## prepares, which the window swaps with its own when it takes a preparation
## (so neither side ever touches the other's).
struct Preparing:
var lock: sync.Mutex
var wake: sync.Condition
## Signalled when the thread finishes a preparation (`settle` waits on it).
var finished: sync.Condition
var asked: Asked
var done: Prepared
var film: Film
## The serial the thread is working on (0: none).
var working: u64
var stopping: bool
var told: Wake?
## Whether a preparation is asked for and not yet done.
func outstanding() -> bool:
return self.asked.serial != 0 and (self.working == self.asked.serial or self.done.serial < self.asked.serial)
func prepare_work(context: void*?):
let shared = (Preparing*)(context else return)
var taken: u64 = 0
while true:
shared.lock.lock()
while not shared.stopping and shared.asked.serial <= taken:
shared.wake.wait(&shared.lock)
if shared.stopping:
shared.lock.unlock()
return
let job = shared.asked
taken = job.serial
shared.working = job.serial
# A newer preparation supersedes one the window has not taken.
shared.done.discard()
shared.lock.unlock()
var good = true
var made = Prepared(tables = no_tables(), settings = job.settings, grains = job.grains, serial = job.serial, ready = true,
view_table = no_tables(), print_data = no_data(), view_key = view_key(&job.settings))
made.tables = prepared_tables(&job.settings) catch failure:
good = false
recover no_tables()
if good and made.view_key != job.view_known:
bake_view(&made) catch failure:
good = false
if good:
prepare_film(&shared.film, &job) catch failure:
good = false
shared.lock.lock()
shared.working = 0
if good:
shared.done = made
else:
made.discard()
# Answered, though nothing can be shown for it: the window keeps
# what it shows.
shared.done.serial = job.serial
let told = shared.told
shared.lock.unlock()
shared.finished.broadcast()
if let hook = told:
hook.call(hook.context)
func nothing_asked() -> Asked:
return Asked(settings = defaults(), input = film_exposure.Input())
func nothing_done() -> Prepared:
return Prepared(tables = no_tables(), settings = defaults(), view_table = no_tables(), print_data = no_data())
func no_tables() -> f16[]:
var empty: f16[]
return empty
func no_data() -> f32[]:
var empty: f32[]
return empty
## The view `made`'s settings show through: the ACES, Standard or Linear view's
## table, or the print and paper views' data (computed per pixel, not tabled).
func bake_view(made: Prepared*) -> !:
let settings = &made.settings
let shown_view = (View)(i64)settings.get(.view)
if shown_view == View.print or shown_view == View.paper:
made.print_data = try new f32[film_print.print_atlas_width * film_print.print_atlas_rows * 4] --- in memory.heap
view.pack(shown_view, made.print_data, silver = film_print.silver_kept(settings.get(.print_silver)), paper = film.paper_settings(settings),
material = (i64)settings.get(.print_material))
return
let n = view.lut_size
made.view_table = try new f16[n * n * n * 4] --- in memory.heap
view.bake(shown_view, made.view_table)
## The develop's tables for `settings`, as half floats on the heap.
func prepared_tables(settings: const Settings*) -> f16[]!:
let built = tables.build(settings)
let texels = try new f16[tables.table_width * tables.table_rows * 4] --- in memory.heap
tables.half(&built, texels)
return texels
func prepare_film(made: Film*, job: const Asked*) -> !:
try made.prepare(&job.settings, job.input)
if job.grains:
try made.fit_grains()
## One develop of the shown scene: its settings, compiled for one output, and
## the GPU state they make (the tables, the view's table, the film's atlas and
## the passes that film the scene, whose result is theirs).
struct Developing:
## The settings the GPU state is of (what is drawn), and the newest asked
## for, sent to the preparing thread when `tables_stale`; the serial of the
## last preparation asked for and of the one shown.
var settings: Settings
var wanted: Settings
var tables_stale: bool
var asked_serial: u64
var shown_serial: u64
## Whether the last preparation asked for is only the grains for what is shown.
var asked_grains: bool
var view_baked: i64
var tables_texture: gpu.Texture?
var view_texture: gpu.Texture?
## The print and paper views' data (view.lucb's `pack`): the GPU computes
## them per pixel, as the CPU does, not through a table.
var print_texture: gpu.Texture?
var film: Film
var film_texture: gpu.Texture?
var film_passes: FilmPasses
var filmed: gpu.Texture?
var film_stale: bool
## The scene at the scan's samples (film.scan_samples) where it is finer,
## which the film is filmed from: its width (0: none made) and height.
var scanned_texture: gpu.Texture?
var scanned_columns: usize
var scanned_rows: usize
func take(settings: Settings):
self.wanted = settings
self.tables_stale = true
func release():
self.film.release()
self.film_passes.release()
self.filmed = none
self.scanned_columns = 0
for slot in [&self.tables_texture, &self.view_texture, &self.print_texture, &self.film_texture, &self.scanned_texture]:
if let held = *slot:
var gone = held
gone.destroy()
*slot = none
## What a view's table or packed data depends on, as one number: the view;
## the print's silver and material; the paper's choices.
func view_key(settings: const Settings*) -> i64:
var key = (i64)settings.get(.view)
for parameter in [Parameter.print_silver, Parameter.paper_stock, Parameter.paper_grade, Parameter.paper_enlarger, Parameter.paper_exposure,
Parameter.paper_yellow, Parameter.paper_magenta, Parameter.paper_cyan, Parameter.film_stock, Parameter.print_material,
Parameter.paper_surface]:
key = key *% 1000003 +% (i64)math.round(settings.get(parameter) * 100.0)
return key
## How long watching development takes, seconds of real time.
let watch_seconds: f64 = 2.5
## The stochastic render (film_grains.lucb): samples a traced pixel takes among
## its grains, and how many pixels a frame traces (frames stay a few tens of
## milliseconds while it refines, however large the photo).
pub let refine_target: u32 = 256
let frame_work: f64 = 4096.0
func developing() -> Developing:
return Developing(settings = defaults(), wanted = defaults(), view_baked = -1)
pub struct Renderer:
var loading: Loading*?
var worker: thread.Handle
## The preparing thread and what it shares.
var preparing: Preparing*?
var preparer: thread.Handle
## The scene shown, and whether its pixels still need to go up; the
## quarter turns its pixels have had, and the settings' (geometry_turn).
var shown: Scene
var turned: i64
var turn_wanted: i64
var shown_serial: u64
var upload: bool
## The develop drawn; and the photo before its film, drawn left of `split`
## (0..1 of the photo's width) while `comparing`.
var develop: Developing
var before: Developing
var comparing: bool
var split: f64
## Watching development: each change of the settings develops the film
## again over `watch_seconds`, frame by frame, from nothing (when it began,
## ns, and whether it is still going).
var watching: bool
var watch_began: u64
var watch_running: bool
## Made on the first draw, on the window's device.
var device: gpu.Device?
var shader: gpu.Shader?
var pipeline: gpu.Pipeline?
var scene_texture: gpu.Texture?
var problem: u8[256]
var problem_length: usize
## The format of the targets drawn into: the window's when none.
var format: gpu.Format?
## Whether draws apply the geometry; off while guides are drawn on the photo
## as it was taken. Whether they apply the crop; off while it is chosen.
var geometry_shown: bool
var crop_shown: bool
## The stochastic render: whether it refines the film once the settings settle.
var refining: bool
## For the histogram: a pipeline drawing into 8-bit textures, and the bins.
var probe_pipeline: gpu.Pipeline?
var bins: i64[1024]
## Load the photo at `path` at most `edge` pixels on its longer side (0:
## its full size); the current one stays shown until it is in (see `poll`).
pub func open(path: str, edge: i64) -> !:
let loading = self.loading else error(invalid, "the renderer is closed")
if edge != 0 and edge < 16:
error(invalid, "a renderer needs a size")
let copied = try strings.copy(path)
loading.lock.lock()
if loading.wanted.length > 0:
strings.release(loading.wanted)
loading.wanted = copied
loading.edge = (usize)edge
loading.serial += 1
loading.lock.unlock()
loading.wake.signal()
## Show `shown` now, without loading: the renderer owns it from here.
pub func show(shown: Scene):
self.shown.close()
self.shown = shown
self.turned = 0
self.upload = self.shown.width() > 0
## Show nothing.
pub func clear():
self.shown.close()
self.upload = false
if let held = self.loading:
held.lock.lock()
held.serial += 1
held.lock.unlock()
## Take in a scene that finished loading; whether one did (redraw then). A
## failed load shows nothing and answers true too; `failure` says why.
pub func poll() -> bool:
let loading = self.loading else return false
loading.lock.lock()
defer loading.lock.unlock()
if loading.done_serial == 0 or loading.done_serial == self.shown_serial or loading.done_serial != loading.serial:
return false
self.shown.close()
self.shown = loading.done
self.turned = 0
loading.done = Scene()
self.shown_serial = loading.done_serial
memory.copy(self.problem[..<loading.failure_length], loading.failure[..<loading.failure_length], loading.failure_length)
self.problem_length = loading.failure_length
self.upload = self.shown.width() > 0
return true
## Why the last load failed, or "".
pub func failure() -> str:
return (str)self.problem[..<self.problem_length]
## Whether a photo is shown, its size, and its as-shot white balance.
pub func has_image() -> bool:
return self.shown.width() > 0
pub func width() -> i64:
return self.shown.width()
pub func height() -> i64:
return self.shown.height()
pub func is_raw() -> bool:
return self.shown.is_raw()
pub func shot_temperature() -> f64:
return self.shown.shot_temperature
pub func shot_tint() -> f64:
return self.shown.shot_tint
## How long the shown photo was exposed (seconds; zero when unknown).
pub func shot_seconds() -> f64:
return self.shown.shot_seconds
## Apply the geometry (perspective, rotation, crop to fit) or show the photo
## as it was taken, for drawing guides on.
pub func show_geometry(on: bool):
self.geometry_shown = on
## Apply the crop, or show the whole frame for choosing it.
pub func show_crop(on: bool):
self.crop_shown = on
## The output's size as drawn: the crop of the scene (all of it while the
## crop or the geometry is off).
func output_size() -> (f64, f64):
let width = (f64)self.shown.width()
let height = (f64)self.shown.height()
if not self.geometry_shown or not self.crop_shown:
return (width, height)
return geometry.output_size(&self.develop.settings, width, height)
## The output's width and height in scene pixels, for placing it.
pub func output_width() -> f64:
return self.output_size().0
pub func output_height() -> f64:
return self.output_size().1
## Develop with `look`'s settings from the next draw on.
pub func set_look(look: interop.Reference[Look]) -> !:
self.set_settings((try look.get()).value())
## Develop with `settings` from the next draw on.
pub func set_settings(settings: Settings):
if self.watching:
self.watch_began = time.now()
self.watch_running = true
self.turn_wanted = (i64)settings.get(.geometry_turn)
self.develop.take(compile(&settings))
self.before.take(before_film(&settings))
## Watch the film develop: after each change, over a couple of seconds, the
## negative (or what is made from it) as development runs its course.
pub func watch_development(on: bool):
self.watching = on
self.watch_running = on
self.watch_began = time.now()
self.develop.film_stale = true
## Whether development is being shown running, or the stochastic render is
## still refining (draw again soon).
pub func animating() -> bool:
return self.watch_running or self.still_refining(&self.develop)
## Refine the film stochastically once the settings settle (on by default).
pub func refine_grain(on: bool):
self.refining = on
if not on:
# Back to the statistical film.
self.develop.film_stale = true
## Whether the develop's stochastic render is still refining.
pub func is_refining() -> bool:
return self.still_refining(&self.develop)
## How many samples a pixel the develop's stochastic render has (0 while the
## statistical film shows).
pub func refined_samples() -> i64:
return (i64)self.develop.film_passes.samples
## How much of the develop's stochastic render is done (0..1).
pub func refined_share() -> f64:
return self.develop.film_passes.traced_share()
func still_refining(which: const Developing*) -> bool:
let wanted = self.refining and not self.watch_running and which.film.active() and which.settings.get(.film_grain) > 0.0
return wanted and which.film_passes.samples < refine_target
## Whether the develop shown is not yet what was asked for: a photo still
## loading, settings still being prepared, or the film not yet on the
## negative. The last develop stays shown meanwhile; draw again when the
## renderer wakes the window (`tell`).
pub func busy() -> bool:
if let loading = self.loading:
loading.lock.lock()
let loading_now = loading.serial != 0 and loading.serial != loading.done_serial
loading.lock.unlock()
if loading_now:
return true
if not self.has_image():
return false
let which = &self.develop
if which.tables_stale or which.shown_serial == 0 or (self.outstanding() and not which.asked_grains):
return true
return which.film.active() and (which.filmed == none or which.film_stale)
## Compare the photo before its film (left of the split) with the develop.
pub func compare_before(on: bool):
self.comparing = on
pub func is_comparing() -> bool:
return self.comparing
pub func split_at() -> f64:
return self.split
pub func set_split(at: f64):
self.split = math.clamp(at, 0.0, 1.0)
## Whether the develop has anything to draw yet (until then a window shows
## what it had, a preview).
pub func ready() -> bool:
if not self.has_image() or self.develop.shown_serial == 0 or self.develop.tables_texture == none or self.develop.film_texture == none:
return false
return not self.develop.film.active() or self.develop.filmed != none
## Wait until the preparing thread has done everything asked of it (for
## tests and off-screen renders: the next draw then takes it).
pub func settle():
let shared = self.preparing else return
shared.lock.lock()
while shared.outstanding():
shared.finished.wait(&shared.lock)
shared.lock.unlock()
func outstanding() -> bool:
let shared = self.preparing else return false
shared.lock.lock()
defer shared.lock.unlock()
return shared.outstanding()
## Ask the preparing thread for settings `wanted` (with the stochastic
## render's grains when `grains`).
func ask(which: Developing*, wanted: const Settings*, grains: bool) -> !:
let shared = self.preparing else return
let camera = film.camera_settings(wanted)
let input = try self.shown.film_input(&camera)
shared.lock.lock()
which.asked_serial += 1
which.asked_grains = grains
shared.asked = Asked(settings = *wanted, input = input, grains = grains, serial = which.asked_serial, view_known = which.view_baked)
shared.lock.unlock()
shared.wake.signal()
## Take the finished preparation, if a newer one is ready: its film swapped
## in, its tables and atlas up; whether one was.
func take_prepared(device: gpu.Device, which: Developing*) -> bool!:
let shared = self.preparing else return false
shared.lock.lock()
let done = &shared.done
if not done.ready or done.serial <= which.shown_serial:
shared.lock.unlock()
return false
let kept = which.film
which.film = shared.film
shared.film = kept
# The arrays move to `taken`; the thread's slot is left empty.
var taken = *done
done.tables = no_tables()
done.view_table = no_tables()
done.print_data = no_data()
done.ready = false
# A grains preparation is asked for with the settings shown (`refine_develop`).
let grains_only = done.grains and which.shown_serial > 0
which.settings = done.settings
which.shown_serial = done.serial
shared.lock.unlock()
defer taken.discard()
try upload_prepared(device, which, &taken)
try upload_atlas(device, which)
# Grains fitted for what is shown: the filmed scene stays, the render refines on.
if not grains_only:
which.film_stale = true
return true
## The matrix from the scene into AP1 for `which`: the white balance's, or as
## shot when the film sees the light on set (film.camera_settings).
func scene_matrix(which: const Developing*) -> f64[9]!:
let camera = film.camera_settings(&which.settings)
return try self.shown.matrix(&camera)
## The lens's veiling glare for `which`: a share of the scene's mean light
## (lens.lucb).
func veil_of(which: const Developing*) -> f64!:
let m = try self.scene_matrix(which)
let mean = self.shown.average()
let ap1: f64[3] = [m[0] * mean[0] + m[1] * mean[1] + m[2] * mean[2], m[3] * mean[0] + m[4] * mean[1] + m[5] * mean[2],
m[6] * mean[0] + m[7] * mean[1] + m[8] * mean[2]]
return lens.veil(&which.settings, ap1)
## Draw the photo into `x`, `y`, `width` × `height` points of `target`.
pub func draw(target: interop.View[gpu.RenderTarget], x: f64, y: f64, width: f64, height: f64) -> !:
if not self.has_image() or width <= 0.0 or height <= 0.0:
return
let checked = try target.get()
try self.prepare(checked)
let pipeline = self.pipeline else return
if not self.comparing:
try self.shade(checked, pipeline, &self.develop, x, y, width, height, x, width)
return
let middle = width * self.split
try self.shade(checked, pipeline, &self.before, x, y, width, height, x, middle)
try self.shade(checked, pipeline, &self.develop, x, y, width, height, x + middle, width - middle)
## One develop pass of `which` into `target` with `pipeline`: the photo
## placed at `x`, `y`, `width` × `height`, drawn only from `left` across
## `across`.
func shade(checked: const gpu.RenderTarget*, pipeline: gpu.Pipeline, which: const Developing*, x: f64, y: f64, width: f64, height: f64,
left: f64, across: f64) -> !:
if across <= 0.0:
return
let scene_texture = self.scene_texture else return
let tables_texture = which.tables_texture else return
let shown_view = which.settings.get(.view)
let printed_view = shown_view == (f64)(i64)View.print or shown_view == (f64)(i64)View.paper
let view_texture = (which.print_texture if printed_view else which.view_texture) else return
let film_texture = which.film_texture else return
let place = try checked.placement()
let size = try checked.size()
let scale = size.pixel_width / size.width if size.width > 0.0 else 1.0
# With film the scene is the filmed one, already in AP1.
var source_texture = scene_texture
var m = try self.scene_matrix(which)
# The lens's veil, unless the film took it in (film_gpu's expose pass).
var veil = try self.veil_of(which)
if which.film.active():
source_texture = which.filmed else return
m = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]
veil = 0.0
let identity: geometry.Matrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]
let map = geometry.frame_map(&which.settings, (f64)self.shown.width(), (f64)self.shown.height(), self.crop_shown) if self.geometry_shown else identity
let (out_width, out_height) = self.output_size()
var uniforms: f32[32] = [
(f32)((place.x + x) * scale), (f32)((place.y + y) * scale), (f32)(width * scale), (f32)(height * scale),
(f32)m[0], (f32)m[1], (f32)m[2], (f32)veil, (f32)m[3], (f32)m[4], (f32)m[5], 0.0f32, (f32)m[6], (f32)m[7], (f32)m[8], 0.0f32,
(f32)(which.settings.get(.vibrance) / 100.0), (f32)(which.settings.get(.saturation) / 100.0), (f32)which.settings.get(.view), (f32)(out_width / out_height),
(f32)map[0], (f32)map[1], (f32)map[2], 0.0f32, (f32)map[3], (f32)map[4], (f32)map[5], 0.0f32, (f32)map[6], (f32)map[7], (f32)map[8], 0.0f32]
# Only the part on the target is drawn: zoomed in, the photo's place runs
# far past it (and past the largest region a draw may have); the shader
# places the photo by the uniforms, not by the region.
let region_left = math.max(left, 0.0)
let region_top = math.max(y, 0.0)
let region_right = math.min(left + across, size.width)
let region_bottom = math.min(y + height, size.height)
if region_right <= region_left or region_bottom <= region_top:
return
let images: gpu.Texture[4] = [source_texture, tables_texture, view_texture, film_texture]
try gpu.shade(checked, pipeline, gpu.Rect(region_left, region_top, region_right - region_left, region_bottom - region_top),
u8[]((u8*)&uniforms[0], 128), images, gpu.Filter.linear)
## Count the develop as shown into the histogram (`histogram`): the photo is
## developed at most 256 pixels on its longer side, off screen, and read back.
## A viewer calls this once the settings have settled, not every frame. It
## needs a draw first (the device is the window's).
pub func compute_histogram() -> !:
let device = self.device else return
if not self.has_image():
return
let (full_width, full_height) = self.output_size()
let scale = math.min(1.0, 256.0 / math.max(full_width, full_height))
let width = math.max(1.0, math.round(full_width * scale))
let height = math.max(1.0, math.round(full_height * scale))
if self.probe_pipeline == none:
let shader = self.shader else return
self.probe_pipeline = try gpu.Pipeline.create(device, shader, gpu.Blend.replace, gpu.Format.rgba8)
let pipeline = self.probe_pipeline else return
var texture = try gpu.Texture.create(device, (u32)width, (u32)height, gpu.Format.rgba8)
defer texture.destroy()
let frame = try texture.frame()
defer frame.release()
let area = try frame.value().target()
defer area.release()
try self.shade(try area.get(), pipeline, &self.develop, 0.0, 0.0, width, height, 0.0, width)
_ = try frame.value().present(gpu.Color(0.0, 0.0, 0.0, 1.0))
let pixels = try new u8[(usize)(width * height) * 4] in memory.heap
defer free(pixels) in memory.heap
try texture.read(pixels)
for at in 0..<(usize)1024:
self.bins[at] = 0
for at in 0..<pixels.length // 4:
let r = pixels[at * 4]
let g = pixels[at * 4 + 1]
let b = pixels[at * 4 + 2]
self.bins[r] += 1
self.bins[256 + (usize)g] += 1
self.bins[512 + (usize)b] += 1
# Rec. 709 luma of the encoded values, as photo editors draw it.
let luma = ((u32)r * 54 + (u32)g * 183 + (u32)b * 19) >> 8
self.bins[768 + (usize)luma] += 1
## The last histogram's bin `at`: 256 bins each of red, green, blue and luma,
## in that order, over the displayed 8-bit values.
pub func histogram_bin(at: i64) -> i64:
return self.bins[(usize)at] if at >= 0 and at < 1024 else 0
## The pipeline and the textures, made or refreshed for what changed.
func prepare(target: const gpu.RenderTarget*) -> !:
if self.device == none:
let device = try gpu.device_of(target)
var shader = try gpu.Shader.create(device, develop_frag_words, develop_frag_msl)
errdefer shader.destroy()
let pipeline = try gpu.Pipeline.create(device, shader, gpu.Blend.replace, self.format)
self.device = device
self.shader = shader
self.pipeline = pipeline
let device = self.device else return
# Another Turn: the pixels turned by the difference, and up again.
if self.shown.width() > 0 and self.turned != self.turn_wanted:
try self.shown.turn(self.turn_wanted - self.turned)
self.turned = self.turn_wanted
self.upload = true
if self.upload:
if let old = self.scene_texture:
var gone = old
gone.destroy()
self.scene_texture = none
var texture = try gpu.Texture.create(device, (u32)self.shown.width(), (u32)self.shown.height(), gpu.Format.rgba16_float)
errdefer texture.destroy()
try texture.upload(self.shown.bytes())
self.scene_texture = texture
self.upload = false
# A new scene: its film input changes the film's exposure too.
self.develop.film_stale = true
self.develop.tables_stale = true
self.develop.scanned_columns = 0
self.before.tables_stale = true
# While development is being watched, how much of it is still to come
# (the last frame the developed film).
if self.watch_running:
let elapsed = (f64)(time.now() - self.watch_began) / 1.0e9
let remaining = math.max(0.0, 1.0 - elapsed / watch_seconds)
self.develop.film_passes.remaining = remaining
self.develop.film_stale = true
if remaining <= 0.0:
self.watch_running = false
try self.prepare_develop(device, &self.develop)
if self.comparing:
try self.prepare_before(device)
## `which`'s tables, view table, film atlas and filmed scene, made or
## refreshed for what changed.
func prepare_develop(device: gpu.Device, which: Developing*) -> !:
# New settings go to the preparing thread; what it has done comes in.
if which.tables_stale:
which.tables_stale = false
try self.ask(which, &which.wanted, false)
_ = try self.take_prepared(device, which)
if which.shown_serial == 0:
return
# Film the scene on the negative when it or the settings changed.
if which.film.active() and (which.film_stale or which.filmed == none):
let scene_texture = self.scene_texture else return
let tables_texture = which.tables_texture else return
let film_texture = which.film_texture else return
let aspect = (f64)self.shown.width() / (f64)self.shown.height()
# Filmed at the scan's samples where the scene is finer: the draw
# filters the filmed scene up to the photo's place.
var filming = scene_texture
var columns = (usize)self.shown.width()
var rows = (usize)self.shown.height()
let scan = film.scan_samples(&which.settings)
if scan > 0 and columns > scan:
filming = try self.scanned(device, which, scan)
columns = which.scanned_columns
rows = which.scanned_rows
which.filmed = try which.film_passes.run(device, filming, tables_texture, film_texture, &which.film,
try self.scene_matrix(which), aspect, (u32)columns, (u32)rows, try self.veil_of(which))
which.film_stale = false
elif self.still_refining(which):
try self.refine_develop(device, which)
## The photo before its film: no film, so its tables, its (empty) film atlas
## and its view are made here, at once.
func prepare_before(device: gpu.Device) -> !:
let which = &self.before
if which.tables_stale or which.shown_serial == 0:
which.tables_stale = false
which.settings = which.wanted
which.shown_serial = 1
var made = Prepared(tables = try prepared_tables(&which.settings), settings = which.settings, ready = true,
view_table = no_tables(), print_data = no_data(), view_key = view_key(&which.settings))
defer made.discard()
if made.view_key != which.view_baked:
try bake_view(&made)
let camera = film.camera_settings(&which.settings)
try which.film.prepare(&which.settings, try self.shown.film_input(&camera))
try upload_prepared(device, which, &made)
try upload_atlas(device, which)
## The shown scene at `columns` samples across for `which`, made when it is not.
func scanned(device: gpu.Device, which: Developing*, columns: usize) -> gpu.Texture!:
if let held = which.scanned_texture:
if which.scanned_columns == columns:
return held
var gone = held
gone.destroy()
which.scanned_texture = none
var sampled = try self.shown.sampled(columns)
defer sampled.close()
var texture = try gpu.Texture.create(device, (u32)sampled.width(), (u32)sampled.height(), gpu.Format.rgba16_float)
errdefer texture.destroy()
try texture.upload(sampled.bytes())
which.scanned_texture = texture
which.scanned_columns = columns
which.scanned_rows = (usize)sampled.height()
return texture
## More of `which`'s stochastic render (a frame's share), once the
## preparing thread has fitted its grains; shown once it has enough.
func refine_develop(device: gpu.Device, which: Developing*) -> !:
let tables_texture = which.tables_texture else return
if not which.film.has_grains():
if not self.outstanding() and not which.tables_stale:
try self.ask(which, &which.settings, true)
return
let film_texture = which.film_texture else return
if let resolved = try which.film_passes.refine(device, tables_texture, film_texture, refine_target, frame_work):
which.filmed = resolved
## Stop the loading thread and let every texture go.
## Tell `hook` whenever a scene this renderer loads is ready (none: nobody).
pub func tell(hook: Wake?):
if let loading = self.loading:
loading.lock.lock()
loading.told = hook
loading.lock.unlock()
if let shared = self.preparing:
shared.lock.lock()
shared.told = hook
shared.lock.unlock()
pub func close():
if let loading = self.loading:
loading.lock.lock()
loading.stopping = true
loading.lock.unlock()
loading.wake.broadcast()
self.worker.join() catch failure:
trap("the renderer's loading thread could not be joined")
loading.done.close()
if loading.wanted.length > 0:
strings.release(loading.wanted)
free(loading) in memory.heap
self.loading = none
if let shared = self.preparing:
shared.lock.lock()
shared.stopping = true
shared.lock.unlock()
shared.wake.broadcast()
self.preparer.join() catch failure:
trap("the renderer's preparing thread could not be joined")
shared.done.discard()
shared.film.release()
free(shared) in memory.heap
self.preparing = none
self.shown.close()
self.develop.release()
self.before.release()
if let held = self.scene_texture:
var gone = held
gone.destroy()
self.scene_texture = none
if let held = self.pipeline:
var gone = held
gone.destroy()
if let held = self.probe_pipeline:
var gone = held
gone.destroy()
self.probe_pipeline = none
if let held = self.shader:
var gone = held
gone.destroy()
self.pipeline = none
self.shader = none
self.device = none
func trace(visit: func(ownership.Object*, void*) -> unit, context: void*):
_ = self
_ = visit
_ = context
pub let renderer_type: interop.Type[Renderer] = interop.Type[Renderer]("Renderer", Renderer.close, Renderer.trace, closeable = true, main_thread = true)
## What `made` holds onto the GPU for `which`: its view's table or the print
## and paper views' data when it has them, and its tables.
func upload_prepared(device: gpu.Device, which: Developing*, made: const Prepared*) -> !:
if made.view_table.length > 0:
if which.view_texture == none:
which.view_texture = try gpu.Texture.create(device, (u32)(view.lut_size * view.lut_size), (u32)view.lut_size, gpu.Format.rgba16_float)
let view_held = which.view_texture else return
try view_held.upload(u8[]((u8*)made.view_table.data, made.view_table.length * 2))
which.view_baked = made.view_key
if made.print_data.length > 0:
if which.print_texture == none:
which.print_texture = try gpu.Texture.create(device, (u32)film_print.print_atlas_width, (u32)film_print.print_atlas_rows,
gpu.Format.rgba32_float)
let print_held = which.print_texture else return
try print_held.upload(u8[]((u8*)made.print_data.data, made.print_data.length * 4))
which.view_baked = made.view_key
if which.tables_texture == none:
which.tables_texture = try gpu.Texture.create(device, (u32)tables.table_width, (u32)tables.table_rows, gpu.Format.rgba16_float)
let held = which.tables_texture else return
try held.upload(u8[]((u8*)made.tables.data, made.tables.length * 2))
## `which`'s film atlas onto the GPU.
func upload_atlas(device: gpu.Device, which: Developing*) -> !:
let atlas = try new f16[film.atlas_width * film.atlas_rows * 4] --- in memory.heap
defer free(atlas) in memory.heap
for at in 0..<atlas.length:
atlas[at] = (f16)which.film.texels[at]
if which.film_texture == none:
which.film_texture = try gpu.Texture.create(device, (u32)film.atlas_width, (u32)film.atlas_rows, gpu.Format.rgba16_float)
let film_held = which.film_texture else return
try film_held.upload(u8[]((u8*)atlas.data, atlas.length * 2))
## A renderer drawing into targets of `format` (the window's when none), its
## loading thread started; the caller closes it.
pub func create(format: gpu.Format? = none) -> Renderer!:
let loading = try new Loading in memory.heap
errdefer free(loading) in memory.heap
let shared = try new Preparing(asked = nothing_asked(), done = nothing_done()) in memory.heap
errdefer free(shared) in memory.heap
let worker = try thread.spawn(load, (void*)loading, name = "luce-develop load")
let preparer = thread.spawn(prepare_work, (void*)shared, name = "luce-develop prepare") catch failure:
loading.lock.lock()
loading.stopping = true
loading.lock.unlock()
loading.wake.broadcast()
worker.join() catch joined:
trap("the renderer's loading thread could not be joined")
error(failure.code, failure.message)
return Renderer(loading = loading, worker = worker, preparing = shared, preparer = preparer, develop = developing(), before = developing(), split = 0.5, format = format,
geometry_shown = true, crop_shown = true, refining = true)
## A renderer for Luce, drawing into the window.
pub func start() -> interop.Reference[Renderer]!:
var made = try create()
let renderer = new Renderer(loading = made.loading, worker = made.worker, preparing = made.preparing, preparer = made.preparer, develop = developing(),
before = developing(), split = 0.5, geometry_shown = true, crop_shown = true, refining = true) in memory.heap catch failure:
made.close()
error(failure.code, failure.message)
return try interop.Reference[Renderer].adopt(renderer, renderer_type, memory.heap)