darkly 0.5.0

A GPU-native paint engine on wgpu: brushes, layers, blend modes, masks, selections, and undo.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
use crate::coord::CanvasRect;
use crate::gpu::blend_mode::{self, BlendModeRegistration};
use crate::gpu::params::ParamValue;

slotmap::new_key_type! {
    /// Unique identifier for any node, group, or filter in a [`Document`].
    /// Backed by a slotmap key — generational, so stale ids return `None` from
    /// [`Document`] lookups instead of aliasing onto a recycled slot.
    ///
    /// At the WASM/JS boundary, marshal as `u64` via [`LayerId::to_ffi`] /
    /// [`LayerId::from_ffi`].
    ///
    /// [`Document`]: crate::document::Document
    pub struct LayerId;
}

impl LayerId {
    /// Pack into a `u64` for the WASM/JS boundary. Index in the low 32 bits,
    /// generation in the high 32. Round-trips losslessly through
    /// [`LayerId::from_ffi`].
    pub fn to_ffi(self) -> u64 {
        slotmap::Key::data(&self).as_ffi()
    }

    /// Unpack a `u64` previously produced by [`LayerId::to_ffi`]. The result
    /// is only meaningful within the [`Document`] that minted the original key.
    ///
    /// [`Document`]: crate::document::Document
    pub fn from_ffi(v: u64) -> Self {
        slotmap::KeyData::from_ffi(v).into()
    }
}

/// Properties shared by every node in the tree — raster layers, groups, and
/// filters. Lock prevents any mutation; lives on every node by construction
/// so the universal check is one line at every mutation entry point.
pub struct NodeCommon {
    pub name: String,
    pub visible: bool,
    pub locked: bool,
}

impl NodeCommon {
    pub fn new(name: String) -> Self {
        NodeCommon {
            name,
            visible: true,
            locked: false,
        }
    }
}

/// Compositing properties for nodes that participate in normal blending
/// (raster layers and groups). Filters don't have one — masks structurally
/// have no opacity or blend mode.
///
/// `blend_mode` is a registry reference, not an enum: `type_id` is the
/// identity (used by the wire format, undo, and `set_blend_mode`), and
/// `gpu_value` is the integer the composite shader switches on. There is no
/// parallel enum representation — registry-resolved registrations are the
/// only carrier.
pub struct BlendProps {
    pub opacity: f32,
    pub blend_mode: &'static BlendModeRegistration,
}

impl BlendProps {
    pub fn new() -> Self {
        BlendProps {
            opacity: 1.0,
            blend_mode: blend_mode::registry().default(),
        }
    }
}

impl Default for BlendProps {
    fn default() -> Self {
        Self::new()
    }
}

/// Pixel-storage metadata for any node holding GPU pixels (raster layers, mask
/// filters, future filter caches). Bulk pixel data is GPU-authoritative; this
/// struct only carries canvas-space metadata: extent and texture format.
///
/// Every `PixelBuffer` is sampled independently — the blend shader computes UV
/// from each buffer's own bounds. Lockstep growth (host + non-locked mask grow
/// together) is a document-side convenience that drops out for free when both
/// buffers receive the same rasterized transform.
pub struct PixelBuffer {
    pub bounds: CanvasRect,
    pub format: wgpu::TextureFormat,
}

impl PixelBuffer {
    pub fn new(bounds: CanvasRect, format: wgpu::TextureFormat) -> Self {
        PixelBuffer { bounds, format }
    }
}

/// A raster (pixel) layer.
pub struct RasterLayer {
    pub id: LayerId,
    pub common: NodeCommon,
    pub blend: BlendProps,
    pub pixels: PixelBuffer,
    /// Filters attached to this layer, in bottom-up order. Each entry is a
    /// [`LayerId`] resolvable in the owning [`Document`]'s entity store.
    ///
    /// [`Document`]: crate::document::Document
    pub filters: Vec<LayerId>,
}

impl RasterLayer {
    /// Construct a raster layer. `name` is the display name shown in the
    /// layer panel — owners (the [`Document`]) supply a sequential
    /// "Layer N" string rather than letting each constructor invent one
    /// from the slotmap key, which would surface raw ffi values like
    /// "Layer 4294967301" to the user.
    pub fn new(id: LayerId, bounds: CanvasRect, name: String) -> Self {
        RasterLayer {
            id,
            common: NodeCommon::new(name),
            blend: BlendProps::new(),
            pixels: PixelBuffer::new(bounds, wgpu::TextureFormat::Rgba8Unorm),
            filters: Vec::new(),
        }
    }
}

/// A void (procedural) layer. Generates its pixels from a GPU shader instead
/// of storing them — see [`crate::gpu::void::Void`] for the trait + registry,
/// and the README's "Voids" section for the user-facing concept.
///
/// Void state is exactly: a [`crate::gpu::void::VoidRegistration::type_id`]
/// string identifying which procedural kind to run, plus the parameter
/// values for that kind. There is no pixel buffer — the compositor allocates
/// a derived texture on demand and re-renders it from these inputs.
pub struct VoidLayer {
    pub id: LayerId,
    pub common: NodeCommon,
    pub blend: BlendProps,
    /// Which void type from [`crate::gpu::void::VoidRegistry`] this layer
    /// runs. Stable string id (e.g. `"noise"`), not a registration pointer:
    /// the registry is a process-global and the document must survive
    /// serialization without holding live pointers.
    pub void_type: String,
    /// Parameter values matching the void type's
    /// [`crate::gpu::void::ParamDef`] schema, in order.
    pub params: Vec<ParamValue>,
    /// User transform (pan / scale / rotate) applied to the void's output,
    /// edited by the generic transform gizmo. Persistent / undoable /
    /// serializable document state. Voids that don't opt into live transform
    /// (see [`crate::gpu::void::VoidRegistration::supports_live_transform`])
    /// simply leave this at identity. Default `Basic(IDENTITY)`.
    pub transform: crate::transform::Transform,
    pub filters: Vec<LayerId>,
    /// Optional persistent frame snapshot. Most voids leave this `None`
    /// (their output is purely procedural — replays from params). The
    /// camera void uses it to round-trip the last received webcam frame
    /// through save/load so reopening a `.darkly` doesn't show a black
    /// rectangle until permission is regranted. When set, the save flow
    /// readbacks the void's aux texture into a pixel blob keyed
    /// `"layers/<id>.pixels"`, and the load flow restores it via
    /// [`crate::gpu::compositor::Compositor::restore_void_pixels`].
    pub frame: Option<crate::format::manifest::ManifestPixelRef>,
}

impl VoidLayer {
    pub fn new(id: LayerId, name: String, void_type: String, params: Vec<ParamValue>) -> Self {
        VoidLayer {
            id,
            common: NodeCommon::new(name),
            blend: BlendProps::new(),
            void_type,
            params,
            transform: crate::transform::Transform::identity(),
            filters: Vec::new(),
            frame: None,
        }
    }
}

/// A filter layer — a non-destructive procedural *transform* in the layer
/// tree. Where a [`VoidLayer`] is a procedural *source* (it generates pixels),
/// a filter layer transforms the composite of everything below it in place
/// (the group accumulator), leaving the lower layers' own pixels untouched.
/// This is Krita's *adjustment layer*. Scope it to one layer by placing it in a
/// non-passthrough (isolated) group.
///
/// State is exactly: a `pipeline` id naming which
/// [`crate::gpu::filter::FilterPipelineRegistry`] transform to run (e.g.
/// `"invert"`), plus that transform's parameter values. There is no pixel
/// buffer — the compositor runs the shared filter pipeline over the running
/// accumulator each frame.
pub struct FilterLayer {
    pub id: LayerId,
    pub common: NodeCommon,
    pub blend: BlendProps,
    /// Stable `type_id` from [`crate::gpu::filter::FilterPipelineRegistry`]
    /// (e.g. `"invert"`). Named `pipeline` rather than `filter_type` because
    /// `filters` (below) already means the attached mask/selection list — two
    /// "filter" fields on one struct would be a footgun.
    pub pipeline: String,
    /// Parameter values matching the filter pipeline's schema, in order. Empty
    /// for parameter-free filters like invert.
    pub params: Vec<ParamValue>,
    /// Attached mask / selection filters (same polymorphic list every layer
    /// kind carries).
    pub filters: Vec<LayerId>,
}

impl FilterLayer {
    pub fn new(id: LayerId, name: String, pipeline: String, params: Vec<ParamValue>) -> Self {
        FilterLayer {
            id,
            common: NodeCommon::new(name),
            blend: BlendProps::new(),
            pipeline,
            params,
            filters: Vec::new(),
        }
    }
}

pub struct LayerGroup {
    pub id: LayerId,
    pub common: NodeCommon,
    pub blend: BlendProps,
    /// Child node ids in display order (bottom-to-top). Resolve via the owning
    /// [`Document`]'s entity store.
    ///
    /// [`Document`]: crate::document::Document
    pub children: Vec<LayerId>,
    pub filters: Vec<LayerId>,
    /// True = passthrough (default), false = normal isolated group.
    pub passthrough: bool,
    /// UI state: whether the group is visually collapsed in the layer panel.
    pub collapsed: bool,
}

impl LayerGroup {
    /// Construct a group. `name` is the display name; same rationale as
    /// [`RasterLayer::new`] — owners pass a sequential string.
    pub fn new(id: LayerId, name: String) -> Self {
        LayerGroup {
            id,
            common: NodeCommon::new(name),
            blend: BlendProps::new(),
            children: Vec::new(),
            filters: Vec::new(),
            passthrough: true,
            collapsed: false,
        }
    }
}

/// A node in the layer tree — either a leaf layer or a group containing children.
/// Filters are NOT [`LayerNode`]s; they live on a host's `filters` list as
/// [`LayerId`] references and are resolved through the owning [`Document`].
///
/// [`Document`]: crate::document::Document
pub enum LayerNode {
    Layer(Layer),
    Group(LayerGroup),
}

impl LayerNode {
    pub fn id(&self) -> LayerId {
        match self {
            LayerNode::Layer(l) => l.id(),
            LayerNode::Group(g) => g.id,
        }
    }

    pub fn common(&self) -> &NodeCommon {
        match self {
            LayerNode::Layer(l) => l.common(),
            LayerNode::Group(g) => &g.common,
        }
    }

    pub fn common_mut(&mut self) -> &mut NodeCommon {
        match self {
            LayerNode::Layer(l) => l.common_mut(),
            LayerNode::Group(g) => &mut g.common,
        }
    }

    pub fn blend(&self) -> &BlendProps {
        match self {
            LayerNode::Layer(l) => l.blend(),
            LayerNode::Group(g) => &g.blend,
        }
    }

    pub fn blend_mut(&mut self) -> &mut BlendProps {
        match self {
            LayerNode::Layer(l) => l.blend_mut(),
            LayerNode::Group(g) => &mut g.blend,
        }
    }

    pub fn filters(&self) -> &[LayerId] {
        match self {
            LayerNode::Layer(l) => l.filters(),
            LayerNode::Group(g) => &g.filters,
        }
    }

    pub fn modifiers_mut(&mut self) -> &mut Vec<LayerId> {
        match self {
            LayerNode::Layer(l) => l.modifiers_mut(),
            LayerNode::Group(g) => &mut g.filters,
        }
    }

    pub fn pixels(&self) -> Option<&PixelBuffer> {
        match self {
            LayerNode::Layer(l) => l.pixels(),
            LayerNode::Group(_) => None,
        }
    }

    pub fn pixels_mut(&mut self) -> Option<&mut PixelBuffer> {
        match self {
            LayerNode::Layer(l) => l.pixels_mut(),
            LayerNode::Group(_) => None,
        }
    }

    pub fn visible(&self) -> bool {
        self.common().visible
    }

    pub fn locked(&self) -> bool {
        self.common().locked
    }

    /// The registration record for this node's kind — owns `type_id` (wire
    /// format), `display_name` (UI), and any future per-kind metadata. The
    /// match arms reference each kind module's own `TYPE_ID` constant rather
    /// than re-typing the string literal, so there is no parallel name to
    /// keep in sync with the registration files.
    pub fn kind(&self) -> &'static crate::document::LayerKindRegistration {
        use crate::document::layer_kind::registry;
        use crate::document::layer_kinds::{filter, group, raster, void};
        match self {
            LayerNode::Layer(Layer::Raster(_)) => registry().get(raster::TYPE_ID).unwrap(),
            LayerNode::Layer(Layer::Void(_)) => registry().get(void::TYPE_ID).unwrap(),
            LayerNode::Layer(Layer::Filter(_)) => registry().get(filter::TYPE_ID).unwrap(),
            LayerNode::Group(_) => registry().get(group::TYPE_ID).unwrap(),
        }
    }

    /// Convenience for the wire format / save file — just the stable `type_id`
    /// string from `kind()`.
    pub fn type_id(&self) -> &'static str {
        self.kind().type_id
    }

    /// Composite this node into its parent group's accumulators. The
    /// variant dispatch is owned by `LayerNode` so the compositor's child
    /// walk never re-introduces a centralised match on node kind. Each arm
    /// delegates back through `ctx` into a compositor-private method that
    /// owns the GPU work — variant *knows itself*, compositor *does the
    /// work*.
    pub fn compose_into(&self, ctx: &mut crate::gpu::compositor::CompositionContext<'_>) {
        match self {
            LayerNode::Layer(layer) => ctx.compose_layer(layer),
            LayerNode::Group(group) => ctx.compose_group(group),
        }
    }

    /// Whether this node transforms the running parent accumulator *in place*
    /// (the composite of everything below it) rather than blending its own
    /// discrete texture in. A passthrough group inlines its children into the
    /// parent; a filter layer runs its pipeline over the accumulator. Both want
    /// a snapshot+lerp detour when they carry a visible mask, so the compositor
    /// keys its mask-snapshot resource off this predicate instead of
    /// enumerating which kinds qualify — a new in-place kind is purely additive.
    /// Isolated groups, raster, and void layers blend a texture and answer
    /// `false`.
    pub fn composites_in_place(&self) -> bool {
        match self {
            LayerNode::Group(g) => g.passthrough,
            LayerNode::Layer(Layer::Filter(_)) => true,
            LayerNode::Layer(_) => false,
        }
    }
}

/// How a layer answers "can the user transform me, and how?" — consumed by the
/// Transform tool to pick which binding drives the generic gizmo. This is the
/// layer describing *itself* (type-owned dispatch); the transform subsystem
/// never branches on layer kind.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TransformCapability {
    /// Live, non-destructive, persistent transform property (e.g. a camera
    /// void). The gizmo edits the stored [`crate::transform::Transform`].
    Live,
    /// Destructive extract-and-commit (raster layers — today's floating).
    Destructive,
    /// Not user-transformable (groups, non-transformable voids).
    None,
}

pub enum Layer {
    Raster(RasterLayer),
    Void(VoidLayer),
    Filter(FilterLayer),
}

impl Layer {
    /// Whether and how the user can transform this layer. The void's opinion is
    /// static, looked up from the registry by `void_type` — passed in because
    /// [`VoidRegistry`] is owned by the compositor, not a global.
    ///
    /// [`VoidRegistry`]: crate::gpu::void::VoidRegistry
    pub fn transform_capability(
        &self,
        reg: &crate::gpu::void::VoidRegistry,
    ) -> TransformCapability {
        match self {
            Layer::Raster(_) => TransformCapability::Destructive,
            Layer::Void(v) => {
                if reg.supports_live_transform(&v.void_type) {
                    TransformCapability::Live
                } else {
                    TransformCapability::None
                }
            }
            // A full-frame filter has no meaningful transform — there are no
            // pixels of its own to move.
            Layer::Filter(_) => TransformCapability::None,
        }
    }

    /// Whether this layer participates in the standard blend pipeline — i.e.
    /// it has a node texture + blend uniforms in the compositor's
    /// `layer_cache`. Raster and void layers do; a filter layer transforms the
    /// running group accumulator instead of contributing a texture of its own,
    /// so it is realized by `compose_filter_arm`, not the content walk.
    pub fn is_blend_content(&self) -> bool {
        !matches!(self, Layer::Filter(_))
    }

    pub fn id(&self) -> LayerId {
        match self {
            Layer::Raster(r) => r.id,
            Layer::Void(v) => v.id,
            Layer::Filter(f) => f.id,
        }
    }

    pub fn common(&self) -> &NodeCommon {
        match self {
            Layer::Raster(r) => &r.common,
            Layer::Void(v) => &v.common,
            Layer::Filter(f) => &f.common,
        }
    }

    pub fn common_mut(&mut self) -> &mut NodeCommon {
        match self {
            Layer::Raster(r) => &mut r.common,
            Layer::Void(v) => &mut v.common,
            Layer::Filter(f) => &mut f.common,
        }
    }

    pub fn blend(&self) -> &BlendProps {
        match self {
            Layer::Raster(r) => &r.blend,
            Layer::Void(v) => &v.blend,
            Layer::Filter(f) => &f.blend,
        }
    }

    pub fn blend_mut(&mut self) -> &mut BlendProps {
        match self {
            Layer::Raster(r) => &mut r.blend,
            Layer::Void(v) => &mut v.blend,
            Layer::Filter(f) => &mut f.blend,
        }
    }

    pub fn filters(&self) -> &[LayerId] {
        match self {
            Layer::Raster(r) => &r.filters,
            Layer::Void(v) => &v.filters,
            Layer::Filter(f) => &f.filters,
        }
    }

    pub fn modifiers_mut(&mut self) -> &mut Vec<LayerId> {
        match self {
            Layer::Raster(r) => &mut r.filters,
            Layer::Void(v) => &mut v.filters,
            Layer::Filter(f) => &mut f.filters,
        }
    }

    /// Pixel buffer for this layer, if any. Void and filter layers have no
    /// pixels — a void regenerates from `params`, a filter transforms the
    /// accumulator below it.
    pub fn pixels(&self) -> Option<&PixelBuffer> {
        match self {
            Layer::Raster(r) => Some(&r.pixels),
            Layer::Void(_) | Layer::Filter(_) => None,
        }
    }

    pub fn pixels_mut(&mut self) -> Option<&mut PixelBuffer> {
        match self {
            Layer::Raster(r) => Some(&mut r.pixels),
            Layer::Void(_) | Layer::Filter(_) => None,
        }
    }

    pub fn visible(&self) -> bool {
        self.common().visible
    }

    pub fn locked(&self) -> bool {
        self.common().locked
    }

    /// Regenerable procedural state — `(params, transform)` — for void layers,
    /// `None` for raster. Used by `sync_compositor_layers` to push the doc's
    /// authoritative void state downhill to the compositor after any doc
    /// mutation (undo / redo / load), so the running void instance never drifts
    /// from the document.
    pub fn void_state(&self) -> Option<(&[ParamValue], &crate::transform::Transform)> {
        match self {
            Layer::Void(v) => Some((&v.params, &v.transform)),
            Layer::Raster(_) | Layer::Filter(_) => None,
        }
    }
}