@margoengine/dof 0.0.0-stage → 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 ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Scott Campbell
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Margo Engine
2
+ Copyright 2026 Scott Campbell
3
+
4
+ This product includes Margo Engine (https://margoengine.com) by Scott Campbell.
package/README.md CHANGED
@@ -1,3 +1,283 @@
1
- # Temporary Holding Version
1
+ # @margoengine/dof
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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.
@@ -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;
@@ -0,0 +1,61 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import { type Engine, type EnginePlugin, type FrameGraph } from '@margoengine/core/extension';
4
+ import type { DOF } from './index.js';
5
+ /** `Autofocus` settings, read from `autofocus.options` every frame. */
6
+ export interface AutofocusOptions {
7
+ /** CSS pixel whose depth sets the focus, such as the pointer. Default: the middle of the canvas. */
8
+ point?: readonly [number, number];
9
+ /** World point to keep in focus, with no depth read. Wins over `point` while the camera sees it; behind the camera or
10
+ * outside the frame it is ignored and `point` is read. */
11
+ target?: ArrayLike<number>;
12
+ /** Seconds the focus takes to get about two thirds of the way; 0 jumps. Default 0.2. */
13
+ smoothing?: number;
14
+ }
15
+ /**
16
+ * Keeps `dof.options.focalDistance` on what a pixel shows, or on a world point. The depth is read back a frame or two
17
+ * later without waiting, so a frame never stalls for it; the sky leaves the focus where it is.
18
+ * @throws TypeError without a `DOF`.
19
+ * @throws MargoError `'unsupported'` on a WebGL engine, `'disposed'` after `dispose()`.
20
+ */
21
+ export declare class Autofocus implements EnginePlugin {
22
+ readonly dof: DOF;
23
+ readonly options: AutofocusOptions;
24
+ readonly name = "dof-autofocus";
25
+ private engine?;
26
+ private pipeline?;
27
+ private uniform?;
28
+ private texel?;
29
+ private read?;
30
+ private group?;
31
+ private depth?;
32
+ private state;
33
+ private near;
34
+ private far;
35
+ private flat;
36
+ private previous;
37
+ private clock;
38
+ private settled;
39
+ private disposed;
40
+ private readonly point;
41
+ /** Same as `engine.use(new Autofocus(dof, options))`; returns the Autofocus. */
42
+ static attach(engine: EngineKernel, dof: DOF, options?: AutofocusOptions): Autofocus;
43
+ constructor(dof: DOF, options?: AutofocusOptions);
44
+ /** Seconds of frame time this autofocus has run for; the smoothing counts it. A fresh one reads 0. */
45
+ get time(): number;
46
+ /**
47
+ * Moves the smoothing clock by `delta` seconds: the CPU part of the frame update, which a seek from
48
+ * `@margoengine/cutscene/seek` replays. The focus follows frame time, not the wall clock, so a frame rendered
49
+ * slower than real time (an offline film render) eases the same as a live one.
50
+ */
51
+ advanceTime(delta: number): void;
52
+ onPreUpdate(delta: number): void;
53
+ setup(engine: Engine): void;
54
+ registerPasses(graph: FrameGraph): void;
55
+ private frame;
56
+ private focus;
57
+ private release;
58
+ onDeviceRestored(engine: Engine): void;
59
+ dispose(): void;
60
+ [Symbol.dispose]: () => void;
61
+ }