@razorpay/blade 12.92.1 → 12.93.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/assets/spark/bottom-frame.jpg +0 -0
- package/assets/spark/colorama-center-gradient-map.jpg +0 -0
- package/assets/spark/colorama-gradient-map-blue.jpg +0 -0
- package/assets/spark/colorama-gradient-map-green.jpg +0 -0
- package/assets/spark/ray-pulse.mp4 +0 -0
- package/assets/spark/spark-base-video.mp4 +0 -0
- package/assets/spark/success-animation-circle.mp4 +0 -0
- package/build/lib/native/components/Spark/RazorSenseGradient/FluidGradient.js +9 -0
- package/build/lib/native/components/Spark/RazorSenseGradient/FluidGradient.js.map +1 -0
- package/build/lib/native/components/Spark/RazorSenseGradient/FluidGradientMount.js +18 -0
- package/build/lib/native/components/Spark/RazorSenseGradient/FluidGradientMount.js.map +1 -0
- package/build/lib/native/components/Spark/RazorSenseGradient/shader.js +69 -0
- package/build/lib/native/components/Spark/RazorSenseGradient/shader.js.map +1 -0
- package/build/lib/native/components/Spark/RazorSenseGradient/useFluidGradient.js +7 -0
- package/build/lib/native/components/Spark/RazorSenseGradient/useFluidGradient.js.map +1 -0
- package/build/lib/native/components/Spark/RzpGlass/PerformanceManager.js +7 -0
- package/build/lib/native/components/Spark/RzpGlass/PerformanceManager.js.map +1 -0
- package/build/lib/native/components/Spark/RzpGlass/RzpGlass.js +13 -0
- package/build/lib/native/components/Spark/RzpGlass/RzpGlass.js.map +1 -0
- package/build/lib/native/components/Spark/RzpGlass/RzpGlassMount.js +28 -0
- package/build/lib/native/components/Spark/RzpGlass/RzpGlassMount.js.map +1 -0
- package/build/lib/native/components/Spark/RzpGlass/presets.js +4 -0
- package/build/lib/native/components/Spark/RzpGlass/presets.js.map +1 -0
- package/build/lib/native/components/Spark/RzpGlass/rzpGlassShader.js +920 -0
- package/build/lib/native/components/Spark/RzpGlass/rzpGlassShader.js.map +1 -0
- package/build/lib/native/components/Spark/RzpGlass/utils.js +4 -0
- package/build/lib/native/components/Spark/RzpGlass/utils.js.map +1 -0
- package/build/lib/native/components/Spark/RzpGlass/webgl-utils.js +7 -0
- package/build/lib/native/components/Spark/RzpGlass/webgl-utils.js.map +1 -0
- package/build/lib/native/components/index.js +2 -0
- package/build/lib/native/components/index.js.map +1 -1
- package/build/lib/web/development/_virtual/flatten.js +1 -1
- package/build/lib/web/development/_virtual/flatten3.js +1 -1
- package/build/lib/web/development/components/Spark/RazorSenseGradient/FluidGradient.js +92 -0
- package/build/lib/web/development/components/Spark/RazorSenseGradient/FluidGradient.js.map +1 -0
- package/build/lib/web/development/components/Spark/RazorSenseGradient/FluidGradientMount.js +110 -0
- package/build/lib/web/development/components/Spark/RazorSenseGradient/FluidGradientMount.js.map +1 -0
- package/build/lib/web/development/components/Spark/RazorSenseGradient/index.js +2 -0
- package/build/lib/web/development/components/Spark/RazorSenseGradient/index.js.map +1 -0
- package/build/lib/web/development/components/Spark/RazorSenseGradient/shader.js +18 -0
- package/build/lib/web/development/components/Spark/RazorSenseGradient/shader.js.map +1 -0
- package/build/lib/web/development/components/Spark/RazorSenseGradient/useFluidGradient.js +34 -0
- package/build/lib/web/development/components/Spark/RazorSenseGradient/useFluidGradient.js.map +1 -0
- package/build/lib/web/development/components/Spark/RzpGlass/PerformanceManager.js +455 -0
- package/build/lib/web/development/components/Spark/RzpGlass/PerformanceManager.js.map +1 -0
- package/build/lib/web/development/components/Spark/RzpGlass/RzpGlass.js +263 -0
- package/build/lib/web/development/components/Spark/RzpGlass/RzpGlass.js.map +1 -0
- package/build/lib/web/development/components/Spark/RzpGlass/RzpGlassMount.js +908 -0
- package/build/lib/web/development/components/Spark/RzpGlass/RzpGlassMount.js.map +1 -0
- package/build/lib/web/development/components/Spark/RzpGlass/index.js +24 -0
- package/build/lib/web/development/components/Spark/RzpGlass/index.js.map +1 -0
- package/build/lib/web/development/components/Spark/RzpGlass/presets.js +151 -0
- package/build/lib/web/development/components/Spark/RzpGlass/presets.js.map +1 -0
- package/build/lib/web/development/components/Spark/RzpGlass/rzpGlassShader.js +5 -0
- package/build/lib/web/development/components/Spark/RzpGlass/rzpGlassShader.js.map +1 -0
- package/build/lib/web/development/components/Spark/RzpGlass/utils.js +77 -0
- package/build/lib/web/development/components/Spark/RzpGlass/utils.js.map +1 -0
- package/build/lib/web/development/components/Spark/RzpGlass/webgl-utils.js +200 -0
- package/build/lib/web/development/components/Spark/RzpGlass/webgl-utils.js.map +1 -0
- package/build/lib/web/development/components/Spark/index.js +3 -0
- package/build/lib/web/development/components/Spark/index.js.map +1 -0
- package/build/lib/web/development/components/index.js +3 -0
- package/build/lib/web/development/components/index.js.map +1 -1
- package/build/lib/web/development/node_modules/es-toolkit/dist/array/flatten.js +1 -1
- package/build/lib/web/development/node_modules/es-toolkit/dist/compat/array/flatten.js +1 -1
- package/build/lib/web/development/node_modules/es-toolkit/dist/compat/array/sortBy.js +2 -2
- package/build/lib/web/development/node_modules/es-toolkit/dist/compat/object/omit.js +2 -2
- package/build/lib/web/production/_virtual/cloneDeep.js +1 -1
- package/build/lib/web/production/_virtual/cloneDeep3.js +1 -1
- package/build/lib/web/production/components/Spark/RazorSenseGradient/FluidGradient.js +92 -0
- package/build/lib/web/production/components/Spark/RazorSenseGradient/FluidGradient.js.map +1 -0
- package/build/lib/web/production/components/Spark/RazorSenseGradient/FluidGradientMount.js +110 -0
- package/build/lib/web/production/components/Spark/RazorSenseGradient/FluidGradientMount.js.map +1 -0
- package/build/lib/web/production/components/Spark/RazorSenseGradient/index.js +2 -0
- package/build/lib/web/production/components/Spark/RazorSenseGradient/index.js.map +1 -0
- package/build/lib/web/production/components/Spark/RazorSenseGradient/shader.js +18 -0
- package/build/lib/web/production/components/Spark/RazorSenseGradient/shader.js.map +1 -0
- package/build/lib/web/production/components/Spark/RazorSenseGradient/useFluidGradient.js +34 -0
- package/build/lib/web/production/components/Spark/RazorSenseGradient/useFluidGradient.js.map +1 -0
- package/build/lib/web/production/components/Spark/RzpGlass/PerformanceManager.js +455 -0
- package/build/lib/web/production/components/Spark/RzpGlass/PerformanceManager.js.map +1 -0
- package/build/lib/web/production/components/Spark/RzpGlass/RzpGlass.js +263 -0
- package/build/lib/web/production/components/Spark/RzpGlass/RzpGlass.js.map +1 -0
- package/build/lib/web/production/components/Spark/RzpGlass/RzpGlassMount.js +908 -0
- package/build/lib/web/production/components/Spark/RzpGlass/RzpGlassMount.js.map +1 -0
- package/build/lib/web/production/components/Spark/RzpGlass/index.js +24 -0
- package/build/lib/web/production/components/Spark/RzpGlass/index.js.map +1 -0
- package/build/lib/web/production/components/Spark/RzpGlass/presets.js +151 -0
- package/build/lib/web/production/components/Spark/RzpGlass/presets.js.map +1 -0
- package/build/lib/web/production/components/Spark/RzpGlass/rzpGlassShader.js +5 -0
- package/build/lib/web/production/components/Spark/RzpGlass/rzpGlassShader.js.map +1 -0
- package/build/lib/web/production/components/Spark/RzpGlass/utils.js +77 -0
- package/build/lib/web/production/components/Spark/RzpGlass/utils.js.map +1 -0
- package/build/lib/web/production/components/Spark/RzpGlass/webgl-utils.js +200 -0
- package/build/lib/web/production/components/Spark/RzpGlass/webgl-utils.js.map +1 -0
- package/build/lib/web/production/components/Spark/index.js +3 -0
- package/build/lib/web/production/components/Spark/index.js.map +1 -0
- package/build/lib/web/production/components/index.js +3 -0
- package/build/lib/web/production/components/index.js.map +1 -1
- package/build/lib/web/production/node_modules/es-toolkit/dist/compat/object/cloneDeep.js +1 -1
- package/build/lib/web/production/node_modules/es-toolkit/dist/compat/predicate/matches.js +2 -2
- package/build/lib/web/production/node_modules/es-toolkit/dist/compat/predicate/matchesProperty.js +2 -2
- package/build/lib/web/production/node_modules/es-toolkit/dist/object/cloneDeep.js +1 -1
- package/build/types/components/index.d.ts +297 -1
- package/build/types/components/index.native.d.ts +297 -1
- package/package.json +2 -1
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import 'react';
|
|
2
|
+
import { useFluidGradient } from './useFluidGradient.js';
|
|
3
|
+
import { useId } from '../../../utils/useId.js';
|
|
4
|
+
import { jsxs, jsx } from 'react/jsx-runtime';
|
|
5
|
+
|
|
6
|
+
var CANVAS_SCALE=1.4;function FluidGradient(_ref){var children=_ref.children,_ref$size=_ref.size,size=_ref$size===void 0?200:_ref$size,_ref$viewBox=_ref.viewBox,viewBox=_ref$viewBox===void 0?'0 0 24 24':_ref$viewBox,_ref$origin=_ref.origin,origin=_ref$origin===void 0?[0.5,0.0]:_ref$origin,className=_ref.className,style=_ref.style;var uid=useId('rzp-sense-gradient');var maskId=`fg-mask-${uid}`;var canvasSize=Math.round(size*CANVAS_SCALE);var offset=(canvasSize-size)/2;var containerRef=useFluidGradient({size:canvasSize,origin:origin});var vbW=parseViewBoxSize(viewBox,'w');var vbH=parseViewBoxSize(viewBox,'h');return jsxs("div",{className:className,style:Object.assign({position:'relative',width:size,height:size,display:'inline-block',overflow:'hidden'},style),children:[jsx("svg",{"aria-hidden":true,style:{position:'absolute',width:0,height:0,overflow:'hidden'},children:jsx("defs",{children:jsx("mask",{id:maskId,maskUnits:"userSpaceOnUse",x:"0",y:"0",width:canvasSize,height:canvasSize,children:jsx("g",{transform:`translate(${offset}, ${offset}) scale(${size/vbW}, ${size/vbH})`,children:children})})})}),jsx("div",{ref:containerRef,style:{position:'absolute',top:-offset,left:-offset,mask:`url(#${maskId})`,WebkitMask:`url(#${maskId})`}})]});}function parseViewBoxSize(viewBox,dim){var parts=viewBox.trim().split(/[\s,]+/);var val=dim==='w'?parseFloat(parts[2]):parseFloat(parts[3]);return val>0?val:24;}
|
|
7
|
+
|
|
8
|
+
export { FluidGradient };
|
|
9
|
+
//# sourceMappingURL=FluidGradient.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"FluidGradient.js","sources":["../../../../../../src/components/Spark/RazorSenseGradient/FluidGradient.tsx"],"sourcesContent":["/* eslint-disable @typescript-eslint/explicit-function-return-type */\nimport React from 'react';\nimport { useFluidGradient } from './useFluidGradient';\nimport { useId } from '~utils/useId';\n\n// Canvas renders this much larger than the visible area so the gradient\n// fills the logo shape fully rather than fading at the edges.\nconst CANVAS_SCALE = 1.4;\n\nexport interface FluidGradientProps {\n /**\n * SVG children define the mask shape.\n * Use SVG elements (path, g, circle, etc.) or framer-motion SVG\n * variants (motion.path, motion.g) directly.\n *\n * Shapes must use fill=\"white\" to be visible through the gradient.\n *\n * The coordinate space matches `viewBox` (defaults to \"0 0 24 24\").\n *\n * @example\n * <FluidGradient>\n * <motion.path d=\"M3 3...\" fill=\"white\" />\n * </FluidGradient>\n *\n * @example with motion.div wrapping an SVG:\n * <FluidGradient>\n * <motion.g animate={{ scale: 1.2 }} style={{ originX: \"50%\", originY: \"50%\" }}>\n * <path d=\"M3 3...\" fill=\"white\" />\n * </motion.g>\n * </FluidGradient>\n */\n children?: React.ReactNode;\n\n /** Side length of the square canvas in CSS pixels. Default: 200 */\n size?: number;\n\n /**\n * viewBox for the SVG mask coordinate space.\n * Match this to your path's native coordinate system.\n * Default: \"0 0 24 24\"\n */\n viewBox?: string;\n\n /**\n * Origin of the radial gradient in UV space.\n * [0, 0] = top-left [0.5, 0.5] = center (default) [1, 1] = bottom-right\n * Accepts any [x, y] tuple; values outside [0,1] push the origin off-canvas.\n */\n origin?: [number, number];\n\n className?: string;\n style?: React.CSSProperties;\n}\n\n/**\n * FluidGradient renders an animated WebGL gradient clipped to whatever\n * SVG shape you pass as children.\n *\n * Children are placed inside an SVG <mask>, so they should be valid SVG\n * elements. Use `fill=\"white\"` for the visible area.\n * Animate with framer-motion's SVG variants: motion.path, motion.g, motion.svg.\n */\nexport function FluidGradient({\n children,\n size = 200,\n viewBox = '0 0 24 24',\n origin = [0.5, 0.0],\n className,\n style,\n}: FluidGradientProps) {\n const uid = useId('rzp-sense-gradient');\n const maskId = `fg-mask-${uid}`;\n\n // Canvas is larger than the visible area; offset centers it behind the mask\n const canvasSize = Math.round(size * CANVAS_SCALE);\n const offset = (canvasSize - size) / 2;\n\n const containerRef = useFluidGradient({ size: canvasSize, origin });\n\n const vbW = parseViewBoxSize(viewBox, 'w');\n const vbH = parseViewBoxSize(viewBox, 'h');\n\n return (\n <div\n className={className}\n style={{\n position: 'relative',\n width: size,\n height: size,\n display: 'inline-block',\n overflow: 'hidden',\n ...style,\n }}\n >\n {/* Hidden SVG that defines the mask shape */}\n <svg aria-hidden style={{ position: 'absolute', width: 0, height: 0, overflow: 'hidden' }}>\n <defs>\n {/*\n * Mask coordinate space = the canvas element (canvasSize × canvasSize).\n * Paths are scaled to fit `size`, then shifted by `offset` to center\n * them inside the larger canvas.\n */}\n <mask\n id={maskId}\n maskUnits=\"userSpaceOnUse\"\n x=\"0\"\n y=\"0\"\n width={canvasSize}\n height={canvasSize}\n >\n <g transform={`translate(${offset}, ${offset}) scale(${size / vbW}, ${size / vbH})`}>\n {children}\n </g>\n </mask>\n </defs>\n </svg>\n\n {/* Canvas is larger and centered behind the mask via negative offset */}\n <div\n ref={containerRef}\n style={{\n position: 'absolute',\n top: -offset,\n left: -offset,\n mask: `url(#${maskId})`,\n WebkitMask: `url(#${maskId})`,\n }}\n />\n </div>\n );\n}\n\n/** Extract width or height from a viewBox string like \"0 0 24 24\" */\nfunction parseViewBoxSize(viewBox: string, dim: 'w' | 'h'): number {\n const parts = viewBox.trim().split(/[\\s,]+/);\n const val = dim === 'w' ? parseFloat(parts[2]) : parseFloat(parts[3]);\n return val > 0 ? val : 24;\n}\n"],"names":["CANVAS_SCALE","FluidGradient","_ref","children","_ref$size","size","_ref$viewBox","viewBox","_ref$origin","origin","className","style","uid","useId","maskId","canvasSize","Math","round","offset","containerRef","useFluidGradient","vbW","parseViewBoxSize","vbH","_jsxs","Object","assign","position","width","height","display","overflow","_jsx","id","maskUnits","x","y","transform","ref","top","left","mask","WebkitMask","dim","parts","trim","split","val","parseFloat"],"mappings":";;;;;AAOA,IAAMA,YAAY,CAAG,GAAG,CAuDR,SAA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KAAK,CAAC,CAAC,CAAC,CAAC,CAAGI,UAAU,CAACJ,KAAK,CAAC,CAAC,CAAC,CAAC,CACrE,OAAOG,GAAG,CAAG,CAAC,CAAGA,GAAG,CAAG,EAAE,CAC3B;;;;"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import _classCallCheck from '@babel/runtime/helpers/classCallCheck';
|
|
2
|
+
import _createClass from '@babel/runtime/helpers/createClass';
|
|
3
|
+
import { createProgram, setupFullscreenQuad } from '../RzpGlass/webgl-utils.js';
|
|
4
|
+
import { FLUID_GRADIENT_LOOP, fragmentShader } from './shader.js';
|
|
5
|
+
|
|
6
|
+
var vertexShader=`
|
|
7
|
+
precision mediump float;
|
|
8
|
+
attribute vec2 position;
|
|
9
|
+
attribute vec2 uv;
|
|
10
|
+
varying vec2 vUv;
|
|
11
|
+
void main() {
|
|
12
|
+
vUv = uv;
|
|
13
|
+
gl_Position = vec4(position, 0, 1);
|
|
14
|
+
}
|
|
15
|
+
`;var FluidGradientMount=function(){function FluidGradientMount(parentElement,size){var _this=this;var origin=arguments.length>2&&arguments[2]!==undefined?arguments[2]:[0.5,0.5];_classCallCheck(this,FluidGradientMount);this.gl=null;this.program=null;this.buffers=null;this.rafId=null;this.uTimeLoc=null;this.uOriginLoc=null;this.hasBeenDisposed=false;this.render=function(t){if(_this.hasBeenDisposed||!_this.gl)return;_this.rafId=requestAnimationFrame(_this.render);_this.gl.uniform1f(_this.uTimeLoc,t*0.001%FLUID_GRADIENT_LOOP);_this.gl.drawArrays(_this.gl.TRIANGLES,0,6);};this.parentElement=parentElement;var dpr=Math.min(window.devicePixelRatio,2);var pixelSize=Math.round(size*dpr);this.canvasElement=document.createElement('canvas');this.canvasElement.width=pixelSize;this.canvasElement.height=pixelSize;this.canvasElement.style.display='block';this.canvasElement.style.width=`${size}px`;this.canvasElement.style.height=`${size}px`;parentElement.appendChild(this.canvasElement);var gl=this.canvasElement.getContext('webgl',{antialias:false,powerPreference:'high-performance',alpha:true});if(!gl){console.error('FluidGradientMount: WebGL not supported');return;}this.gl=gl;this.setup(gl,pixelSize,origin);this.rafId=requestAnimationFrame(this.render);}return _createClass(FluidGradientMount,[{key:"setup",value:function setup(gl,pixelSize,origin){var program=createProgram(gl,vertexShader,fragmentShader);if(!program)return;this.program=program;var buffers=setupFullscreenQuad(gl,program);if(!buffers){gl.deleteProgram(program);this.program=null;return;}this.buffers=buffers;gl.useProgram(program);gl.viewport(0,0,pixelSize,pixelSize);gl.disable(gl.DEPTH_TEST);this.uTimeLoc=gl.getUniformLocation(program,'uTime');this.uOriginLoc=gl.getUniformLocation(program,'uOrigin');var iResolutionLoc=gl.getUniformLocation(program,'iResolution');gl.uniform2f(iResolutionLoc,pixelSize,pixelSize);gl.uniform2f(this.uOriginLoc,origin[0],origin[1]);}},{key:"setOrigin",value:function setOrigin(origin){if(!this.gl||!this.uOriginLoc)return;this.gl.uniform2f(this.uOriginLoc,origin[0],origin[1]);}},{key:"dispose",value:function dispose(){this.hasBeenDisposed=true;if(this.rafId!==null){cancelAnimationFrame(this.rafId);this.rafId=null;}if(this.gl){var _this$gl$getExtension;if(this.program){this.gl.deleteProgram(this.program);this.program=null;}if(this.buffers){this.gl.deleteBuffer(this.buffers.positionBuffer);this.gl.deleteBuffer(this.buffers.uvBuffer);this.buffers=null;}(_this$gl$getExtension=this.gl.getExtension('WEBGL_lose_context'))==null?void 0:_this$gl$getExtension.loseContext();}if(this.parentElement.contains(this.canvasElement)){this.parentElement.removeChild(this.canvasElement);}}}]);}();
|
|
16
|
+
|
|
17
|
+
export { FluidGradientMount };
|
|
18
|
+
//# sourceMappingURL=FluidGradientMount.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"FluidGradientMount.js","sources":["../../../../../../src/components/Spark/RazorSenseGradient/FluidGradientMount.ts"],"sourcesContent":["/**\n * FluidGradientMount\n *\n * Vanilla class that owns the full WebGL lifecycle for the fluid gradient effect.\n * Modelled after RzpGlassMount — create it with a parent element, call setOrigin()\n * to update the gradient origin reactively, and dispose() to clean up.\n */\n\nimport type { FullscreenQuadBuffers } from '../RzpGlass/webgl-utils';\nimport { createProgram, setupFullscreenQuad } from '../RzpGlass/webgl-utils';\nimport { fragmentShader, FLUID_GRADIENT_LOOP } from './shader';\n\nconst vertexShader = /* glsl */ `\n precision mediump float;\n attribute vec2 position;\n attribute vec2 uv;\n varying vec2 vUv;\n void main() {\n vUv = uv;\n gl_Position = vec4(position, 0, 1);\n }\n`;\n\nexport class FluidGradientMount {\n public readonly canvasElement: HTMLCanvasElement;\n\n private readonly parentElement: HTMLElement;\n private readonly gl: WebGLRenderingContext | null = null;\n\n private program: WebGLProgram | null = null;\n private buffers: FullscreenQuadBuffers | null = null;\n private rafId: number | null = null;\n\n // Uniform locations\n private uTimeLoc: WebGLUniformLocation | null = null;\n private uOriginLoc: WebGLUniformLocation | null = null;\n\n private hasBeenDisposed = false;\n\n constructor(parentElement: HTMLElement, size: number, origin: [number, number] = [0.5, 0.5]) {\n this.parentElement = parentElement;\n\n const dpr = Math.min(window.devicePixelRatio, 2);\n const pixelSize = Math.round(size * dpr);\n\n this.canvasElement = document.createElement('canvas');\n this.canvasElement.width = pixelSize;\n this.canvasElement.height = pixelSize;\n this.canvasElement.style.display = 'block';\n this.canvasElement.style.width = `${size}px`;\n this.canvasElement.style.height = `${size}px`;\n parentElement.appendChild(this.canvasElement);\n\n const gl = this.canvasElement.getContext('webgl', {\n antialias: false,\n powerPreference: 'high-performance',\n alpha: true,\n });\n\n if (!gl) {\n console.error('FluidGradientMount: WebGL not supported');\n return;\n }\n\n this.gl = gl;\n this.setup(gl, pixelSize, origin);\n this.rafId = requestAnimationFrame(this.render);\n }\n\n private setup(gl: WebGLRenderingContext, pixelSize: number, origin: [number, number]): void {\n const program = createProgram(gl, vertexShader, fragmentShader);\n if (!program) return;\n this.program = program;\n\n const buffers = setupFullscreenQuad(gl, program);\n if (!buffers) {\n gl.deleteProgram(program);\n this.program = null;\n return;\n }\n this.buffers = buffers;\n\n gl.useProgram(program);\n gl.viewport(0, 0, pixelSize, pixelSize);\n gl.disable(gl.DEPTH_TEST);\n\n this.uTimeLoc = gl.getUniformLocation(program, 'uTime');\n this.uOriginLoc = gl.getUniformLocation(program, 'uOrigin');\n const iResolutionLoc = gl.getUniformLocation(program, 'iResolution');\n\n gl.uniform2f(iResolutionLoc, pixelSize, pixelSize);\n gl.uniform2f(this.uOriginLoc, origin[0], origin[1]);\n }\n\n private render = (t: number): void => {\n if (this.hasBeenDisposed || !this.gl) return;\n this.rafId = requestAnimationFrame(this.render);\n this.gl.uniform1f(this.uTimeLoc, (t * 0.001) % FLUID_GRADIENT_LOOP);\n this.gl.drawArrays(this.gl.TRIANGLES, 0, 6);\n };\n\n /** Update the gradient origin in UV space without re-initialising WebGL. */\n public setOrigin(origin: [number, number]): void {\n if (!this.gl || !this.uOriginLoc) return;\n this.gl.uniform2f(this.uOriginLoc, origin[0], origin[1]);\n }\n\n /** Tear down the render loop, release all WebGL resources, and remove the canvas. */\n public dispose(): void {\n this.hasBeenDisposed = true;\n\n if (this.rafId !== null) {\n cancelAnimationFrame(this.rafId);\n this.rafId = null;\n }\n\n if (this.gl) {\n if (this.program) {\n this.gl.deleteProgram(this.program);\n this.program = null;\n }\n if (this.buffers) {\n this.gl.deleteBuffer(this.buffers.positionBuffer);\n this.gl.deleteBuffer(this.buffers.uvBuffer);\n this.buffers = null;\n }\n this.gl.getExtension('WEBGL_lose_context')?.loseContext();\n }\n\n if (this.parentElement.contains(this.canvasElement)) {\n this.parentElement.removeChild(this.canvasElement);\n }\n }\n}\n"],"names":["vertexShader","FluidGradientMount","parentElement","size","_this","origin","arguments","length","undefined","_classCallCheck","gl","program","buffers","rafId","uTimeLoc","uOriginLoc","hasBeenDisposed","render","t","requestAnimationFrame","uniform1f","FLUID_GRADIENT_LOOP","drawArrays","TRIANGLES","dpr","Math","min","window","devicePixelRatio","pixelSize","round","canvasElement","document","createElement","width","height","style","display","appendChild","getContext","antialias","powerPreference","alpha","console","error","setup","_createClass","key","value","createProgram","fragmentShader","setupFullscreenQuad","deleteProgram","useProgram","viewport","disable","DEPTH_TEST","getUniformLocation","iResolutionLoc","uniform2f","setOrigin","dispose","cancelAnimationFrame","_this$gl$getExtension","deleteBuffer","positionBuffer","uvBuffer","getExtension","loseContext","contains","removeChild"],"mappings":";;;;;AAYA,IAAMA,YAAY,CAAc,CAAA;AAChC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC,CAEY,IAAAC,kBAAkB,CAAA,UAAA,CAgB7B,SAAAA,kBAAYC,CAAAA,aAA0B,CAAEC,IAAY,CAAyC,CAAAC,IAAAA,KAAA,UAAvCC,MAAwB,CAAAC,SAAA,CAAAC,MAAA,CAAA,CAAA,EAAAD,SAAA,CAAAE,CAAAA,CAAAA,GAAAA,SAAA,CAAAF,SAAA,IAAG,CAAC,GAAG,CAAE,GAAG,CAAC,CAAAG,eAAA,MAAAR,kBAAA,CAAA,CAAA,IAAA,CAZ1ES,EAAE,CAAiC,IAAI,CAEhDC,IAAAA,CAAAA,OAAO,CAAwB,IAAI,CAAA,IAAA,CACnCC,OAAO,CAAiC,IAAI,CAC5CC,IAAAA,CAAAA,KAAK,CAAkB,IAAI,MAG3BC,QAAQ,CAAgC,IAAI,CAC5CC,IAAAA,CAAAA,UAAU,CAAgC,IAAI,CAAA,IAAA,CAE9CC,eAAe,CAAG,KAAK,CAyDvBC,IAAAA,CAAAA,MAAM,CAAG,SAACC,CAAS,CAAW,CACpC,GAAId,KAAI,CAACY,eAAe,EAAI,CAACZ,KAAI,CAACM,EAAE,CAAE,OACtCN,KAAI,CAACS,KAAK,CAAGM,qBAAqB,CAACf,KAAI,CAACa,MAAM,CAAC,CAC/Cb,KAAI,CAACM,EAAE,CAACU,SAAS,CAAChB,KAAI,CAACU,QAAQ,CAAGI,CAAC,CAAG,KAAK,CAAIG,mBAAmB,CAAC,CACnEjB,KAAI,CAACM,EAAE,CAACY,UAAU,CAAClB,KAAI,CAACM,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WAAW,CAAC,IAAI,CAACvC,aAAa,CAAC,CACpD,CACF,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA;;;;"}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
var FLUID_GRADIENT_LOOP=12.0;var fragmentShader=`
|
|
2
|
+
precision mediump float;
|
|
3
|
+
|
|
4
|
+
uniform float uTime; // pre-wrapped: mod(raw, LOOP)
|
|
5
|
+
uniform vec2 iResolution;
|
|
6
|
+
uniform vec2 uOrigin; // gradient origin in UV space (0,0)=top-left (1,1)=bottom-right
|
|
7
|
+
varying vec2 vUv;
|
|
8
|
+
|
|
9
|
+
// Cubic smoothstep inside each segment — no kink at stop boundaries
|
|
10
|
+
vec3 gradientColor(float t) {
|
|
11
|
+
t = clamp(t, 0.0, 1.0);
|
|
12
|
+
vec3 c0 = vec3(0.682, 0.957, 0.831); // 174, 244, 212
|
|
13
|
+
vec3 c1 = vec3(0.310, 0.882, 0.620); // 79, 225, 158
|
|
14
|
+
vec3 c2 = vec3(0.306, 0.973, 0.910); // 78, 248, 232
|
|
15
|
+
vec3 c3 = vec3(0.004, 0.753, 0.443); // 1, 192, 113
|
|
16
|
+
vec3 c4 = vec3(0.004, 0.753, 0.443); // 1, 192, 113
|
|
17
|
+
float s;
|
|
18
|
+
if (t < 0.25) { s = smoothstep(0.0,1.0, t/0.25); return mix(c0,c1,s); }
|
|
19
|
+
if (t < 0.55) { s = smoothstep(0.0,1.0,(t-0.25)/0.30); return mix(c1,c2,s); }
|
|
20
|
+
if (t < 0.80) { s = smoothstep(0.0,1.0,(t-0.55)/0.25); return mix(c2,c3,s); }
|
|
21
|
+
s = smoothstep(0.0,1.0,(t-0.80)/0.20); return mix(c3,c4,s);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Value noise
|
|
25
|
+
float hash(vec2 p) { return fract(sin(dot(p,vec2(127.1,311.7)))*43758.5453); }
|
|
26
|
+
float vnoise(vec2 p) {
|
|
27
|
+
vec2 i = floor(p), f = fract(p);
|
|
28
|
+
vec2 u = f*f*(3.0-2.0*f);
|
|
29
|
+
return mix(mix(hash(i),hash(i+vec2(1,0)),u.x), mix(hash(i+vec2(0,1)),hash(i+vec2(1,1)),u.x),u.y);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
void main() {
|
|
33
|
+
vec2 uv = vUv - uOrigin;
|
|
34
|
+
float angle = atan(uv.y, uv.x);
|
|
35
|
+
float r = length(uv);
|
|
36
|
+
|
|
37
|
+
// Warp: traces a circle in noise space → exactly periodic in LOOP seconds.
|
|
38
|
+
// speed = 2π * n / LOOP (n integer → 1 full orbit per loop)
|
|
39
|
+
float ws = 6.2832 / 12.0; // 2π/LOOP — 1 orbit in LOOP s
|
|
40
|
+
float ws2 = ws * 2.0; // 2 orbits in LOOP s
|
|
41
|
+
float warp =
|
|
42
|
+
vnoise(vec2(cos(angle)*1.4 + sin(uTime*ws )*2.0, sin(angle)*1.4 + cos(uTime*ws )*2.0)) * 0.50 +
|
|
43
|
+
vnoise(vec2(cos(angle)*2.6 + sin(uTime*ws2)*1.2, sin(angle)*2.6 + cos(uTime*ws2)*1.2)) * 0.25;
|
|
44
|
+
float organicR = r + (warp - 0.45) * 0.04;
|
|
45
|
+
|
|
46
|
+
// Three wave sines — speeds are 2π*n/LOOP (n=3,2,1) → integer cycles in LOOP s.
|
|
47
|
+
// Spatial frequencies are irrational ratios so they never phase-lock into
|
|
48
|
+
// distinct bands; the result is one broad, shifting swell.
|
|
49
|
+
float s1 = 6.2832 * 3.0 / 12.0; // 3 cycles in LOOP s
|
|
50
|
+
float s2 = 6.2832 * 2.0 / 12.0; // 2 cycles
|
|
51
|
+
float s3 = 6.2832 * 1.0 / 12.0; // 1 cycle
|
|
52
|
+
float w =
|
|
53
|
+
sin(organicR * 4.80 - uTime * s1) * 0.55 +
|
|
54
|
+
sin(organicR * 2.55 - uTime * s2) * 0.30 +
|
|
55
|
+
sin(organicR * 1.45 - uTime * s3) * 0.15;
|
|
56
|
+
|
|
57
|
+
float phase = w * 0.5 + 0.5;
|
|
58
|
+
vec3 color = gradientColor(phase);
|
|
59
|
+
|
|
60
|
+
float envelope = smoothstep(0.75, 0.42, r);
|
|
61
|
+
float centerFill = smoothstep(0.06, 0.0, r);
|
|
62
|
+
color = mix(color * envelope, gradientColor(0.0), centerFill);
|
|
63
|
+
|
|
64
|
+
gl_FragColor = vec4(color, 1.0);
|
|
65
|
+
}
|
|
66
|
+
`;
|
|
67
|
+
|
|
68
|
+
export { FLUID_GRADIENT_LOOP, fragmentShader };
|
|
69
|
+
//# sourceMappingURL=shader.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"shader.js","sources":["../../../../../../src/components/Spark/RazorSenseGradient/shader.ts"],"sourcesContent":["export const FLUID_GRADIENT_LOOP = 12.0;\n\n// vec3 c0 = vec3(0.55, 0.95, 0.75);\n// vec3 c1 = vec3(0.35, 0.90, 0.65);\n// vec3 c2 = vec3(0.20, 0.88, 0.70);\n// vec3 c3 = vec3(0.08, 0.82, 0.48);\n// vec3 c4 = vec3(0.04, 0.68, 0.30);\n\n// vec3 c0 = vec3(0.72, 0.92, 1.00); // light sky blue\n// vec3 c1 = vec3(0.38, 0.72, 0.98); // cornflower blue\n// vec3 c2 = vec3(0.16, 0.50, 0.92); // medium blue\n// vec3 c3 = vec3(0.08, 0.30, 0.78); // deep royal blue\n// vec3 c4 = vec3(0.10, 0.28, 0.72); // deep blue (not black)\n\nexport const fragmentShader = /* glsl */ `\nprecision mediump float;\n\nuniform float uTime; // pre-wrapped: mod(raw, LOOP)\nuniform vec2 iResolution;\nuniform vec2 uOrigin; // gradient origin in UV space (0,0)=top-left (1,1)=bottom-right\nvarying vec2 vUv;\n\n// Cubic smoothstep inside each segment — no kink at stop boundaries\nvec3 gradientColor(float t) {\n t = clamp(t, 0.0, 1.0);\n vec3 c0 = vec3(0.682, 0.957, 0.831); // 174, 244, 212\n vec3 c1 = vec3(0.310, 0.882, 0.620); // 79, 225, 158\n vec3 c2 = vec3(0.306, 0.973, 0.910); // 78, 248, 232\n vec3 c3 = vec3(0.004, 0.753, 0.443); // 1, 192, 113\n vec3 c4 = vec3(0.004, 0.753, 0.443); // 1, 192, 113\n float s;\n if (t < 0.25) { s = smoothstep(0.0,1.0, t/0.25); return mix(c0,c1,s); }\n if (t < 0.55) { s = smoothstep(0.0,1.0,(t-0.25)/0.30); return mix(c1,c2,s); }\n if (t < 0.80) { s = smoothstep(0.0,1.0,(t-0.55)/0.25); return mix(c2,c3,s); }\n s = smoothstep(0.0,1.0,(t-0.80)/0.20); return mix(c3,c4,s);\n}\n\n// Value noise\nfloat hash(vec2 p) { return fract(sin(dot(p,vec2(127.1,311.7)))*43758.5453); }\nfloat vnoise(vec2 p) {\n vec2 i = floor(p), f = fract(p);\n vec2 u = f*f*(3.0-2.0*f);\n return mix(mix(hash(i),hash(i+vec2(1,0)),u.x), mix(hash(i+vec2(0,1)),hash(i+vec2(1,1)),u.x),u.y);\n}\n\nvoid main() {\n vec2 uv = vUv - uOrigin;\n float angle = atan(uv.y, uv.x);\n float r = length(uv);\n\n // Warp: traces a circle in noise space → exactly periodic in LOOP seconds.\n // speed = 2π * n / LOOP (n integer → 1 full orbit per loop)\n float ws = 6.2832 / 12.0; // 2π/LOOP — 1 orbit in LOOP s\n float ws2 = ws * 2.0; // 2 orbits in LOOP s\n float warp =\n vnoise(vec2(cos(angle)*1.4 + sin(uTime*ws )*2.0, sin(angle)*1.4 + cos(uTime*ws )*2.0)) * 0.50 +\n vnoise(vec2(cos(angle)*2.6 + sin(uTime*ws2)*1.2, sin(angle)*2.6 + cos(uTime*ws2)*1.2)) * 0.25;\n float organicR = r + (warp - 0.45) * 0.04;\n\n // Three wave sines — speeds are 2π*n/LOOP (n=3,2,1) → integer cycles in LOOP s.\n // Spatial frequencies are irrational ratios so they never phase-lock into\n // distinct bands; the result is one broad, shifting swell.\n float s1 = 6.2832 * 3.0 / 12.0; // 3 cycles in LOOP s\n float s2 = 6.2832 * 2.0 / 12.0; // 2 cycles\n float s3 = 6.2832 * 1.0 / 12.0; // 1 cycle\n float w =\n sin(organicR * 4.80 - uTime * s1) * 0.55 +\n sin(organicR * 2.55 - uTime * s2) * 0.30 +\n sin(organicR * 1.45 - uTime * s3) * 0.15;\n\n float phase = w * 0.5 + 0.5;\n vec3 color = gradientColor(phase);\n\n float envelope = smoothstep(0.75, 0.42, r);\n float centerFill = smoothstep(0.06, 0.0, r);\n color = mix(color * envelope, gradientColor(0.0), centerFill);\n\n gl_FragColor = vec4(color, 1.0);\n}\n`;\n"],"names":["FLUID_GRADIENT_LOOP","fragmentShader"],"mappings":"AAAa,IAAAA,mBAAmB,CAAG,KActB,IAAAC,cAAc,CAAc,CAAA;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { useRef, useEffect } from 'react';
|
|
2
|
+
import { FluidGradientMount } from './FluidGradientMount.js';
|
|
3
|
+
|
|
4
|
+
function useFluidGradient(_ref){var size=_ref.size,_ref$origin=_ref.origin,origin=_ref$origin===void 0?[0.5,0.5]:_ref$origin;var containerRef=useRef(null);var mountRef=useRef(null);useEffect(function(){var _mountRef$current;(_mountRef$current=mountRef.current)==null?void 0:_mountRef$current.setOrigin(origin);},[origin[0],origin[1]]);useEffect(function(){var container=containerRef.current;if(!container)return;var mount=new FluidGradientMount(container,size,origin);mountRef.current=mount;return function(){mount.dispose();mountRef.current=null;};},[size]);return containerRef;}
|
|
5
|
+
|
|
6
|
+
export { useFluidGradient };
|
|
7
|
+
//# sourceMappingURL=useFluidGradient.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useFluidGradient.js","sources":["../../../../../../src/components/Spark/RazorSenseGradient/useFluidGradient.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable consistent-return */\nimport { useEffect, useRef } from 'react';\nimport { FluidGradientMount } from './FluidGradientMount';\n\ninterface UseFluidGradientOptions {\n size: number;\n /** Gradient origin in UV space. [0.5, 0.5] = center (default). */\n origin?: [number, number];\n}\n\nexport function useFluidGradient({ size, origin = [0.5, 0.5] }: UseFluidGradientOptions) {\n const containerRef = useRef<HTMLDivElement>(null);\n const mountRef = useRef<FluidGradientMount | null>(null);\n\n // Reactively update origin without re-initialising WebGL\n useEffect(() => {\n mountRef.current?.setOrigin(origin);\n }, [origin[0], origin[1]]); // eslint-disable-line react-hooks/exhaustive-deps\n\n useEffect(() => {\n const container = containerRef.current;\n if (!container) return;\n\n const mount = new FluidGradientMount(container, size, origin);\n mountRef.current = mount;\n\n return () => {\n mount.dispose();\n mountRef.current = null;\n };\n }, [size]); // eslint-disable-line react-hooks/exhaustive-deps\n\n return containerRef;\n}\n"],"names":["useFluidGradient","_ref","size","_ref$origin","origin","containerRef","useRef","mountRef","useEffect","_mountRef$current","current","setOrigin","container","mount","FluidGradientMount","dispose"],"mappings":";;;SAWgBA,gBAAgBA,CAAAC,IAAA,CAAyD,CAAtD,IAAAC,IAAI,CAAAD,IAAA,CAAJC,IAAI,CAAAC,WAAA,CAAAF,IAAA,CAAEG,MAAM,CAANA,MAAM,CAAAD,WAAA,UAAG,CAAC,GAAG,CAAE,GAAG,CAAC,CAAAA,WAAA,CAC1D,IAAME,YAAY,CAAGC,MAAM,CAAiB,IAAI,CAAC,CACjD,IAAMC,QAAQ,CAAGD,MAAM,CAA4B,IAAI,CAAC,CAGxDE,SAAS,CAAC,UAAM,CAAA,IAAAC,iBAAA,CACd,CAAAA,iBAAA,CAAAF,QAAQ,CAACG,OAAO,GAAhBD,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,iBAAA,CAAkBE,SAAS,CAACP,MAAM,CAAC,CACrC,CAAC,CAAE,CAACA,MAAM,CAAC,CAAC,CAAC,CAAEA,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAE1BI,SAAS,CAAC,UAAM,CACd,IAAMI,SAAS,CAAGP,YAAY,CAACK,OAAO,CACtC,GAAI,CAACE,SAAS,CAAE,OAEhB,IAAMC,KAAK,CAAG,IAAIC,kBAAkB,CAACF,SAAS,CAAEV,IAAI,CAAEE,MAAM,CAAC,CAC7DG,QAAQ,CAACG,OAAO,CAAGG,KAAK,CAExB,OAAa,UAAA,CACXA,KAAK,CAACE,OAAO,EAAE,CACfR,QAAQ,CAACG,OAAO,CAAG,IAAI,CACzB,CAAC,CACH,CAAC,CAAE,CAACR,IAAI,CAAC,CAAC,CAEV,OAAOG,YAAY,CACrB;;;;"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import _classCallCheck from '@babel/runtime/helpers/classCallCheck';
|
|
2
|
+
import _createClass from '@babel/runtime/helpers/createClass';
|
|
3
|
+
|
|
4
|
+
var POTATO_TIER_PATTERNS=[/swiftshader/,/llvmpipe/,/softpipe/,/microsoft basic render/,/virgl/];var LOW_TIER_PATTERNS=[/intel.*hd\s*(graphics)?\s*(2000|3000|4000|400|500|510|520|530)/,/intel.*gma/,/amd.*radeon.*r[2-5]\s/,/amd.*radeon.*hd\s*(6|7)\d{3}/,/nvidia.*geforce\s*(4|5|6|7|8|9)\d{2}[^0]/,/mali-(4|t[0-9]|g5[0-7])\d*/,/adreno\s*(3|4)\d{2}/,/powervr.*sgx/,/vivante/,/gc\d{3}[^0-9]/];var HIGH_TIER_PATTERNS=[/nvidia.*rtx/,/nvidia.*gtx\s*1[0-9]{3}/,/nvidia.*gtx\s*[2-9]\d{3}/,/nvidia.*quadro/,/nvidia.*titan/,/amd.*rx\s*(5|6|7)\d{3}/,/amd.*radeon\s*(pro|rx)\s*(vega|5|6|7)/,/radeon\s*r9/,/apple\s*(m[1-9]|a1[5-9]|a[2-9]\d)/,/adreno\s*(7[3-9]\d|8\d{2})/,/mali-g(7[1-9]|[89]\d|[1-9]\d{2})/,/gpu\s*family\s*(apple\s*[5-9]|apple\s*[1-9]\d)/];function isMobileDevice(){return /android|iphone|ipad|ipod|mobile/i.test(navigator.userAgent);}function getDeviceMemoryGB(){var mem=navigator.deviceMemory;return mem!=null?mem:null;}function getCpuCores(){var _navigator$hardwareCo;return (_navigator$hardwareCo=navigator.hardwareConcurrency)!=null?_navigator$hardwareCo:2;}function getGpuStrings(gl){var ext=gl.getExtension('WEBGL_debug_renderer_info');if(!ext)return {renderer:null,vendor:null};var renderer=gl.getParameter(ext.UNMASKED_RENDERER_WEBGL);var vendor=gl.getParameter(ext.UNMASKED_VENDOR_WEBGL);return {renderer:renderer,vendor:vendor};}function checkMajorPerformanceCaveat(){var canvas=document.createElement('canvas');var gl=canvas.getContext('webgl',{failIfMajorPerformanceCaveat:true});return gl===null;}function classifyByRendererString(renderer,vendor){if(!renderer&&!vendor)return null;var combined=`${renderer!=null?renderer:''} ${vendor!=null?vendor:''}`.toLowerCase();for(var pattern of POTATO_TIER_PATTERNS){if(pattern.test(combined))return 'potato';}for(var _pattern of LOW_TIER_PATTERNS){if(_pattern.test(combined))return 'low';}for(var _pattern2 of HIGH_TIER_PATTERNS){if(_pattern2.test(combined))return 'high';}return null;}function classifyByDeviceSignals(memoryGB,cores,mobile){if(memoryGB!==null&&memoryGB<=2)return 'low';if(cores<=2)return 'low';if(memoryGB!==null&&memoryGB>=8&&cores>=8&&!mobile)return 'high';if(memoryGB!==null&&memoryGB>=6&&cores>=6)return 'high';return 'mid';}var RENDER_SETTINGS={high:{maxPixelCount:1920*1080*4,minPixelRatio:2},mid:{maxPixelCount:1920*1080*2,minPixelRatio:1},low:{maxPixelCount:1280*720,minPixelRatio:1},potato:{maxPixelCount:0,minPixelRatio:1},unknown:{maxPixelCount:1920*1080*2,minPixelRatio:1}};var LEVEL_RENDER_SETTINGS={3:RENDER_SETTINGS.high,2:RENDER_SETTINGS.mid,1:RENDER_SETTINGS.low,0:RENDER_SETTINGS.low};var PerformanceManager=function(){function PerformanceManager(){_classCallCheck(this,PerformanceManager);}return _createClass(PerformanceManager,null,[{key:"detect",value:function detect(gl){var ownedCanvas=false;var ctx=gl!=null?gl:null;if(!ctx){var _canvas$getContext;var canvas=document.createElement('canvas');canvas.width=1;canvas.height=1;ctx=(_canvas$getContext=canvas.getContext('webgl'))!=null?_canvas$getContext:null;ownedCanvas=true;}var mobile=isMobileDevice();var memoryGB=getDeviceMemoryGB();var cores=getCpuCores();var hasMajorPerformanceCaveat=checkMajorPerformanceCaveat();var gpuRenderer=null;var gpuVendor=null;if(ctx){var _getGpuStrings=getGpuStrings(ctx),renderer=_getGpuStrings.renderer,vendor=_getGpuStrings.vendor;gpuRenderer=renderer;gpuVendor=vendor;if(ownedCanvas){ctx=null;}}var tier;if(hasMajorPerformanceCaveat){tier='potato';}else {var _classifyByRendererSt;tier=(_classifyByRendererSt=classifyByRendererString(gpuRenderer,gpuVendor))!=null?_classifyByRendererSt:classifyByDeviceSignals(memoryGB,cores,mobile);}if(tier==='high'&&mobile){tier='mid';}return {tier:tier,gpuRenderer:gpuRenderer,gpuVendor:gpuVendor,deviceMemory:memoryGB,hardwareConcurrency:cores,isMobile:mobile,hasMajorPerformanceCaveat:hasMajorPerformanceCaveat,renderSettings:RENDER_SETTINGS[tier]};}},{key:"getRenderSettings",value:function getRenderSettings(gl){return PerformanceManager.detect(gl).renderSettings;}}]);}();var TIER_INITIAL_STATE={high:3,mid:2,low:1,potato:0,unknown:2};var WebGLPerformanceController=function(){function WebGLPerformanceController(_ref){var _this=this;var gl=_ref.gl,_ref$onLevelChange=_ref.onLevelChange,onLevelChange=_ref$onLevelChange===void 0?null:_ref$onLevelChange;_classCallCheck(this,WebGLPerformanceController);this.cooldown=3000;this.lastChange=0;this.frameCount=0;this.lastTime=performance.now();this.fps=60;this.rafId=null;this.disposed=false;this.handleVisibilityChange=function(){if(document.hidden){if(_this.rafId!==null){cancelAnimationFrame(_this.rafId);_this.rafId=null;}}else {_this.frameCount=0;_this.lastTime=performance.now();_this.fps=60;_this.startMonitoring();}};this.onLevelChange=onLevelChange;var _PerformanceManager$d=PerformanceManager.detect(gl),tier=_PerformanceManager$d.tier;this.level=TIER_INITIAL_STATE[tier];if(this.level===0){this.forceStaticFallback();return;}onLevelChange==null?void 0:onLevelChange(this.level);this.startMonitoring();document.addEventListener('visibilitychange',this.handleVisibilityChange);}return _createClass(WebGLPerformanceController,[{key:"setLevel",value:function setLevel(level){var _this$onLevelChange;if(this.level===level)return;var now=performance.now();if(now-this.lastChange<this.cooldown)return;this.level=level;this.lastChange=now;if(level===0){this.forceStaticFallback();return;}(_this$onLevelChange=this.onLevelChange)==null?void 0:_this$onLevelChange.call(this,level);}},{key:"forceStaticFallback",value:function forceStaticFallback(){var _this$onLevelChange2;this.level=0;(_this$onLevelChange2=this.onLevelChange)==null?void 0:_this$onLevelChange2.call(this,0);}},{key:"evaluatePerformance",value:function evaluatePerformance(){if(this.fps<20){this.setLevel(0);}else if(this.fps<40){this.setLevel(1);}else if(this.fps<55){this.setLevel(2);}else {this.setLevel(3);}}},{key:"startMonitoring",value:function startMonitoring(){var _this2=this;var _loop=function loop(){if(_this2.disposed)return;var now=performance.now();_this2.frameCount++;if(now-_this2.lastTime>=1000){_this2.fps=_this2.frameCount;_this2.frameCount=0;_this2.lastTime=now;_this2.evaluatePerformance();}_this2.rafId=requestAnimationFrame(_loop);};this.rafId=requestAnimationFrame(_loop);}},{key:"isPotato",value:function isPotato(){return this.level===0;}},{key:"getLevel",value:function getLevel(){return this.level;}},{key:"dispose",value:function dispose(){this.disposed=true;if(this.rafId!==null){cancelAnimationFrame(this.rafId);this.rafId=null;}document.removeEventListener('visibilitychange',this.handleVisibilityChange);}}]);}();
|
|
5
|
+
|
|
6
|
+
export { LEVEL_RENDER_SETTINGS, RENDER_SETTINGS, WebGLPerformanceController };
|
|
7
|
+
//# sourceMappingURL=PerformanceManager.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PerformanceManager.js","sources":["../../../../../../src/components/Spark/RzpGlass/PerformanceManager.ts"],"sourcesContent":["/**\n * PerformanceManager\n *\n * Detects GPU tier and device capability, then produces recommended\n * RzpGlass render settings. Uses a layered heuristic approach:\n *\n * 1. WEBGL_debug_renderer_info – parse GPU renderer/vendor strings\n * 2. failIfMajorPerformanceCaveat – fast browser-level GPU check\n * 3. Device signals – deviceMemory, hardwareConcurrency, mobile UA\n *\n * Tier definitions:\n * high – discrete / flagship mobile GPU, ample memory\n * mid – integrated / mid-range mobile GPU\n * low – software renderer, very old GPU, or constrained device\n * unknown – could not determine (treated as mid for safety)\n */\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport type GpuTier = 'high' | 'mid' | 'low' | 'potato' | 'unknown';\n\nexport type RenderSettings = {\n /** Max rendered pixel count passed to RzpGlassMount */\n maxPixelCount: number;\n /** Minimum device pixel ratio passed to RzpGlassMount */\n minPixelRatio: number;\n};\n\nexport type PerformanceProfile = {\n tier: GpuTier;\n /** Raw GL_RENDERER string (null if extension unavailable) */\n gpuRenderer: string | null;\n /** Raw GL_VENDOR string (null if extension unavailable) */\n gpuVendor: string | null;\n /** navigator.deviceMemory in GB (null if unavailable) */\n deviceMemory: number | null;\n /** navigator.hardwareConcurrency */\n hardwareConcurrency: number;\n isMobile: boolean;\n /** Whether the browser signalled a major performance caveat */\n hasMajorPerformanceCaveat: boolean;\n /** Render settings for the detected tier */\n renderSettings: RenderSettings;\n};\n\n// ---------------------------------------------------------------------------\n// Known renderer pattern lists\n// ---------------------------------------------------------------------------\n\n/**\n * Patterns that indicate a software / CPU renderer (potato tier).\n * These devices cannot run WebGL at any usable framerate.\n */\nconst POTATO_TIER_PATTERNS: RegExp[] = [\n /swiftshader/,\n /llvmpipe/,\n /softpipe/,\n /microsoft basic render/,\n /virgl/,\n];\n\n/**\n * Patterns that strongly indicate a low-end GPU.\n * Tested against the lowercased GL_RENDERER string.\n */\nconst LOW_TIER_PATTERNS: RegExp[] = [\n // Old Intel integrated\n /intel.*hd\\s*(graphics)?\\s*(2000|3000|4000|400|500|510|520|530)/,\n /intel.*gma/,\n // Old AMD integrated\n /amd.*radeon.*r[2-5]\\s/,\n /amd.*radeon.*hd\\s*(6|7)\\d{3}/,\n // Very old NVIDIA\n /nvidia.*geforce\\s*(4|5|6|7|8|9)\\d{2}[^0]/,\n // Old mobile GPUs\n /mali-(4|t[0-9]|g5[0-7])\\d*/,\n /adreno\\s*(3|4)\\d{2}/,\n /powervr.*sgx/,\n /vivante/,\n /gc\\d{3}[^0-9]/, // Vivante GC series\n];\n\n/**\n * Patterns that indicate a high-end GPU.\n */\nconst HIGH_TIER_PATTERNS: RegExp[] = [\n // NVIDIA discrete\n /nvidia.*rtx/,\n /nvidia.*gtx\\s*1[0-9]{3}/,\n /nvidia.*gtx\\s*[2-9]\\d{3}/,\n /nvidia.*quadro/,\n /nvidia.*titan/,\n // AMD discrete\n /amd.*rx\\s*(5|6|7)\\d{3}/,\n /amd.*radeon\\s*(pro|rx)\\s*(vega|5|6|7)/,\n /radeon\\s*r9/,\n // Apple Silicon\n /apple\\s*(m[1-9]|a1[5-9]|a[2-9]\\d)/,\n // Modern mobile flagship\n /adreno\\s*(7[3-9]\\d|8\\d{2})/,\n /mali-g(7[1-9]|[89]\\d|[1-9]\\d{2})/,\n /gpu\\s*family\\s*(apple\\s*[5-9]|apple\\s*[1-9]\\d)/,\n];\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction isMobileDevice(): boolean {\n return /android|iphone|ipad|ipod|mobile/i.test(navigator.userAgent);\n}\n\nfunction getDeviceMemoryGB(): number | null {\n const mem = (navigator as Navigator & { deviceMemory?: number }).deviceMemory;\n return mem != null ? mem : null;\n}\n\nfunction getCpuCores(): number {\n return navigator.hardwareConcurrency ?? 2;\n}\n\n/**\n * Probes the WEBGL_debug_renderer_info extension to get raw GPU strings.\n * Returns nulls if the extension is unavailable or blocked (privacy protection).\n */\nfunction getGpuStrings(\n gl: WebGLRenderingContext,\n): { renderer: string | null; vendor: string | null } {\n const ext = gl.getExtension('WEBGL_debug_renderer_info');\n if (!ext) return { renderer: null, vendor: null };\n\n const renderer = gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) as string | null;\n const vendor = gl.getParameter(ext.UNMASKED_VENDOR_WEBGL) as string | null;\n return { renderer, vendor };\n}\n\n/**\n * Checks whether the browser signals a major performance caveat (software/swiftshader).\n */\nfunction checkMajorPerformanceCaveat(): boolean {\n const canvas = document.createElement('canvas');\n const gl = canvas.getContext('webgl', { failIfMajorPerformanceCaveat: true });\n return gl === null;\n}\n\n/**\n * Classify a GPU into a tier using the renderer / vendor strings.\n * Returns null if classification is inconclusive.\n */\nfunction classifyByRendererString(renderer: string | null, vendor: string | null): GpuTier | null {\n if (!renderer && !vendor) return null;\n\n const combined = `${renderer ?? ''} ${vendor ?? ''}`.toLowerCase();\n\n for (const pattern of POTATO_TIER_PATTERNS) {\n if (pattern.test(combined)) return 'potato';\n }\n\n for (const pattern of LOW_TIER_PATTERNS) {\n if (pattern.test(combined)) return 'low';\n }\n\n for (const pattern of HIGH_TIER_PATTERNS) {\n if (pattern.test(combined)) return 'high';\n }\n\n return null; // inconclusive – fall through to device signals\n}\n\n/**\n * Derive a tier purely from device-level signals (no GPU string needed).\n */\nfunction classifyByDeviceSignals(memoryGB: number | null, cores: number, mobile: boolean): GpuTier {\n // Very constrained device\n if (memoryGB !== null && memoryGB <= 2) return 'low';\n if (cores <= 2) return 'low';\n\n // Well-resourced device\n if (memoryGB !== null && memoryGB >= 8 && cores >= 8 && !mobile) return 'high';\n if (memoryGB !== null && memoryGB >= 6 && cores >= 6) return 'high';\n\n return 'mid';\n}\n\n// ---------------------------------------------------------------------------\n// Per-tier render settings\n// ---------------------------------------------------------------------------\n\nconst RENDER_SETTINGS: Record<GpuTier, RenderSettings> = {\n high: {\n // ~4K equivalent\n maxPixelCount: 1920 * 1080 * 4,\n minPixelRatio: 2,\n },\n mid: {\n // ~1080p equivalent\n maxPixelCount: 1920 * 1080 * 2,\n minPixelRatio: 1,\n },\n low: {\n // ~720p max\n maxPixelCount: 1280 * 720,\n minPixelRatio: 1,\n },\n potato: {\n // Software renderer – show static fallback immediately\n maxPixelCount: 0,\n minPixelRatio: 1,\n },\n unknown: {\n // Treat conservatively – same as mid\n maxPixelCount: 1920 * 1080 * 2,\n minPixelRatio: 1,\n },\n};\n\n/**\n * Maps PerformanceLevel → RenderSettings so callers can apply the right\n * pixel budget when the level changes. Reuses RENDER_SETTINGS values so the\n * two tables stay in sync.\n *\n * 3 (full) → high tier settings\n * 2 (stable) → mid tier settings\n * 1 (degraded) → low tier settings\n * 0 (fallback) → low tier settings (canvas will be hidden anyway)\n */\nconst LEVEL_RENDER_SETTINGS: Record<PerformanceLevel, RenderSettings> = {\n 3: RENDER_SETTINGS.high,\n 2: RENDER_SETTINGS.mid,\n 1: RENDER_SETTINGS.low,\n 0: RENDER_SETTINGS.low,\n};\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Builds a PerformanceProfile by inspecting the provided WebGL context and\n * available browser / navigator APIs. No async work is performed.\n *\n * @example\n * ```ts\n * const profile = PerformanceManager.detect(gl);\n * console.log(profile.tier); // 'high' | 'mid' | 'low' | 'unknown'\n *\n * const mount = new RzpGlassMount(\n * el,\n * assets,\n * {},\n * 0,\n * profile.renderSettings.minPixelRatio,\n * profile.renderSettings.maxPixelCount,\n * );\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-extraneous-class\nclass PerformanceManager {\n /**\n * Detect GPU tier and return a full PerformanceProfile.\n *\n * @param gl - An existing WebGLRenderingContext (e.g. from RzpGlassMount).\n * If not provided, a temporary offscreen context is created.\n */\n static detect(gl?: WebGLRenderingContext): PerformanceProfile {\n let ownedCanvas = false;\n let ctx = gl ?? null;\n\n if (!ctx) {\n const canvas = document.createElement('canvas');\n canvas.width = 1;\n canvas.height = 1;\n ctx = canvas.getContext('webgl') ?? null;\n ownedCanvas = true;\n }\n\n const mobile = isMobileDevice();\n const memoryGB = getDeviceMemoryGB();\n const cores = getCpuCores();\n const hasMajorPerformanceCaveat = checkMajorPerformanceCaveat();\n\n let gpuRenderer: string | null = null;\n let gpuVendor: string | null = null;\n\n if (ctx) {\n const { renderer, vendor } = getGpuStrings(ctx);\n gpuRenderer = renderer;\n gpuVendor = vendor;\n if (ownedCanvas) {\n // Let the browser GC the temp context – no explicit destroy needed\n ctx = null;\n }\n }\n\n // Immediate potato-tier signal from caveat check (software renderer)\n let tier: GpuTier;\n if (hasMajorPerformanceCaveat) {\n tier = 'potato';\n } else {\n tier =\n classifyByRendererString(gpuRenderer, gpuVendor) ??\n classifyByDeviceSignals(memoryGB, cores, mobile);\n }\n\n // Downgrade high → mid on mobile (thermal / power constraints)\n if (tier === 'high' && mobile) {\n tier = 'mid';\n }\n\n return {\n tier,\n gpuRenderer,\n gpuVendor,\n deviceMemory: memoryGB,\n hardwareConcurrency: cores,\n isMobile: mobile,\n hasMajorPerformanceCaveat,\n renderSettings: RENDER_SETTINGS[tier],\n };\n }\n\n /**\n * Convenience: returns only the recommended RenderSettings without the\n * full diagnostic data.\n */\n static getRenderSettings(gl?: WebGLRenderingContext): RenderSettings {\n return PerformanceManager.detect(gl).renderSettings;\n }\n}\n\n// ---------------------------------------------------------------------------\n// WebGLPerformanceController\n// ---------------------------------------------------------------------------\n\n/** Performance level: 3 = full quality, 0 = static fallback */\nexport type PerformanceLevel = 0 | 1 | 2 | 3;\n\nexport type WebGLPerformanceControllerOptions = {\n gl: WebGLRenderingContext;\n /** Called whenever the level changes (including forced fallback at level 0) */\n onLevelChange?: ((level: PerformanceLevel) => void) | null;\n};\n\nconst TIER_INITIAL_STATE: Record<GpuTier, PerformanceLevel> = {\n high: 3,\n mid: 2,\n low: 1,\n potato: 0,\n unknown: 2,\n};\n\n/**\n * Monitors real-time FPS and fires onLevelChange when quality should be adjusted.\n * Initial level is seeded from the GPU tier detected by PerformanceManager.\n *\n * Level semantics:\n * 3 – full quality\n * 2 – stable\n * 1 – degraded\n * 0 – static fallback (onLevelChange(0) fired)\n *\n * @example\n * ```ts\n * const controller = new WebGLPerformanceController({\n * canvas,\n * gl,\n * onLevelChange: (level) => {\n * if (level === 0) showStaticFallback();\n * },\n * });\n *\n * // When done:\n * controller.dispose();\n * ```\n */\nclass WebGLPerformanceController {\n private onLevelChange: ((level: PerformanceLevel) => void) | null;\n\n private level: PerformanceLevel;\n\n private readonly cooldown = 3000;\n private lastChange = 0;\n\n private frameCount = 0;\n private lastTime = performance.now();\n private fps = 60;\n\n private rafId: number | null = null;\n private disposed = false;\n\n constructor({ gl, onLevelChange = null }: WebGLPerformanceControllerOptions) {\n this.onLevelChange = onLevelChange;\n\n const { tier } = PerformanceManager.detect(gl);\n this.level = TIER_INITIAL_STATE[tier];\n\n if (this.level === 0) {\n this.forceStaticFallback();\n return;\n }\n\n onLevelChange?.(this.level);\n this.startMonitoring();\n document.addEventListener('visibilitychange', this.handleVisibilityChange);\n }\n\n private handleVisibilityChange = (): void => {\n if (document.hidden) {\n // Pause the monitoring loop — RAF is throttled while hidden and would\n // produce artificially low FPS readings that trigger false fallbacks.\n if (this.rafId !== null) {\n cancelAnimationFrame(this.rafId);\n this.rafId = null;\n }\n } else {\n // Reset FPS state so the stale hidden-period sample is discarded,\n // then resume monitoring from a clean baseline.\n this.frameCount = 0;\n this.lastTime = performance.now();\n this.fps = 60;\n this.startMonitoring();\n }\n };\n\n private setLevel(level: PerformanceLevel): void {\n if (this.level === level) return;\n\n const now = performance.now();\n if (now - this.lastChange < this.cooldown) return;\n\n this.level = level;\n this.lastChange = now;\n\n if (level === 0) {\n this.forceStaticFallback();\n return;\n }\n\n this.onLevelChange?.(level);\n }\n\n forceStaticFallback(): void {\n this.level = 0;\n this.onLevelChange?.(0);\n }\n\n private evaluatePerformance(): void {\n if (this.fps < 20) {\n this.setLevel(0);\n } else if (this.fps < 40) {\n this.setLevel(1);\n } else if (this.fps < 55) {\n this.setLevel(2);\n } else {\n this.setLevel(3);\n }\n }\n\n private startMonitoring(): void {\n const loop = (): void => {\n if (this.disposed) return;\n\n const now = performance.now();\n this.frameCount++;\n\n if (now - this.lastTime >= 1000) {\n this.fps = this.frameCount;\n this.frameCount = 0;\n this.lastTime = now;\n this.evaluatePerformance();\n }\n\n this.rafId = requestAnimationFrame(loop);\n };\n\n this.rafId = requestAnimationFrame(loop);\n }\n\n isPotato(): boolean {\n return this.level === 0;\n }\n\n /** Current performance level (3 = full, 0 = fallback) */\n getLevel(): PerformanceLevel {\n return this.level;\n }\n\n /** Stop the monitoring loop and release resources */\n dispose(): void {\n this.disposed = true;\n if (this.rafId !== null) {\n cancelAnimationFrame(this.rafId);\n this.rafId = null;\n }\n document.removeEventListener('visibilitychange', this.handleVisibilityChange);\n }\n}\n\nexport { WebGLPerformanceController, RENDER_SETTINGS, LEVEL_RENDER_SETTINGS };\n"],"names":["POTATO_TIER_PATTERNS","LOW_TIER_PATTERNS","HIGH_TIER_PATTERNS","isMobileDevice","test","navigator","userAgent","getDeviceMemoryGB","mem","deviceMemory","getCpuCores","_navigator$hardwareCo","hardwareConcurrency","getGpuStrings","gl","ext","getExtension","renderer","vendor","getParameter","UNMASKED_RENDERER_WEBGL","UNMASKED_VENDOR_WEBGL","checkMajorPerformanceCaveat","canvas","document","createElement","getContext","failIfMajorPerformanceCaveat","classifyByRendererString","combined","toLowerCase","pattern","classifyByDeviceSignals","memoryGB","cores","mobile","RENDER_SETTINGS","high","maxPixelCount","minPixelRatio","mid","low","potato","unknown","LEVEL_RENDER_SETTINGS","PerformanceManager","_classCallCheck","_createClass","key","value","detect","ownedCanvas","ctx","_canvas$getContext","width","height","hasMajorPerformanceCaveat","gpuRenderer","gpuVendor","_getGpuStrings","tier","_classifyByRendererSt","isMobile","renderSettings","getRenderSettings","TIER_INITIAL_STATE","WebGLPerformanceController","_ref","_this","_ref$onLevelChange","onLevelChange","cooldown","lastChange","frameCount","lastTime","performance","now","fps","rafId","disposed","handleVisibilityChange","hidden","cancelAnimationFrame","startMonitoring","_PerformanceManager$d","level","forceStaticFallback","addEventListener","setLevel","_this$onLevelChange","call","_this$onLevelChange2","evaluatePerformance","_this2","loop","requestAnimationFrame","isPotato","getLevel","dispose","removeEventListener"],"mappings":";;;AAuDA,IAAMA,oBAA8B,CAAG,CACrC,aAAa,CACb,UAAU,CACV,UAAU,CACV,wBAAwB,CACxB,OAAO,CACR,CAMD,IAAMC,iBAA2B,CAAG,CAElC,gEAAgE,CAChE,YAAY,CAEZ,uBAAuB,CACvB,8BAA8B,CAE9B,0CAA0C,CAE1C,4BAA4B,CAC5B,qBAAqB,CACrB,cAAc,CACd,SAAS,CACT,eAAe,CAChB,CAKD,IAAMC,kBAA4B,CAAG,CAEnC,aAAa,CACb,yBAAyB,CACzB,0BAA0B,CAC1B,gBAAgB,CAChB,eAAe,CAEf,wBAAwB,CACxB,uCAAuC,CACvC,aAAa,CAEb,mCAAmC,CAEnC,4BAA4B,CAC5B,kCAAkC,CAClC,gDAAgD,CACjD,CAMD,SAASC,cAAcA,EAAY,CACjC,OAAO,kCAAkC,CAACC,IAAI,CAACC,SAAS,CAACC,SAAS,CAAC,CACrE,CAEA,SAASC,iBAAiBA,EAAkB,CAC1C,IAAMC,GAAG,CAAIH,SAAS,CAA2CI,YAAY,CAC7E,OAAOD,GAAG,EAAI,IAAI,CAAGA,GAAG,CAAG,IAAI,CACjC,CAEA,SAASE,WAAWA,EAAW,KAAAC,qBAAA,CAC7B,QAAAA,qBAAA,CAAON,SAAS,CAACO,mBAAmB,QAAAD,qBAAA,CAAI,CAAC,CAC3C,CAMA,SAASE,aAAaA,CACpBC,EAAyB,CAC2B,CACpD,IAAMC,GAAG,CAAGD,EAAE,CAACE,YAAY,C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AGH,CAAA,CAAA,CAAA,CAAA;;;;"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
|
|
2
|
+
import _asyncToGenerator from '@babel/runtime/helpers/asyncToGenerator';
|
|
3
|
+
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
|
|
4
|
+
import _objectWithoutProperties from '@babel/runtime/helpers/objectWithoutProperties';
|
|
5
|
+
import { forwardRef, useState, useRef, useEffect, useCallback } from 'react';
|
|
6
|
+
import { RzpGlassMount } from './RzpGlassMount.js';
|
|
7
|
+
import { PRESETS } from './presets.js';
|
|
8
|
+
import { jsx } from 'react/jsx-runtime';
|
|
9
|
+
|
|
10
|
+
var _excluded=["width","height","className","style","onLoad","onError","preset","cdnPath","gradientMapSrc","gradientMap2Src","gradientMapCanvas","imageSrc"],_excluded2=["width","height","className","style","onLoad","onError","cdnPath","gradientMapCanvas","gradientMapSrc","gradientMap2Src","imageSrc"];var DEFAULT_CDN_PATH='https://cdn.jsdelivr.net/gh/razorpay/blade@feat/expose-assets-folder/packages/blade/assets/spark';var getDefaultAssets=function getDefaultAssets(cdnPath){return {videoSrc:`${cdnPath}/spark-base-video.mp4`,imageSrc:`${cdnPath}/bottom-frame.jpg`,gradientMapSrc:`${cdnPath}/colorama-gradient-map-green.jpg`,gradientMap2Src:`${cdnPath}/colorama-gradient-map-blue.jpg`,centerGradientMapSrc:`${cdnPath}/colorama-center-gradient-map.jpg`};};function useMergeRefs(refs){return useCallback(function(value){refs.forEach(function(ref){if(typeof ref==='function'){ref(value);}else if(ref!=null){ref.current=value;}});},[refs]);}function extractConfig(props){props.width;props.height;props.className;props.style;props.onLoad;props.onError;props.preset;props.cdnPath;props.gradientMapSrc;props.gradientMap2Src;props.gradientMapCanvas;props.imageSrc;var config=_objectWithoutProperties(props,_excluded);return Object.fromEntries(Object.entries(config).filter(function(_ref){var _ref2=_slicedToArray(_ref,2),v=_ref2[1];return v!==undefined;}));}var ASSET_KEYS=new Set(['videoSrc','imageSrc','gradientMapSrc','gradientMap2Src','centerGradientMapSrc']);function getPresetDefinition(preset){if(preset&&preset in PRESETS)return Object.assign({},PRESETS[preset]);return {};}function getPresetConfig(preset){var def=getPresetDefinition(preset);return Object.fromEntries(Object.entries(def).filter(function(_ref3){var _ref4=_slicedToArray(_ref3,1),k=_ref4[0];return !ASSET_KEYS.has(k);}));}function getPresetAssets(preset){var def=getPresetDefinition(preset);return Object.fromEntries(Object.entries(def).filter(function(_ref5){var _ref6=_slicedToArray(_ref5,1),k=_ref6[0];return ASSET_KEYS.has(k);}));}function resolveConfig(props){return Object.assign({},getPresetConfig(props.preset),extractConfig(props));}var RzpGlass=forwardRef(function RzpGlass(props,forwardedRef){var _presetAssets$videoSr,_ref7,_ref8,_presetAssets$centerG,_configProps$edgeFeat;var _props$width=props.width,width=_props$width===void 0?'100%':_props$width,_props$height=props.height,height=_props$height===void 0?'100%':_props$height,className=props.className,style=props.style,onLoad=props.onLoad,onError=props.onError,cdnPathProp=props.cdnPath,gradientMapCanvas=props.gradientMapCanvas,gradientMapSrcProp=props.gradientMapSrc,gradientMap2SrcProp=props.gradientMap2Src,imageSrcProp=props.imageSrc,configProps=_objectWithoutProperties(props,_excluded2);var cdnPath=cdnPathProp!=null?cdnPathProp:DEFAULT_CDN_PATH;var defaultAssets=getDefaultAssets(cdnPath);var presetAssets=getPresetAssets(props.preset);var imageSrc=imageSrcProp!=null?imageSrcProp:presetAssets.imageSrc;var videoSrc=imageSrc?undefined:(_presetAssets$videoSr=presetAssets.videoSrc)!=null?_presetAssets$videoSr:defaultAssets.videoSrc;var gradientMapSrc=(_ref7=gradientMapSrcProp!=null?gradientMapSrcProp:presetAssets.gradientMapSrc)!=null?_ref7:defaultAssets.gradientMapSrc;var gradientMap2Src=(_ref8=gradientMap2SrcProp!=null?gradientMap2SrcProp:presetAssets.gradientMap2Src)!=null?_ref8:defaultAssets.gradientMap2Src;var centerGradientMapSrc=(_presetAssets$centerG=presetAssets.centerGradientMapSrc)!=null?_presetAssets$centerG:defaultAssets.centerGradientMapSrc;var _useState=useState(false),_useState2=_slicedToArray(_useState,2),isInitialized=_useState2[0],setIsInitialized=_useState2[1];var _useState3=useState(null),_useState4=_slicedToArray(_useState3,2),error=_useState4[0],setError=_useState4[1];var divRef=useRef(null);var mountRef=useRef(null);useEffect(function(){var init=function(){var _ref9=_asyncToGenerator(function*(){if(!divRef.current||mountRef.current)return;try{var config=resolveConfig(props);mountRef.current=new RzpGlassMount(divRef.current,{videoSrc:videoSrc,imageSrc:imageSrc,gradientMapSrc:gradientMapSrc,gradientMap2Src:gradientMap2Src,centerGradientMapSrc:centerGradientMapSrc},config);yield mountRef.current.loadAssets();setIsInitialized(true);onLoad==null?void 0:onLoad();}catch(err){var _error=err instanceof Error?err:new Error(String(err));setError(_error);onError==null?void 0:onError(_error);}});return function init(){return _ref9.apply(this,arguments);};}();void init();return function(){var _mountRef$current;(_mountRef$current=mountRef.current)==null?void 0:_mountRef$current.dispose();mountRef.current=null;setIsInitialized(false);};},[cdnPath,videoSrc,imageSrc,gradientMapSrc,gradientMap2Src,centerGradientMapSrc,configProps.preset]);useEffect(function(){if(isInitialized&&mountRef.current){var config=resolveConfig(props);mountRef.current.setUniforms(config);}},[isInitialized,configProps.preset,configProps.inputMin,configProps.inputMax,configProps.modifyGamma,configProps.posterizeLevels,configProps.cycleRepetitions,configProps.phaseShift,configProps.cycleSpeed,configProps.wrapMode,configProps.reverse,configProps.blendWithOriginal,configProps.numSegments,configProps.slitAngle,configProps.displacementX,configProps.displacementY,configProps.enableCenterElement,configProps.centerAnimDuration,configProps.ccBlackPoint,configProps.ccWhitePoint,configProps.ccMidtoneGamma,configProps.ccGamma,configProps.ccContrast,configProps.zoom,configProps.panX,configProps.panY].concat(_toConsumableArray((_configProps$edgeFeat=configProps.edgeFeather)!=null?_configProps$edgeFeat:[0,0,0,0]),[configProps.enableDisplacement,configProps.enableColorama,configProps.enableBloom,configProps.enableLightSweep,configProps.lightIntensity,configProps.lightStartFrame,configProps.paused,configProps.startTime,configProps.endTime,configProps.animateLightIndependently,configProps.animateCycleReps,configProps.cycleRepetitionsStart,configProps.cycleRepetitionsEnd,configProps.cycleRepetitionsStartFrame,configProps.cycleRepetitionsDuration,configProps.gradientMapBlend,configProps.gradientMapBlendDuration]));useEffect(function(){if(isInitialized&&mountRef.current&&gradientMapCanvas){mountRef.current.updateGradientMapTexture(gradientMapCanvas);}},[isInitialized,gradientMapCanvas]);var mergedRef=useMergeRefs([divRef,forwardedRef]);var widthStyle=typeof width==='number'?`${width}px`:width;var heightStyle=typeof height==='number'?`${height}px`:height;if(error){return jsx("div",{ref:mergedRef,className:className,style:Object.assign({width:widthStyle,height:heightStyle},style)});}return jsx("div",{ref:mergedRef,className:className,style:Object.assign({width:widthStyle,height:heightStyle,position:'relative',overflow:'hidden',backgroundColor:'transparent',transition:'2s opacity'},isInitialized?{opacity:1}:{opacity:0},style)});});
|
|
11
|
+
|
|
12
|
+
export { RzpGlass, RzpGlass as default };
|
|
13
|
+
//# sourceMappingURL=RzpGlass.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"RzpGlass.js","sources":["../../../../../../src/components/Spark/RzpGlass/RzpGlass.tsx"],"sourcesContent":["/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable @typescript-eslint/no-unsafe-argument */\n/* eslint-disable @typescript-eslint/no-unsafe-assignment */\n/* eslint-disable react/react-in-jsx-scope */\n/* eslint-disable react-hooks/exhaustive-deps */\n/* eslint-disable @typescript-eslint/no-implicit-any-catch */\n/* eslint-disable @typescript-eslint/no-shadow */\n/**\n * RzpGlass React Component\n *\n * A React wrapper for the RzpGlassMount WebGL shader effect.\n * Manages the component lifecycle with useEffect hooks.\n *\n * @example\n * ```tsx\n * // Uses default assets and config\n * <RzpGlass width=\"400px\" height=\"300px\" />\n *\n * // With custom assets\n * <RzpGlass\n * videoSrc=\"/custom_video.mp4\"\n * gradientMapSrc=\"/custom-gradient.jpg\"\n * enableBloom={true}\n * />\n * ```\n */\n\nimport { forwardRef, useEffect, useRef, useState, useCallback } from 'react';\nimport { RzpGlassMount } from './RzpGlassMount';\nimport type {\n RzpGlassProps,\n RzpGlassConfig,\n RzpGlassAssets,\n RzpGlassPresetDefinition,\n} from './types';\nimport { PRESETS } from './presets';\nimport type { RzpGlassPreset } from './presets';\n\nconst DEFAULT_CDN_PATH =\n 'https://cdn.jsdelivr.net/gh/razorpay/blade@feat/expose-assets-folder/packages/blade/assets/spark';\n\nconst getDefaultAssets = (cdnPath: string): Required<RzpGlassAssets> => ({\n videoSrc: `${cdnPath}/spark-base-video.mp4`,\n imageSrc: `${cdnPath}/bottom-frame.jpg`,\n gradientMapSrc: `${cdnPath}/colorama-gradient-map-green.jpg`,\n gradientMap2Src: `${cdnPath}/colorama-gradient-map-blue.jpg`,\n centerGradientMapSrc: `${cdnPath}/colorama-center-gradient-map.jpg`,\n});\n\n/**\n * Hook to merge multiple refs into one\n */\nfunction useMergeRefs<T>(refs: (React.Ref<T> | undefined)[]): React.RefCallback<T> {\n return useCallback(\n (value: T) => {\n refs.forEach((ref) => {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref != null) {\n (ref as React.MutableRefObject<T | null>).current = value;\n }\n });\n },\n [refs],\n );\n}\n\n/**\n * Extract config from props (exclude non-config props).\n * Strips undefined values so they don't clobber preset defaults.\n */\nfunction extractConfig(props: RzpGlassProps): Partial<RzpGlassConfig> {\n const {\n width: _width,\n height: _height,\n className: _className,\n style: _style,\n onLoad: _onLoad,\n onError: _onError,\n preset: _preset,\n cdnPath: _cdnPath,\n gradientMapSrc: _gradientMapSrc,\n gradientMap2Src: _gradientMap2Src,\n gradientMapCanvas: _gradientMapCanvas,\n imageSrc: _imageSrc,\n ...config\n } = props;\n\n // Drop keys with undefined values so preset config isn't overridden by unset props\n return Object.fromEntries(\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n Object.entries(config).filter(([, v]) => v !== undefined),\n ) as Partial<RzpGlassConfig>;\n}\n\nconst ASSET_KEYS = new Set<string>([\n 'videoSrc',\n 'imageSrc',\n 'gradientMapSrc',\n 'gradientMap2Src',\n 'centerGradientMapSrc',\n]);\n\n/* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-return */\nfunction getPresetDefinition(preset: RzpGlassPreset | undefined): RzpGlassPresetDefinition {\n if (preset && preset in PRESETS) return { ...PRESETS[preset] };\n return {};\n}\n\nfunction getPresetConfig(preset: RzpGlassPreset | undefined): Partial<RzpGlassConfig> {\n const def = getPresetDefinition(preset) as Record<string, unknown>;\n return Object.fromEntries(\n Object.entries(def).filter(([k]) => !ASSET_KEYS.has(k)),\n ) as Partial<RzpGlassConfig>;\n}\n\nfunction getPresetAssets(preset: RzpGlassPreset | undefined): Partial<RzpGlassAssets> {\n const def = getPresetDefinition(preset) as Record<string, unknown>;\n return Object.fromEntries(\n Object.entries(def).filter(([k]) => ASSET_KEYS.has(k)),\n ) as Partial<RzpGlassAssets>;\n}\n\n/**\n * Merge preset config with user-provided config.\n * Preset values are used as base; any explicit prop overrides them.\n */\nfunction resolveConfig(props: RzpGlassProps): Partial<RzpGlassConfig> {\n return {\n ...getPresetConfig(props.preset),\n ...extractConfig(props),\n };\n}\n\nexport const RzpGlass = forwardRef<HTMLDivElement, RzpGlassProps>(function RzpGlass(\n props,\n forwardedRef,\n) {\n const {\n width = '100%',\n height = '100%',\n className,\n style,\n onLoad,\n onError,\n cdnPath: cdnPathProp,\n gradientMapCanvas,\n gradientMapSrc: gradientMapSrcProp,\n gradientMap2Src: gradientMap2SrcProp,\n imageSrc: imageSrcProp,\n ...configProps\n } = props;\n\n // Get default assets based on cdnPath\n const cdnPath: string = cdnPathProp ?? DEFAULT_CDN_PATH;\n const defaultAssets = getDefaultAssets(cdnPath);\n\n // Resolve assets: prop overrides preset, preset overrides default\n const presetAssets = getPresetAssets(props.preset);\n const imageSrc = imageSrcProp ?? presetAssets.imageSrc;\n const videoSrc = imageSrc ? undefined : presetAssets.videoSrc ?? defaultAssets.videoSrc;\n const gradientMapSrc =\n gradientMapSrcProp ?? presetAssets.gradientMapSrc ?? defaultAssets.gradientMapSrc;\n const gradientMap2Src =\n gradientMap2SrcProp ?? presetAssets.gradientMap2Src ?? defaultAssets.gradientMap2Src;\n const centerGradientMapSrc =\n presetAssets.centerGradientMapSrc ?? defaultAssets.centerGradientMapSrc;\n\n const [isInitialized, setIsInitialized] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const divRef = useRef<HTMLDivElement>(null);\n const mountRef = useRef<RzpGlassMount | null>(null);\n\n // Initialize on mount\n useEffect(() => {\n const init = async () => {\n if (!divRef.current || mountRef.current) return;\n\n try {\n const config = resolveConfig(props);\n\n mountRef.current = new RzpGlassMount(\n divRef.current,\n {\n videoSrc,\n imageSrc,\n gradientMapSrc,\n gradientMap2Src,\n centerGradientMapSrc,\n },\n config,\n );\n\n await mountRef.current.loadAssets();\n setIsInitialized(true);\n onLoad?.();\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n setError(error);\n onError?.(error);\n }\n };\n\n void init();\n\n return () => {\n mountRef.current?.dispose();\n mountRef.current = null;\n setIsInitialized(false);\n };\n }, [\n cdnPath,\n videoSrc,\n imageSrc,\n gradientMapSrc,\n gradientMap2Src,\n centerGradientMapSrc,\n configProps.preset,\n ]);\n\n // Update uniforms when config props change\n useEffect(() => {\n if (isInitialized && mountRef.current) {\n const config = resolveConfig(props);\n mountRef.current.setUniforms(config);\n }\n }, [\n isInitialized,\n configProps.preset,\n // Colorama\n configProps.inputMin,\n configProps.inputMax,\n configProps.modifyGamma,\n configProps.posterizeLevels,\n configProps.cycleRepetitions,\n configProps.phaseShift,\n configProps.cycleSpeed,\n configProps.wrapMode,\n configProps.reverse,\n configProps.blendWithOriginal,\n // Displacement\n configProps.numSegments,\n configProps.slitAngle,\n configProps.displacementX,\n configProps.displacementY,\n // Center element\n configProps.enableCenterElement,\n configProps.centerAnimDuration,\n // Color correction\n configProps.ccBlackPoint,\n configProps.ccWhitePoint,\n configProps.ccMidtoneGamma,\n configProps.ccGamma,\n configProps.ccContrast,\n // Zoom & Pan\n configProps.zoom,\n configProps.panX,\n configProps.panY,\n // eslint-disable-next-line react-hooks/exhaustive-deps\n ...(configProps.edgeFeather ?? [0, 0, 0, 0]),\n // Effect toggles\n configProps.enableDisplacement,\n configProps.enableColorama,\n configProps.enableBloom,\n configProps.enableLightSweep,\n // Light\n configProps.lightIntensity,\n configProps.lightStartFrame,\n // Playback\n configProps.paused,\n configProps.startTime,\n configProps.endTime,\n configProps.animateLightIndependently,\n // Cycle animation\n configProps.animateCycleReps,\n configProps.cycleRepetitionsStart,\n configProps.cycleRepetitionsEnd,\n configProps.cycleRepetitionsStartFrame,\n configProps.cycleRepetitionsDuration,\n // Gradient map blend\n configProps.gradientMapBlend,\n configProps.gradientMapBlendDuration,\n ]);\n\n // Update gradient map texture when a canvas is provided\n useEffect(() => {\n if (isInitialized && mountRef.current && gradientMapCanvas) {\n mountRef.current.updateGradientMapTexture(gradientMapCanvas);\n }\n }, [isInitialized, gradientMapCanvas]);\n\n const mergedRef = useMergeRefs([divRef, forwardedRef]);\n\n // Convert width/height to string if number\n const widthStyle = typeof width === 'number' ? `${width}px` : width;\n const heightStyle = typeof height === 'number' ? `${height}px` : height;\n\n if (error) {\n return (\n <div\n ref={mergedRef}\n className={className}\n style={{\n width: widthStyle,\n height: heightStyle,\n ...style,\n }}\n />\n );\n }\n\n return (\n <div\n ref={mergedRef}\n className={className}\n style={{\n width: widthStyle,\n height: heightStyle,\n position: 'relative',\n overflow: 'hidden',\n backgroundColor: 'transparent',\n transition: '2s opacity',\n ...(isInitialized ? { opacity: 1 } : { opacity: 0 }),\n ...style,\n }}\n />\n );\n});\n\nexport default RzpGlass;\n"],"names":["DEFAULT_CDN_PATH","getDefaultAssets","cdnPath","videoSrc","imageSrc","gradientMapSrc","gradientMap2Src","centerGradientMapSrc","useMergeRefs","refs","useCallback","value","forEach","ref","current","extractConfig","props","width","height","className","style","onLoad","onError","preset","gradientMapCanvas","config","_objectWithoutProperties","_excluded","Object","fromEntries","entries","filter","_ref","_ref2","_slicedToArray","v","undefined","ASSET_KEYS","Set","getPresetDefinition","PRESETS","assign","getPresetConfig","def","_ref3","_ref4","k","has","getPresetAssets","_ref5","_ref6","resolveConfig","RzpGlass","forwardRef","forwardedRef","_presetAssets$videoSr","_ref7","_ref8","_presetAssets$centerG","_configProps$edgeFeat","_props$width","_props$height","cdnPathProp","gradientMapSrcProp","gradientMap2SrcProp","imageSrcProp","configProps","_excluded2","defaultAssets","presetAssets","_useState","useState","_useState2","isInitialized","setIsInitialized","_useState3","_useState4","error","setError","divRef","useRef","mountRef","useEffect","init","_ref9","_asyncToGenerator","RzpGlassMount","loadAssets","err","Error","String","apply","arguments","_mountRef$current","dispose","setUniforms","inputMin","inputMax","modifyGamma","posterizeLevels","cycleRepetitions","phaseShift","cycleSpeed","wrapMode","reverse","blendWithOriginal","numSegments","slitAngle","displacementX","displacementY","enableCenterElement","centerAnimDuration","ccBlackPoint","ccWhitePoint","ccMidtoneGamma","ccGamma","ccContrast","zoom","panX","panY","concat","_toConsumableArray","edgeFeather","enableDisplacement","enableColorama","enableBloom","enableLightSweep","lightIntensity","lightStartFrame","paused","startTime","endTime","animateLightIndependently","animateCycleReps","cycleRepetitionsStart","cycleRepetitionsEnd","cycleRepetitionsStartFrame","cycleRepetitionsDuration","gradientMapBlend","gradientMapBlendDuration","updateGradientMapTexture","mergedRef","widthStyle","heightStyle","_jsx","position","overflow","backgroundColor","transition","opacity"],"mappings":";;;;;;;;;AA2BA,IAAA,SAAA,CAAA,CAAA,OAAA,CAAA,QAAA,CAAA,WAAA,CAAA,OAAA,CAAA,QAAA,CAAA,SAAA,CAAA,QAAA,CAAA,SAAA,CAAA,gBAAA,CAAA,iBAAA,CAAA,mBAAA,CAAA,UAAA,CAAA,CAAA,UAAA,CAAA,CAAA,OAAA,CAAA,QAAA,CAAA,WA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CAAEgI,SAAU,CACf1H,SAAS,CAAEA,SAAU,CACrBC,KAAK,CAAAQ,MAAA,CAAAa,MAAA,EACHxB,KAAK,CAAE6H,UAAU,CACjB5H,MAAM,CAAE6H,WAAW,CAChB3H,CAAAA,KAAK,CACR,CACH,CAAC,CAEN,CAEA,OACE4H,GAAA,CAAA,KAAA,CAAA,CACEnI,GAAG,CAAEgI,SAAU,CACf1H,SAAS,CAAEA,SAAU,CACrBC,KAAK,CAAAQ,MAAA,CAAAa,MAAA,CACHxB,CAAAA,KAAK,CAAE6H,UAAU,CACjB5H,MAAM,CAAE6H,WAAW,CACnBE,QAAQ,CAAE,UAAU,CACpBC,QAAQ,CAAE,QAAQ,CAClBC,eAAe,CAAE,aAAa,CAC9BC,UAAU,CAAE,YAAY,CACpB3E,CAAAA,aAAa,CAAG,CAAE4E,OAAO,CAAE,CAAE,CAAC,CAAG,CAAEA,OAAO,CAAE,CAAE,CAAC,CAChDjI,KAAK,CACR,CACH,CAAC,CAEN,CAAC;;;;"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
|
|
2
|
+
import _asyncToGenerator from '@babel/runtime/helpers/asyncToGenerator';
|
|
3
|
+
import _classCallCheck from '@babel/runtime/helpers/classCallCheck';
|
|
4
|
+
import _createClass from '@babel/runtime/helpers/createClass';
|
|
5
|
+
import { rzpGlassFragmentShader, rzpGlassVertexShader } from './rzpGlassShader.js';
|
|
6
|
+
import { DEFAULT_CONFIG } from './presets.js';
|
|
7
|
+
import { loadImage, loadVideo, isSafari, bestGuessBrowserZoom } from './utils.js';
|
|
8
|
+
import { createProgram, setupFullscreenQuad, Texture } from './webgl-utils.js';
|
|
9
|
+
import { WebGLPerformanceController, LEVEL_RENDER_SETTINGS } from './PerformanceManager.js';
|
|
10
|
+
|
|
11
|
+
var REF_RESOLUTION={width:3000,height:2000};var DEFAULT_MAX_PIXEL_COUNT=1920*1080*4;var defaultStyle=`@layer rzp-glass {
|
|
12
|
+
:where([data-rzp-glass]) {
|
|
13
|
+
isolation: isolate;
|
|
14
|
+
position: relative;
|
|
15
|
+
overflow: hidden;
|
|
16
|
+
|
|
17
|
+
& canvas {
|
|
18
|
+
contain: strict;
|
|
19
|
+
display: block;
|
|
20
|
+
position: absolute;
|
|
21
|
+
z-index: -1;
|
|
22
|
+
border-radius: inherit;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}`;var CONFIG_TO_UNIFORM={enableDisplacement:'uEnableDisplacement',enableColorama:'uEnableColorama',enableBloom:'uEnableBloom',enableLightSweep:'uEnableLightSweep',inputMin:'uInputMin',inputMax:'uInputMax',modifyGamma:'uModifyGamma',posterizeLevels:'uPosterizeLevels',cycleRepetitions:'uCycleRepetitions',phaseShift:'uPhaseShift',cycleSpeed:'uCycleSpeed',wrapMode:'uWrapMode',reverse:'uReverse',blendWithOriginal:'uBlendWithOriginal',lightIntensity:'uLightIntensity',lightStartFrame:'uLightStartFrame',numSegments:'uNumSegments',slitAngle:'uSlitAngle',displacementX:'uDisplacementX',displacementY:'uDisplacementY',enableCenterElement:'uEnableCenterElement',centerAnimDuration:'uCenterAnimDuration',ccBlackPoint:'uCCBlackPoint',ccWhitePoint:'uCCWhitePoint',ccMidtoneGamma:'uCCMidtoneGamma',ccGamma:'uCCGamma',ccContrast:'uCCContrast',zoom:'uZoom',edgeFeather:'uEdgeFeather'};var RzpGlassMount=function(){function RzpGlassMount(parentElement,assets){var _this=this,_visualViewport2;var config=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};var frame=arguments.length>3&&arguments[3]!==undefined?arguments[3]:0;var _minPixelRatio=arguments.length>4&&arguments[4]!==undefined?arguments[4]:1;var _maxPixelCount=arguments.length>5&&arguments[5]!==undefined?arguments[5]:DEFAULT_MAX_PIXEL_COUNT;_classCallCheck(this,RzpGlassMount);this.program=null;this.uniformLocations={};this.uniformCache={};this.videoTexture=null;this.gradientMapTexture=null;this.gradientMap2Texture=null;this.centerGradientMapTexture=null;this.currentGradientMapBlend=0;this.video=null;this.videoFrameCallbackId=null;this.rafId=null;this.lastRenderTime=0;this.currentFrame=0;this.independentLightTime=0;this.lastVideoTime=0;this.hasBeenDisposed=false;this.isInitialized=false;this.resolutionChanged=true;this.visibleUvBounds=[0,0,1,1];this.resizeObserver=null;this.renderScale=1;this.parentWidth=0;this.parentHeight=0;this.parentDevicePixelWidth=0;this.parentDevicePixelHeight=0;this.devicePixelsSupported=false;this.isSafariBrowser=isSafari();this.performanceController=null;this.handleVisualViewportChange=function(){var _this$resizeObserver;(_this$resizeObserver=_this.resizeObserver)==null?void 0:_this$resizeObserver.disconnect();_this.setupResizeObserver();};this.handleResize=function(){var _visualViewport$scale,_visualViewport;var containerWidth=_this.parentWidth||_this.parentElement.clientWidth;var containerHeight=_this.parentHeight||_this.parentElement.clientHeight;var containerAspect=containerWidth/containerHeight;var canvasWidth;var canvasHeight;var targetAspectRatio=_this.config.aspectRatio;if(containerAspect>targetAspectRatio){canvasWidth=containerWidth;canvasHeight=containerWidth/targetAspectRatio;}else {canvasHeight=containerHeight;canvasWidth=containerHeight*targetAspectRatio;}var offsetX=(containerWidth-canvasWidth)/2;var offsetY=(containerHeight-canvasHeight)/2;var visibleMinX=-offsetX/canvasWidth;var visibleMaxX=(containerWidth-offsetX)/canvasWidth;var visibleMinY=-offsetY/canvasHeight;var visibleMaxY=(containerHeight-offsetY)/canvasHeight;_this.visibleUvBounds=[visibleMinX,visibleMinY,visibleMaxX,visibleMaxY];_this.canvasElement.style.width=`${canvasWidth}px`;_this.canvasElement.style.height=`${canvasHeight}px`;_this.canvasElement.style.left=`${offsetX}px`;_this.canvasElement.style.top=`${offsetY}px`;var targetPixelWidth=0;var targetPixelHeight=0;var dpr=Math.max(1,window.devicePixelRatio);var pinchZoom=(_visualViewport$scale=(_visualViewport=visualViewport)==null?void 0:_visualViewport.scale)!=null?_visualViewport$scale:1;if(_this.devicePixelsSupported){var canvasToParentRatioX=canvasWidth/containerWidth;var canvasToParentRatioY=canvasHeight/containerHeight;var scaleToMeetMinPixelRatio=Math.max(1,_this.minPixelRatio/dpr);targetPixelWidth=_this.parentDevicePixelWidth*canvasToParentRatioX*scaleToMeetMinPixelRatio*pinchZoom;targetPixelHeight=_this.parentDevicePixelHeight*canvasToParentRatioY*scaleToMeetMinPixelRatio*pinchZoom;}else {var targetRenderScale=Math.max(dpr,_this.minPixelRatio)*pinchZoom;if(_this.isSafariBrowser){var zoomLevel=bestGuessBrowserZoom();targetRenderScale*=Math.max(1,zoomLevel);}targetPixelWidth=Math.round(canvasWidth)*targetRenderScale;targetPixelHeight=Math.round(canvasHeight)*targetRenderScale;}var maxPixelCountHeadroom=Math.sqrt(_this.maxPixelCount)/Math.sqrt(targetPixelWidth*targetPixelHeight);var scaleToMeetMaxPixelCount=Math.min(1,maxPixelCountHeadroom);var newWidth=Math.round(targetPixelWidth*scaleToMeetMaxPixelCount);var newHeight=Math.round(targetPixelHeight*scaleToMeetMaxPixelCount);var newRenderScale=newWidth/Math.round(canvasWidth);if(_this.canvasElement.width!==newWidth||_this.canvasElement.height!==newHeight||_this.renderScale!==newRenderScale){_this.renderScale=newRenderScale;_this.canvasElement.width=newWidth;_this.canvasElement.height=newHeight;_this.resolutionChanged=true;_this.gl.viewport(0,0,newWidth,newHeight);if(_this.rafId===null){_this.render(performance.now());}}};this.handleDocumentVisibilityChange=function(){if(document.hidden){var _this$video;_this.stopRenderLoop();(_this$video=_this.video)==null?void 0:_this$video.pause();}else {_this.startRenderLoop();if(!_this.config.paused){var _this$video2;(_this$video2=_this.video)==null?void 0:_this$video2.play().catch(function(){});}}};this.render=function(currentTime){if(_this.hasBeenDisposed)return;_this.rafId=requestAnimationFrame(_this.render);if(_this.program===null){console.warn('Tried to render before program was initialized');return;}var gl=_this.gl;var video=_this.video;gl.clear(gl.COLOR_BUFFER_BIT);var currentTimeSeconds=currentTime*0.001;var deltaTime=currentTimeSeconds-_this.lastRenderTime;_this.lastRenderTime=currentTimeSeconds;_this.currentFrame++;var usingStaticImage=!video&&_this.videoTexture!==null;if(!usingStaticImage){if(!video||video.readyState<video.HAVE_CURRENT_DATA){return;}if(!('requestVideoFrameCallback'in video)&&_this.videoTexture){_this.videoTexture.update(video);}if(!_this.config.paused){if(video.currentTime<_this.config.startTime||video.currentTime>=_this.config.endTime){video.currentTime=_this.config.startTime;}}}var videoAnimTime=usingStaticImage?currentTimeSeconds:video.currentTime-_this.config.startTime;if(_this.config.animateLightIndependently||usingStaticImage){_this.independentLightTime+=deltaTime;}else {var videoTimeDelta=videoAnimTime-_this.lastVideoTime;var isVideoJump=Math.abs(videoTimeDelta)>0.1||videoTimeDelta<-0.01;if(isVideoJump){_this.independentLightTime=videoAnimTime;}else {_this.independentLightTime+=deltaTime;}}_this.lastVideoTime=videoAnimTime;gl.useProgram(_this.program);gl.uniform1f(_this.uniformLocations.uTime,currentTimeSeconds);var frameCount=_this.config.animateLightIndependently?_this.independentLightTime*30:videoAnimTime*30;gl.uniform1f(_this.uniformLocations.uFrameCount,frameCount);gl.uniform1f(_this.uniformLocations.uCenterAnimTime,_this.independentLightTime);if(_this.resolutionChanged){gl.uniform2f(_this.uniformLocations.iResolution,_this.canvasElement.width,_this.canvasElement.height);gl.uniform1f(_this.uniformLocations.uDpr,_this.renderScale);gl.uniform4f(_this.uniformLocations.uVisibleUvBounds,_this.visibleUvBounds[0],_this.visibleUvBounds[1],_this.visibleUvBounds[2],_this.visibleUvBounds[3]);_this.resolutionChanged=false;}if(_this.config.animateCycleReps&&_this.currentFrame>_this.config.cycleRepetitionsStartFrame){var elapsed=_this.currentFrame-_this.config.cycleRepetitionsStartFrame;var cycleProgress=elapsed%(_this.config.cycleRepetitionsDuration*2)/_this.config.cycleRepetitionsDuration;var pingPong=cycleProgress<=1?cycleProgress:2-cycleProgress;var eased=pingPong*pingPong*(3-2*pingPong);var delta=_this.config.cycleRepetitionsEnd-_this.config.cycleRepetitionsStart;gl.uniform1f(_this.uniformLocations.uCycleRepetitions,_this.config.cycleRepetitionsStart+eased*delta);}else {gl.uniform1f(_this.uniformLocations.uCycleRepetitions,_this.config.cycleRepetitions);}var targetBlend=_this.config.gradientMapBlend;if(_this.currentGradientMapBlend!==targetBlend){var speed=1.0/_this.config.gradientMapBlendDuration;var diff=targetBlend-_this.currentGradientMapBlend;var step=Math.sign(diff)*Math.min(Math.abs(diff),speed*deltaTime);_this.currentGradientMapBlend+=step;gl.uniform1f(_this.uniformLocations.uGradientMapBlend,_this.currentGradientMapBlend);}gl.drawArrays(gl.TRIANGLES,0,6);};this.handlePerformanceLevelChange=function(level){if(level===0){_this.stopRenderLoop();_this.canvasElement.style.display='none';return;}var _LEVEL_RENDER_SETTING=LEVEL_RENDER_SETTINGS[level],maxPixelCount=_LEVEL_RENDER_SETTING.maxPixelCount,minPixelRatio=_LEVEL_RENDER_SETTING.minPixelRatio;_this.maxPixelCount=maxPixelCount;_this.minPixelRatio=minPixelRatio;if(_this.canvasElement.style.display==='none'){_this.canvasElement.style.display='';}if(_this.isInitialized){_this.startRenderLoop();}_this.handleResize();};this.parentElement=parentElement;this.assets=assets;this.config=Object.assign({},DEFAULT_CONFIG,config);this.currentFrame=frame;this.minPixelRatio=_minPixelRatio;this.maxPixelCount=_maxPixelCount;if(!document.querySelector('style[data-rzp-glass-style]')){var styleElement=document.createElement('style');styleElement.innerHTML=defaultStyle;styleElement.setAttribute('data-rzp-glass-style','');document.head.prepend(styleElement);}this.canvasElement=document.createElement('canvas');this.parentElement.prepend(this.canvasElement);this.parentElement.setAttribute('data-rzp-glass','');var _gl=this.canvasElement.getContext('webgl',{antialias:false,premultipliedAlpha:false,depth:false,alpha:true,powerPreference:'high-performance'});this.gl=_gl;this.performanceController=new WebGLPerformanceController({gl:this.gl,onLevelChange:this.handlePerformanceLevelChange});this.stopIfPotato();_gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL,true);_gl.disable(_gl.DEPTH_TEST);_gl.disable(_gl.CULL_FACE);_gl.clearColor(0,0,0,0);this.initProgram();this.setupPositionAttribute();this.setupUniformLocations();this.setupResizeObserver();(_visualViewport2=visualViewport)==null?void 0:_visualViewport2.addEventListener('resize',this.handleVisualViewportChange);document.addEventListener('visibilitychange',this.handleDocumentVisibilityChange);}return _createClass(RzpGlassMount,[{key:"stopIfPotato",value:function stopIfPotato(){var _this$performanceCont;if(!((_this$performanceCont=this.performanceController)!=null&&_this$performanceCont.isPotato())){return;}this.stopRenderLoop();throw new Error('RzpGlass: WebGL is not supported in this browser');}},{key:"loadAssets",value:(function(){var _loadAssets=_asyncToGenerator(function*(){this.stopIfPotato();try{var _this$assets$gradient;var useStaticImage=Boolean(this.assets.imageSrc);var gradientMap2Src=(_this$assets$gradient=this.assets.gradientMap2Src)!=null?_this$assets$gradient:this.assets.gradientMapSrc;var _yield$Promise$all=yield Promise.all([useStaticImage?loadImage(this.assets.imageSrc):loadVideo(this.assets.videoSrc),loadImage(this.assets.gradientMapSrc),loadImage(gradientMap2Src),loadImage(this.assets.centerGradientMapSrc)]),_yield$Promise$all2=_slicedToArray(_yield$Promise$all,4),baseAsset=_yield$Promise$all2[0],gradientMap=_yield$Promise$all2[1],gradientMap2=_yield$Promise$all2[2],centerGradientMap=_yield$Promise$all2[3];if(useStaticImage){this.setupImageTexture('uVideoTexture',baseAsset,0);}else {this.video=baseAsset;this.setupVideoTexture();this.video.currentTime=this.config.startTime;this.video.playbackRate=this.config.playbackRate;if(!this.config.paused){yield this.video.play().catch(function(e){console.warn('Video autoplay failed:',e);});}}this.setupImageTexture('uGradientMap',gradientMap,1);this.setupImageTexture('uCenterGradientMap',centerGradientMap,2);this.setupImageTexture('uGradientMap2',gradientMap2,3);this.setAllUniforms();this.isInitialized=true;this.handleResize();this.startRenderLoop();}catch(error){console.error('RzpGlass: Failed to load assets',error);throw error;}});function loadAssets(){return _loadAssets.apply(this,arguments);}return loadAssets;}())},{key:"initProgram",value:function initProgram(){var program=createProgram(this.gl,rzpGlassVertexShader,rzpGlassFragmentShader);if(!program){throw new Error('RzpGlass: Failed to create WebGL program');}this.program=program;}},{key:"setupPositionAttribute",value:function setupPositionAttribute(){var buffers=setupFullscreenQuad(this.gl,this.program);if(!buffers){throw new Error('RzpGlass: Failed to setup fullscreen quad');}}},{key:"setupUniformLocations",value:function setupUniformLocations(){var gl=this.gl;var program=this.program;var uniformNames=['uTime','iResolution','uDpr','uVideoTexture','uGradientMap','uGradientMap2','uGradientMapBlend','uCenterGradientMap','uEnableDisplacement','uEnableColorama','uEnableBloom','uEnableLightSweep','uInputMin','uInputMax','uModifyGamma','uPosterizeLevels','uCycleRepetitions','uPhaseShift','uCycleSpeed','uWrapMode','uReverse','uBlendWithOriginal','uLightIntensity','uFrameCount','uLightStartFrame','uNumSegments','uSlitAngle','uDisplacementX','uDisplacementY','uEnableCenterElement','uCenterAnimDuration','uCenterAnimTime','uCCBlackPoint','uCCWhitePoint','uCCMidtoneGamma','uCCGamma','uCCContrast','uZoom','uPan','uEdgeFeather','uRefResolution','uVisibleUvBounds','uBackgroundColor','uEnableRippleWave','uRippleSpeed','uRippleBlend','uRippleAngularPower','uRippleRadialFalloff','uRippleWaitTime'];for(var name of uniformNames){this.uniformLocations[name]=gl.getUniformLocation(program,name);}}},{key:"setupVideoTexture",value:function setupVideoTexture(){var _this2=this;this.videoTexture=new Texture(this.gl,{textureUnit:0});if(this.video&&'requestVideoFrameCallback'in this.video){var _updateVideoFrame=function updateVideoFrame(){if(_this2.hasBeenDisposed||!_this2.video||!_this2.videoTexture)return;_this2.videoTexture.update(_this2.video);_this2.videoFrameCallbackId=_this2.video.requestVideoFrameCallback(_updateVideoFrame);};this.videoFrameCallbackId=this.video.requestVideoFrameCallback(_updateVideoFrame);}}},{key:"setupImageTexture",value:function setupImageTexture(uniformName,image,textureUnit){var texture=new Texture(this.gl,{textureUnit:textureUnit});texture.image(image);if(uniformName==='uVideoTexture'){this.videoTexture=texture;}else if(uniformName==='uGradientMap'){this.gradientMapTexture=texture;}else if(uniformName==='uGradientMap2'){this.gradientMap2Texture=texture;}else if(uniformName==='uCenterGradientMap'){this.centerGradientMapTexture=texture;}}},{key:"updateGradientMapTexture",value:function updateGradientMapTexture(source){if(!this.isInitialized||!this.gradientMapTexture)return;this.gradientMapTexture.image(source);}},{key:"setupResizeObserver",value:function setupResizeObserver(){var _this3=this;this.resizeObserver=new ResizeObserver(function(_ref){var _ref2=_slicedToArray(_ref,1),entry=_ref2[0];if(entry!=null&&entry.borderBoxSize[0]){var _entry$devicePixelCon;var physicalPixelSize=(_entry$devicePixelCon=entry.devicePixelContentBoxSize)==null?void 0:_entry$devicePixelCon[0];if(physicalPixelSize!==undefined){_this3.devicePixelsSupported=true;_this3.parentDevicePixelWidth=physicalPixelSize.inlineSize;_this3.parentDevicePixelHeight=physicalPixelSize.blockSize;}_this3.parentWidth=entry.borderBoxSize[0].inlineSize;_this3.parentHeight=entry.borderBoxSize[0].blockSize;}_this3.handleResize();});this.resizeObserver.observe(this.parentElement);}},{key:"setAllUniforms",value:function setAllUniforms(){var gl=this.gl;gl.useProgram(this.program);gl.uniform1i(this.uniformLocations.uVideoTexture,0);gl.uniform1i(this.uniformLocations.uGradientMap,1);gl.uniform1i(this.uniformLocations.uCenterGradientMap,2);gl.uniform1i(this.uniformLocations.uGradientMap2,3);gl.uniform1f(this.uniformLocations.uGradientMapBlend,this.currentGradientMapBlend);this.setUniformValues(this.config);gl.uniform2f(this.uniformLocations.uPan,this.config.panX,this.config.panY);gl.uniform2f(this.uniformLocations.uRefResolution,REF_RESOLUTION.width,REF_RESOLUTION.height);if(this.config.backgroundColor){var _this$config$backgrou=_slicedToArray(this.config.backgroundColor,3),r=_this$config$backgrou[0],g=_this$config$backgrou[1],b=_this$config$backgrou[2];gl.uniform3f(this.uniformLocations.uBackgroundColor,r,g,b);gl.clearColor(r,g,b,1.0);}else {gl.uniform3f(this.uniformLocations.uBackgroundColor,-1.0,-1.0,-1.0);gl.clearColor(0,0,0,0);}gl.uniform4f(this.uniformLocations.uVisibleUvBounds,this.visibleUvBounds[0],this.visibleUvBounds[1],this.visibleUvBounds[2],this.visibleUvBounds[3]);}},{key:"areUniformValuesEqual",value:function areUniformValuesEqual(a,b){var _this4=this;if(a===b)return true;if(Array.isArray(a)&&Array.isArray(b)&&a.length===b.length){return a.every(function(val,i){return _this4.areUniformValuesEqual(val,b[i]);});}return false;}},{key:"setUniformValues",value:function setUniformValues(config){var _this5=this;var gl=this.gl;gl.useProgram(this.program);Object.entries(config).forEach(function(_ref3){var _ref4=_slicedToArray(_ref3,2),key=_ref4[0],value=_ref4[1];if(value===undefined)return;if(_this5.areUniformValuesEqual(_this5.uniformCache[key],value))return;_this5.uniformCache[key]=value;var uniformName=CONFIG_TO_UNIFORM[key];if(!uniformName)return;var location=_this5.uniformLocations[uniformName];if(!location)return;if(typeof value==='boolean'){gl.uniform1f(location,value?1:0);}else if(typeof value==='number'){gl.uniform1f(location,value);}else if(Array.isArray(value)){var flatArray=value.flat();switch(flatArray.length){case 2:gl.uniform2fv(location,flatArray);break;case 3:gl.uniform3fv(location,flatArray);break;case 4:gl.uniform4fv(location,flatArray);break;}}});if(config.panX!==undefined||config.panY!==undefined){var panCacheKey='pan';var panValue=[this.config.panX,this.config.panY];if(!this.areUniformValuesEqual(this.uniformCache[panCacheKey],panValue)){this.uniformCache[panCacheKey]=panValue;gl.uniform2f(this.uniformLocations.uPan,panValue[0],panValue[1]);}}if(config.backgroundColor!==undefined){var bgCacheKey='backgroundColor';if(!this.areUniformValuesEqual(this.uniformCache[bgCacheKey],config.backgroundColor)){this.uniformCache[bgCacheKey]=config.backgroundColor;if(config.backgroundColor){var _config$backgroundCol=_slicedToArray(config.backgroundColor,3),r=_config$backgroundCol[0],g=_config$backgroundCol[1],b=_config$backgroundCol[2];gl.uniform3f(this.uniformLocations.uBackgroundColor,r,g,b);gl.clearColor(r,g,b,1.0);}else {gl.uniform3f(this.uniformLocations.uBackgroundColor,-1.0,-1.0,-1.0);gl.clearColor(0,0,0,0);}}}}},{key:"setUniforms",value:function setUniforms(newConfig){this.config=Object.assign({},this.config,newConfig);if(!this.isInitialized)return;this.setUniformValues(newConfig);if(newConfig.paused!==undefined){if(newConfig.paused){var _this$video3;(_this$video3=this.video)==null?void 0:_this$video3.pause();}else {var _this$video4;(_this$video4=this.video)==null?void 0:_this$video4.play().catch(function(){});}}if(newConfig.playbackRate!==undefined&&this.video){this.video.playbackRate=newConfig.playbackRate;}if(newConfig.aspectRatio!==undefined){this.handleResize();}}},{key:"startRenderLoop",value:function startRenderLoop(){if(this.rafId!==null)return;this.lastRenderTime=performance.now()*0.001;this.rafId=requestAnimationFrame(this.render);}},{key:"stopRenderLoop",value:function stopRenderLoop(){if(this.rafId!==null){cancelAnimationFrame(this.rafId);this.rafId=null;}}},{key:"getCurrentFrame",value:function getCurrentFrame(){return this.currentFrame;}},{key:"setFrame",value:function setFrame(newFrame){this.currentFrame=newFrame;}},{key:"setMaxPixelCount",value:function setMaxPixelCount(){var newMaxPixelCount=arguments.length>0&&arguments[0]!==undefined?arguments[0]:DEFAULT_MAX_PIXEL_COUNT;this.maxPixelCount=newMaxPixelCount;this.handleResize();}},{key:"setMinPixelRatio",value:function setMinPixelRatio(){var newMinPixelRatio=arguments.length>0&&arguments[0]!==undefined?arguments[0]:2;this.minPixelRatio=newMinPixelRatio;this.handleResize();}},{key:"play",value:function play(){var _this$video5;this.config.paused=false;(_this$video5=this.video)==null?void 0:_this$video5.play().catch(function(){});}},{key:"pause",value:function pause(){var _this$video6;this.config.paused=true;(_this$video6=this.video)==null?void 0:_this$video6.pause();}},{key:"setTime",value:function setTime(time){if(this.video){this.video.currentTime=time;}}},{key:"dispose",value:function dispose(){var _this$performanceCont2,_visualViewport3;this.hasBeenDisposed=true;if(this.rafId!==null){cancelAnimationFrame(this.rafId);this.rafId=null;}if(this.videoFrameCallbackId!==null&&this.video&&'cancelVideoFrameCallback'in this.video){this.video.cancelVideoFrameCallback(this.videoFrameCallbackId);}if(this.video){this.video.pause();this.video.src='';this.video.load();this.video=null;}if(this.gl&&this.program){var _this$videoTexture,_this$gradientMapText,_this$gradientMap2Tex,_this$centerGradientM;(_this$videoTexture=this.videoTexture)==null?void 0:_this$videoTexture.destroy();(_this$gradientMapText=this.gradientMapTexture)==null?void 0:_this$gradientMapText.destroy();(_this$gradientMap2Tex=this.gradientMap2Texture)==null?void 0:_this$gradientMap2Tex.destroy();(_this$centerGradientM=this.centerGradientMapTexture)==null?void 0:_this$centerGradientM.destroy();this.gl.deleteProgram(this.program);this.program=null;this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null);this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER,null);this.gl.bindRenderbuffer(this.gl.RENDERBUFFER,null);this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,null);this.gl.getError();}(_this$performanceCont2=this.performanceController)==null?void 0:_this$performanceCont2.dispose();this.performanceController=null;if(this.resizeObserver){this.resizeObserver.disconnect();this.resizeObserver=null;}(_visualViewport3=visualViewport)==null?void 0:_visualViewport3.removeEventListener('resize',this.handleVisualViewportChange);document.removeEventListener('visibilitychange',this.handleDocumentVisibilityChange);this.uniformLocations={};this.uniformCache={};this.canvasElement.remove();this.parentElement.removeAttribute('data-rzp-glass');}}]);}();
|
|
26
|
+
|
|
27
|
+
export { RzpGlassMount };
|
|
28
|
+
//# sourceMappingURL=RzpGlassMount.js.map
|