aboutsummaryrefslogtreecommitdiff
path: root/build/js/render/compositor.js
blob: 150f00571e9b3ee37f50727a2a85a658caaafce1 (plain)
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
// Blends a document's layers into a single canvas, including live (uncommitted)
// strokes, floating pixels, layer masks and clipping masks.
import { createCanvas } from '../core/util.js';
import { blendOp } from '../core/layer.js';
import { hasEffects, renderEffects } from './effects.js';

const pool = new Map();
/** Reusable scratch canvas of a given size. */
export function scratch(name, w, h) {
  let c = pool.get(name);
  if (!c) { c = createCanvas(w, h); pool.set(name, c); }
  if (c.width !== w || c.height !== h) { c.width = w; c.height = h; }
  const ctx = c.getContext('2d');
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.globalAlpha = 1;
  ctx.globalCompositeOperation = 'source-over';
  ctx.clearRect(0, 0, w, h);
  return c;
}

/**
 * Draw a stroke buffer onto ctx. The stroke buffer holds paint at full strength;
 * stroke.opacity / stroke.composite decide how it lands. Clipped to the selection.
 */
export function applyStroke(ctx, stroke, selection) {
  let src = stroke.buffer;
  if (selection) {
    const tmp = scratch('stroke-clip', src.width, src.height);
    const t = tmp.getContext('2d');
    t.drawImage(src, 0, 0);
    t.globalCompositeOperation = 'destination-in';
    t.drawImage(selection.mask, 0, 0);
    src = tmp;
  }
  ctx.save();
  ctx.globalAlpha = stroke.opacity;
  ctx.globalCompositeOperation = stroke.composite || 'source-over';
  ctx.drawImage(src, 0, 0);
  ctx.restore();
}

/**
 * Canvas holding the final pixels of a layer including its layer styles (before
 * opacity/blend), or the raw canvas if nothing applies.
 */
export function layerSurface(doc, layer, poolName = 'surface') {
  const content = layerContent(doc, layer, poolName);
  if (!hasEffects(layer)) return content;
  const live = (doc.stroke && doc.stroke.layer === layer) || (doc.floating && doc.floating.layer === layer) || layer.preview;
  if (live) return renderEffects(content, layer.effects, scratch(`${poolName}-fx`, content.width, content.height));
  // Effects are costly (distance fields, blurs): cache them until the layer changes.
  const key = `${layer.thumbVersion}|${layer.maskVersion}|${layer.maskEnabled}|${layer.dx},${layer.dy}|${JSON.stringify(layer.effects)}`;
  const c = layer._fxCache;
  if (c && c.key === key && c.canvas === layer.canvas && c.mask === layer.mask) return c.out;
  const out = renderEffects(content, layer.effects, c?.out || createCanvas(content.width, content.height));
  layer._fxCache = { key, canvas: layer.canvas, mask: layer.mask, out };
  return out;
}

/** The layer's pixels with live stroke, floating pixels, move offset and mask applied (no effects). */
export function layerContent(doc, layer, poolName = 'surface') {
  const live = doc.stroke && doc.stroke.layer === layer ? doc.stroke : null;
  const floating = doc.floating && doc.floating.layer === layer ? doc.floating : null;
  const useMask = layer.mask && layer.maskEnabled;
  const base = layer.preview || layer.canvas;
  if (!live && !floating && !useMask && !layer.dx && !layer.dy) return base;

  const w = base.width, h = base.height;
  const out = scratch(poolName, w, h);
  const ctx = out.getContext('2d');
  ctx.drawImage(base, layer.dx, layer.dy);
  if (live && live.key === 'canvas') applyStroke(ctx, live, doc.selection);
  if (floating) {
    ctx.save();
    ctx.globalAlpha = floating.opacity ?? 1;
    if (floating.transform) {
      const t = floating.transform;
      ctx.setTransform(t.a, t.b, t.c, t.d, t.e, t.f);
      ctx.imageSmoothingQuality = 'high';
      ctx.drawImage(floating.canvas, 0, 0);
    } else {
      ctx.drawImage(floating.canvas, floating.dx, floating.dy);
    }
    ctx.restore();
  }
  if (useMask) {
    let alpha;
    if (live && live.key === 'mask') {
      const m = scratch(poolName + '-mask', w, h);
      const mctx = m.getContext('2d');
      mctx.drawImage(layer.mask, 0, 0);
      applyStroke(mctx, live, doc.selection);
      alpha = layer.maskAlpha(m);
      layer._maskAlphaVersion = -1;
    } else {
      alpha = layer.maskAlpha();
    }
    ctx.globalCompositeOperation = 'destination-in';
    ctx.drawImage(alpha, layer.dx, layer.dy);
    ctx.globalCompositeOperation = 'source-over';
  }
  return out;
}

/**
 * Composite `layers` (default: all document layers) into `out`, which is resized to the document.
 * Options: background (CSS color drawn first, or null for transparent).
 */
export function compositeDocument(doc, out, { layers = doc.layers, background = null } = {}) {
  if (out.width !== doc.width || out.height !== doc.height) {
    out.width = doc.width;
    out.height = doc.height;
  }
  const ctx = out.getContext('2d');
  ctx.save();
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.globalAlpha = 1;
  ctx.globalCompositeOperation = 'source-over';
  ctx.clearRect(0, 0, out.width, out.height);
  if (background) {
    ctx.fillStyle = background;
    ctx.fillRect(0, 0, out.width, out.height);
  }
  for (let i = 0; i < layers.length; i++) {
    const layer = layers[i];
    // Clipped layers are handled together with their base layer.
    const isClipped = layer.clip && i > 0 && hasBase(layers, i);
    if (isClipped) continue;
    const clipped = [];
    for (let j = i + 1; j < layers.length && layers[j].clip; j++) clipped.push(layers[j]);
    if (!layer.visible) continue;

    let baseAlpha = null;
    if (clipped.some((c) => c.visible)) {
      // Clipped layers follow the base layer's pixels, not its shadows or glows.
      baseAlpha = scratch('clip-base', doc.width, doc.height);
      baseAlpha.getContext('2d').drawImage(layerContent(doc, layer, 'surface'), 0, 0);
    }
    const surface = layerSurface(doc, layer, 'surface');
    ctx.globalAlpha = layer.opacity;
    ctx.globalCompositeOperation = blendOp(layer.blendMode);
    ctx.drawImage(surface, 0, 0);

    for (const c of clipped) {
      if (!c.visible) continue;
      const cs = layerSurface(doc, c, 'surface-clip');
      const tmp = scratch('clip-tmp', doc.width, doc.height);
      const t = tmp.getContext('2d');
      t.drawImage(cs, 0, 0);
      t.globalCompositeOperation = 'destination-in';
      t.drawImage(baseAlpha, 0, 0);
      ctx.globalAlpha = c.opacity * layer.opacity;
      ctx.globalCompositeOperation = blendOp(c.blendMode);
      ctx.drawImage(tmp, 0, 0);
    }
  }
  ctx.restore();
  return out;
}

function hasBase(layers, i) {
  for (let j = i - 1; j >= 0; j--) if (!layers[j].clip) return true;
  return false;
}

/** Fresh canvas with the flattened document. */
export function flattenToCanvas(doc, background = null) {
  return compositeDocument(doc, createCanvas(doc.width, doc.height), { background });
}