@margoengine/html 0.0.0-stage → 0.1.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,88 @@
1
- # Temporary Holding Version
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.
1
+ # @margoengine/html
2
+
3
+ World-space DOM anchors, CSS3D placement and scene-depth occlusion.
4
+
5
+ Import `margoengine/html` from the `margoengine` package, or `@margoengine/html` 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).
6
+
7
+ World-space DOM anchors reuse labels' projection, frustum clipping, inherited visibility and CSS3D placement. 2D anchors additionally use asynchronous scene-depth occlusion.
8
+
9
+ ```ts
10
+ import {HTML} from 'margoengine/html';
11
+ import {Engine} from 'margoengine/core';
12
+ import {createMesh} from 'margoengine/materials';
13
+ import {box} from 'margoengine/core';
14
+ const engine = await Engine.create(document.querySelector('canvas')!);
15
+ const mesh = engine.createMesh().setGeometry(box());
16
+ const element = document.createElement('div');
17
+ const html = HTML.attach(engine);
18
+ html.add(element, {mesh, offset: [0,1,0]});
19
+ ```
20
+
21
+ WebGPU defaults to a shared sampleable depth target, also used by water. Pass depth: () => effect.depthTexture with SSAO/DOF, or depth: false to disable GPU occlusion. On the WebGL2 preview backend (`@margoengine/webgl2-compat/preview`), whose canvas depth cannot be sampled, the same tests run as occlusion queries: after the scene, one point a test is drawn at the anchor with colour and depth writes off inside an `ANY_SAMPLES_PASSED` query, and the result is read when the browser makes it available, a frame or more later. A round of queries is in flight per anchor at a time; `fade` there costs `samples` x `samples` points and queries an anchor, so keep it small (`samples: 2`) with many anchors. Capacity defaults to 1024 anchors, maximum 1,048,576 (`capacity`); storage starts at 64 slots and doubles as anchors are added, and each frame's depth work runs to the highest slot in use, not to the capacity. Depth results arrive asynchronously and stale results after substantial motion are ignored; there can be a frame of visibility latency. depthBias is reversed-Z depth, not world units. CSS3D objects are projected but not sampled for depth. dispose removes the overlay and owned elements.
22
+
23
+ ## Smooth partial occlusion
24
+
25
+ `fade` fades an anchor as geometry slides over it instead of hiding it at once. Each frame the depth pass tests an `samples` x `samples` grid over a square `radius` CSS pixels around the anchor (4 x 4 over 8 px by default) and the element's `style.opacity` moves toward the share of tests the scene leaves clear, at most from 1 to 0 in `duration` seconds (default 0.15; 0 follows each result at once). At opacity 0 the element is hidden (`display: none`); at 1 its inline opacity is removed again. Both backends; style the element's own opacity on a child, since fade writes the element's.
26
+
27
+ ```ts
28
+ import {HTML} from 'margoengine/html';
29
+ import {Engine, box} from 'margoengine/core';
30
+ const engine = await Engine.create(document.querySelector('canvas')!);
31
+ engine.createMesh().setGeometry(box());
32
+ const html = HTML.attach(engine, {fade: {radius: 8, samples: 4, duration: 0.15}});
33
+ const tip = document.createElement('div');
34
+ tip.textContent = 'Behind the box';
35
+ html.add(tip, {position: [0.6, 0, -1]});
36
+ ```
37
+
38
+ Results arrive a frame or two late, like the hard test's. A result taken before the anchor moved more than `radius` (at least 4) CSS pixels is not applied and the anchor's target opacity goes back to 1, as a moving anchor is never hidden by where it was.
39
+
40
+ ## DOM drawn into the scene
41
+
42
+ `margoengine/html/texture` (`@margoengine/html/texture`) draws HTML elements as textures on quads in the scene. A quad is depth-tested and writes depth like scene geometry, so a mesh in front of it hides its part, and the page's pointer reaches the element where it hits the quad: hover, focus, clicks and typing go to the element itself, through the browser's own hit test. WebGPU only.
43
+
44
+ ```ts
45
+ import {HTMLTexture} from 'margoengine/html/texture';
46
+ import {Engine} from 'margoengine/core';
47
+ const engine = await Engine.create(document.querySelector('canvas')!);
48
+ const panel = document.createElement('div');
49
+ panel.style.cssText = 'width:200px;height:100px;background:#0af';
50
+ const button = document.createElement('button');
51
+ button.textContent = 'Press';
52
+ button.addEventListener('click', () => (button.textContent = 'Pressed'));
53
+ panel.append(button);
54
+ const textures = HTMLTexture.attach(engine);
55
+ // 2 x 1 world units at the origin, facing +Z; pass {mesh} to follow a mesh, or {matrix} for any pose.
56
+ const surface = textures.add(panel, {width: 2, height: 1});
57
+ ```
58
+
59
+ `add` moves the element into an invisible holder at the top left of the page (opacity 0, no pointer events), where it keeps its layout, focus and events. The size defaults to the element's CSS size at 100 CSS pixels a world unit, the texture to `devicePixelRatio` texture pixels a CSS pixel (`pixelRatio`, 0.25 to 4). Two rasterizers draw the element: `'element-image'`, the HTML-in-canvas `drawElementImage` where the browser has it (the default there), and `'foreign-object'`, the element's tree with its computed styles inlined into an SVG `foreignObject` image, everywhere else. The texture is drawn again when the element changes (a mutation, input, focus or hover, or an HTML-in-canvas paint event); call `surface.invalidate()` after a change none of these shows, such as a loaded font. While the pointer is over a quad, the holder moves so that the element's point under the pointer is the hit point on the quad; off every quad it moves back out of the way. A raster that fails (a `prepare` that rejects, a tainting or broken image) reaches `engine.onError` as a `MargoError` with code `failed` and the original error as `cause`; the surface keeps its last texture until `surface.invalidate()` draws it again.
60
+
61
+ With `'foreign-object'`, fonts and images the element uses must be same-origin data the SVG image can embed (data URLs); the browser loads nothing from inside it. Scene geometry in front of a quad hides it on screen but does not stop the pointer reaching the element. On a linear HDR target (rgba16float, as post-processing uses) the element's sRGB colour is decoded to linear light (the CSS Color 4 sRGB curve), as `ColorBackground` does, so the post chain's tone map and encode apply to it like any unlit surface; on a display target the bytes are drawn as they are. Pointer routing maps the whole canvas: with a view rectangle or several views it does not follow the view's camera. `textures.dispose()` removes the holders and the elements in them.
62
+
63
+ ## Many anchors
64
+
65
+ One overlay takes up to 1,048,576 anchors. Its point, result and readback buffers start at 64 slots and double as anchors are added (re-made at the next depth test, never while a read is in flight), a removed anchor's slot is taken again first, and the per-frame depth work, WebGL2 queries included, runs to the highest slot in use.
66
+
67
+ ```ts
68
+ import {HTML} from 'margoengine/html';
69
+ import {Engine} from 'margoengine/core';
70
+ const engine = await Engine.create(document.querySelector('canvas')!);
71
+ // 10,000 map pins in one overlay: past the old 4,096 limit.
72
+ const pins = HTML.attach(engine, {capacity: 10_000});
73
+ for (let i = 0; i < 10_000; i++) {
74
+ const pin = document.createElement('div');
75
+ pin.textContent = String(i);
76
+ pins.add(pin, {position: [(i % 100) - 50, 0, Math.floor(i / 100) - 50]});
77
+ }
78
+ ```
79
+
80
+ Apache-2.0. Optional, tree-shakable package; core peer: ^0.1.0 || ^1.0.0.
81
+
82
+ Build and unit tests: npm test --workspace @margoengine/html
83
+
84
+ ## Preview tier contract
85
+
86
+ 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.
87
+
88
+ `HTMLBlend`, `HTMLTextureGL` and `HTMLTexture` are reviewed preview routes in `scripts/check-preview-contract.mjs` (2026-11-10): each has one `backend` test and real drawing on the small preview. `HTMLBlend` punches its mask with WebGL2 on the preview and with WebGPU elsewhere; `HTMLTextureGL` draws textured quads with WebGL2 on the preview; plain `HTMLTexture` refuses the preview (`unsupported`) and draws only through its `HTMLTextureGL` subclass there. Pixel evidence for both backends is `test/html-browser.js` (`npm run test:browser`, also with `MARGO_COMPAT=1`); the plain refusal is in `test/texture.test.js`. No behaviour changed; the routes were added after `4e3337946` first broke `npm run verify`.
@@ -0,0 +1,33 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import { type FrameGraph } from '@margoengine/core/extension';
4
+ import { LabelRenderer, type Label, type CSS3DObject, type CSS3DOptions, type LabelRendererOptions } from '@margoengine/labels';
5
+ /** CSS3D panels behind a depth-tested transparent canvas aperture. Rectangular panels retain real DOM content. */
6
+ export declare class HTMLBlend extends LabelRenderer {
7
+ private runtime?;
8
+ private readonly masks;
9
+ private readonly pipelines;
10
+ private readonly values;
11
+ private readonly viewport;
12
+ private readonly descriptor;
13
+ private glState?;
14
+ private disposed;
15
+ constructor(options?: LabelRendererOptions);
16
+ /** Attaches the DOM layer and the mask pass; preview must be created with an alpha-enabled renderer. */
17
+ static attach(engine: EngineKernel, options?: LabelRendererOptions): HTMLBlend;
18
+ setup(instance: EngineKernel): void;
19
+ add3D(element: HTMLElement, options?: CSS3DOptions): CSS3DObject;
20
+ remove(item: Label | CSS3DObject): void;
21
+ registerPasses(graph: FrameGraph): void;
22
+ private configuration;
23
+ private configure;
24
+ private pipeline;
25
+ private explicitViewport;
26
+ private drawGPU;
27
+ private drawGL;
28
+ private releaseGL;
29
+ /** Rebuilds lazily after restoration and reapplies alpha compositing to the restored canvas. */
30
+ onDeviceRestored(): void;
31
+ dispose(): void;
32
+ [Symbol.dispose]: () => void;
33
+ }
package/dist/blend.js ADDED
@@ -0,0 +1,185 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const a=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { t as e } from "./errors-fc4i1pSL.js";
5
+ import { t } from "./view-rect-Be4T67Kk.js";
6
+ import { t as n } from "./pass-BVRaGB09.js";
7
+ import { n as r, t as i } from "./gl-j8yV2Jj1.js";
8
+ import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
9
+ import { LabelRenderer as o } from "@margoengine/labels";
10
+ //#region src/blend.ts
11
+ var s = "struct Mask {camera:mat4x4f,model:mat4x4f,size:vec4f}\n@group(0) @binding(0) var<uniform> mask:Mask;\n@vertex fn vertex(@builtin(vertex_index) i:u32)->@builtin(position) vec4f {\n let p=array<vec2f,6>(vec2f(-.5,.5),vec2f(.5,.5),vec2f(-.5,-.5),vec2f(-.5,-.5),vec2f(.5,.5),vec2f(.5,-.5))[i];\n return mask.camera*mask.model*vec4f(p*mask.size.xy,0,1);\n}\n@fragment fn fragment()->@location(0) vec4f {return vec4f(0);}", c = "#version 300 es\nuniform mat4 camera,model;uniform vec2 size;\nvoid main(){vec2 p[6]=vec2[6](vec2(-.5,.5),vec2(.5,.5),vec2(-.5,-.5),vec2(-.5,-.5),vec2(.5,.5),vec2(.5,-.5));\ngl_Position=camera*model*vec4(p[gl_VertexID]*size,0,1);}", l = "#version 300 es\nprecision highp float;out vec4 color;void main(){color=vec4(0);}", u = /* @__PURE__ */ new WeakMap(), d = class d extends o {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);
12
+ constructor(e = {}) {
13
+ super({
14
+ ...e,
15
+ name: e.name ?? "html-blend",
16
+ zIndex: e.zIndex ?? 0
17
+ }), this.masks = /* @__PURE__ */ new Map(), this.pipelines = /* @__PURE__ */ new Map(), this.values = /* @__PURE__ */ new Float32Array(36), this.viewport = [
18
+ 0,
19
+ 0,
20
+ 0,
21
+ 0
22
+ ], this.descriptor = n(), this.disposed = !1;
23
+ }
24
+ static attach(e, t) {__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));
25
+ let n = new d(t);
26
+ return a(e).use(n), n;
27
+ }
28
+ setup(t) {
29
+ if (this.disposed) throw e("disposed", "HTMLBlend is disposed; create a new HTMLBlend");
30
+ let n = a(t), r = n.canvas;
31
+ if (!n.gpu && !r.getContext("webgl2")?.getContextAttributes()?.alpha) throw e("unsupported", "HTMLBlend needs canvas alpha; create the preview with webglRenderer(canvas, {transparent: true})");
32
+ this.runtime = n;
33
+ let i = u.get(r);
34
+ i || (i = {
35
+ owners: 0,
36
+ position: r.style.position,
37
+ zIndex: r.style.zIndex,
38
+ pointerEvents: r.style.pointerEvents,
39
+ alphaMode: this.configuration()?.alphaMode ?? "opaque"
40
+ }, u.set(r, i)), i.owners++, r.style.position ||= "relative", r.style.zIndex = "1", r.style.pointerEvents = "none", this.configure("premultiplied"), super.setup(t);
41
+ }
42
+ add3D(t, n = {}) {
43
+ if (this.disposed) throw e("disposed", "HTMLBlend is disposed; create a new HTMLBlend");
44
+ let r = super.add3D(t, {
45
+ pointerEvents: "auto",
46
+ ...n
47
+ });
48
+ return this.masks.set(r, {}), r;
49
+ }
50
+ remove(e) {
51
+ this.masks.get(e)?.uniform?.destroy(), this.masks.delete(e), super.remove(e);
52
+ }
53
+ registerPasses(e) {
54
+ e.add({
55
+ name: this.name,
56
+ order: .9,
57
+ execute: (e) => {
58
+ for (let e of this.masks.keys()) e.remeasure();
59
+ this.update(), e.backend === "webgpu" ? this.drawGPU(e) : this.drawGL(e);
60
+ }
61
+ });
62
+ }
63
+ configuration() {
64
+ if (this.runtime?.gpu) return this.runtime.canvas.getContext("webgpu")?.getConfiguration?.();
65
+ }
66
+ configure(e) {
67
+ let t = this.runtime;
68
+ t?.gpu && !t.disposed && t.canvas.getContext("webgpu").configure({
69
+ ...this.configuration(),
70
+ device: t.gpu,
71
+ format: this.configuration()?.format ?? navigator.gpu.getPreferredCanvasFormat(),
72
+ alphaMode: e
73
+ });
74
+ }
75
+ pipeline(e) {
76
+ let t = e.descriptor, n = `${e.format} ${t.multisample?.count} ${t.depthStencil?.format} ${t.depthStencil?.depthCompare}`, r = this.pipelines.get(n);
77
+ if (!r) {
78
+ let i = e.device.createShaderModule({ code: s });
79
+ r = e.device.createRenderPipeline({
80
+ layout: "auto",
81
+ vertex: {
82
+ module: i,
83
+ entryPoint: "vertex"
84
+ },
85
+ fragment: {
86
+ module: i,
87
+ entryPoint: "fragment",
88
+ targets: [{ format: e.format }]
89
+ },
90
+ primitive: {
91
+ topology: "triangle-list",
92
+ cullMode: "none"
93
+ },
94
+ depthStencil: t.depthStencil && {
95
+ format: t.depthStencil.format,
96
+ depthWriteEnabled: !0,
97
+ depthCompare: t.depthStencil.depthCompare ?? "less"
98
+ },
99
+ multisample: t.multisample
100
+ }), this.pipelines.set(n, r);
101
+ }
102
+ return r;
103
+ }
104
+ explicitViewport(e) {
105
+ let t = this.view;
106
+ if (!t) return;
107
+ let [n, r, i, a] = t.viewport ?? [
108
+ 0,
109
+ 0,
110
+ 1,
111
+ 1
112
+ ], o = this.runtime.canvas, s = t.pixels ? e.width / o.width : e.width, c = t.pixels ? e.height / o.height : e.height;
113
+ return this.viewport[0] = n * s, this.viewport[1] = r * c, this.viewport[2] = i * s, this.viewport[3] = a * c, this.viewport;
114
+ }
115
+ drawGPU(e) {
116
+ if (!this.masks.size) return;
117
+ let n = this.pipeline(e), r = this.explicitViewport(e), i = this.view ? this.view.camera ?? this.runtime.camera : e.camera, a;
118
+ for (let [o, s] of this.masks) if (o.onScreen) {
119
+ if (s.uniform ??= e.device.createBuffer({
120
+ size: 144,
121
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
122
+ }), s.pipeline !== n && (s.group = void 0, s.pipeline = n), s.group ??= e.device.createBindGroup({
123
+ layout: n.getBindGroupLayout(0),
124
+ entries: [{
125
+ binding: 0,
126
+ resource: { buffer: s.uniform }
127
+ }]
128
+ }), this.values.set(i.matrix), this.values.set(o.matrix, 16), this.values[32] = o.element.offsetWidth * o.pixelScale, this.values[33] = o.element.offsetHeight * o.pixelScale, e.device.queue.writeBuffer(s.uniform, 0, this.values), !a) {
129
+ if (this.descriptor.colorAttachments[0].view = e.color, this.descriptor.depthStencilAttachment.view = e.depth, a = e.encoder.beginRenderPass(this.descriptor), r) {
130
+ let [t, n, i, o] = r, s = Math.max(0, Math.floor(t)), c = Math.max(0, Math.floor(n)), l = Math.min(e.width, Math.ceil(t + i)), u = Math.min(e.height, Math.ceil(n + o));
131
+ a.setViewport(t, n, i, o, 0, 1), a.setScissorRect(s, c, Math.max(0, l - s), Math.max(0, u - c));
132
+ } else t(a, e);
133
+ a.setPipeline(n);
134
+ }
135
+ a.setBindGroup(0, s.group), a.draw(6);
136
+ }
137
+ a?.end();
138
+ }
139
+ drawGL(e) {
140
+ if (!this.masks.size || e.gl.isContextLost()) return;
141
+ let t = e.gl;
142
+ this.glState?.gl !== t && this.releaseGL(), this.glState ??= {
143
+ gl: t,
144
+ program: r(t, c, l),
145
+ vao: t.createVertexArray()
146
+ };
147
+ let { program: n, vao: a } = this.glState, o = i(t);
148
+ try {
149
+ let r = this.explicitViewport(e), [i, o, s, c] = r ?? e.view?.viewport ?? [
150
+ 0,
151
+ 0,
152
+ e.width,
153
+ e.height
154
+ ], l = this.view ? this.view.camera ?? this.runtime.camera : e.camera;
155
+ if (t.viewport(i, e.height - o - c, s, c), r) {
156
+ let n = Math.max(0, Math.floor(i)), r = Math.max(0, Math.floor(o)), a = Math.min(e.width, Math.ceil(i + s)), l = Math.min(e.height, Math.ceil(o + c));
157
+ t.enable(t.SCISSOR_TEST), t.scissor(n, e.height - l, Math.max(0, a - n), Math.max(0, l - r));
158
+ }
159
+ t.useProgram(n), t.bindVertexArray(a), t.disable(t.BLEND), t.disable(t.CULL_FACE), t.enable(t.DEPTH_TEST), t.depthFunc(t.LESS), t.depthMask(!0), t.colorMask(!0, !0, !0, !0), t.uniformMatrix4fv(t.getUniformLocation(n, "camera"), !1, l.matrix);
160
+ for (let e of this.masks.keys()) e.onScreen && (t.uniformMatrix4fv(t.getUniformLocation(n, "model"), !1, new Float32Array(e.matrix)), t.uniform2f(t.getUniformLocation(n, "size"), e.element.offsetWidth * e.pixelScale, e.element.offsetHeight * e.pixelScale), t.drawArrays(t.TRIANGLES, 0, 6));
161
+ } finally {
162
+ o();
163
+ }
164
+ }
165
+ releaseGL() {
166
+ let e = this.glState;
167
+ this.glState = void 0, e && !e.gl.isContextLost() && (e.gl.deleteProgram(e.program), e.gl.deleteVertexArray(e.vao));
168
+ }
169
+ onDeviceRestored() {
170
+ this.pipelines.clear();
171
+ for (let e of this.masks.values()) e.uniform = e.group = e.pipeline = void 0;
172
+ this.releaseGL(), this.configure("premultiplied");
173
+ }
174
+ dispose() {
175
+ if (this.disposed) return;
176
+ this.disposed = !0, this.releaseGL();
177
+ let e = this.runtime?.canvas, t = e && u.get(e);
178
+ t && --t.owners === 0 && (this.configure(t.alphaMode), e.style.position = t.position, e.style.zIndex = t.zIndex, e.style.pointerEvents = t.pointerEvents, u.delete(e)), super.dispose(), this.pipelines.clear(), this.runtime = void 0;
179
+ }
180
+ [Symbol.dispose ?? Symbol()]() {
181
+ this.dispose();
182
+ }
183
+ };
184
+ //#endregion
185
+ export { d as HTMLBlend };
@@ -0,0 +1,17 @@
1
+ //#region src/dom.ts
2
+ function e(t) {
3
+ let n = t.cloneNode(!1), r = t.ownerDocument.defaultView;
4
+ if (t instanceof r.HTMLElement || t instanceof r.SVGElement) {
5
+ let e = r.getComputedStyle(t), i = "";
6
+ for (let t = 0; t < e.length; t++) {
7
+ let n = e[t];
8
+ i += `${n}:${e.getPropertyValue(n)};`;
9
+ }
10
+ n.setAttribute("style", i);
11
+ }
12
+ if (t instanceof r.HTMLInputElement && (n.setAttribute("value", t.value), t.checked ? n.setAttribute("checked", "") : n.removeAttribute("checked")), t instanceof r.HTMLOptionElement && (t.selected ? n.setAttribute("selected", "") : n.removeAttribute("selected")), t instanceof r.HTMLTextAreaElement) n.textContent = t.value;
13
+ else for (let r of t.childNodes) n.appendChild(r.nodeType === 1 ? e(r) : r.cloneNode(!1));
14
+ return n;
15
+ }
16
+ //#endregion
17
+ export { e as t };
package/dist/dom.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ /** @internal Inline computed styles and live form state without changing the source tree. */
2
+ export declare function inlineCopy(source: Element): Element;
@@ -0,0 +1,7 @@
1
+ //#region ../shared/errors.js
2
+ var e = (e, t) => Object.assign(Error(t), {
3
+ name: "MargoError",
4
+ code: e
5
+ });
6
+ //#endregion
7
+ export { e as t };
@@ -0,0 +1,31 @@
1
+ import { t as e } from "./errors-fc4i1pSL.js";
2
+ //#region src/gl.ts
3
+ function t(t, n, r) {
4
+ let i = t.createProgram();
5
+ for (let [e, a] of [[t.VERTEX_SHADER, n], [t.FRAGMENT_SHADER, r]]) {
6
+ let n = t.createShader(e);
7
+ t.shaderSource(n, a), t.compileShader(n), t.attachShader(i, n), t.deleteShader(n);
8
+ }
9
+ if (t.linkProgram(i), !t.getProgramParameter(i, t.LINK_STATUS)) {
10
+ let n = t.getProgramInfoLog(i);
11
+ throw t.deleteProgram(i), e("failed", `HTML preview shader failed: ${n}; check WebGL2 support`);
12
+ }
13
+ return i;
14
+ }
15
+ function n(e) {
16
+ let t = e.getParameter(e.CURRENT_PROGRAM), n = e.getParameter(e.VERTEX_ARRAY_BINDING), r = e.getParameter(e.VIEWPORT), i = e.getParameter(e.SCISSOR_BOX), a = e.getParameter(e.COLOR_WRITEMASK), o = e.getParameter(e.DEPTH_WRITEMASK), s = e.getParameter(e.DEPTH_FUNC), c = e.getParameter(e.BLEND_SRC_RGB), l = e.getParameter(e.BLEND_DST_RGB), u = e.getParameter(e.BLEND_SRC_ALPHA), d = e.getParameter(e.BLEND_DST_ALPHA), f = e.getParameter(e.BLEND_EQUATION_RGB), p = e.getParameter(e.BLEND_EQUATION_ALPHA), m = e.getParameter(e.ACTIVE_TEXTURE), h = [
17
+ e.BLEND,
18
+ e.CULL_FACE,
19
+ e.DEPTH_TEST,
20
+ e.SCISSOR_TEST
21
+ ].map((t) => [t, e.isEnabled(t)]);
22
+ e.activeTexture(e.TEXTURE0);
23
+ let g = e.getParameter(e.TEXTURE_BINDING_2D), _ = e.getParameter(e.SAMPLER_BINDING);
24
+ return () => {
25
+ e.useProgram(t), e.bindVertexArray(n), e.viewport(r[0], r[1], r[2], r[3]), e.scissor(i[0], i[1], i[2], i[3]), e.colorMask(a[0], a[1], a[2], a[3]), e.depthMask(o), e.depthFunc(s), e.blendFuncSeparate(c, l, u, d), e.blendEquationSeparate(f, p);
26
+ for (let [t, n] of h) n ? e.enable(t) : e.disable(t);
27
+ e.activeTexture(e.TEXTURE0), e.bindTexture(e.TEXTURE_2D, g), e.bindSampler(0, _), e.activeTexture(m);
28
+ };
29
+ }
30
+ //#endregion
31
+ export { t as n, n as t };
package/dist/gl.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ /** Internal clean-room GL program builder, shared by HTML's optional preview passes. */
2
+ export declare function htmlProgram(gl: WebGL2RenderingContext, vertex: string, fragment: string): WebGLProgram;
3
+ /** Preserve every draw state changed by either HTML pass, including texture unit zero's sampler. */
4
+ export declare function htmlGLState(gl: WebGL2RenderingContext): () => void;