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
|
// Non-destructive layer styles: drop shadow, outer glow, inner shadow, color overlay
// and stroke. They are computed from a layer's final pixels (after the mask, live
// strokes and floating pixels) every time the layer is composited, so painting,
// moving or masking the layer updates its effects too.
//
// `layer.effects` is either null or { [effectId]: { enabled, ...params } }. Treat it
// as immutable: replace the whole object so history can keep references.
import { createCanvas } from '../core/util.js';
import { blendOp } from '../core/layer.js';
const pct = (key, label, def) => ({ key, label, type: 'range', min: 0, max: 100, default: def, unit: '%' });
const px = (key, label, def, min = 0, max = 100) => ({ key, label, type: 'range', min, max, default: def, unit: 'px' });
const angle = (def) => ({ key: 'angle', label: 'Angle', type: 'range', min: -180, max: 180, default: def, unit: '°' });
export const EFFECTS = [
{
id: 'dropShadow', label: 'Drop Shadow',
params: [{ key: 'color', label: 'Color', type: 'color', default: '#000000' }, pct('opacity', 'Opacity', 60), angle(135), px('distance', 'Distance', 8, 0, 300), px('size', 'Size', 10, 0, 150)],
},
{
id: 'outerGlow', label: 'Outer Glow',
params: [{ key: 'color', label: 'Color', type: 'color', default: '#ffd84a' }, pct('opacity', 'Opacity', 80), pct('spread', 'Spread', 0), px('size', 'Size', 16, 1, 150)],
},
{
id: 'innerShadow', label: 'Inner Shadow',
params: [{ key: 'color', label: 'Color', type: 'color', default: '#000000' }, pct('opacity', 'Opacity', 50), angle(135), px('distance', 'Distance', 5, 0, 300), px('size', 'Size', 6, 0, 150)],
},
{
id: 'colorOverlay', label: 'Color Overlay',
params: [{ key: 'color', label: 'Color', type: 'color', default: '#e5484d' }, pct('opacity', 'Opacity', 100), { key: 'blendMode', label: 'Blend mode', type: 'select', default: 'normal', options: 'blend' }],
},
{
id: 'stroke', label: 'Stroke',
params: [
px('size', 'Size', 3, 1, 100),
{
key: 'position', label: 'Position', type: 'select', default: 'outside',
options: [{ value: 'outside', label: 'Outside' }, { value: 'center', label: 'Center' }, { value: 'inside', label: 'Inside' }],
},
{ key: 'color', label: 'Color', type: 'color', default: '#000000' },
pct('opacity', 'Opacity', 100),
],
},
];
export const EFFECT_IDS = EFFECTS.map((e) => e.id);
/** Settings for one effect with every parameter at its default. */
export function defaultEffect(id) {
const spec = EFFECTS.find((e) => e.id === id);
const out = { enabled: false };
for (const p of spec.params) out[p.key] = p.default;
return out;
}
/** A complete effects object (all effects present), filled in from `fx`. */
export function normalizeEffects(fx) {
const out = {};
for (const id of EFFECT_IDS) out[id] = { ...defaultEffect(id), ...(fx?.[id] || {}) };
return out;
}
export function hasEffects(layer) {
const fx = layer?.effects;
return !!fx && EFFECT_IDS.some((id) => fx[id]?.enabled);
}
/** Labels of the enabled effects (for tooltips and badges). */
export function effectNames(fx) {
return EFFECTS.filter((e) => fx?.[e.id]?.enabled).map((e) => e.label);
}
// ---------------------------------------------------------------- scratch canvases
const pool = new Map();
function pooled(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.shadowColor = 'transparent';
ctx.filter = 'none';
ctx.clearRect(0, 0, w, h);
return c;
}
function rgba(hex, alpha) {
const s = String(hex || '#000000').replace('#', '');
const n = (i) => parseInt(s.slice(i, i + 2), 16) || 0;
return `rgba(${n(0)},${n(2)},${n(4)},${Math.max(0, Math.min(1, alpha))})`;
}
/** Silhouette of `src` (its alpha) filled with a single color. */
function silhouette(name, src, color) {
const c = pooled(name, src.width, src.height);
const ctx = c.getContext('2d');
ctx.drawImage(src, 0, 0);
ctx.globalCompositeOperation = 'source-in';
ctx.fillStyle = color;
ctx.fillRect(0, 0, c.width, c.height);
ctx.globalCompositeOperation = 'source-over';
return c;
}
/**
* Draw only the (blurred, offset) shadow of `img` onto ctx. The image itself is
* drawn far outside the canvas and the shadow offset brings the shadow back.
*/
function drawShadowOnly(ctx, img, x, y, color, blur, dx, dy) {
const far = img.width + ctx.canvas.width + blur * 4 + 256;
ctx.save();
ctx.shadowColor = color;
ctx.shadowBlur = blur;
ctx.shadowOffsetX = dx + far;
ctx.shadowOffsetY = dy;
ctx.drawImage(img, x - far, y);
ctx.restore();
}
/** Light angle (degrees, Photoshop convention) and distance to a shadow offset. */
function offsetFor(fx) {
const a = (fx.angle * Math.PI) / 180;
return { dx: -Math.cos(a) * fx.distance, dy: Math.sin(a) * fx.distance };
}
// ---------------------------------------------------------------- distance fields
const INF = 1e20;
/** 1-D squared distance transform (Felzenszwalb & Huttenlocher). */
function edt1d(f, n, d, v, z) {
let k = 0;
v[0] = 0; z[0] = -INF; z[1] = INF;
for (let q = 1; q < n; q++) {
let s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);
while (s <= z[k]) {
k--;
s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);
}
k++;
v[k] = q; z[k] = s; z[k + 1] = INF;
}
k = 0;
for (let q = 0; q < n; q++) {
while (z[k + 1] < q) k++;
const t = q - v[k];
d[q] = t * t + f[v[k]];
}
}
/** Squared Euclidean distance from every cell to the nearest cell where target[i] === want. */
function distanceTransform(target, w, h, want) {
const grid = new Float32Array(w * h);
for (let i = 0; i < grid.length; i++) grid[i] = target[i] === want ? 0 : INF;
const n = Math.max(w, h);
const f = new Float64Array(n), d = new Float64Array(n), v = new Int32Array(n), z = new Float64Array(n + 1);
for (let x = 0; x < w; x++) {
for (let y = 0, i = x; y < h; y++, i += w) f[y] = grid[i];
edt1d(f, h, d, v, z);
for (let y = 0, i = x; y < h; y++, i += w) grid[i] = d[y];
}
for (let y = 0; y < h; y++) {
const row = y * w;
for (let x = 0; x < w; x++) f[x] = grid[row + x];
edt1d(f, w, d, v, z);
for (let x = 0; x < w; x++) grid[row + x] = d[x];
}
return grid;
}
/**
* Inside/outside distances around the opaque part (alpha >= 128) of src, over its
* bounding box grown by `pad`. Pixels beyond the canvas count as transparent.
*/
function distanceFields(src, pad, needInside) {
const w = src.width, h = src.height;
const data = src.getContext('2d', { willReadFrequently: true }).getImageData(0, 0, w, h).data;
let x0 = w, y0 = h, x1 = -1, y1 = -1;
for (let y = 0; y < h; y++) {
for (let x = 0, i = y * w * 4 + 3; x < w; x++, i += 4) {
if (data[i] >= 128) {
if (x < x0) x0 = x;
if (x > x1) x1 = x;
if (y < y0) y0 = y;
if (y > y1) y1 = y;
}
}
}
if (x1 < 0) return null;
const rx = x0 - pad, ry = y0 - pad, rw = x1 - x0 + 1 + pad * 2, rh = y1 - y0 + 1 + pad * 2;
const inside = new Uint8Array(rw * rh);
for (let y = 0; y < rh; y++) {
const sy = y + ry;
if (sy < 0 || sy >= h) continue;
for (let x = 0; x < rw; x++) {
const sx = x + rx;
if (sx >= 0 && sx < w && data[(sy * w + sx) * 4 + 3] >= 128) inside[y * rw + x] = 1;
}
}
return {
rx, ry, rw, rh, inside,
dOut2: distanceTransform(inside, rw, rh, 1), // squared distance to the shape (0 inside)
dIn2: needInside ? distanceTransform(inside, rw, rh, 0) : null, // squared distance to the outside
};
}
/**
* Paint a band around the shape edge in `color` onto a pooled doc-sized canvas.
* side 'outside': the shape grown by `radius` (inside included); 'inside': the inner
* `radius` px of the shape. Edges get one pixel of anti-aliasing.
*/
function bandCanvas(name, field, w, h, color, radius, side) {
const c = pooled(name, w, h);
const { rx, ry, rw, rh, inside } = field;
const dist2 = side === 'outside' ? field.dOut2 : field.dIn2;
const cx0 = Math.max(0, rx), cy0 = Math.max(0, ry);
const cx1 = Math.min(w, rx + rw), cy1 = Math.min(h, ry + rh);
if (cx1 <= cx0 || cy1 <= cy0) return c;
const s = String(color).replace('#', '');
const r = parseInt(s.slice(0, 2), 16) || 0, g = parseInt(s.slice(2, 4), 16) || 0, b = parseInt(s.slice(4, 6), 16) || 0;
const full2 = Math.max(0, radius - 0.5) ** 2, edge2 = (radius + 0.5) ** 2;
const ctx = c.getContext('2d');
const ow = cx1 - cx0;
const id = ctx.createImageData(ow, cy1 - cy0);
const d = id.data;
for (let y = cy0; y < cy1; y++) {
let i = (y - ry) * rw + (cx0 - rx);
let o = (y - cy0) * ow * 4;
for (let x = cx0; x < cx1; x++, i++, o += 4) {
let a;
if (side === 'outside' && inside[i]) a = 255;
else if (side === 'inside' && !inside[i]) continue;
else {
const q = dist2[i];
if (q >= edge2) continue;
a = q <= full2 ? 255 : Math.round((radius + 0.5 - Math.sqrt(q)) * 255);
if (a <= 0) continue;
}
d[o] = r; d[o + 1] = g; d[o + 2] = b; d[o + 3] = a;
}
}
ctx.putImageData(id, cx0, cy0);
return c;
}
// ---------------------------------------------------------------- render
/**
* Render `src` (a layer's final pixels) with its effects into `out` (cleared and
* resized to src). Returns `out`.
*/
export function renderEffects(src, fx, out) {
const w = src.width, h = src.height;
if (out.width !== w || out.height !== h) { out.width = w; out.height = h; }
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, w, h);
const on = (id) => fx?.[id]?.enabled;
const stroke = on('stroke') ? fx.stroke : null;
const glow = on('outerGlow') ? fx.outerGlow : null;
const glowSpread = glow ? (glow.spread / 100) * glow.size : 0;
let field = null;
if (stroke || glowSpread >= 0.5) {
const pad = Math.ceil(Math.max(stroke ? stroke.size : 0, glowSpread)) + 2;
field = distanceFields(src, pad, stroke && stroke.position !== 'outside');
}
// -- below the layer content
if (on('dropShadow')) {
const s = fx.dropShadow;
const { dx, dy } = offsetFor(s);
drawShadowOnly(ctx, src, 0, 0, rgba(s.color, s.opacity / 100), s.size, dx, dy);
}
if (glow) {
const shape = glowSpread >= 0.5 && field ? bandCanvas('fx-glow', field, w, h, '#000000', glowSpread, 'outside') : src;
drawShadowOnly(ctx, shape, 0, 0, rgba(glow.color, glow.opacity / 100), Math.max(1, glow.size - glowSpread), 0, 0);
}
if (stroke && field && stroke.position !== 'inside') {
const r = stroke.position === 'center' ? stroke.size / 2 : stroke.size;
const ring = bandCanvas('fx-stroke', field, w, h, stroke.color, r, 'outside');
ctx.globalAlpha = stroke.opacity / 100;
ctx.drawImage(ring, 0, 0);
ctx.globalAlpha = 1;
}
// -- the content, with overlay and inner shadow applied to it
let content = src;
if (on('colorOverlay') || on('innerShadow')) {
const c = pooled('fx-content', w, h);
const cctx = c.getContext('2d');
cctx.drawImage(src, 0, 0);
if (on('colorOverlay')) {
const o = fx.colorOverlay;
if (o.blendMode === 'normal' || !o.blendMode) {
cctx.globalCompositeOperation = 'source-atop';
cctx.fillStyle = rgba(o.color, o.opacity / 100);
cctx.fillRect(0, 0, w, h);
} else {
cctx.globalCompositeOperation = blendOp(o.blendMode);
cctx.drawImage(silhouette('fx-sil', src, rgba(o.color, o.opacity / 100)), 0, 0);
cctx.globalCompositeOperation = 'destination-in';
cctx.drawImage(src, 0, 0);
}
cctx.globalCompositeOperation = 'source-over';
}
if (on('innerShadow')) {
const s = fx.innerShadow;
const { dx, dy } = offsetFor(s);
// The shadow is cast by everything outside the shape, including beyond the canvas.
const m = Math.ceil(Math.abs(dx) + Math.abs(dy) + s.size * 2 + 2);
const inv = pooled('fx-inv', w + m * 2, h + m * 2);
const ictx = inv.getContext('2d');
ictx.fillStyle = '#000';
ictx.fillRect(0, 0, inv.width, inv.height);
ictx.globalCompositeOperation = 'destination-out';
ictx.drawImage(src, m, m);
ictx.globalCompositeOperation = 'source-over';
const sh = pooled('fx-inner', w, h);
const sctx = sh.getContext('2d');
drawShadowOnly(sctx, inv, -m, -m, rgba(s.color, s.opacity / 100), s.size, dx, dy);
sctx.globalCompositeOperation = 'destination-in';
sctx.drawImage(src, 0, 0);
sctx.globalCompositeOperation = 'source-over';
cctx.globalCompositeOperation = 'source-atop';
cctx.drawImage(sh, 0, 0);
cctx.globalCompositeOperation = 'source-over';
}
content = c;
}
ctx.drawImage(content, 0, 0);
// -- above the content
if (stroke && field && stroke.position !== 'outside') {
const r = stroke.position === 'center' ? stroke.size / 2 : stroke.size;
const ring = bandCanvas('fx-stroke', field, w, h, stroke.color, r, 'inside');
ctx.globalAlpha = stroke.opacity / 100;
ctx.drawImage(ring, 0, 0);
}
ctx.restore();
return out;
}
|