diff --git a/dependencies.json b/dependencies.json index 4e53fb5..dac25f8 100644 --- a/dependencies.json +++ b/dependencies.json @@ -35,7 +35,8 @@ "easyeffects": "Dashboard Media tab equalizer only; writes the glassmxrph_eq output preset and starts EasyEffects in service mode on apply", "wttr.in (network)": "Weather desktop widget only; fetched every 30 minutes while a weather widget exists", "Nerd Font": "Icon glyphs in Settings (any installed Nerd Font, e.g. Symbols Nerd Font); letters are used otherwise", - "nvidia-smi": "Read-only NVIDIA GPU telemetry through the host driver tool; other metrics do not require it" + "nvidia-smi": "Read-only NVIDIA GPU telemetry through the host driver tool; other metrics do not require it", + "BiRefNet + onnxruntime/opencv/numpy/pillow": "Outline wallpaper transitions only; set GLASSMXRPH_WALLFX_PYTHON (an interpreter with those modules) and GLASSMXRPH_WALLFX_MODEL (the BiRefNet ONNX file). The Nix package sets both; without them every change uses colonies" }, "development": [ "qmllint", diff --git a/packaging/nix/package.nix b/packaging/nix/package.nix index df29daf..c3e112f 100644 --- a/packaging/nix/package.nix +++ b/packaging/nix/package.nix @@ -1,4 +1,13 @@ -{ lib, stdenvNoCC, makeWrapper, quickshell, qt6, nodejs, source }: +{ lib, stdenvNoCC, makeWrapper, quickshell, qt6, nodejs, python3, fetchurl, source }: +let + # Outline wallpaper transitions (quickshell/helpers/wallfx.py): BiRefNet lite + # finds a wallpaper's subject, run on the CPU through onnxruntime. + wallfxPython = python3.withPackages (ps: [ ps.numpy ps.opencv4 ps.pillow ps.onnxruntime ]); + wallfxModel = fetchurl { + url = "https://github.com/danielgatis/rembg/releases/download/v0.0.0/BiRefNet-general-bb_swin_v1_tiny-epoch_232.onnx"; + sha256 = "0crky386fm0268hy5qglpqv1d5p5n6pv0phahxbsawpmfr1h402n"; + }; +in stdenvNoCC.mkDerivation { pname = "glassMxrph"; version = "0.2.0"; @@ -12,7 +21,9 @@ stdenvNoCC.mkDerivation { cp -r quickshell scripts tests docs dependencies.json README.md $out/share/glassMxrph/ makeWrapper $out/share/glassMxrph/scripts/glassmxrph $out/bin/glassmxrph \ --prefix PATH : ${lib.makeBinPath [ quickshell ]} \ - --prefix QT_PLUGIN_PATH : ${qt6.qtimageformats}/${qt6.qtbase.qtPluginPrefix} + --prefix QT_PLUGIN_PATH : ${qt6.qtimageformats}/${qt6.qtbase.qtPluginPrefix} \ + --set-default GLASSMXRPH_WALLFX_PYTHON ${wallfxPython}/bin/python3 \ + --set-default GLASSMXRPH_WALLFX_MODEL ${wallfxModel} ''; meta = { description = "Modular glass desktop shell for Quickshell and Hyprland"; diff --git a/quickshell/config/defaults.json b/quickshell/config/defaults.json index 09a27b7..4f49155 100644 --- a/quickshell/config/defaults.json +++ b/quickshell/config/defaults.json @@ -147,7 +147,8 @@ "backend": "native", "command": [], "providerPaths": {}, - "history": [] + "history": [], + "outlineExclude": [] }, "controlCenter": { "version": 2, diff --git a/quickshell/helpers/wallfx.py b/quickshell/helpers/wallfx.py new file mode 100644 index 0000000..b5a5e78 --- /dev/null +++ b/quickshell/helpers/wallfx.py @@ -0,0 +1,255 @@ +#!/usr/bin/env python3 +"""Outline maps for the wallpaper change (wallpaper/shaders/colonies.frag, mode 1). + +When a new wallpaper has a clear subject, the change draws the subject's +outline, fills it in from that outline, and then grows the rest of the picture +out of it. This helper finds the subject (BiRefNet, through onnxruntime) and +bakes two RGB maps in the image's own space; the shader only reads them. + + field.png R depth inside the subject: 0 on its outline, 1 at its deepest + G signed distance to the outline, +-SD_RANGE map px, 0.5 on it + line.png R position along the outline (two pens from the top), 0 = no line + G/B order in which the outside arrives, 16 bits, smooth + +Maps are cached per image (path, size and mtime). Commands, each printing one +JSON object: + + choose IMG {"kind": "outline", "field", "line"} when cached maps exist, + {"kind": "colonies", "pending": true} when IMG is not + processed yet, {"kind": "colonies"} when it has no subject. + Uses only the standard library, so it answers at once. + warm IMG... processes every image not cached yet; one warm at a time. + outline IMG [--force] + +Requires GLASSMXRPH_WALLFX_MODEL (BiRefNet ONNX) and numpy, opencv, pillow and +onnxruntime in the interpreter running this file. +""" +import hashlib +import json +import os +import sys + +CACHE = os.path.join(os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache"), "glassMxrph", "wallfx") +MODEL = os.environ.get("GLASSMXRPH_WALLFX_MODEL", "") +MAP_MAX = 1280 # long side of the maps; the shader interpolates them +SD_RANGE = 16.0 # signed distance kept within +-16 map px of the outline +EXTS = (".jpg", ".jpeg", ".png", ".webp", ".bmp") + + +def key(img): + st = os.stat(img) + return hashlib.sha1(f"{os.path.realpath(img)}|{st.st_size}|{int(st.st_mtime)}".encode()).hexdigest()[:16] + + +def cached(img): + """(field, line) if IMG has cached maps, False if it has no subject, None if unprocessed.""" + base = os.path.join(CACHE, key(img)) + try: + with open(base + ".json") as f: + meta = json.load(f) + except (OSError, ValueError): + return None + if not meta.get("ok"): + return False + field, line = base + "-field.png", base + "-line.png" + return (field, line) if os.path.exists(field) and os.path.exists(line) else None + + +# ───────────────────────────── subject mask ───────────────────────────── + +_session = None + + +def mask_of(im): + """BiRefNet's foreground probability for a PIL RGB image, as float32 0..1.""" + global _session + import numpy as np + import onnxruntime as ort + from PIL import Image + if _session is None: + opts = ort.SessionOptions() + opts.intra_op_num_threads = max(1, (os.cpu_count() or 2) // 2) # leave the desktop room + _session = ort.InferenceSession(MODEL, opts, providers=["CPUExecutionProvider"]) + x = np.asarray(im.resize((1024, 1024), Image.Resampling.LANCZOS), np.float32) + x /= max(float(x.max()), 1e-6) + x = (x - np.array([0.485, 0.456, 0.406], np.float32)) / np.array([0.229, 0.224, 0.225], np.float32) + x = x.transpose(2, 0, 1)[None].astype(np.float32) + out = _session.run(None, {_session.get_inputs()[0].name: x})[0][0, 0] + p = 1.0 / (1.0 + np.exp(-out)) + p = (p - p.min()) / max(float(p.max() - p.min()), 1e-6) + m = Image.fromarray((p * 255).astype(np.uint8)).resize(im.size, Image.Resampling.LANCZOS) + return np.asarray(m, np.float32) / 255.0 + + +# ───────────────────────────── maps ───────────────────────────── + +def value_noise(rng, w, h, scale): + import numpy as np + lat = rng.random((int(h / scale) + 3, int(w / scale) + 3)) + xs, ys = np.arange(w) / scale, np.arange(h) / scale + ix, iy = xs.astype(int), ys.astype(int) + fx, fy = xs - ix, ys - iy + fx, fy = fx * fx * (3 - 2 * fx), fy * fy * (3 - 2 * fy) + top = lat[iy][:, ix] * (1 - fx) + lat[iy][:, ix + 1] * fx + bot = lat[iy + 1][:, ix] * (1 - fx) + lat[iy + 1][:, ix + 1] * fx + return top * (1 - fy)[:, None] + bot * fy[:, None] + + +def write_png(path, rgb): + """Atomic: the shell may be reading the previous maps while these are written. + RGB without alpha, so Qt does not premultiply the numbers.""" + from PIL import Image + tmp = f"{path}.{os.getpid()}.tmp.png" + Image.fromarray(rgb, "RGB").save(tmp) + os.replace(tmp, path) + + +def build(img, force=False): + """Bake IMG's maps; returns (field, line) or None when it has no clear subject.""" + import fcntl + os.makedirs(CACHE, exist_ok=True) + base = os.path.join(CACHE, key(img)) + with open(base + ".lock", "w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) # one bake per image at a time + if not force: + hit = cached(img) + if hit is not None: + return hit or None + import cv2 + import numpy as np + from PIL import Image + + im = Image.open(img).convert("RGB") + im.thumbnail((MAP_MAX, MAP_MAX)) + mask_path = base + "-mask.png" # the slow part; kept across --force + if os.path.exists(mask_path): + m = np.asarray(Image.open(mask_path).convert("L").resize(im.size), np.float32) / 255.0 + else: + m = mask_of(im) + Image.fromarray((m * 255).astype(np.uint8)).save(mask_path) + h, w = m.shape + b = (m > 0.5).astype(np.uint8) + # Specks of foreground would be outlined as dots all over the screen. + n, lab, stats, _ = cv2.connectedComponentsWithStats(b, connectivity=8) + keep = np.zeros(n, bool) + keep[1:] = stats[1:, cv2.CC_STAT_AREA] >= 0.002 * w * h + b = keep[lab].astype(np.uint8) + cover = float(b.mean()) + unsure = float(((m > 0.1) & (m < 0.9)).mean()) + # A subject takes part of the picture, not nearly all of it nor a crumb, + # and the model is sure where it ends. + ok = 0.008 <= cover <= 0.72 and unsure <= 0.06 + meta = {"img": img, "ok": ok, "cover": round(cover, 3), "unsure": round(unsure, 3)} + if ok: + din = cv2.distanceTransform(b, cv2.DIST_L2, 5) + dout = cv2.distanceTransform(1 - b, cv2.DIST_L2, 5) + sd = dout - din # > 0 outside + inner = np.clip(din / max(float(np.percentile(din[b > 0], 99)), 1.0), 0, 1) + + # Outside order: distance from the subject, bent by noise so the front + # is not a plain offset of the silhouette, then ranked by area. + rng = np.random.default_rng(int(key(img)[:8], 16)) + noise = 0.6 * value_noise(rng, w, h, w / 9.0) + 0.4 * value_noise(rng, w, h, w / 28.0) + warped = dout * (0.75 + 0.5 * noise) + noise * 0.08 * max(w, h) + outside = b == 0 + order = np.zeros((h, w), np.float32) + vals = warped[outside] + rank = np.empty(vals.size) + rank[np.argsort(vals, kind="stable")] = np.arange(vals.size) + order[outside] = rank / max(vals.size - 1, 1) + order = cv2.GaussianBlur(order, (0, 0), 4.0) + + # Along the outline: each contour starts at its top point, drawn by two + # pens going round in opposite directions that meet on the far side. + edge = np.zeros((h, w), np.uint8) + param = np.zeros((h, w), np.float32) + contours, _ = cv2.findContours(b, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) + for c in contours: + if len(c) < 40 or abs(cv2.contourArea(c)) < 0.0008 * w * h: + continue # tiny holes get no line + c = c[:, 0, :] + seg = np.sqrt((np.diff(c, axis=0, append=c[:1]) ** 2).sum(1)) + s = np.concatenate([[0], np.cumsum(seg)[:-1]]) + total = s[-1] + seg[-1] + s = (s - s[np.argmin(c[:, 1])]) % total + p = np.minimum(s, total - s) / (total / 2) + # Where the subject runs off the picture its contour follows the + # border: that is not an outline. + p[(c[:, 0] <= 1) | (c[:, 0] >= w - 2) | (c[:, 1] <= 1) | (c[:, 1] >= h - 2)] = -1 + edge[c[:, 1], c[:, 0]] = 1 + param[c[:, 1], c[:, 0]] = p + line = np.zeros((h, w), np.uint8) + if edge.any(): + _, labels = cv2.distanceTransformWithLabels(1 - edge, cv2.DIST_L2, 5, + labelType=cv2.DIST_LABEL_PIXEL) + ys, xs = np.nonzero(edge) + table = np.concatenate([[0], param[ys, xs]]) + near = np.abs(sd) < SD_RANGE + v = table[labels[near]] + line[near] = np.where(v < 0, 0, np.clip(v * 255, 1, 255)).astype(np.uint8) + + field = np.zeros((h, w, 3), np.uint8) + field[..., 0] = np.clip(inner * 255, 0, 255) + field[..., 1] = np.clip((sd + SD_RANGE) / (2 * SD_RANGE) * 255, 0, 255) + q = np.clip(order * 65535.0 + 0.5, 0, 65535).astype(np.uint16) + lines = np.zeros((h, w, 3), np.uint8) + lines[..., 0] = line + lines[..., 1] = q >> 8 + lines[..., 2] = q & 255 + write_png(base + "-field.png", field) + write_png(base + "-line.png", lines) + tmp = f"{base}.json.{os.getpid()}.tmp" + with open(tmp, "w") as f: + json.dump(meta, f) + os.replace(tmp, base + ".json") + return (base + "-field.png", base + "-line.png") if ok else None + + +def warm(paths): + import fcntl + os.makedirs(CACHE, exist_ok=True) + with open(os.path.join(CACHE, ".warm.lock"), "w") as lock: + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + return # another warm is already on it + for path in paths: + if not path.lower().endswith(EXTS) or not os.path.isfile(path): + continue + try: + if cached(path) is None: + r = build(path) + print(("outline " if r else "colonies ") + path, file=sys.stderr, flush=True) + except Exception as e: # one bad file must not stop the rest + print(f"error {path}: {e}", file=sys.stderr, flush=True) + + +def main(argv): + if len(argv) < 2 or argv[0] not in ("choose", "warm", "outline"): + print(__doc__, file=sys.stderr) + return 2 + cmd, rest = argv[0], argv[1:] + if cmd == "choose": + try: + hit = cached(rest[0]) + except OSError: + hit = False + if hit: + out = {"kind": "outline", "field": hit[0], "line": hit[1]} + else: + out = {"kind": "colonies", "pending": hit is None and bool(MODEL)} + elif not MODEL or not os.path.exists(MODEL): + print("wallfx: GLASSMXRPH_WALLFX_MODEL is not set or missing", file=sys.stderr) + return 1 + elif cmd == "warm": + warm(rest) + return 0 + else: + r = build(rest[0], force="--force" in rest) + out = {"kind": "outline", "field": r[0], "line": r[1]} if r else {"kind": "colonies"} + print(json.dumps(out)) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/quickshell/services/ConfigLogic.js b/quickshell/services/ConfigLogic.js index 02d45a9..904d2aa 100644 --- a/quickshell/services/ConfigLogic.js +++ b/quickshell/services/ConfigLogic.js @@ -96,6 +96,7 @@ function validate(c) { if(!Number.isInteger(c.metrics.interval) || c.metrics.interval<1 || c.metrics.interval>30)throw Error("Invalid metrics geometry or interval"); if(!Array.isArray(c.metrics.storagePaths) || c.metrics.storagePaths.length>8 || c.metrics.storagePaths.some(p=>typeof p!=="string" || !p.startsWith("/") || p.includes("\u0000")) || new Set(c.metrics.storagePaths).size!==c.metrics.storagePaths.length || typeof c.metrics.networkInterface!=="string" || !c.metrics.networkInterface || typeof c.metrics.gpu!=="string" || !c.metrics.gpu)throw Error("Invalid metrics sources"); if(!Array.isArray(c.wallpaper.history) || c.wallpaper.history.length>50 || c.wallpaper.history.some(p=>typeof p!=="string"))throw Error("Invalid wallpaper history"); + if(!Array.isArray(c.wallpaper.outlineExclude) || c.wallpaper.outlineExclude.some(p=>typeof p!=="string"))throw Error("Invalid wallpaper outline exclusions"); if(typeof c.hyprglass.enabled!=="boolean" || typeof c.hyprglass.layers!=="boolean" || typeof c.hyprglass.effectEnabled!=="boolean")throw Error("Invalid glass toggle"); for(const [key,min,max] of [["blur_strength",0,5],["blur_iterations",1,5],["refraction_strength",0,8],["chromatic_aberration",0,1],["fresnel_strength",0,1],["specular_strength",0,1],["edge_thickness",0,.15],["lens_distortion",0,1],["brightness",.2,2],["contrast",.2,2],["saturation",0,2],["vibrancy",0,1],["adaptive_dim",0,1]])if(!Number.isFinite(c.hyprglass.values[key]) || c.hyprglass.values[key]max)throw Error("Invalid glass "+key); if(!Number.isInteger(c.hyprglass.values.blur_iterations))throw Error("Invalid blur passes"); diff --git a/quickshell/services/WallpaperService.qml b/quickshell/services/WallpaperService.qml index 5382d50..d3768d9 100644 --- a/quickshell/services/WallpaperService.qml +++ b/quickshell/services/WallpaperService.qml @@ -53,6 +53,7 @@ Singleton { if (!ConfigService.ready || !ConfigService.writable || !outputs.length || !outputs[0] || busy) return false; error = ""; + prepareTransition(path); // Native rendering needs no provider round trip: decode once, then switch // every output in one write so their transitions start together. if (backend === "native" && ["native", "auto"].includes(ConfigService.data.wallpaper.backend)) { @@ -106,6 +107,7 @@ Singleton { onFinished: (request, result) => { if (result.ok) { root.images = result.images; + root.warmOutlines(result.images.map(image => image.path)); root.notice = (result.notice || "") + (result.limited ? " Showing the first 1,000 images." : ""); } else root.error = result.error; @@ -144,6 +146,76 @@ Singleton { ConfigService.setValue("wallpaper.history",[result.path].concat(ConfigService.data.wallpaper.history.filter(p=>p!==result.path)).slice(0,50)); Qt.callLater(root.applyNext); } + // Which change a wallpaper gets (wallpaper/shaders/transition.frag): its + // subject's outline when helpers/wallfx.py has cached maps for it, colonies + // otherwise. Nothing waits for a cut-out: an unprocessed wallpaper gets + // colonies now and is processed in the background for next time. The + // package sets GLASSMXRPH_WALLFX_PYTHON (numpy, opencv, onnxruntime) and + // GLASSMXRPH_WALLFX_MODEL; without them every change is colonies. + readonly property string wallfxPython: Quickshell.env("GLASSMXRPH_WALLFX_PYTHON") || "" + readonly property bool outlinesAvailable: wallfxPython !== "" && (Quickshell.env("GLASSMXRPH_WALLFX_MODEL") || "") !== "" + property var transitions: ({}) // path -> {kind, field, line} + property var choosing: [] + function setTransition(path, plan) { + const next = Object.assign({}, transitions); + next[path] = plan; + transitions = next; + } + // `ifUnknown`: keep an answer already given in this change (the picker asks + // at apply time, every output's background asks again when it switches). + function prepareTransition(path, ifUnknown) { + if (!path || choosing.includes(path) || (ifUnknown && path in transitions)) + return; + const excluded = ConfigService.ready && ConfigService.data.wallpaper.outlineExclude.includes(path); + if (!outlinesAvailable || excluded) + return setTransition(path, {kind: "colonies"}); + const next = Object.assign({}, transitions); + delete next[path]; + transitions = next; + choosing = choosing.concat([path]); + chooseNext(); + } + function chooseNext() { + if (chooseJob.running || !choosing.length) + return; + chooseJob.path = choosing[0]; + chooseJob.command = [wallfxPython, Quickshell.shellPath("helpers/wallfx.py"), "choose", choosing[0]]; + chooseJob.running = true; + } + function warmOutlines(paths) { + if (!outlinesAvailable || warmJob.running || !paths.length) + return; + warmJob.command = ["nice", "-n", "15", wallfxPython, Quickshell.shellPath("helpers/wallfx.py"), "warm"].concat(paths); + warmJob.running = true; + } + // Session libraries on LD_LIBRARY_PATH (JACK, SANE) can be built against + // another glibc than the helper's interpreter: keep them out. + Process { + id: chooseJob + property string path: "" + environment: ({LD_LIBRARY_PATH: null}) + stdout: StdioCollector { + id: chooseOutput + } + onExited: { + let plan = {kind: "colonies"}; + try { + plan = JSON.parse(chooseOutput.text); + } catch (error) {} + const path = chooseJob.path; + root.choosing = root.choosing.filter(p => p !== path); + root.setTransition(path, plan); + if (plan.pending) + root.warmOutlines([path]); + Qt.callLater(root.chooseNext); + } + } + // Processes uncached wallpapers at low priority (~5 s each on the CPU); + // one pass at a time, and the helper skips what is already cached. + Process { + id: warmJob + environment: ({LD_LIBRARY_PATH: null}) + } // Native backgrounds report when their new image has decoded; the reveal // starts on every output together once all of them are ready. property var revealWaiting: ({}) diff --git a/quickshell/wallpaper/WallpaperBackground.qml b/quickshell/wallpaper/WallpaperBackground.qml index 34053ae..752e26c 100644 --- a/quickshell/wallpaper/WallpaperBackground.qml +++ b/quickshell/wallpaper/WallpaperBackground.qml @@ -15,8 +15,9 @@ PanelWindow { WlrLayershell.layer:WlrLayer.Background WlrLayershell.namespace:"glassMxrph-wallpaper" mask:Region {} - readonly property string target:ConfigService.ready && ConfigService.data.wallpaper.byMonitor[root.modelData.name] ? "file://"+encodeURI(ConfigService.data.wallpaper.byMonitor[root.modelData.name]).replace(/#/g,"%23").replace(/\?/g,"%3F") : "" - // 0..1 while colonies of the new wallpaper eat through the old one. + readonly property string targetPath:ConfigService.ready ? (ConfigService.data.wallpaper.byMonitor[root.modelData.name] || "") : "" + readonly property string target:targetPath ? "file://"+encodeURI(targetPath).replace(/#/g,"%23").replace(/\?/g,"%3F") : "" + // 0..1 while the new wallpaper takes over (shaders/transition.frag). property real progress:0 readonly property bool transitioning:incoming.source.toString()!=="" // The first wallpaper (and reduced motion) appears directly; later changes @@ -24,7 +25,12 @@ PanelWindow { onTargetChanged:{ if(!shown.source.toString() || Theme.duration===0) {reveal.stop();incoming.source="";shown.source=target;} else if(target===shown.source.toString()) {reveal.stop();incoming.source="";} - else {reveal.stop();progress=0;WallpaperService.revealLoading(modelData.name);incoming.source=target;} + else { + reveal.stop();progress=0;reported=false; + WallpaperService.revealLoading(modelData.name); + WallpaperService.prepareTransition(targetPath,true); + incomingPath=targetPath;incoming.source=target; + } } Component.onCompleted:shown.source=target function settle() { @@ -40,8 +46,8 @@ PanelWindow { // Drop the overlay only once the base layer shows the new image. onStatusChanged:root.settle() } - // The incoming image is only a texture: the colonies shader draws the - // change over `shown` (shaders/colonies.frag). + // The incoming image and the outline maps are only textures: the shader + // draws the change over `shown`. Image { id:incoming visible:false @@ -49,10 +55,43 @@ PanelWindow { asynchronous:true fillMode:Image.PreserveAspectCrop onStatusChanged:{ - if(status===Image.Ready && source.toString())WallpaperService.revealReady(root.modelData.name); - else if(status===Image.Error)incoming.source=""; + if(status===Image.Error)incoming.source=""; + else root.reportIfReady(); } } + // The outline plan for the incoming wallpaper (WallpaperService), once known. + property string incomingPath:"" + readonly property var plan:root.transitioning ? WallpaperService.transitions[root.incomingPath] : undefined + readonly property bool wantsOutline:!!root.plan && root.plan.kind==="outline" + readonly property bool outlineReady:root.wantsOutline && fieldMap.status===Image.Ready && lineMap.status===Image.Ready + // Settled: colonies, outline maps loaded, or maps that failed (colonies then). + readonly property bool planSettled:root.plan!==undefined && (!root.wantsOutline || root.outlineReady + || fieldMap.status===Image.Error || lineMap.status===Image.Error) + onPlanSettledChanged:reportIfReady() + property bool reported:false + // Ready once the image is decoded and the plan settled. The service's + // fallback starts the change anyway if this takes too long; it then uses + // colonies unless the maps happen to be in. + function reportIfReady() { + if(reported || incoming.status!==Image.Ready || !incoming.source.toString() || !planSettled)return; + reported=true; + WallpaperService.revealReady(root.modelData.name); + } + // Maps hold numbers, not colours, at their own size; the shader interpolates. + Image { + id:fieldMap + visible:false + asynchronous:true + cache:false + source:root.wantsOutline ? "file://"+root.plan.field : "" + } + Image { + id:lineMap + visible:false + asynchronous:true + cache:false + source:root.wantsOutline ? "file://"+root.plan.line : "" + } // PreserveAspectCrop decodes to cover the output, so the texture can be // larger than the item on one axis: sample its centred window. function crop(img) { @@ -75,17 +114,30 @@ PanelWindow { property vector4d cropOld:root.crop(shown) property vector4d cropNew:root.crop(incoming) property color ember:root.ember - fragmentShader:Qt.resolvedUrl("shaders/colonies.frag.qsb") + property color ink:Theme.text + property real mode:root.mode + // Unused in colonies mode, but every sampler needs a texture. + property var fieldTex:root.outlineReady ? fieldMap : incoming + property var lineTex:root.outlineReady ? lineMap : incoming + property real fw:Math.max(fieldMap.implicitWidth,1) + property real fh:Math.max(fieldMap.implicitHeight,1) + property real lineW:1.5 + property real sdRange:16 + fragmentShader:Qt.resolvedUrl("shaders/transition.frag.qsb") } // Captured when a change starts, so the burn keeps its colour even if the // palette regenerates from the new wallpaper halfway through. property real seed:0 property color ember:Theme.accentVivid + property real mode:0 Connections { target:WallpaperService function onRevealSerialChanged() { if(incoming.status===Image.Ready && incoming.source.toString() && !reveal.running && root.progress===0) { - root.seed=Math.random()*100;root.ember=Theme.accentVivid;reveal.restart(); + root.seed=Math.random()*100;root.ember=Theme.accentVivid; + root.mode=root.outlineReady ? 1 : 0; + reveal.duration=root.mode ? 2000 : 1800; + reveal.restart(); } } } @@ -93,8 +145,7 @@ PanelWindow { id:reveal target:root;property:"progress" from:0;to:1 - // Linear time: the shader eases its own fronts. - duration:1800 + // Linear time: the shader eases its own phases. Set per change. easing.type:Easing.Linear onFinished:{shown.source=incoming.source;Qt.callLater(root.settle);} } diff --git a/quickshell/wallpaper/shaders/colonies.frag.qsb b/quickshell/wallpaper/shaders/colonies.frag.qsb deleted file mode 100644 index d3440dc..0000000 Binary files a/quickshell/wallpaper/shaders/colonies.frag.qsb and /dev/null differ diff --git a/quickshell/wallpaper/shaders/colonies.frag b/quickshell/wallpaper/shaders/transition.frag similarity index 53% rename from quickshell/wallpaper/shaders/colonies.frag rename to quickshell/wallpaper/shaders/transition.frag index e3e9c4a..7c984fd 100644 --- a/quickshell/wallpaper/shaders/colonies.frag +++ b/quickshell/wallpaper/shaders/transition.frag @@ -1,12 +1,20 @@ #version 440 -// Wallpaper change: colonies of the new wallpaper land at a few places and -// moments and eat through the old one in crisp pixel cells, along organic, -// noise-warped fronts. Each cell that has just flipped burns for an instant in -// the accent colour, a thin glow rides the front, and now and then a spark -// jumps ahead of it. Everything is procedural: `seed` makes every change differ. -// Extra effects scale with sin(pi*t), so t=0 is exactly the old wallpaper and +// Wallpaper change, two kinds, both in crisp pixel cells: +// +// COLONIES (mode 0), any wallpaper: colonies of the new wallpaper land at a +// few places and moments and eat through the old one along noise-warped +// fronts. Each flipped cell burns for an instant in the accent colour, a thin +// glow rides the front, and now and then a spark jumps ahead. Procedural: +// `seed` makes every change differ. +// +// OUTLINE (mode 1), a wallpaper with a clear subject: the old wallpaper steps +// back, a thin line draws the subject's outline (two pens from its top), the +// subject fills in from that outline, and the rest of the picture grows out +// of it. The maps come from helpers/wallfx.py, in the new image's space. +// +// Extra effects vanish at both ends, so t=0 is exactly the old wallpaper and // t=1 exactly the new one. -// Rebuild colonies.frag.qsb with scripts/build-shaders after editing. +// Rebuild transition.frag.qsb with scripts/build-shaders after editing. layout(location = 0) in vec2 qt_TexCoord0; layout(location = 0) out vec4 fragColor; @@ -14,17 +22,25 @@ layout(std140, binding = 0) uniform buf { mat4 qt_Matrix; float qt_Opacity; float t; // 0..1, linear in time + float mode; // 0 colonies, 1 outline float sw; // item size, px float sh; float cell; // cell size, px float glow; // 0..1, strength of the burn and the front glow float seed; + float fw; // fieldTex / lineTex size, texels (outline only) + float fh; + float lineW; // outline width, px + float sdRange; // fieldTex G spans +-sdRange map px vec4 cropOld; // texture uv = xy + item uv * zw (PreserveAspectCrop) vec4 cropNew; - vec4 ember; + vec4 ember; // accent: the colonies' burning edge + vec4 ink; // light tone: the outline's line }; layout(binding = 1) uniform sampler2D oldTex; layout(binding = 2) uniform sampler2D newTex; +layout(binding = 3) uniform sampler2D fieldTex; +layout(binding = 4) uniform sampler2D lineTex; const float PI = 3.14159265; const int COLS = 3; // seeds are stratified on a COLS x ROWS grid, so @@ -89,10 +105,11 @@ float arrivalAt(vec2 c) { } vec3 oldAt(vec2 uv) { return texture(oldTex, cropOld.xy + uv * cropOld.zw).rgb; } -vec3 newAt(vec2 uv, float zoom) { return texture(newTex, cropNew.xy + (0.5 + (uv - 0.5) / zoom) * cropNew.zw).rgb; } +vec2 newUv(vec2 uv, float zoom) { return cropNew.xy + (0.5 + (uv - 0.5) / zoom) * cropNew.zw; } +vec3 newAt(vec2 uv, float zoom) { return texture(newTex, newUv(uv, zoom)).rgb; } +float luma(vec3 c) { return dot(c, vec3(0.299, 0.587, 0.114)); } -void main() { - vec2 uv = qt_TexCoord0; +vec3 colonies(vec2 uv) { float energy = sin(PI * t); float span = maxArrival(); float T = areaToArrival(escena(t)) * (span + LIFE + 0.01) - 0.01; @@ -114,7 +131,61 @@ void main() { float burn = (1.0 - life) * (1.0 - life) * (edge ? 1.0 : 0.55); c = mix(c, hot, burn * (0.55 + 0.45 * flick) * 0.85 * glow); } - c += ember.rgb * 0.22 * glow * energy * exp(-abs(a - T) / 0.012); - if (t >= 1.0) c = newAt(uv, 1.0); + return c + ember.rgb * 0.22 * glow * energy * exp(-abs(a - T) / 0.012); +} + +// 16-bit order in lineTex G (high) and B (low), interpolated by hand: the +// sampler's bilinear filter would blend the two bytes separately. +float order16(vec2 texel) { + texel = clamp(texel, vec2(0.0), vec2(fw, fh) - 1.0); + vec4 f = texture(lineTex, (texel + 0.5) / vec2(fw, fh)); + return (floor(f.g * 255.0 + 0.5) * 256.0 + floor(f.b * 255.0 + 0.5)) / 65535.0; +} +float orderAt(vec2 tuv) { + vec2 p = tuv * vec2(fw, fh) - 0.5; + vec2 i = floor(p), f = p - i; + return mix(mix(order16(i), order16(i + vec2(1.0, 0.0)), f.x), + mix(order16(i + vec2(0.0, 1.0)), order16(i + vec2(1.0, 1.0)), f.x), f.y); +} + +vec3 outline(vec2 uv) { + // The subject settles from a touch closer than its background: a little depth. + float zIn = 1.0 + 0.03 * (1.0 - escena(t)); + float zOut = 1.0 + 0.015 * (1.0 - escena(t)); + vec4 f = texture(fieldTex, newUv(uv, zIn)); + float sdPx = (f.g * 2.0 - 1.0) * sdRange * sw * zIn / (fw * cropNew.z); // screen px, > 0 outside + float aa = max(fwidth(sdPx), 1e-3); + float inside = clamp(0.5 - sdPx / aa, 0.0, 1.0); + + // The old wallpaper steps back: a fifth darker, a quarter greyer. + float back = escena(t / 0.18) * (1.0 - escena((t - 0.85) / 0.15)); + vec3 st = oldAt(uv); + st = mix(st, vec3(luma(st)), 0.25 * back) * (1.0 - 0.2 * back); + + // Fronts decide per cell centre, so they are crisp and stepped; the + // silhouette itself stays smooth. + vec2 grid = vec2(sw, sh) / cell; + vec2 cuv = (floor(uv * grid) + 0.5) / grid; + float Ti = escena((t - 0.32) / 0.32) * 1.02 - 0.01; // fill, once the line is nearly drawn + vec3 cIn = texture(fieldTex, newUv(cuv, zIn)).r <= Ti ? newAt(uv, zIn) : st; + float To = escena((t - 0.45) / 0.50) * 1.02 - 0.01; // then the world grows out of it + vec3 cOut = orderAt(newUv(cuv, zOut)) <= To ? newAt(uv, zOut) : st; + vec3 c = mix(cOut, cIn, inside); + + // The line: thin and quiet, drawn by two pens from the top of every + // contour, gone once the subject is in. + float drawn = escena((t - 0.02) / 0.33); + float lp = texture(lineTex, newUv(uv, zIn)).r; + float fade = 1.0 - escena((t - 0.45) / 0.25); + if (lp > 0.0 && lp <= drawn && fade > 0.0) { + float core = clamp(0.5 - (abs(sdPx) - lineW * 0.5) / aa, 0.0, 1.0); + c = mix(c, ink.rgb, core * 0.75 * fade); + } + return c; +} + +void main() { + vec2 uv = qt_TexCoord0; + vec3 c = t >= 1.0 ? newAt(uv, 1.0) : (mode < 0.5 ? colonies(uv) : outline(uv)); fragColor = vec4(clamp(c, 0.0, 1.0), 1.0) * qt_Opacity; } diff --git a/quickshell/wallpaper/shaders/transition.frag.qsb b/quickshell/wallpaper/shaders/transition.frag.qsb new file mode 100644 index 0000000..0422f2c Binary files /dev/null and b/quickshell/wallpaper/shaders/transition.frag.qsb differ