@paper-design/shaders 0.0.0-canary.0d8316e

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.
Files changed (127) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +5 -0
  3. package/README.md +7 -0
  4. package/dist/empty-pixel.d.ts +1 -0
  5. package/dist/empty-pixel.js +10 -0
  6. package/dist/empty-pixel.js.map +7 -0
  7. package/dist/get-shader-color-from-string.d.ts +3 -0
  8. package/dist/get-shader-color-from-string.js +101 -0
  9. package/dist/get-shader-color-from-string.js.map +7 -0
  10. package/dist/get-shader-noise-texture.d.ts +1 -0
  11. package/dist/get-shader-noise-texture.js +18 -0
  12. package/dist/get-shader-noise-texture.js.map +7 -0
  13. package/dist/html-in-canvas.d.ts +35 -0
  14. package/dist/html-in-canvas.js +79 -0
  15. package/dist/html-in-canvas.js.map +7 -0
  16. package/dist/index.d.ts +69 -0
  17. package/dist/index.js +196 -0
  18. package/dist/index.js.map +7 -0
  19. package/dist/shader-color-spaces.d.ts +6 -0
  20. package/dist/shader-color-spaces.js +96 -0
  21. package/dist/shader-color-spaces.js.map +7 -0
  22. package/dist/shader-mount.d.ts +151 -0
  23. package/dist/shader-mount.js +605 -0
  24. package/dist/shader-mount.js.map +7 -0
  25. package/dist/shader-sizing.d.ts +30 -0
  26. package/dist/shader-sizing.js +38 -0
  27. package/dist/shader-sizing.js.map +7 -0
  28. package/dist/shader-utils.d.ts +10 -0
  29. package/dist/shader-utils.js +131 -0
  30. package/dist/shader-utils.js.map +7 -0
  31. package/dist/shaders/color-panels.d.ts +70 -0
  32. package/dist/shaders/color-panels.js +224 -0
  33. package/dist/shaders/color-panels.js.map +7 -0
  34. package/dist/shaders/dithering.d.ts +62 -0
  35. package/dist/shaders/dithering.js +271 -0
  36. package/dist/shaders/dithering.js.map +7 -0
  37. package/dist/shaders/dot-grid.d.ts +65 -0
  38. package/dist/shaders/dot-grid.js +110 -0
  39. package/dist/shaders/dot-grid.js.map +7 -0
  40. package/dist/shaders/dot-orbit.d.ts +57 -0
  41. package/dist/shaders/dot-orbit.js +123 -0
  42. package/dist/shaders/dot-orbit.js.map +7 -0
  43. package/dist/shaders/fluted-glass.d.ts +115 -0
  44. package/dist/shaders/fluted-glass.js +361 -0
  45. package/dist/shaders/fluted-glass.js.map +7 -0
  46. package/dist/shaders/gem-smoke.d.ts +96 -0
  47. package/dist/shaders/gem-smoke.js +573 -0
  48. package/dist/shaders/gem-smoke.js.map +7 -0
  49. package/dist/shaders/god-rays.d.ts +67 -0
  50. package/dist/shaders/god-rays.js +133 -0
  51. package/dist/shaders/god-rays.js.map +7 -0
  52. package/dist/shaders/grain-gradient.d.ts +80 -0
  53. package/dist/shaders/grain-gradient.js +301 -0
  54. package/dist/shaders/grain-gradient.js.map +7 -0
  55. package/dist/shaders/halftone-cmyk.d.ts +107 -0
  56. package/dist/shaders/halftone-cmyk.js +319 -0
  57. package/dist/shaders/halftone-cmyk.js.map +7 -0
  58. package/dist/shaders/halftone-dots.d.ts +83 -0
  59. package/dist/shaders/halftone-dots.js +345 -0
  60. package/dist/shaders/halftone-dots.js.map +7 -0
  61. package/dist/shaders/heatmap.d.ts +66 -0
  62. package/dist/shaders/heatmap.js +384 -0
  63. package/dist/shaders/heatmap.js.map +7 -0
  64. package/dist/shaders/image-dithering.d.ts +66 -0
  65. package/dist/shaders/image-dithering.js +209 -0
  66. package/dist/shaders/image-dithering.js.map +7 -0
  67. package/dist/shaders/lens-distortion.d.ts +100 -0
  68. package/dist/shaders/lens-distortion.js +290 -0
  69. package/dist/shaders/lens-distortion.js.map +7 -0
  70. package/dist/shaders/liquid-metal.d.ts +89 -0
  71. package/dist/shaders/liquid-metal.js +633 -0
  72. package/dist/shaders/liquid-metal.js.map +7 -0
  73. package/dist/shaders/mesh-gradient.d.ts +52 -0
  74. package/dist/shaders/mesh-gradient.js +131 -0
  75. package/dist/shaders/mesh-gradient.js.map +7 -0
  76. package/dist/shaders/metaballs.d.ts +51 -0
  77. package/dist/shaders/metaballs.js +111 -0
  78. package/dist/shaders/metaballs.js.map +7 -0
  79. package/dist/shaders/neuro-noise.d.ts +47 -0
  80. package/dist/shaders/neuro-noise.js +77 -0
  81. package/dist/shaders/neuro-noise.js.map +7 -0
  82. package/dist/shaders/paper-texture.d.ts +113 -0
  83. package/dist/shaders/paper-texture.js +541 -0
  84. package/dist/shaders/paper-texture.js.map +7 -0
  85. package/dist/shaders/perlin-noise.d.ts +52 -0
  86. package/dist/shaders/perlin-noise.js +167 -0
  87. package/dist/shaders/perlin-noise.js.map +7 -0
  88. package/dist/shaders/pulsing-border.d.ts +98 -0
  89. package/dist/shaders/pulsing-border.js +239 -0
  90. package/dist/shaders/pulsing-border.js.map +7 -0
  91. package/dist/shaders/simplex-noise.d.ts +45 -0
  92. package/dist/shaders/simplex-noise.js +92 -0
  93. package/dist/shaders/simplex-noise.js.map +7 -0
  94. package/dist/shaders/smoke-ring.d.ts +61 -0
  95. package/dist/shaders/smoke-ring.js +133 -0
  96. package/dist/shaders/smoke-ring.js.map +7 -0
  97. package/dist/shaders/spiral.d.ts +61 -0
  98. package/dist/shaders/spiral.js +83 -0
  99. package/dist/shaders/spiral.js.map +7 -0
  100. package/dist/shaders/static-mesh-gradient.d.ts +63 -0
  101. package/dist/shaders/static-mesh-gradient.js +131 -0
  102. package/dist/shaders/static-mesh-gradient.js.map +7 -0
  103. package/dist/shaders/static-radial-gradient.d.ts +72 -0
  104. package/dist/shaders/static-radial-gradient.js +188 -0
  105. package/dist/shaders/static-radial-gradient.js.map +7 -0
  106. package/dist/shaders/swirl.d.ts +63 -0
  107. package/dist/shaders/swirl.js +104 -0
  108. package/dist/shaders/swirl.js.map +7 -0
  109. package/dist/shaders/voronoi.d.ts +65 -0
  110. package/dist/shaders/voronoi.js +139 -0
  111. package/dist/shaders/voronoi.js.map +7 -0
  112. package/dist/shaders/warp.d.ts +70 -0
  113. package/dist/shaders/warp.js +130 -0
  114. package/dist/shaders/warp.js.map +7 -0
  115. package/dist/shaders/water.d.ts +63 -0
  116. package/dist/shaders/water.js +135 -0
  117. package/dist/shaders/water.js.map +7 -0
  118. package/dist/shaders/waves.d.ts +53 -0
  119. package/dist/shaders/waves.js +66 -0
  120. package/dist/shaders/waves.js.map +7 -0
  121. package/dist/types.d.ts +3 -0
  122. package/dist/types.js +6 -0
  123. package/dist/types.js.map +7 -0
  124. package/dist/vertex-shader.d.ts +2 -0
  125. package/dist/vertex-shader.js +163 -0
  126. package/dist/vertex-shader.js.map +7 -0
  127. package/package.json +29 -0
@@ -0,0 +1,605 @@
1
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * * *
2
+ * Paper Shaders *
3
+ * https://github.com/paper-design/shaders *
4
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * */
5
+
6
+ import { vertexShaderSource } from "./vertex-shader.js";
7
+ import {
8
+ attachHtml,
9
+ drawHtml,
10
+ findReactCanvas,
11
+ isHtmlInCanvasSupported,
12
+ isHtmlUniform
13
+ } from "./html-in-canvas.js";
14
+ const DEFAULT_MAX_PIXEL_COUNT = 1920 * 1080 * 4;
15
+ class ShaderMount {
16
+ parentElement;
17
+ canvasElement;
18
+ gl;
19
+ program = null;
20
+ uniformLocations = {};
21
+ /** The fragment shader that we are using */
22
+ fragmentShader;
23
+ /** Stores the RAF for the render loop */
24
+ rafId = null;
25
+ /** Time of the last rendered frame */
26
+ lastRenderTime = 0;
27
+ /** Total time that we have played any animation, passed as a uniform to the shader for time-based VFX */
28
+ currentFrame = 0;
29
+ /** The speed that we progress through animation time (multiplies by delta time every update). Allows negatives to play in reverse. If set to 0, rAF will stop entirely so static shaders have no recurring performance costs */
30
+ speed = 0;
31
+ /** Actual speed used that accounts for visibility: we pause the shader if the tab is hidden or the element out of the viewport */
32
+ currentSpeed = 0;
33
+ /** Uniforms that are provided by the user for the specific shader being mounted (not including uniforms that this Mount adds, like time and resolution) */
34
+ providedUniforms;
35
+ /** Names of the uniforms that should have mipmaps generated for them */
36
+ mipmaps = [];
37
+ /** Just a sanity check to make sure frames don't run after we're disposed */
38
+ hasBeenDisposed = false;
39
+ /** If the resolution of the canvas has changed since the last render */
40
+ resolutionChanged = true;
41
+ /** Store textures that are provided by the user */
42
+ textures = /* @__PURE__ */ new Map();
43
+ minPixelRatio;
44
+ maxPixelCount;
45
+ isSafari = isSafari();
46
+ uniformCache = {};
47
+ textureUnitMap = /* @__PURE__ */ new Map();
48
+ ownerDocument;
49
+ htmlUniforms = /* @__PURE__ */ new Map();
50
+ isReactCanvas = false;
51
+ constructor(parentElement, fragmentShader, uniforms, webGlContextAttributes, speed = 0, frame = 0, minPixelRatio = 2, maxPixelCount = DEFAULT_MAX_PIXEL_COUNT, mipmaps = []) {
52
+ if (parentElement?.nodeType === 1) {
53
+ this.parentElement = parentElement;
54
+ } else {
55
+ throw new Error("Paper Shaders: parent element must be an HTMLElement");
56
+ }
57
+ this.ownerDocument = parentElement.ownerDocument;
58
+ if (!this.ownerDocument.querySelector("style[data-paper-shader]")) {
59
+ const styleElement = this.ownerDocument.createElement("style");
60
+ styleElement.innerHTML = defaultStyle;
61
+ styleElement.setAttribute("data-paper-shader", "");
62
+ this.ownerDocument.head.prepend(styleElement);
63
+ }
64
+ const reactCanvas = findReactCanvas(Object.values(uniforms), this.parentElement);
65
+ const canvasElement = reactCanvas ?? this.ownerDocument.createElement("canvas");
66
+ this.canvasElement = canvasElement;
67
+ this.isReactCanvas = reactCanvas !== null;
68
+ if (!reactCanvas) {
69
+ this.parentElement.prepend(canvasElement);
70
+ }
71
+ canvasElement.addEventListener("paint", this.handleCanvasPaint);
72
+ this.fragmentShader = fragmentShader;
73
+ this.providedUniforms = uniforms;
74
+ this.mipmaps = mipmaps;
75
+ this.currentFrame = frame;
76
+ this.minPixelRatio = minPixelRatio;
77
+ this.maxPixelCount = maxPixelCount;
78
+ const gl = canvasElement.getContext("webgl2", {
79
+ antialias: false,
80
+ depth: false,
81
+ stencil: false,
82
+ ...webGlContextAttributes
83
+ });
84
+ if (!gl) {
85
+ throw new Error("Paper Shaders: WebGL is not supported in this browser");
86
+ }
87
+ this.gl = gl;
88
+ this.gl.pixelStorei(this.gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
89
+ this.initProgram();
90
+ this.setupPositionAttribute();
91
+ this.setupUniforms();
92
+ this.setUniformValues(this.providedUniforms);
93
+ this.setupResizeObserver();
94
+ visualViewport?.addEventListener("resize", this.handleVisualViewportChange);
95
+ this.setupIntersectionObserver();
96
+ this.setSpeed(speed);
97
+ this.parentElement.setAttribute("data-paper-shader", "");
98
+ this.parentElement.paperShaderMount = this;
99
+ this.ownerDocument.addEventListener("visibilitychange", this.handleDocumentVisibilityChange);
100
+ }
101
+ initProgram = () => {
102
+ const program = createProgram(this.gl, vertexShaderSource, this.fragmentShader);
103
+ if (!program) return;
104
+ this.program = program;
105
+ this.gl.useProgram(program);
106
+ };
107
+ setupPositionAttribute = () => {
108
+ const positionAttributeLocation = this.gl.getAttribLocation(this.program, "a_position");
109
+ const positionBuffer = this.gl.createBuffer();
110
+ this.gl.bindBuffer(this.gl.ARRAY_BUFFER, positionBuffer);
111
+ const positions = [-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1];
112
+ this.gl.bufferData(this.gl.ARRAY_BUFFER, new Float32Array(positions), this.gl.STATIC_DRAW);
113
+ this.gl.enableVertexAttribArray(positionAttributeLocation);
114
+ this.gl.vertexAttribPointer(positionAttributeLocation, 2, this.gl.FLOAT, false, 0, 0);
115
+ };
116
+ setupUniforms = () => {
117
+ const uniformLocations = {
118
+ u_time: this.gl.getUniformLocation(this.program, "u_time"),
119
+ u_pixelRatio: this.gl.getUniformLocation(this.program, "u_pixelRatio"),
120
+ u_resolution: this.gl.getUniformLocation(this.program, "u_resolution")
121
+ };
122
+ Object.entries(this.providedUniforms).forEach(([key, value]) => {
123
+ uniformLocations[key] = this.gl.getUniformLocation(this.program, key);
124
+ if (value instanceof HTMLImageElement || isHtmlUniform(value)) {
125
+ const aspectRatioUniformName = `${key}AspectRatio`;
126
+ uniformLocations[aspectRatioUniformName] = this.gl.getUniformLocation(this.program, aspectRatioUniformName);
127
+ uniformLocations[`${key}IsHtml`] = this.gl.getUniformLocation(this.program, `${key}IsHtml`);
128
+ }
129
+ });
130
+ this.uniformLocations = uniformLocations;
131
+ };
132
+ /**
133
+ * The scale that we should render at.
134
+ * - Used to target 2x rendering even on 1x screens for better antialiasing
135
+ * - Prevents the virtual resolution from going beyond the maximum resolution
136
+ * - Accounts for the page zoom level so we render in physical device pixels rather than CSS pixels
137
+ */
138
+ renderScale = 1;
139
+ parentWidth = 0;
140
+ parentHeight = 0;
141
+ parentDevicePixelWidth = 0;
142
+ parentDevicePixelHeight = 0;
143
+ devicePixelsSupported = false;
144
+ intersectionObserver = null;
145
+ isInViewport = true;
146
+ resizeObserver = null;
147
+ setupResizeObserver = () => {
148
+ this.resizeObserver = new ResizeObserver(([entry]) => {
149
+ if (entry?.borderBoxSize[0]) {
150
+ const physicalPixelSize = entry.devicePixelContentBoxSize?.[0];
151
+ if (physicalPixelSize !== void 0) {
152
+ this.devicePixelsSupported = true;
153
+ this.parentDevicePixelWidth = physicalPixelSize.inlineSize;
154
+ this.parentDevicePixelHeight = physicalPixelSize.blockSize;
155
+ }
156
+ this.parentWidth = entry.borderBoxSize[0].inlineSize;
157
+ this.parentHeight = entry.borderBoxSize[0].blockSize;
158
+ }
159
+ this.handleResize();
160
+ });
161
+ this.resizeObserver.observe(this.parentElement);
162
+ };
163
+ setupIntersectionObserver = () => {
164
+ const view = this.ownerDocument.defaultView;
165
+ if (!view?.IntersectionObserver) return;
166
+ this.intersectionObserver = new view.IntersectionObserver(([entry]) => {
167
+ this.isInViewport = entry?.isIntersecting ?? true;
168
+ this.updateCurrentSpeed();
169
+ });
170
+ this.intersectionObserver.observe(this.parentElement);
171
+ };
172
+ // Visual viewport resize handler, mainly used to react to browser zoom changes.
173
+ // Resize observer by itself does not react to pinch zoom, and although it usually
174
+ // reacts to classic browser zoom, it's not guaranteed in edge cases.
175
+ // Since timing between visual viewport changes and resize observer is complex
176
+ // and because we'd like to know the device pixel sizes of elements, we just restart
177
+ // the observer to get a guaranteed fresh callback regardless if it would have triggered or not.
178
+ handleVisualViewportChange = () => {
179
+ this.resizeObserver?.disconnect();
180
+ this.setupResizeObserver();
181
+ };
182
+ /** Resize handler for when the container div changes size or the max pixel count changes and we want to resize our canvas to match */
183
+ handleResize = () => {
184
+ let targetPixelWidth = 0;
185
+ let targetPixelHeight = 0;
186
+ const dpr = Math.max(1, window.devicePixelRatio);
187
+ const pinchZoom = visualViewport?.scale ?? 1;
188
+ if (this.devicePixelsSupported) {
189
+ const scaleToMeetMinPixelRatio = Math.max(1, this.minPixelRatio / dpr);
190
+ targetPixelWidth = this.parentDevicePixelWidth * scaleToMeetMinPixelRatio * pinchZoom;
191
+ targetPixelHeight = this.parentDevicePixelHeight * scaleToMeetMinPixelRatio * pinchZoom;
192
+ } else {
193
+ let targetRenderScale = Math.max(dpr, this.minPixelRatio) * pinchZoom;
194
+ if (this.isSafari) {
195
+ const zoomLevel = bestGuessBrowserZoom(this.ownerDocument);
196
+ targetRenderScale *= Math.max(1, zoomLevel);
197
+ }
198
+ targetPixelWidth = Math.round(this.parentWidth) * targetRenderScale;
199
+ targetPixelHeight = Math.round(this.parentHeight) * targetRenderScale;
200
+ }
201
+ const maxPixelCountHeadroom = Math.sqrt(this.maxPixelCount) / Math.sqrt(targetPixelWidth * targetPixelHeight);
202
+ const scaleToMeetMaxPixelCount = Math.min(1, maxPixelCountHeadroom);
203
+ const newWidth = Math.round(targetPixelWidth * scaleToMeetMaxPixelCount);
204
+ const newHeight = Math.round(targetPixelHeight * scaleToMeetMaxPixelCount);
205
+ const newRenderScale = newWidth / Math.round(this.parentWidth);
206
+ if (this.canvasElement.width !== newWidth || this.canvasElement.height !== newHeight || this.renderScale !== newRenderScale) {
207
+ this.renderScale = newRenderScale;
208
+ this.canvasElement.width = newWidth;
209
+ this.canvasElement.height = newHeight;
210
+ this.resolutionChanged = true;
211
+ this.gl.viewport(0, 0, this.gl.canvas.width, this.gl.canvas.height);
212
+ this.captureHtml(true);
213
+ if (this.htmlUniforms.size > 0) {
214
+ this.canvasElement.requestPaint();
215
+ }
216
+ this.render(performance.now());
217
+ }
218
+ };
219
+ render = (currentTime) => {
220
+ if (this.hasBeenDisposed) return;
221
+ if (this.program === null) {
222
+ console.warn("Tried to render before program or gl was initialized");
223
+ return;
224
+ }
225
+ const dt = currentTime - this.lastRenderTime;
226
+ this.lastRenderTime = currentTime;
227
+ if (this.currentSpeed !== 0) {
228
+ this.currentFrame += dt * this.currentSpeed;
229
+ }
230
+ this.gl.clear(this.gl.COLOR_BUFFER_BIT);
231
+ this.gl.uniform1f(this.uniformLocations.u_time, this.currentFrame * 1e-3);
232
+ if (this.resolutionChanged) {
233
+ this.gl.uniform2f(this.uniformLocations.u_resolution, this.gl.canvas.width, this.gl.canvas.height);
234
+ this.gl.uniform1f(this.uniformLocations.u_pixelRatio, this.renderScale);
235
+ this.resolutionChanged = false;
236
+ }
237
+ this.gl.drawArrays(this.gl.TRIANGLES, 0, 6);
238
+ if (this.currentSpeed !== 0) {
239
+ this.requestRender();
240
+ } else {
241
+ this.rafId = null;
242
+ }
243
+ };
244
+ requestRender = () => {
245
+ if (this.rafId !== null) {
246
+ cancelAnimationFrame(this.rafId);
247
+ }
248
+ this.rafId = requestAnimationFrame(this.render);
249
+ };
250
+ /** Creates a texture from an image and sets it into a uniform value */
251
+ setTextureUniform = (uniformName, image) => {
252
+ if (!image.complete || image.naturalWidth === 0) {
253
+ throw new Error(`Paper Shaders: image for uniform ${uniformName} must be fully loaded`);
254
+ }
255
+ this.unsetHtmlUniform(uniformName);
256
+ const { texture, textureUnit } = this.createTexture(uniformName);
257
+ this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, this.gl.RGBA, this.gl.UNSIGNED_BYTE, image);
258
+ if (this.mipmaps.includes(uniformName)) {
259
+ this.gl.generateMipmap(this.gl.TEXTURE_2D);
260
+ this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MIN_FILTER, this.gl.LINEAR_MIPMAP_LINEAR);
261
+ }
262
+ const error = this.gl.getError();
263
+ if (error !== this.gl.NO_ERROR || texture === null) {
264
+ console.error("Paper Shaders: WebGL error when uploading texture:", error);
265
+ return;
266
+ }
267
+ this.textures.set(uniformName, texture);
268
+ const location = this.uniformLocations[uniformName];
269
+ if (location) {
270
+ this.gl.uniform1i(location, textureUnit);
271
+ const aspectRatioUniformName = `${uniformName}AspectRatio`;
272
+ const aspectRatioLocation = this.uniformLocations[aspectRatioUniformName];
273
+ if (aspectRatioLocation) {
274
+ const aspectRatio = image.naturalWidth / image.naturalHeight;
275
+ this.gl.uniform1f(aspectRatioLocation, aspectRatio);
276
+ }
277
+ this.gl.uniform1f(this.uniformLocations[`${uniformName}IsHtml`] ?? null, 0);
278
+ }
279
+ };
280
+ createTexture = (uniformName) => {
281
+ const existingTexture = this.textures.get(uniformName);
282
+ if (existingTexture) {
283
+ this.gl.deleteTexture(existingTexture);
284
+ }
285
+ if (!this.textureUnitMap.has(uniformName)) {
286
+ this.textureUnitMap.set(uniformName, this.textureUnitMap.size);
287
+ }
288
+ const textureUnit = this.textureUnitMap.get(uniformName);
289
+ this.gl.activeTexture(this.gl.TEXTURE0 + textureUnit);
290
+ const texture = this.gl.createTexture();
291
+ this.gl.bindTexture(this.gl.TEXTURE_2D, texture);
292
+ this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, this.gl.CLAMP_TO_EDGE);
293
+ this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, this.gl.CLAMP_TO_EDGE);
294
+ this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MIN_FILTER, this.gl.LINEAR);
295
+ this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MAG_FILTER, this.gl.LINEAR);
296
+ return { texture, textureUnit };
297
+ };
298
+ /** Moves the element into the shader canvas and redraws it into the texture on every canvas paint */
299
+ setHtmlUniform = (uniformName, element) => {
300
+ this.unsetHtmlUniform(uniformName);
301
+ const { texture, textureUnit } = this.createTexture(uniformName);
302
+ if (texture === null) return;
303
+ this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, 1, 1, 0, this.gl.RGBA, this.gl.UNSIGNED_BYTE, null);
304
+ this.textures.set(uniformName, texture);
305
+ this.gl.uniform1i(this.uniformLocations[uniformName] ?? null, textureUnit);
306
+ this.gl.uniform1f(this.uniformLocations[`${uniformName}IsHtml`] ?? null, 1);
307
+ if (!isHtmlInCanvasSupported()) {
308
+ console.warn(
309
+ `Paper Shaders: HTML for ${uniformName} needs HTML in canvas support (chrome://flags/#canvas-draw-element)`
310
+ );
311
+ return;
312
+ }
313
+ const canvas = this.canvasElement;
314
+ this.htmlUniforms.set(uniformName, { element, detach: attachHtml(canvas, element), hasGeometry: false });
315
+ canvas.requestPaint();
316
+ };
317
+ /** Captures each HTML uniform into its texture. On resize only HTML that has a snapshot already, so it can't throw */
318
+ captureHtml = (isResize) => {
319
+ const canvas = this.canvasElement;
320
+ this.htmlUniforms.forEach((html, uniformName) => {
321
+ if (isResize && html.layout === void 0) return;
322
+ this.gl.activeTexture(this.gl.TEXTURE0 + this.textureUnitMap.get(uniformName));
323
+ this.gl.bindTexture(this.gl.TEXTURE_2D, this.textures.get(uniformName));
324
+ html.layout = drawHtml(this.gl, canvas, html.element, html.layout);
325
+ });
326
+ };
327
+ unsetHtmlUniform = (uniformName) => {
328
+ this.htmlUniforms.get(uniformName)?.detach();
329
+ this.htmlUniforms.delete(uniformName);
330
+ };
331
+ handleCanvasPaint = () => {
332
+ const canvas = this.canvasElement;
333
+ this.captureHtml(false);
334
+ this.htmlUniforms.forEach((html) => {
335
+ if (!html.hasGeometry) {
336
+ canvas.updateElementGeometry(html.element, { canvasTransform: new DOMMatrix() });
337
+ html.hasGeometry = true;
338
+ }
339
+ });
340
+ this.renderUnlessAnimating();
341
+ };
342
+ /** Utility: recursive equality test for all the uniforms */
343
+ areUniformValuesEqual = (a, b) => {
344
+ if (a === b) return true;
345
+ if (Array.isArray(a) && Array.isArray(b) && a.length === b.length) {
346
+ return a.every((val, i) => this.areUniformValuesEqual(val, b[i]));
347
+ }
348
+ return false;
349
+ };
350
+ /** Sets the provided uniform values into the WebGL program, can be a partial list of uniforms that have changed */
351
+ setUniformValues = (updatedUniforms) => {
352
+ Object.entries(updatedUniforms).forEach(([key, value]) => {
353
+ let cacheValue = value;
354
+ if (value instanceof HTMLImageElement) {
355
+ cacheValue = `${value.src.slice(0, 200)}|${value.naturalWidth}x${value.naturalHeight}`;
356
+ }
357
+ if (this.areUniformValuesEqual(this.uniformCache[key], cacheValue)) return;
358
+ this.uniformCache[key] = cacheValue;
359
+ const location = this.uniformLocations[key];
360
+ if (!location) {
361
+ console.warn(`Uniform location for ${key} not found`);
362
+ return;
363
+ }
364
+ if (value instanceof HTMLImageElement) {
365
+ this.setTextureUniform(key, value);
366
+ } else if (isHtmlUniform(value)) {
367
+ this.setHtmlUniform(key, value);
368
+ } else if (Array.isArray(value)) {
369
+ let flatArray = null;
370
+ let valueLength = null;
371
+ if (value[0] !== void 0 && Array.isArray(value[0])) {
372
+ const firstChildLength = value[0].length;
373
+ if (value.every((arr) => arr.length === firstChildLength)) {
374
+ flatArray = value.flat();
375
+ valueLength = firstChildLength;
376
+ } else {
377
+ console.warn(`All child arrays must be the same length for ${key}`);
378
+ return;
379
+ }
380
+ } else {
381
+ flatArray = value;
382
+ valueLength = flatArray.length;
383
+ }
384
+ switch (valueLength) {
385
+ case 2:
386
+ this.gl.uniform2fv(location, flatArray);
387
+ break;
388
+ case 3:
389
+ this.gl.uniform3fv(location, flatArray);
390
+ break;
391
+ case 4:
392
+ this.gl.uniform4fv(location, flatArray);
393
+ break;
394
+ case 9:
395
+ this.gl.uniformMatrix3fv(location, false, flatArray);
396
+ break;
397
+ case 16:
398
+ this.gl.uniformMatrix4fv(location, false, flatArray);
399
+ break;
400
+ default:
401
+ console.warn(`Unsupported uniform array length: ${valueLength}`);
402
+ }
403
+ } else if (typeof value === "number") {
404
+ this.gl.uniform1f(location, value);
405
+ } else if (typeof value === "boolean") {
406
+ this.gl.uniform1i(location, value ? 1 : 0);
407
+ } else {
408
+ console.warn(`Unsupported uniform type for ${key}: ${typeof value}`);
409
+ }
410
+ });
411
+ };
412
+ /** Gets the current total animation time from 0ms */
413
+ getCurrentFrame = () => {
414
+ return this.currentFrame;
415
+ };
416
+ /** Set a frame to get a deterministic result, frames are literally just milliseconds from zero since the animation started */
417
+ setFrame = (newFrame) => {
418
+ this.currentFrame = newFrame;
419
+ this.lastRenderTime = performance.now();
420
+ this.renderUnlessAnimating();
421
+ };
422
+ /** Set an animation speed (or 0 to stop animation) */
423
+ setSpeed = (newSpeed = 1) => {
424
+ this.speed = newSpeed;
425
+ this.updateCurrentSpeed();
426
+ };
427
+ /** Apply the target speed, pausing (0) while the tab is hidden or the element is out of the viewport */
428
+ updateCurrentSpeed = () => {
429
+ this.setCurrentSpeed(this.ownerDocument.hidden || !this.isInViewport ? 0 : this.speed);
430
+ };
431
+ setCurrentSpeed = (newSpeed) => {
432
+ this.currentSpeed = newSpeed;
433
+ if (this.rafId === null && newSpeed !== 0) {
434
+ this.lastRenderTime = performance.now();
435
+ this.rafId = requestAnimationFrame(this.render);
436
+ }
437
+ if (this.rafId !== null && newSpeed === 0) {
438
+ cancelAnimationFrame(this.rafId);
439
+ this.rafId = null;
440
+ }
441
+ };
442
+ /** Set the maximum pixel count for the shader, this will limit the number of pixels that will be rendered */
443
+ setMaxPixelCount = (newMaxPixelCount = DEFAULT_MAX_PIXEL_COUNT) => {
444
+ this.maxPixelCount = newMaxPixelCount;
445
+ this.handleResize();
446
+ };
447
+ /** Set the minimum pixel ratio for the shader */
448
+ setMinPixelRatio = (newMinPixelRatio = 2) => {
449
+ this.minPixelRatio = newMinPixelRatio;
450
+ this.handleResize();
451
+ };
452
+ /** Update the uniforms that are provided by the outside shader, can be a partial set with only the uniforms that have changed */
453
+ setUniforms = (newUniforms) => {
454
+ this.setUniformValues(newUniforms);
455
+ this.providedUniforms = { ...this.providedUniforms, ...newUniforms };
456
+ this.renderUnlessAnimating();
457
+ };
458
+ /** Render right away only when the rAF loop isn't running */
459
+ renderUnlessAnimating = () => {
460
+ if (this.rafId === null) {
461
+ this.render(performance.now());
462
+ }
463
+ };
464
+ handleDocumentVisibilityChange = () => {
465
+ this.updateCurrentSpeed();
466
+ };
467
+ /** Dispose of the shader mount, cleaning up all of the WebGL resources */
468
+ dispose = () => {
469
+ this.hasBeenDisposed = true;
470
+ if (this.rafId !== null) {
471
+ cancelAnimationFrame(this.rafId);
472
+ this.rafId = null;
473
+ }
474
+ this.canvasElement.removeEventListener("paint", this.handleCanvasPaint);
475
+ this.htmlUniforms.forEach(({ detach }) => detach());
476
+ this.htmlUniforms.clear();
477
+ if (this.gl && this.program) {
478
+ this.textures.forEach((texture) => {
479
+ this.gl.deleteTexture(texture);
480
+ });
481
+ this.textures.clear();
482
+ this.gl.deleteProgram(this.program);
483
+ this.program = null;
484
+ this.gl.bindBuffer(this.gl.ARRAY_BUFFER, null);
485
+ this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER, null);
486
+ this.gl.bindRenderbuffer(this.gl.RENDERBUFFER, null);
487
+ this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, null);
488
+ this.gl.getError();
489
+ }
490
+ if (this.resizeObserver) {
491
+ this.resizeObserver.disconnect();
492
+ this.resizeObserver = null;
493
+ }
494
+ if (this.intersectionObserver) {
495
+ this.intersectionObserver.disconnect();
496
+ this.intersectionObserver = null;
497
+ }
498
+ visualViewport?.removeEventListener("resize", this.handleVisualViewportChange);
499
+ this.ownerDocument.removeEventListener("visibilitychange", this.handleDocumentVisibilityChange);
500
+ this.uniformLocations = {};
501
+ if (!this.isReactCanvas) {
502
+ this.canvasElement.remove();
503
+ }
504
+ delete this.parentElement.paperShaderMount;
505
+ };
506
+ }
507
+ function createShader(gl, type, source) {
508
+ const shader = gl.createShader(type);
509
+ if (!shader) return null;
510
+ gl.shaderSource(shader, source);
511
+ gl.compileShader(shader);
512
+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
513
+ console.error("An error occurred compiling the shaders: " + gl.getShaderInfoLog(shader));
514
+ gl.deleteShader(shader);
515
+ return null;
516
+ }
517
+ return shader;
518
+ }
519
+ function createProgram(gl, vertexShaderSource2, fragmentShaderSource) {
520
+ const format = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT);
521
+ const precision = format ? format.precision : null;
522
+ if (precision && precision < 23) {
523
+ vertexShaderSource2 = vertexShaderSource2.replace(/precision\s+(lowp|mediump)\s+float;/g, "precision highp float;");
524
+ fragmentShaderSource = fragmentShaderSource.replace(/precision\s+(lowp|mediump)\s+float/g, "precision highp float").replace(/\b(uniform|varying|attribute)\s+(lowp|mediump)\s+(\w+)/g, "$1 highp $3");
525
+ }
526
+ const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource2);
527
+ const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);
528
+ if (!vertexShader || !fragmentShader) return null;
529
+ const program = gl.createProgram();
530
+ if (!program) return null;
531
+ gl.attachShader(program, vertexShader);
532
+ gl.attachShader(program, fragmentShader);
533
+ gl.linkProgram(program);
534
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
535
+ console.error("Unable to initialize the shader program: " + gl.getProgramInfoLog(program));
536
+ gl.deleteProgram(program);
537
+ gl.deleteShader(vertexShader);
538
+ gl.deleteShader(fragmentShader);
539
+ return null;
540
+ }
541
+ gl.detachShader(program, vertexShader);
542
+ gl.detachShader(program, fragmentShader);
543
+ gl.deleteShader(vertexShader);
544
+ gl.deleteShader(fragmentShader);
545
+ return program;
546
+ }
547
+ const defaultStyle = `@layer paper-shaders {
548
+ :where([data-paper-shader]) {
549
+ isolation: isolate;
550
+ position: relative;
551
+
552
+ & > canvas {
553
+ contain: strict;
554
+ display: block;
555
+ position: absolute;
556
+ inset: 0;
557
+ z-index: -1;
558
+ width: 100%;
559
+ height: 100%;
560
+ border-radius: inherit;
561
+ corner-shape: inherit;
562
+ }
563
+
564
+ & > canvas > [drawable],
565
+ & > [drawable] {
566
+ box-sizing: border-box;
567
+ position: relative;
568
+ width: 100%;
569
+ height: 100%;
570
+ }
571
+ }
572
+ }`;
573
+ function isPaperShaderElement(element) {
574
+ return "paperShaderMount" in element;
575
+ }
576
+ function isSafari() {
577
+ const ua = navigator.userAgent.toLowerCase();
578
+ return ua.includes("safari") && !ua.includes("chrome") && !ua.includes("android");
579
+ }
580
+ function bestGuessBrowserZoom(doc) {
581
+ const viewportScale = visualViewport?.scale ?? 1;
582
+ const viewportWidth = visualViewport?.width ?? window.innerWidth;
583
+ const scrollbarWidth = window.innerWidth - doc.documentElement.clientWidth;
584
+ const innerWidth = viewportScale * viewportWidth + scrollbarWidth;
585
+ const ratio = outerWidth / innerWidth;
586
+ const zoomPercentageRounded = Math.round(100 * ratio);
587
+ if (zoomPercentageRounded % 5 === 0) {
588
+ return zoomPercentageRounded / 100;
589
+ }
590
+ if (zoomPercentageRounded === 33) {
591
+ return 1 / 3;
592
+ }
593
+ if (zoomPercentageRounded === 67) {
594
+ return 2 / 3;
595
+ }
596
+ if (zoomPercentageRounded === 133) {
597
+ return 4 / 3;
598
+ }
599
+ return ratio;
600
+ }
601
+ export {
602
+ ShaderMount,
603
+ isPaperShaderElement
604
+ };
605
+ //# sourceMappingURL=shader-mount.js.map