@margoengine/dof 0.1.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -201
- package/NOTICE +4 -4
- package/README.md +283 -235
- package/dist/alpha.d.ts +13 -0
- package/dist/autofocus.js +4 -4
- package/dist/index.d.ts +36 -1
- package/dist/index.js +331 -126
- package/dist/shaders.d.ts +15 -1
- package/package.json +63 -63
package/README.md
CHANGED
|
@@ -1,235 +1,283 @@
|
|
|
1
|
-
# @margoengine/dof
|
|
2
|
-
|
|
3
|
-
Import `margoengine/dof` from the `margoengine` package, or `@margoengine/dof` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
|
|
4
|
-
|
|
5
|
-
Optional WebGPU depth of field; core and stage are unchanged.
|
|
6
|
-
|
|
7
|
-
DOF requires native WebGPU or the WebGL2 compatibility layer's `full` or
|
|
8
|
-
`half-float` tier, including with `temporal: true`. The `ldr` tier cannot preserve
|
|
9
|
-
the HDR scene capture and is refused with MargoError code `unsupported` and a
|
|
10
|
-
[compatibility help link](https://margoengine.com/errors#compatibility-layer).
|
|
11
|
-
Handle that code when attaching DOF and keep rendering without the effect. If
|
|
12
|
-
device restoration selects LDR, DOF disposes and detaches before the engine reports
|
|
13
|
-
one `unsupported` error through `engine.onError`; handle the notification there.
|
|
14
|
-
The scene continues without DOF on later frames. If DOF belongs to an HDR
|
|
15
|
-
`PostStack`, the refused stack and its effects detach together. Recreate effects
|
|
16
|
-
after a suitable device becomes available; disposed effects cannot be reattached.
|
|
17
|
-
|
|
18
|
-
```ts
|
|
19
|
-
import {Engine} from 'margoengine/core';
|
|
20
|
-
import {DOF} from 'margoengine/dof';
|
|
21
|
-
const engine = await Engine.create(document.querySelector('canvas')!, {backend:'webgpu'});
|
|
22
|
-
const unsupported = (error: unknown) =>
|
|
23
|
-
error instanceof Error && 'code' in error && error.code === 'unsupported';
|
|
24
|
-
engine.onError = (error) => {
|
|
25
|
-
if (unsupported(error)) {
|
|
26
|
-
console.info('Depth of field detached: this device cannot preserve HDR.');
|
|
27
|
-
return;
|
|
28
|
-
}
|
|
29
|
-
console.error(error);
|
|
30
|
-
};
|
|
31
|
-
try {
|
|
32
|
-
DOF.attach(engine, {focalDistance:5});
|
|
33
|
-
} catch (error) {
|
|
34
|
-
if (!unsupported(error)) throw error;
|
|
35
|
-
console.info('Depth of field unavailable: rendering the scene without it.');
|
|
36
|
-
}
|
|
37
|
-
// After capability recovery, attach a new DOF; the detached instance is disposed.
|
|
38
|
-
```
|
|
39
|
-
|
|
40
|
-
`DOF` and `Autofocus` detach from their owning scene on disposal, preserving
|
|
41
|
-
same-name effects in other scenes. Use `scene.use()` for a secondary scene:
|
|
42
|
-
|
|
43
|
-
```ts
|
|
44
|
-
import {Engine} from 'margoengine/core';
|
|
45
|
-
import {DOF} from 'margoengine/dof';
|
|
46
|
-
import {Autofocus} from 'margoengine/dof/autofocus';
|
|
47
|
-
const engine = await Engine.create(document.querySelector('canvas')!, {backend:'webgpu'});
|
|
48
|
-
const product = engine.createScene('product');
|
|
49
|
-
const dof = new DOF();
|
|
50
|
-
const focus = new Autofocus(dof);
|
|
51
|
-
product.use(dof);
|
|
52
|
-
product.use(focus);
|
|
53
|
-
focus.dispose();
|
|
54
|
-
dof.dispose();
|
|
55
|
-
engine.dispose();
|
|
56
|
-
```
|
|
57
|
-
|
|
58
|
-
```ts
|
|
59
|
-
import {createStage} from 'margoengine';
|
|
60
|
-
import {DOF} from 'margoengine/dof';
|
|
61
|
-
const stage = await createStage('#viewport', {backend:'webgpu'});
|
|
62
|
-
const dof = DOF.attach(stage.engine, {focalDistance:5, focalLength:0.05, aperture:2.8});
|
|
63
|
-
dof.options.focalDistance = 3;
|
|
64
|
-
dof.enabled = false;
|
|
65
|
-
dof.dispose();
|
|
66
|
-
stage.dispose();
|
|
67
|
-
```
|
|
68
|
-
|
|
69
|
-
Passes capture linear HDR and sampleable reversed-Z depth before drawing, calculate signed thin-lens CoC at order
|
|
70
|
-
|
|
71
|
-
Standalone output uses Margo's display curve (Khronos PBR Neutral, then sRGB), as core does. For color grading, attach DOF first, then `Tonemap.attach(stage.engine, {source:()=>dof.outputTexture})`. The current HDR `outputTexture` and `depthTexture` are undefined before the first frame and change on resize/restoration. With TAA, supply `depth:()=>dof.depthTexture` to TAA. Destroy dependent effects before DOF. Alone, SSAO and Creative PostProcessing own conflicting scene captures and are rejected. To combine DOF with SSAO, Bloom, Tonemap, Creative PostProcessing or FXAA, add it to a `PostStack` from `@margoengine/post/stack`, e.g. `PostStack.attach(stage.engine, [new SSAO(), new DOF(), new Bloom(), new Tonemap()])`; there it reads the stack's shared HDR capture and depth, and its `depthTexture` is the stack's.
|
|
72
|
-
|
|
73
|
-
##
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
import {
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
stage.engine
|
|
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
|
-
import {
|
|
127
|
-
import {
|
|
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
|
-
package is
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
1
|
+
# @margoengine/dof
|
|
2
|
+
|
|
3
|
+
Import `margoengine/dof` from the `margoengine` package, or `@margoengine/dof` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
|
|
4
|
+
|
|
5
|
+
Optional WebGPU depth of field; core and stage are unchanged.
|
|
6
|
+
|
|
7
|
+
DOF requires native WebGPU or the WebGL2 compatibility layer's `full` or
|
|
8
|
+
`half-float` tier, including with `temporal: true`. The `ldr` tier cannot preserve
|
|
9
|
+
the HDR scene capture and is refused with MargoError code `unsupported` and a
|
|
10
|
+
[compatibility help link](https://margoengine.com/errors#compatibility-layer).
|
|
11
|
+
Handle that code when attaching DOF and keep rendering without the effect. If
|
|
12
|
+
device restoration selects LDR, DOF disposes and detaches before the engine reports
|
|
13
|
+
one `unsupported` error through `engine.onError`; handle the notification there.
|
|
14
|
+
The scene continues without DOF on later frames. If DOF belongs to an HDR
|
|
15
|
+
`PostStack`, the refused stack and its effects detach together. Recreate effects
|
|
16
|
+
after a suitable device becomes available; disposed effects cannot be reattached.
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import {Engine} from 'margoengine/core';
|
|
20
|
+
import {DOF} from 'margoengine/dof';
|
|
21
|
+
const engine = await Engine.create(document.querySelector('canvas')!, {backend:'webgpu'});
|
|
22
|
+
const unsupported = (error: unknown) =>
|
|
23
|
+
error instanceof Error && 'code' in error && error.code === 'unsupported';
|
|
24
|
+
engine.onError = (error) => {
|
|
25
|
+
if (unsupported(error)) {
|
|
26
|
+
console.info('Depth of field detached: this device cannot preserve HDR.');
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
console.error(error);
|
|
30
|
+
};
|
|
31
|
+
try {
|
|
32
|
+
DOF.attach(engine, {focalDistance:5});
|
|
33
|
+
} catch (error) {
|
|
34
|
+
if (!unsupported(error)) throw error;
|
|
35
|
+
console.info('Depth of field unavailable: rendering the scene without it.');
|
|
36
|
+
}
|
|
37
|
+
// After capability recovery, attach a new DOF; the detached instance is disposed.
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
`DOF` and `Autofocus` detach from their owning scene on disposal, preserving
|
|
41
|
+
same-name effects in other scenes. Use `scene.use()` for a secondary scene:
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
import {Engine} from 'margoengine/core';
|
|
45
|
+
import {DOF} from 'margoengine/dof';
|
|
46
|
+
import {Autofocus} from 'margoengine/dof/autofocus';
|
|
47
|
+
const engine = await Engine.create(document.querySelector('canvas')!, {backend:'webgpu'});
|
|
48
|
+
const product = engine.createScene('product');
|
|
49
|
+
const dof = new DOF();
|
|
50
|
+
const focus = new Autofocus(dof);
|
|
51
|
+
product.use(dof);
|
|
52
|
+
product.use(focus);
|
|
53
|
+
focus.dispose();
|
|
54
|
+
dof.dispose();
|
|
55
|
+
engine.dispose();
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
import {createStage} from 'margoengine';
|
|
60
|
+
import {DOF} from 'margoengine/dof';
|
|
61
|
+
const stage = await createStage('#viewport', {backend:'webgpu'});
|
|
62
|
+
const dof = DOF.attach(stage.engine, {focalDistance:5, focalLength:0.05, aperture:2.8});
|
|
63
|
+
dof.options.focalDistance = 3;
|
|
64
|
+
dof.enabled = false;
|
|
65
|
+
dof.dispose();
|
|
66
|
+
stage.dispose();
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Passes capture linear HDR and sampleable reversed-Z depth before drawing, calculate signed thin-lens CoC at order 29.8, after every scene draw below 30 (lines, text and labels included), gather circular near/far bokeh separately at 29.9 (six compute passes: the near field's mip chain in four, six for a cap over 62 px, the wide far disks per 2x2 block, the bokeh), then present at 30. Focal distance and focal length use the same scene units; aperture is an f-number. Pixel scale follows camera vertical FOV and viewport height. With an orthographic camera (any `camera.matrix` with a constant clip w, such as `CameraProjection` from `@margoengine/cameras`) depth is linearized from the projection's own near/far and the circle of confusion grows linearly with the distance from the focal plane, `scale * (z - focalDistance) / focalDistance`, with the scale of a perspective lens whose pixel size at the focal distance matches the orthographic zoom; zooming in enlarges the blur in pixels. `maxRadius` (1-32, default 16) caps the blur in pixels of a view `referenceHeight` tall (default 1080) and scales with the view's height, so the cap is one share of the frame on any canvas (see Blur cap below). A deterministic spiral disk per field uses no temporal history. A blurred edge spreads to both sides of its outline, as a lens draws it: a far sample in front of a pixel counts where its own disk reaches that pixel (scatter as gather), and a foreground edge fades over the background seen past it, so a sharp subject never leaks onto its blurred background (measured on WebGPU and the WebGL2 layer: a far card spreads 11 px inward and 12 px outward, a near card 10 and 11, `tests/gpu/lens-check.mjs`). Near samples spread only onto surfaces behind them. The near gather spreads its 64 taps over the largest foreground disk that reaches each 8x8 tile (at most maxRadius), so a small disk keeps its round or polygon shape, and each tap reads a mip chain of the near field (colour premultiplied by the gather weight, radius and depth, and the scene behind; three `rgba16float` textures at the gather's size, six levels, of which a cap up to 62 px reads four) through a trilinear sampler at the level whose footprint matches the taps' spacing (7 px apart at a 32 px disk), read at the two whole levels around it and blended in the shader, so native WebGPU and the WebGL2 layer blend them alike (a sampler's own trilinear blend keeps the level's fraction at a precision and in arithmetic of its own, which drew a one-sample capture one 8-bit level apart on the layer): a sharp edge on a wide near surface blurs into a smooth outline, not steps from row to row (`tests/near-steps.test.js` runs the kernels on the WebGL2 layer's CPU tier; `tests/gpu/lens-check.mjs` measures a receding floor and three-blade bokeh on the GPU). Finite disk sampling can undersample tiny foreground silhouettes; it does not reconstruct hidden geometry. Opaque depth controls blur; transparent materials do not provide separate depth layers.
|
|
70
|
+
|
|
71
|
+
Standalone output uses Margo's display curve (Khronos PBR Neutral, then sRGB), as core does. For color grading, attach DOF first, then `Tonemap.attach(stage.engine, {source:()=>dof.outputTexture})`. The current HDR `outputTexture` and `depthTexture` are undefined before the first frame and change on resize/restoration. With TAA, supply `depth:()=>dof.depthTexture` to TAA. Destroy dependent effects before DOF. Alone, SSAO and Creative PostProcessing own conflicting scene captures and are rejected. To combine DOF with SSAO, Bloom, Tonemap, Creative PostProcessing or FXAA, add it to a `PostStack` from `@margoengine/post/stack`, e.g. `PostStack.attach(stage.engine, [new SSAO(), new DOF(), new Bloom(), new Tonemap()])`; there it reads the stack's shared HDR capture and depth, and its `depthTexture` is the stack's.
|
|
72
|
+
|
|
73
|
+
## Blur cap
|
|
74
|
+
|
|
75
|
+
`maxRadius` is the largest blur disk, in pixels of a view `referenceHeight` pixels tall (default 1080). The cap
|
|
76
|
+
scales with the view's height, as the circle of confusion does, so a canvas twice as tall (a 2x supersampled 1080p
|
|
77
|
+
render) blurs the same share of the frame as a 1080 px one: 16 px at 1080 is 32 px at 2160 and 8 px at 540, at most
|
|
78
|
+
128 px (KB-DOF-CAPSCALE1). To cap in a page's own pixels whatever its size, set `referenceHeight` to that height.
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
import {createStage} from 'margoengine';
|
|
82
|
+
import {DOF} from 'margoengine/dof';
|
|
83
|
+
const stage = await createStage('#viewport', {backend:'webgpu'});
|
|
84
|
+
// 8 px of blur at most on a 1080 px view; 16 px on a 2160 px canvas, the same share of the frame.
|
|
85
|
+
const dof = DOF.attach(stage.engine, {focalDistance:2, aperture:2, maxRadius:8});
|
|
86
|
+
// Or cap in this canvas's own pixels.
|
|
87
|
+
dof.options.referenceHeight = stage.engine.canvas.height;
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
## Focal length from the camera
|
|
91
|
+
|
|
92
|
+
Give `filmGauge` (the sensor size in millimetres) and the focal length follows the camera's field of view every frame,
|
|
93
|
+
as a real lens on that sensor would have it: zooming in (a narrower `camera.fov`) lengthens the lens and deepens the blur,
|
|
94
|
+
with no second number to keep in step.
|
|
95
|
+
|
|
96
|
+
```ts
|
|
97
|
+
import {createStage} from 'margoengine';
|
|
98
|
+
import {DOF} from 'margoengine/dof';
|
|
99
|
+
const stage = await createStage('#viewport', {backend:'webgpu'});
|
|
100
|
+
// A full-frame sensor, 36 mm across the longer side of the view; focalLength is not used.
|
|
101
|
+
const dof = DOF.attach(stage.engine, {focalDistance:4, aperture:1.8, filmGauge:36});
|
|
102
|
+
stage.engine.camera.fov = 20; // a longer lens: about 57 mm in a 16:9 view
|
|
103
|
+
console.log(dof.focalLength); // the focal length in metres the last frame used
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
- `sensorFit` names the side the gauge spans: `'auto'` (the longer side, the default), `'horizontal'` or `'vertical'`, as
|
|
107
|
+
in `lensToFov` and `fovToLens` of `@margoengine/cameras`. Common gauges: 36 full frame, 23.6 APS-C, 17.3 Micro Four
|
|
108
|
+
Thirds, 24.89 Super 35.
|
|
109
|
+
- The focal length comes out in metres, so `focalDistance` is in metres too (glTF's unit). With an orthographic camera
|
|
110
|
+
it still comes from `camera.fov`.
|
|
111
|
+
- To drive the camera from a lens instead (focal length in, field of view out, with exposure and motion blur), use
|
|
112
|
+
`PhysicalCamera` from `@margoengine/cameras/physical`.
|
|
113
|
+
|
|
114
|
+
## Temporal DOF
|
|
115
|
+
|
|
116
|
+
`temporal: true` gathers the bokeh at half resolution, a quarter of the pixels, and turns its taps by the golden angle
|
|
117
|
+
every frame; TAA attached after DOF averages the turns in its history, so the bokeh comes out smooth from a gather over a
|
|
118
|
+
quarter of the pixels (the cost has not been timed). Pixels in focus keep the full-resolution scene as it is.
|
|
119
|
+
|
|
120
|
+
Temporal DOF works on native WebGPU and the full WebGL2 compatibility layer.
|
|
121
|
+
The full layer writes the half scene and CoC first, then computes independent
|
|
122
|
+
tile maxima before gathering; it does not need workgroup shared memory.
|
|
123
|
+
|
|
124
|
+
```ts
|
|
125
|
+
import {createStage} from 'margoengine';
|
|
126
|
+
import {DOF} from 'margoengine/dof';
|
|
127
|
+
import {TAA} from 'margoengine/taa';
|
|
128
|
+
const stage = await createStage('#viewport', {backend:'webgpu'});
|
|
129
|
+
const dof = DOF.attach(stage.engine, {focalDistance:4, aperture:1.4, temporal:true});
|
|
130
|
+
TAA.attach(stage.engine, {depth:()=>dof.depthTexture});
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
- The circle of confusion is still worked out per full-resolution pixel; each 2x2 block of the scene is averaged and
|
|
134
|
+
takes the nearest of its four depths for the half gather. Near-field blur spreads over the focus as before.
|
|
135
|
+
- Read when the effect attaches. Runs on native WebGPU and the full WebGL2 compatibility layer. Without TAA the
|
|
136
|
+
turning taps show as a faint shimmer in large far disks; an aperture image's far taps do not turn.
|
|
137
|
+
|
|
138
|
+
## Autofocus, tilt-shift and blades
|
|
139
|
+
|
|
140
|
+
Each is its own entry, so a page using neither downloads neither. `DOFLens` also draws custom bokeh shapes (below).
|
|
141
|
+
|
|
142
|
+
```ts
|
|
143
|
+
import {Engine} from 'margoengine/core';
|
|
144
|
+
import {DOF} from 'margoengine/dof';
|
|
145
|
+
import {Autofocus} from 'margoengine/dof/autofocus';
|
|
146
|
+
import {DOFLens} from 'margoengine/dof/lens';
|
|
147
|
+
|
|
148
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
149
|
+
// blades: 3 to 16 sided bokeh; tilt in radians, positive moves the focal plane further away towards tiltDirection.
|
|
150
|
+
const lens = new DOFLens({blades: 6, bladeRotation: 0.2, tilt: 0.3, tiltDirection: [0, 1]});
|
|
151
|
+
const dof = DOF.attach(engine, {focalLength: 0.05, aperture: 1.4, lens});
|
|
152
|
+
const autofocus = Autofocus.attach(engine, dof, {smoothing: 0.2});
|
|
153
|
+
addEventListener('pointermove', (e) => { autofocus.options.point = [e.offsetX, e.offsetY]; });
|
|
154
|
+
// Or follow a world point with no depth read:
|
|
155
|
+
autofocus.options.target = [0, 1, 0];
|
|
156
|
+
lens.tilt = 0.1;
|
|
157
|
+
engine.start();
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
- `Autofocus` sets `dof.options.focalDistance`. It reads one depth texel into a buffer and maps it later without waiting, so the focus follows a frame or two behind and a frame never stalls. The sky leaves the focus where it was. `target` (a world point) wins over `point` while the camera sees it; a target behind the camera or outside the frame is ignored and the depth at `point` sets the focus, so a camera that looks away from its subject keeps the view sharp. Attach it after the `DOF`, alone or in a `PostStack`.
|
|
161
|
+
- `smoothing` counts frame time, not the wall clock: the engine's frame updates move `autofocus.time` through `advanceTime(delta)`, so an offline render that takes seconds per frame eases the same as a live one, and `seek` from `margoengine/cutscene/seek` replays the clock. The eased focus itself is view history: after a cut it settles over the scene's warm-up frames (within 1 % of the step after 2.3 x `smoothing` seconds).
|
|
162
|
+
- `DOFLens` is read when the effect attaches; only `tilt` and `tiltDirection` change afterwards. A perspective plane stays a plane: `1/focus` is linear across the screen, and past the horizon of the plane everything counts as in front of it. It is checked on WebGPU and on the WebGL2 layer (`install({force: true})` of `margoengine/webgl2-compat`): there autofocus finds the same focus and every lens case covers the same pixels, within the layer's parity rule (at most 0.1% of pixels more than 2 levels apart). The layer reads multisampled depth as one sample, so DOF's WebGL2 route takes the nearest depth of each pixel and its four neighbours to keep silhouettes on their object; temporal DOF uses a separate half-image and tile-max route on the full layer.
|
|
163
|
+
|
|
164
|
+
## Custom bokeh shapes
|
|
165
|
+
|
|
166
|
+
`DOFLens` also takes an aperture image (hearts, stars, dirty glass): any RGBA pixels, such as a canvas's `ImageData`.
|
|
167
|
+
|
|
168
|
+
```ts
|
|
169
|
+
import {Engine} from 'margoengine/core';
|
|
170
|
+
import {DOF} from 'margoengine/dof';
|
|
171
|
+
import {DOFLens} from 'margoengine/dof/lens';
|
|
172
|
+
|
|
173
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
174
|
+
// Draw a white heart on a transparent 64 x 64 canvas: light passes where the image is bright.
|
|
175
|
+
const art = document.createElement('canvas');
|
|
176
|
+
art.width = art.height = 64;
|
|
177
|
+
const pen = art.getContext('2d')!;
|
|
178
|
+
pen.fillStyle = '#fff';
|
|
179
|
+
pen.font = '60px sans-serif';
|
|
180
|
+
pen.textAlign = 'center';
|
|
181
|
+
pen.textBaseline = 'middle';
|
|
182
|
+
pen.fillText('\u2665', 32, 36);
|
|
183
|
+
const lens = new DOFLens({aperture: pen.getImageData(0, 0, 64, 64)});
|
|
184
|
+
DOF.attach(engine, {focalDistance: 8, focalLength: 0.05, aperture: 1.4, lens});
|
|
185
|
+
engine.start();
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
- Light passes as the image's luminance times its alpha, so grey parts pass part of it (smudged glass). The image's
|
|
189
|
+
inscribed circle covers the blur disk, its top towards the top of the screen; outside that circle nothing passes.
|
|
190
|
+
- The image is baked into the kernels when the effect attaches: a 32 x 32 mask, and far-field taps spread over the open
|
|
191
|
+
part, so detail finer than about 1/16 of the bokeh's diameter is lost. Near and far bokeh show the image the same way
|
|
192
|
+
up (a real lens flips one of them). `blades` and `aperture` do not combine.
|
|
193
|
+
|
|
194
|
+
## Cat's eye and anamorphic bokeh
|
|
195
|
+
|
|
196
|
+
```ts
|
|
197
|
+
import {Engine} from 'margoengine/core';
|
|
198
|
+
import {DOF} from 'margoengine/dof';
|
|
199
|
+
import {DOFLens} from 'margoengine/dof/lens';
|
|
200
|
+
|
|
201
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
202
|
+
// catEye: the barrel circle's offset at the frame corners, in bokeh radii (0 to 1.5); anamorphic: oval squeeze (1 to 4).
|
|
203
|
+
const lens = new DOFLens({catEye: 0.8, anamorphic: 1.5});
|
|
204
|
+
DOF.attach(engine, {focalDistance: 6, focalLength: 0.05, aperture: 1.4, lens});
|
|
205
|
+
engine.start();
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
- Optical vignetting clips each bokeh towards the frame's edges by a second circle, the lens barrel, offset outwards
|
|
209
|
+
in proportion to the pixel's distance from the centre, so corner bokeh turn into cat's eyes whose long side runs
|
|
210
|
+
around the frame; the centre stays round.
|
|
211
|
+
- `anamorphic` makes every bokeh an oval that many times taller than wide, as an anamorphic lens's do. Both combine with
|
|
212
|
+
`blades`, tilt and `temporal`, not with an `aperture` image. Fixed at construction.
|
|
213
|
+
|
|
214
|
+
## Transparent canvas
|
|
215
|
+
|
|
216
|
+
With `TransparentCanvas` (`@margoengine/environment`) every gather gives alpha the same taps and weights as colour, so
|
|
217
|
+
a blurred edge carries its coverage and shows over the page, for the full and half resolution (`temporal`) gathers and
|
|
218
|
+
every lens shape. The display pass encodes the straight colour of partly covered pixels. `outputTexture` holds linear
|
|
219
|
+
premultiplied colour with alpha. It costs one `r32float` plane at a quarter of the gather's pixels, a second at the
|
|
220
|
+
gather's size with `temporal`, on a transparent canvas only; an opaque canvas keeps its shaders. A canvas made
|
|
221
|
+
transparent after DOF attached switches on the next frame. Checked by `tests/gpu/alpha-check.mjs` on WebGPU and the
|
|
222
|
+
WebGL2 layer: colour equals the blur over black, and boxes of one flat colour keep that colour times alpha within one
|
|
223
|
+
8-bit step in eight cases. The weights come from depth and circle of confusion alone, so colour is unchanged. Where the
|
|
224
|
+
near gather's estimate of the background behind a near edge clamps at zero, the result over a transparent canvas matches
|
|
225
|
+
the blur over black, and can differ slightly from a blur rendered over a light background. Sources: T. Porter and T.
|
|
226
|
+
Duff, "Compositing Digital Images", SIGGRAPH 1984, <https://graphics.pixar.com/library/Compositing/paper.pdf>; J.
|
|
227
|
+
Jimenez, "Next Generation Post Processing in Call of Duty: Advanced Warfare", SIGGRAPH 2014.
|
|
228
|
+
|
|
229
|
+
## Cost
|
|
230
|
+
|
|
231
|
+
GPU time of the DOF passes (CoC, wide-disk 2x2-block gather, bokeh), Intel Arc 140V laptop iGPU, Edge 155, DamagedHelmet scene (the earlier test model) with environment light in a `PostStack` [DOF, Tonemap], median of 6 alternating old/new rounds x 90 frames (`examples/package-benchmarks/gates/dof.mjs`, `results/gates-dof.json`). "Before" is the 64-tap full-resolution gather of `5b9dbbd`.
|
|
232
|
+
|
|
233
|
+
| Focus | 720p 4x MSAA | 720p 1x | 1080p 4x | 1080p 1x |
|
|
234
|
+
| --- | --- | --- | --- | --- |
|
|
235
|
+
| 3.4 m, f/1.4, maxRadius 16 | 4.91 → 1.45 ms | 3.35 → 1.77 ms | 8.69 → 3.26 ms | 10.20 → 2.85 ms |
|
|
236
|
+
| 1.6 m (helmet and background blurred) | 5.15 → 2.23 ms | 5.02 → 2.49 ms | 10.06 → 4.28 ms | 10.68 → 4.47 ms |
|
|
237
|
+
| 12 m (helmet and floor in the near field) | 3.80 → 0.86 ms | 3.89 → 0.86 ms | 8.63 → 1.69 ms | 8.63 → 1.85 ms |
|
|
238
|
+
| 2 m, f/0.35, maxRadius 32 (9-23 px disks) | 5.45 → 2.35 ms | 4.86 → 2.75 ms | 10.52 → 4.84 ms | 11.22 → 4.90 ms |
|
|
239
|
+
|
|
240
|
+
MSAA does not change the DOF work (it reads the resolved scene); the 720p 4x/1x gate columns differ by GPU clock between runs. Measured before the near field's mip chain (2026-11-14), which adds one pass writing three textures at the gather's size and three 2x2 reductions of them; not measured since.
|
|
241
|
+
|
|
242
|
+
The work follows the blur: in-focus and foreground pixels skip the far gather; the near gather spreads its taps over the largest foreground disk that reaches the 8x8 tile (nothing when none is in reach); far disks get about one tap per covered pixel (16 taps up to 2.26 px, 32 up to 3.19 px, 64 beyond); disks over 3.19 px are gathered once per 2x2 block and interpolated, except next to a depth change. Against the 64-tap gather the 8-bit frames differ by a mean of 0.00-0.11 levels (at most 0.3% of pixels by more than 6 levels, single pixels on high-contrast edges inside a blur); in-focus pixels and the near field are unchanged.
|
|
243
|
+
|
|
244
|
+
Owned textures, buffers and bind groups are reused between frames, rebuilt on resize/device restoration, and freed on removal. Steady frames construct no typed arrays and no GPU objects (counted by a mock-GPU test); WebGPU itself returns pass encoder objects. Custom draws must write linear HDR into the current `context.color`; the default core shader is adapted through the extension API.
|
|
245
|
+
|
|
246
|
+
From the repository root:
|
|
247
|
+
|
|
248
|
+
```sh
|
|
249
|
+
npm --prefix packages/dof run build
|
|
250
|
+
npm --prefix packages/dof test
|
|
251
|
+
npm --prefix packages/dof run dev
|
|
252
|
+
npm --prefix packages/dof run build:demo
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
The Vite HTML demo is `examples/index.html`. Run `npm run build:packages` once for core/stage artifacts. This package supports core `^0.1.0 || ^1.0.0` through the existing extension API and is included in workspace builds and release checks. No dependencies are bundled from core.
|
|
256
|
+
|
|
257
|
+
The package's `1.0.0` version does not require Engine 1.0. It works with the
|
|
258
|
+
current Core/Stage 0.1.0. `node scripts/build-site.js` assembles its standalone
|
|
259
|
+
demo at `/demos/dof/`; the package catalog links to that built route. The demo
|
|
260
|
+
uses the package's built `dist` entry and marks readiness after the complete scene's
|
|
261
|
+
GPU submission/completion and two later animation callbacks. npm publication
|
|
262
|
+
is separate: use this repository's workspace or packed local archives until the
|
|
263
|
+
package is published.
|
|
264
|
+
|
|
265
|
+
## Exact first frames on the WebGL2 layer
|
|
266
|
+
|
|
267
|
+
`dof.ready` is a promise that settles once every frame draws the blur as it will from then on. On the WebGL2
|
|
268
|
+
compatibility layer `DOF` fetches its compatibility route (`import()`) when it attaches, and until it arrives DOF used
|
|
269
|
+
alone shows the captured scene sharp. On WebGPU it is already settled. Await it before a frame that must be exact, such
|
|
270
|
+
as a film frame or a pixel comparison:
|
|
271
|
+
|
|
272
|
+
```ts
|
|
273
|
+
import {EngineKernel} from 'margoengine/core';
|
|
274
|
+
import {DOF} from 'margoengine/dof';
|
|
275
|
+
const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!, {backend:'webgpu'});
|
|
276
|
+
const dof = DOF.attach(engine, {focalDistance:5});
|
|
277
|
+
await dof.ready;
|
|
278
|
+
engine.render();
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
## Preview tier contract
|
|
282
|
+
|
|
283
|
+
GPU-only attachments refuse the small WebGL2 preview during setup with `MargoError` code `unsupported` and a help link. Native WebGPU and the full WebGL2 compatibility layer expose the WebGPU-shaped device these passes need. Use [automatic escalation](../webgl2-compat/README.md#automatic-escalation) with awaited setup to load the full layer when required. Existing real preview routes remain available.
|
package/dist/alpha.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** The shaders {@link alphaShaders} rewrites; `halfShaders`, when used, and a lens come first. */
|
|
2
|
+
export interface DOFAlphaShaders {
|
|
3
|
+
readonly coarseShader: string;
|
|
4
|
+
readonly bokehShader: string;
|
|
5
|
+
readonly nearShader: string;
|
|
6
|
+
readonly joinShader: string;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* The gather kernels carrying premultiplied alpha. `coarseShader` also writes binding 4 (r32float), `bokehShader` reads
|
|
10
|
+
* it at binding 10; at half resolution `bokehShader` also writes binding 11 (r32float), which `joinShader` reads at its
|
|
11
|
+
* binding 4.
|
|
12
|
+
*/
|
|
13
|
+
export declare function alphaShaders<T extends DOFAlphaShaders>(source: T, half: boolean): T;
|
package/dist/autofocus.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
// @margo/core-built
|
|
1
|
+
// @margo/core-built 1.0.0
|
|
2
2
|
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
-
const t=(engine,version="
|
|
3
|
+
const t=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
|
|
4
4
|
import { t as e } from "./projection-CS2tLkwf.js";
|
|
5
5
|
import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
|
|
6
6
|
import { MargoError as n } from "@margoengine/math/errors";
|
|
7
7
|
//#region src/autofocus.ts
|
|
8
|
-
var r = "@group(0) @binding(0) var depth:texture_depth_2d;\n@group(0) @binding(1) var out:texture_storage_2d<r32float,write>;\n@group(0) @binding(2) var<uniform> at:vec4u;\n@compute @workgroup_size(1) fn main() {\n textureStore(out,vec2i(0),vec4f(textureLoad(depth,vec2i(min(at.xy,textureDimensions(depth)-1u)),0),0,0,0));\n}", i = class i {coreRequirement=__margoCoreRequirement("
|
|
9
|
-
static attach(e, n, r = {}) {__margoAssertCore(e,__margoCoreRequirement("
|
|
8
|
+
var r = "@group(0) @binding(0) var depth:texture_depth_2d;\n@group(0) @binding(1) var out:texture_storage_2d<r32float,write>;\n@group(0) @binding(2) var<uniform> at:vec4u;\n@compute @workgroup_size(1) fn main() {\n textureStore(out,vec2i(0),vec4f(textureLoad(depth,vec2i(min(at.xy,textureDimensions(depth)-1u)),0),0,0,0));\n}", i = class i {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
|
|
9
|
+
static attach(e, n, r = {}) {__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));
|
|
10
10
|
let a = new i(n, r);
|
|
11
11
|
return t(e).use(a), a;
|
|
12
12
|
}
|