@react-three/drei 9.56.9 → 9.56.11

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/README.md CHANGED
@@ -2804,6 +2804,8 @@ This component allows you to render a live scene into a texture which you can th
2804
2804
  eventPriority?: number
2805
2805
  /** Optional frame count, defaults to Infinity. If you set it to 1, it would only render a single frame, etc */
2806
2806
  frames?: number
2807
+ /** Optional event compute, defaults to undefined */
2808
+ compute?: (event: any, state: any, previous: any) => false | undefined
2807
2809
  /** Children will be rendered into a portal */
2808
2810
  children: React.ReactNode
2809
2811
  />
@@ -2834,8 +2836,6 @@ Masks use the stencil buffer to cut out areas of the screen. This is usually che
2834
2836
  colorWrite?: boolean
2835
2837
  /** If depth of the masks own material will leak through, default: false */
2836
2838
  depthWrite?: boolean
2837
- /** children must define a geometry, a render-prop function is allowed which may override the default material */
2838
- children: ((spread: MaskSpread) => React.ReactNode) | React.ReactNode
2839
2839
  />
2840
2840
  ```
2841
2841
 
@@ -2844,6 +2844,7 @@ First you need to define a mask, give it the shape that you want.
2844
2844
  ```jsx
2845
2845
  <Mask id={1}>
2846
2846
  <planeGeometry />
2847
+ <meshBasicMaterial />
2847
2848
  </Mask>
2848
2849
  ```
2849
2850
 
@@ -2857,27 +2858,16 @@ return (
2857
2858
  <meshStandardMaterial {...stencil} />
2858
2859
  ```
2859
2860
 
2860
- You can build compound masks with multiple shapes by re-using an id.
2861
+ You can build compound masks with multiple shapes by re-using an id. You can also use the mask as a normal mesh by providing `colorWrite` and `depthWrite` props.
2861
2862
 
2862
2863
  ```jsx
2863
2864
  <Mask position={[-1, 0, 0]} id={1}>
2864
2865
  <planeGeometry />
2866
+ <meshBasicMaterial />
2865
2867
  </Mask>
2866
- <Mask position={[1, 0, 0]} id={1}>
2868
+ <Mask colorWrite depthWrite position={[1, 0, 0]} id={1}>
2867
2869
  <circleGeometry />
2868
- </Mask>
2869
- ```
2870
-
2871
- You can override the material of a mask by using a render prop.
2872
-
2873
- ```jsx
2874
- <Mask id={1}>
2875
- {(spread) => (
2876
- <>
2877
- <planeGeometry args={[2, 2, 128, 128]} />
2878
- <MeshDistortMaterial distort={0.5} radius={1} speed={10} {...spread} />
2879
- </>
2880
- )}
2870
+ <meshBasicMaterial />
2881
2871
  </Mask>
2882
2872
  ```
2883
2873
 
@@ -3396,6 +3386,7 @@ function Foo() {
3396
3386
  ```
3397
3387
 
3398
3388
  #### SpotLightShadows
3389
+
3399
3390
  [![](https://img.shields.io/badge/-storybook-%23ff69b4)](https://drei.pmnd.rs/?path=/story/staging-spotlight--spotlight-shadows-st)
3400
3391
 
3401
3392
  <p>
package/core/Mask.cjs.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@babel/runtime/helpers/extends"),t=require("three"),n=require("react");function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function c(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}})),t.default=e,Object.freeze(t)}var i=r(e),l=c(t),u=c(n);exports.Mask=function({id:e=1,children:t,colorWrite:n=!1,depthWrite:r=!1,...c}){const s=u.useMemo((()=>({colorWrite:n,depthWrite:r,stencilWrite:!0,stencilRef:e,stencilFunc:l.AlwaysStencilFunc,stencilFail:l.ReplaceStencilOp,stencilZFail:l.ReplaceStencilOp,stencilZPass:l.ReplaceStencilOp})),[e,n,r]);return u.createElement("mesh",i.default({renderOrder:-e},c),u.createElement("meshBasicMaterial",s),"function"==typeof t?t(s):t)},exports.useMask=function(e,t=!1){return{stencilWrite:!0,stencilRef:e,stencilFunc:t?l.NotEqualStencilFunc:l.EqualStencilFunc,stencilFail:l.KeepStencilOp,stencilZFail:l.KeepStencilOp,stencilZPass:l.KeepStencilOp}};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@babel/runtime/helpers/extends"),t=require("three"),r=require("react");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function c(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var i=n(e),l=c(t),u=c(r);const s=u.forwardRef((({id:e=1,colorWrite:t=!1,depthWrite:r=!1,...n},c)=>{const s=u.useRef(null),a=u.useMemo((()=>({colorWrite:t,depthWrite:r,stencilWrite:!0,stencilRef:e,stencilFunc:l.AlwaysStencilFunc,stencilFail:l.ReplaceStencilOp,stencilZFail:l.ReplaceStencilOp,stencilZPass:l.ReplaceStencilOp})),[e,t,r]);return u.useLayoutEffect((()=>{Object.assign(s.current.material,a)})),u.useImperativeHandle(c,(()=>s.current),[]),u.createElement("mesh",i.default({ref:s,renderOrder:-e},n))}));exports.Mask=s,exports.useMask=function(e,t=!1){return{stencilWrite:!0,stencilRef:e,stencilFunc:t?l.NotEqualStencilFunc:l.EqualStencilFunc,stencilFail:l.KeepStencilOp,stencilZFail:l.KeepStencilOp,stencilZPass:l.KeepStencilOp}};
package/core/Mask.d.ts CHANGED
@@ -1,22 +1,10 @@
1
1
  import * as THREE from 'three';
2
2
  import * as React from 'react';
3
- declare type MaskSpread = {
4
- colorWrite: boolean;
5
- depthWrite: boolean;
6
- stencilWrite: boolean;
7
- stencilRef: number;
8
- stencilFunc: THREE.StencilFunc;
9
- stencilFail: THREE.StencilOp;
10
- stencilZFail: THREE.StencilOp;
11
- stencilZPass: THREE.StencilOp;
12
- };
13
- declare type Props = Omit<JSX.IntrinsicElements['mesh'], 'children'> & {
3
+ export declare const Mask: React.ForwardRefExoticComponent<Pick<Omit<import("@react-three/fiber").MeshProps, "id"> & {
14
4
  id: number;
15
- colorWrite?: boolean;
16
- depthWrite?: boolean;
17
- children: ((spread: MaskSpread) => React.ReactNode) | React.ReactNode;
18
- };
19
- export declare function Mask({ id, children, colorWrite, depthWrite, ...props }: Props): JSX.Element;
5
+ colorWrite?: boolean | undefined;
6
+ depthWrite?: boolean | undefined;
7
+ }, "visible" | "attach" | "args" | "children" | "key" | "onUpdate" | "position" | "up" | "scale" | "rotation" | "matrix" | "quaternion" | "layers" | "dispose" | "type" | "id" | "uuid" | "name" | "parent" | "modelViewMatrix" | "normalMatrix" | "matrixWorld" | "matrixAutoUpdate" | "matrixWorldNeedsUpdate" | "castShadow" | "receiveShadow" | "frustumCulled" | "renderOrder" | "animations" | "userData" | "customDepthMaterial" | "customDistanceMaterial" | "isObject3D" | "onBeforeRender" | "onAfterRender" | "applyMatrix4" | "applyQuaternion" | "setRotationFromAxisAngle" | "setRotationFromEuler" | "setRotationFromMatrix" | "setRotationFromQuaternion" | "rotateOnAxis" | "rotateOnWorldAxis" | "rotateX" | "rotateY" | "rotateZ" | "translateOnAxis" | "translateX" | "translateY" | "translateZ" | "localToWorld" | "worldToLocal" | "lookAt" | "add" | "remove" | "removeFromParent" | "clear" | "getObjectById" | "getObjectByName" | "getObjectByProperty" | "getWorldPosition" | "getWorldQuaternion" | "getWorldScale" | "getWorldDirection" | "raycast" | "traverse" | "traverseVisible" | "traverseAncestors" | "updateMatrix" | "updateMatrixWorld" | "updateWorldMatrix" | "toJSON" | "clone" | "copy" | "addEventListener" | "hasEventListener" | "removeEventListener" | "dispatchEvent" | keyof import("@react-three/fiber/dist/declarations/src/core/events").EventHandlers | "material" | "geometry" | "colorWrite" | "depthWrite" | "morphTargetInfluences" | "morphTargetDictionary" | "isMesh" | "updateMorphTargets"> & React.RefAttributes<THREE.Mesh<THREE.BufferGeometry, THREE.Material | THREE.Material[]>>>;
20
8
  export declare function useMask(id: number, inverse?: boolean): {
21
9
  stencilWrite: boolean;
22
10
  stencilRef: number;
@@ -25,4 +13,3 @@ export declare function useMask(id: number, inverse?: boolean): {
25
13
  stencilZFail: THREE.StencilOp;
26
14
  stencilZPass: THREE.StencilOp;
27
15
  };
28
- export {};
package/core/Mask.js CHANGED
@@ -2,13 +2,13 @@ import _extends from '@babel/runtime/helpers/esm/extends';
2
2
  import * as THREE from 'three';
3
3
  import * as React from 'react';
4
4
 
5
- function Mask({
5
+ const Mask = /*#__PURE__*/React.forwardRef(({
6
6
  id = 1,
7
- children,
8
7
  colorWrite = false,
9
8
  depthWrite = false,
10
9
  ...props
11
- }) {
10
+ }, fref) => {
11
+ const ref = React.useRef(null);
12
12
  const spread = React.useMemo(() => ({
13
13
  colorWrite,
14
14
  depthWrite,
@@ -19,10 +19,15 @@ function Mask({
19
19
  stencilZFail: THREE.ReplaceStencilOp,
20
20
  stencilZPass: THREE.ReplaceStencilOp
21
21
  }), [id, colorWrite, depthWrite]);
22
+ React.useLayoutEffect(() => {
23
+ Object.assign(ref.current.material, spread);
24
+ });
25
+ React.useImperativeHandle(fref, () => ref.current, []);
22
26
  return /*#__PURE__*/React.createElement("mesh", _extends({
27
+ ref: ref,
23
28
  renderOrder: -id
24
- }, props), /*#__PURE__*/React.createElement("meshBasicMaterial", spread), typeof children === 'function' ? children(spread) : children);
25
- }
29
+ }, props));
30
+ });
26
31
  function useMask(id, inverse = false) {
27
32
  return {
28
33
  stencilWrite: true,
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var n=require("@babel/runtime/helpers/extends"),e=require("three"),t=require("react"),a=require("@react-three/fiber"),r=require("./useFBO.cjs.js"),o=require("../materials/DiscardMaterial.cjs.js");function i(n){return n&&"object"==typeof n&&"default"in n?n:{default:n}}function s(n){if(n&&n.__esModule)return n;var e=Object.create(null);return n&&Object.keys(n).forEach((function(t){if("default"!==t){var a=Object.getOwnPropertyDescriptor(n,t);Object.defineProperty(e,t,a.get?a:{enumerable:!0,get:function(){return n[t]}})}})),e.default=n,Object.freeze(e)}require("./shaderMaterial.cjs.js");var l=i(n),c=s(e),m=s(t);class u extends c.MeshPhysicalMaterial{constructor(n=6,e=!1){super(),this.uniforms={chromaticAberration:{value:.05},transmission:{value:0},_transmission:{value:1},transmissionMap:{value:null},roughness:{value:0},thickness:{value:0},thicknessMap:{value:null},attenuationDistance:{value:1/0},attenuationColor:{value:new c.Color("white")},anisotropy:{value:.1},time:{value:0},distortion:{value:0},distortionScale:{value:.5},temporalDistortion:{value:0},buffer:{value:null}},this.onBeforeCompile=t=>{t.uniforms={...t.uniforms,...this.uniforms},e?t.defines.USE_SAMPLER="":t.defines.USE_TRANSMISSION="",t.fragmentShader="\n uniform float chromaticAberration; \n uniform float anisotropy; \n uniform float time;\n uniform float distortion;\n uniform float distortionScale;\n uniform float temporalDistortion;\n uniform sampler2D buffer;\n\n vec3 random3(vec3 c) {\n float j = 4096.0*sin(dot(c,vec3(17.0, 59.4, 15.0)));\n vec3 r;\n r.z = fract(512.0*j);\n j *= .125;\n r.x = fract(512.0*j);\n j *= .125;\n r.y = fract(512.0*j);\n return r-0.5;\n }\n\n float seed = 0.0;\n uint hash( uint x ) {\n x += ( x << 10u );\n x ^= ( x >> 6u );\n x += ( x << 3u );\n x ^= ( x >> 11u );\n x += ( x << 15u );\n return x;\n }\n\n // Compound versions of the hashing algorithm I whipped together.\n uint hash( uvec2 v ) { return hash( v.x ^ hash(v.y) ); }\n uint hash( uvec3 v ) { return hash( v.x ^ hash(v.y) ^ hash(v.z) ); }\n uint hash( uvec4 v ) { return hash( v.x ^ hash(v.y) ^ hash(v.z) ^ hash(v.w) ); }\n\n // Construct a float with half-open range [0:1] using low 23 bits.\n // All zeroes yields 0.0, all ones yields the next smallest representable value below 1.0.\n float floatConstruct( uint m ) {\n const uint ieeeMantissa = 0x007FFFFFu; // binary32 mantissa bitmask\n const uint ieeeOne = 0x3F800000u; // 1.0 in IEEE binary32\n m &= ieeeMantissa; // Keep only mantissa bits (fractional part)\n m |= ieeeOne; // Add fractional part to 1.0\n float f = uintBitsToFloat( m ); // Range [1:2]\n return f - 1.0; // Range [0:1]\n }\n\n // Pseudo-random value in half-open range [0:1].\n float random( float x ) { return floatConstruct(hash(floatBitsToUint(x))); }\n float random( vec2 v ) { return floatConstruct(hash(floatBitsToUint(v))); }\n float random( vec3 v ) { return floatConstruct(hash(floatBitsToUint(v))); }\n float random( vec4 v ) { return floatConstruct(hash(floatBitsToUint(v))); }\n\n float rand() {\n float result = random(vec3(gl_FragCoord.xy, seed));\n seed += 1.0;\n return result;\n }\n\n const float F3 = 0.3333333;\n const float G3 = 0.1666667;\n\n float snoise(vec3 p) {\n vec3 s = floor(p + dot(p, vec3(F3)));\n vec3 x = p - s + dot(s, vec3(G3));\n vec3 e = step(vec3(0.0), x - x.yzx);\n vec3 i1 = e*(1.0 - e.zxy);\n vec3 i2 = 1.0 - e.zxy*(1.0 - e);\n vec3 x1 = x - i1 + G3;\n vec3 x2 = x - i2 + 2.0*G3;\n vec3 x3 = x - 1.0 + 3.0*G3;\n vec4 w, d;\n w.x = dot(x, x);\n w.y = dot(x1, x1);\n w.z = dot(x2, x2);\n w.w = dot(x3, x3);\n w = max(0.6 - w, 0.0);\n d.x = dot(random3(s), x);\n d.y = dot(random3(s + i1), x1);\n d.z = dot(random3(s + i2), x2);\n d.w = dot(random3(s + 1.0), x3);\n w *= w;\n w *= w;\n d *= w;\n return dot(d, vec4(52.0));\n }\n\n float snoiseFractal(vec3 m) {\n return 0.5333333* snoise(m)\n +0.2666667* snoise(2.0*m)\n +0.1333333* snoise(4.0*m)\n +0.0666667* snoise(8.0*m);\n }\n"+t.fragmentShader,t.fragmentShader=t.fragmentShader.replace("#include <transmission_pars_fragment>","\n #ifdef USE_TRANSMISSION\n // Transmission code is based on glTF-Sampler-Viewer\n // https://github.com/KhronosGroup/glTF-Sample-Viewer\n uniform float _transmission;\n uniform float thickness;\n uniform float attenuationDistance;\n uniform vec3 attenuationColor;\n #ifdef USE_TRANSMISSIONMAP\n uniform sampler2D transmissionMap;\n #endif\n #ifdef USE_THICKNESSMAP\n uniform sampler2D thicknessMap;\n #endif\n uniform vec2 transmissionSamplerSize;\n uniform sampler2D transmissionSamplerMap;\n uniform mat4 modelMatrix;\n uniform mat4 projectionMatrix;\n varying vec3 vWorldPosition;\n vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n // Direction of refracted light.\n vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n // Compute rotation-independant scaling of the model matrix.\n vec3 modelScale;\n modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n // The thickness is specified in local space.\n return normalize( refractionVector ) * thickness * modelScale;\n }\n float applyIorToRoughness( const in float roughness, const in float ior ) {\n // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and\n // an IOR of 1.5 results in the default amount of microfacet refraction.\n return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n }\n vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n float framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); \n #ifdef USE_SAMPLER\n #ifdef texture2DLodEXT\n return texture2DLodEXT(transmissionSamplerMap, fragCoord.xy, framebufferLod);\n #else\n return texture2D(transmissionSamplerMap, fragCoord.xy, framebufferLod);\n #endif\n #else\n return texture2D(buffer, fragCoord.xy);\n #endif\n }\n vec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n if ( isinf( attenuationDistance ) ) {\n // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.\n return radiance;\n } else {\n // Compute light attenuation using Beer's law.\n vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); // Beer's law\n return transmittance * radiance;\n }\n }\n vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n const in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n const in vec3 attenuationColor, const in float attenuationDistance ) {\n vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n vec3 refractedRayExit = position + transmissionRay;\n // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.\n vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n vec2 refractionCoords = ndcPos.xy / ndcPos.w;\n refractionCoords += 1.0;\n refractionCoords /= 2.0;\n // Sample framebuffer to get pixel the refracted ray hits.\n vec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n vec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n // Get the specular component.\n vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n return vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n }\n #endif\n"),t.fragmentShader=t.fragmentShader.replace("#include <transmission_fragment>",` \n // Improve the refraction to use the world pos\n material.transmission = _transmission;\n material.transmissionAlpha = 1.0;\n material.thickness = thickness;\n material.attenuationDistance = attenuationDistance;\n material.attenuationColor = attenuationColor;\n #ifdef USE_TRANSMISSIONMAP\n material.transmission *= texture2D( transmissionMap, vUv ).r;\n #endif\n #ifdef USE_THICKNESSMAP\n material.thickness *= texture2D( thicknessMap, vUv ).g;\n #endif\n \n vec3 pos = vWorldPosition;\n vec3 v = normalize( cameraPosition - pos );\n vec3 n = inverseTransformDirection( normal, viewMatrix );\n vec3 transmission = vec3(0.0);\n float transmissionR, transmissionB, transmissionG;\n float randomCoords = rand();\n float thickness_smear = thickness * max(pow(roughness, 0.33), anisotropy);\n vec3 distortionNormal = vec3(0.0);\n vec3 temporalOffset = vec3(time, -time, -time) * temporalDistortion;\n if (distortion > 0.0) {\n distortionNormal = distortion * vec3(snoiseFractal(vec3((pos * distortionScale + temporalOffset))), snoiseFractal(vec3(pos.zxy * distortionScale - temporalOffset)), snoiseFractal(vec3(pos.yxz * distortionScale + temporalOffset)));\n }\n for (float i = 0.0; i < ${n}.0; i ++) {\n vec3 sampleNorm = normalize(n + roughness * roughness * 2.0 * normalize(vec3(rand() - 0.5, rand() - 0.5, rand() - 0.5)) * pow(rand(), 0.33) + distortionNormal);\n transmissionR = getIBLVolumeRefraction(\n sampleNorm, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n pos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness + thickness_smear * (i + randomCoords) / float(${n}),\n material.attenuationColor, material.attenuationDistance\n ).r;\n transmissionG = getIBLVolumeRefraction(\n sampleNorm, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n pos, modelMatrix, viewMatrix, projectionMatrix, material.ior * (1.0 + chromaticAberration * (i + randomCoords) / float(${n})) , material.thickness + thickness_smear * (i + randomCoords) / float(${n}),\n material.attenuationColor, material.attenuationDistance\n ).g;\n transmissionB = getIBLVolumeRefraction(\n sampleNorm, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n pos, modelMatrix, viewMatrix, projectionMatrix, material.ior * (1.0 + 2.0 * chromaticAberration * (i + randomCoords) / float(${n})), material.thickness + thickness_smear * (i + randomCoords) / float(${n}),\n material.attenuationColor, material.attenuationDistance\n ).b;\n transmission.r += transmissionR;\n transmission.g += transmissionG;\n transmission.b += transmissionB;\n }\n transmission /= ${n}.0;\n totalDiffuse = mix( totalDiffuse, transmission.rgb, material.transmission );\n`)},Object.keys(this.uniforms).forEach((n=>Object.defineProperty(this,n,{get:()=>this.uniforms[n].value,set:e=>this.uniforms[n].value=e})))}}const f=m.forwardRef((({buffer:n,transmissionSampler:e=!1,backside:t=!1,side:i=c.FrontSide,transmission:s=1,thickness:f=0,backsideThickness:d=0,samples:v=10,resolution:h,backsideResolution:p,background:x,...g},M)=>{a.extend({MeshTransmissionMaterial:u});const S=m.useRef(null),[C]=m.useState((()=>new o.DiscardMaterial)),b=r.useFBO(p||h),y=r.useFBO(h);let w,k,D;return a.useFrame((a=>{S.current.time=a.clock.getElapsedTime(),n||e||(D=S.current.__r3f.parent,D&&(k=a.gl.toneMapping,w=a.scene.background,a.gl.toneMapping=c.NoToneMapping,x&&(a.scene.background=x),D.material=C,t&&(a.gl.setRenderTarget(b),a.gl.render(a.scene,a.camera),D.material=S.current,D.material.buffer=b.texture,D.material.thickness=d,D.material.side=c.BackSide),a.gl.setRenderTarget(y),a.gl.render(a.scene,a.camera),D.material=S.current,D.material.thickness=f,D.material.side=i,D.material.buffer=y.texture,a.scene.background=w,a.gl.setRenderTarget(null),D.material=S.current,a.gl.toneMapping=k))})),m.useImperativeHandle(M,(()=>S.current),[]),m.createElement("meshTransmissionMaterial",l.default({args:[v,e],ref:S},g,{buffer:n||y.texture,_transmission:s,transmission:e?s:0,thickness:f,side:i}))}));exports.MeshTransmissionMaterial=f;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var n=require("@babel/runtime/helpers/extends"),e=require("three"),t=require("react"),a=require("@react-three/fiber"),r=require("./useFBO.cjs.js"),o=require("../materials/DiscardMaterial.cjs.js");function i(n){return n&&"object"==typeof n&&"default"in n?n:{default:n}}function s(n){if(n&&n.__esModule)return n;var e=Object.create(null);return n&&Object.keys(n).forEach((function(t){if("default"!==t){var a=Object.getOwnPropertyDescriptor(n,t);Object.defineProperty(e,t,a.get?a:{enumerable:!0,get:function(){return n[t]}})}})),e.default=n,Object.freeze(e)}require("./shaderMaterial.cjs.js");var l=i(n),c=s(e),m=s(t);class u extends c.MeshPhysicalMaterial{constructor(n=6,e=!1){super(),this.uniforms={chromaticAberration:{value:.05},transmission:{value:0},_transmission:{value:1},transmissionMap:{value:null},roughness:{value:0},thickness:{value:0},thicknessMap:{value:null},attenuationDistance:{value:1/0},attenuationColor:{value:new c.Color("white")},anisotropy:{value:.1},time:{value:0},distortion:{value:0},distortionScale:{value:.5},temporalDistortion:{value:0},buffer:{value:null}},this.onBeforeCompile=t=>{t.uniforms={...t.uniforms,...this.uniforms},e?t.defines.USE_SAMPLER="":t.defines.USE_TRANSMISSION="",t.fragmentShader="\n uniform float chromaticAberration; \n uniform float anisotropy; \n uniform float time;\n uniform float distortion;\n uniform float distortionScale;\n uniform float temporalDistortion;\n uniform sampler2D buffer;\n\n vec3 random3(vec3 c) {\n float j = 4096.0*sin(dot(c,vec3(17.0, 59.4, 15.0)));\n vec3 r;\n r.z = fract(512.0*j);\n j *= .125;\n r.x = fract(512.0*j);\n j *= .125;\n r.y = fract(512.0*j);\n return r-0.5;\n }\n\n float seed = 0.0;\n uint hash( uint x ) {\n x += ( x << 10u );\n x ^= ( x >> 6u );\n x += ( x << 3u );\n x ^= ( x >> 11u );\n x += ( x << 15u );\n return x;\n }\n\n // Compound versions of the hashing algorithm I whipped together.\n uint hash( uvec2 v ) { return hash( v.x ^ hash(v.y) ); }\n uint hash( uvec3 v ) { return hash( v.x ^ hash(v.y) ^ hash(v.z) ); }\n uint hash( uvec4 v ) { return hash( v.x ^ hash(v.y) ^ hash(v.z) ^ hash(v.w) ); }\n\n // Construct a float with half-open range [0:1] using low 23 bits.\n // All zeroes yields 0.0, all ones yields the next smallest representable value below 1.0.\n float floatConstruct( uint m ) {\n const uint ieeeMantissa = 0x007FFFFFu; // binary32 mantissa bitmask\n const uint ieeeOne = 0x3F800000u; // 1.0 in IEEE binary32\n m &= ieeeMantissa; // Keep only mantissa bits (fractional part)\n m |= ieeeOne; // Add fractional part to 1.0\n float f = uintBitsToFloat( m ); // Range [1:2]\n return f - 1.0; // Range [0:1]\n }\n\n // Pseudo-random value in half-open range [0:1].\n float random( float x ) { return floatConstruct(hash(floatBitsToUint(x))); }\n float random( vec2 v ) { return floatConstruct(hash(floatBitsToUint(v))); }\n float random( vec3 v ) { return floatConstruct(hash(floatBitsToUint(v))); }\n float random( vec4 v ) { return floatConstruct(hash(floatBitsToUint(v))); }\n\n float rand() {\n float result = random(vec3(gl_FragCoord.xy, seed));\n seed += 1.0;\n return result;\n }\n\n const float F3 = 0.3333333;\n const float G3 = 0.1666667;\n\n float snoise(vec3 p) {\n vec3 s = floor(p + dot(p, vec3(F3)));\n vec3 x = p - s + dot(s, vec3(G3));\n vec3 e = step(vec3(0.0), x - x.yzx);\n vec3 i1 = e*(1.0 - e.zxy);\n vec3 i2 = 1.0 - e.zxy*(1.0 - e);\n vec3 x1 = x - i1 + G3;\n vec3 x2 = x - i2 + 2.0*G3;\n vec3 x3 = x - 1.0 + 3.0*G3;\n vec4 w, d;\n w.x = dot(x, x);\n w.y = dot(x1, x1);\n w.z = dot(x2, x2);\n w.w = dot(x3, x3);\n w = max(0.6 - w, 0.0);\n d.x = dot(random3(s), x);\n d.y = dot(random3(s + i1), x1);\n d.z = dot(random3(s + i2), x2);\n d.w = dot(random3(s + 1.0), x3);\n w *= w;\n w *= w;\n d *= w;\n return dot(d, vec4(52.0));\n }\n\n float snoiseFractal(vec3 m) {\n return 0.5333333* snoise(m)\n +0.2666667* snoise(2.0*m)\n +0.1333333* snoise(4.0*m)\n +0.0666667* snoise(8.0*m);\n }\n"+t.fragmentShader,t.fragmentShader=t.fragmentShader.replace("#include <transmission_pars_fragment>","\n #ifdef USE_TRANSMISSION\n // Transmission code is based on glTF-Sampler-Viewer\n // https://github.com/KhronosGroup/glTF-Sample-Viewer\n uniform float _transmission;\n uniform float thickness;\n uniform float attenuationDistance;\n uniform vec3 attenuationColor;\n #ifdef USE_TRANSMISSIONMAP\n uniform sampler2D transmissionMap;\n #endif\n #ifdef USE_THICKNESSMAP\n uniform sampler2D thicknessMap;\n #endif\n uniform vec2 transmissionSamplerSize;\n uniform sampler2D transmissionSamplerMap;\n uniform mat4 modelMatrix;\n uniform mat4 projectionMatrix;\n varying vec3 vWorldPosition;\n vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n // Direction of refracted light.\n vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n // Compute rotation-independant scaling of the model matrix.\n vec3 modelScale;\n modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n // The thickness is specified in local space.\n return normalize( refractionVector ) * thickness * modelScale;\n }\n float applyIorToRoughness( const in float roughness, const in float ior ) {\n // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and\n // an IOR of 1.5 results in the default amount of microfacet refraction.\n return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n }\n vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n float framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); \n #ifdef USE_SAMPLER\n #ifdef texture2DLodEXT\n return texture2DLodEXT(transmissionSamplerMap, fragCoord.xy, framebufferLod);\n #else\n return texture2D(transmissionSamplerMap, fragCoord.xy, framebufferLod);\n #endif\n #else\n return texture2D(buffer, fragCoord.xy);\n #endif\n }\n vec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n if ( isinf( attenuationDistance ) ) {\n // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.\n return radiance;\n } else {\n // Compute light attenuation using Beer's law.\n vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); // Beer's law\n return transmittance * radiance;\n }\n }\n vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n const in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n const in vec3 attenuationColor, const in float attenuationDistance ) {\n vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n vec3 refractedRayExit = position + transmissionRay;\n // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.\n vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n vec2 refractionCoords = ndcPos.xy / ndcPos.w;\n refractionCoords += 1.0;\n refractionCoords /= 2.0;\n // Sample framebuffer to get pixel the refracted ray hits.\n vec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n vec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n // Get the specular component.\n vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n return vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n }\n #endif\n"),t.fragmentShader=t.fragmentShader.replace("#include <transmission_fragment>",` \n // Improve the refraction to use the world pos\n material.transmission = _transmission;\n material.transmissionAlpha = 1.0;\n material.thickness = thickness;\n material.attenuationDistance = attenuationDistance;\n material.attenuationColor = attenuationColor;\n #ifdef USE_TRANSMISSIONMAP\n material.transmission *= texture2D( transmissionMap, vUv ).r;\n #endif\n #ifdef USE_THICKNESSMAP\n material.thickness *= texture2D( thicknessMap, vUv ).g;\n #endif\n \n vec3 pos = vWorldPosition;\n vec3 v = normalize( cameraPosition - pos );\n vec3 n = inverseTransformDirection( normal, viewMatrix );\n vec3 transmission = vec3(0.0);\n float transmissionR, transmissionB, transmissionG;\n float randomCoords = rand();\n float thickness_smear = thickness * max(pow(roughness, 0.33), anisotropy);\n vec3 distortionNormal = vec3(0.0);\n vec3 temporalOffset = vec3(time, -time, -time) * temporalDistortion;\n if (distortion > 0.0) {\n distortionNormal = distortion * vec3(snoiseFractal(vec3((pos * distortionScale + temporalOffset))), snoiseFractal(vec3(pos.zxy * distortionScale - temporalOffset)), snoiseFractal(vec3(pos.yxz * distortionScale + temporalOffset)));\n }\n for (float i = 0.0; i < ${n}.0; i ++) {\n vec3 sampleNorm = normalize(n + roughness * roughness * 2.0 * normalize(vec3(rand() - 0.5, rand() - 0.5, rand() - 0.5)) * pow(rand(), 0.33) + distortionNormal);\n transmissionR = getIBLVolumeRefraction(\n sampleNorm, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n pos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness + thickness_smear * (i + randomCoords) / float(${n}),\n material.attenuationColor, material.attenuationDistance\n ).r;\n transmissionG = getIBLVolumeRefraction(\n sampleNorm, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n pos, modelMatrix, viewMatrix, projectionMatrix, material.ior * (1.0 + chromaticAberration * (i + randomCoords) / float(${n})) , material.thickness + thickness_smear * (i + randomCoords) / float(${n}),\n material.attenuationColor, material.attenuationDistance\n ).g;\n transmissionB = getIBLVolumeRefraction(\n sampleNorm, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n pos, modelMatrix, viewMatrix, projectionMatrix, material.ior * (1.0 + 2.0 * chromaticAberration * (i + randomCoords) / float(${n})), material.thickness + thickness_smear * (i + randomCoords) / float(${n}),\n material.attenuationColor, material.attenuationDistance\n ).b;\n transmission.r += transmissionR;\n transmission.g += transmissionG;\n transmission.b += transmissionB;\n }\n transmission /= ${n}.0;\n totalDiffuse = mix( totalDiffuse, transmission.rgb, material.transmission );\n`)},Object.keys(this.uniforms).forEach((n=>Object.defineProperty(this,n,{get:()=>this.uniforms[n].value,set:e=>this.uniforms[n].value=e})))}}const f=m.forwardRef((({buffer:n,transmissionSampler:e=!1,backside:t=!1,side:i=c.FrontSide,transmission:s=1,thickness:f=0,backsideThickness:d=0,samples:v=10,resolution:h,backsideResolution:p,background:x,...g},M)=>{a.extend({MeshTransmissionMaterial:u});const S=m.useRef(null),[C]=m.useState((()=>new o.DiscardMaterial)),b=r.useFBO(p||h),y=r.useFBO(h);let w,k,D;return a.useFrame((a=>{S.current.time=a.clock.getElapsedTime(),n||e||(D=S.current.__r3f.parent,D&&(k=a.gl.toneMapping,w=a.scene.background,a.gl.toneMapping=c.NoToneMapping,x&&(a.scene.background=x),D.material=C,t&&(a.gl.setRenderTarget(b),a.gl.render(a.scene,a.camera),D.material=S.current,D.material.buffer=b.texture,D.material.thickness=d,D.material.side=c.BackSide),a.gl.setRenderTarget(y),a.gl.render(a.scene,a.camera),D.material.thickness=f,D.material.side=i,D.material.buffer=y.texture,a.scene.background=w,a.gl.setRenderTarget(null),D.material=S.current,a.gl.toneMapping=k))})),m.useImperativeHandle(M,(()=>S.current),[]),m.createElement("meshTransmissionMaterial",l.default({args:[v,e],ref:S},g,{buffer:n||y.texture,_transmission:s,transmission:e?s:0,thickness:f,side:i}))}));exports.MeshTransmissionMaterial=f;
@@ -359,7 +359,6 @@ const MeshTransmissionMaterial = /*#__PURE__*/React.forwardRef(({
359
359
 
360
360
  state.gl.setRenderTarget(fboMain);
361
361
  state.gl.render(state.scene, state.camera);
362
- parent.material = ref.current;
363
362
  parent.material.thickness = thickness;
364
363
  parent.material.side = side;
365
364
  parent.material.buffer = fboMain.texture; // Set old state back
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@babel/runtime/helpers/extends"),r=require("three"),t=require("react"),n=require("@react-three/fiber"),a=require("./useFBO.cjs.js");function u(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function i(e){if(e&&e.__esModule)return e;var r=Object.create(null);return e&&Object.keys(e).forEach((function(t){if("default"!==t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}})),r.default=e,Object.freeze(r)}var c=u(e),s=i(r),o=i(t);const l=o.forwardRef((({children:e,width:r,height:t,samples:u=8,renderPriority:i=0,eventPriority:l=0,frames:d=1/0,...m},p)=>{const{size:b,viewport:v}=n.useThree(),y=a.useFBO((r||b.width)*v.dpr,(t||b.height)*v.dpr,{samples:u}),[g]=o.useState((()=>new s.Scene)),h=o.useCallback(((e,r,t)=>{var n,a;let u=null==(n=y.texture)?void 0:n.__r3f.parent;for(;u&&!(u instanceof s.Object3D);)u=u.__r3f.parent;if(!u)return!1;t.raycaster.camera||t.events.compute(e,t,null==(a=t.previousRoot)?void 0:a.getState());const[i]=t.raycaster.intersectObject(u);if(!i)return!1;const c=i.uv;if(!c)return!1;r.raycaster.setFromCamera(r.pointer.set(2*c.x-1,2*c.y-1),r.camera)}),[]);return o.useImperativeHandle(p,(()=>y.texture),[y]),o.createElement(o.Fragment,null,n.createPortal(o.createElement(f,{renderPriority:i,frames:d,fbo:y},e),g,{events:{compute:h,priority:l}}),o.createElement("primitive",c.default({object:y.texture},m)))}));function f({frames:e,renderPriority:r,children:t,fbo:a}){let u=0;return n.useFrame((r=>{(e===1/0||u<e)&&(r.gl.setRenderTarget(a),r.gl.render(r.scene,r.camera),r.gl.setRenderTarget(null),u++)}),r),o.createElement(o.Fragment,null,t)}exports.RenderTexture=l;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@babel/runtime/helpers/extends"),r=require("three"),t=require("react"),n=require("@react-three/fiber"),a=require("./useFBO.cjs.js");function u(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function i(e){if(e&&e.__esModule)return e;var r=Object.create(null);return e&&Object.keys(e).forEach((function(t){if("default"!==t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}})),r.default=e,Object.freeze(r)}var c=u(e),s=i(r),o=i(t);const l=o.forwardRef((({children:e,compute:r,width:t,height:u,samples:i=8,renderPriority:l=0,eventPriority:d=0,frames:m=1/0,...p},b)=>{const{size:v,viewport:y}=n.useThree(),g=a.useFBO((t||v.width)*y.dpr,(u||v.height)*y.dpr,{samples:i}),[h]=o.useState((()=>new s.Scene)),j=o.useCallback(((e,r,t)=>{var n,a;let u=null==(n=g.texture)?void 0:n.__r3f.parent;for(;u&&!(u instanceof s.Object3D);)u=u.__r3f.parent;if(!u)return!1;t.raycaster.camera||t.events.compute(e,t,null==(a=t.previousRoot)?void 0:a.getState());const[i]=t.raycaster.intersectObject(u);if(!i)return!1;const c=i.uv;if(!c)return!1;r.raycaster.setFromCamera(r.pointer.set(2*c.x-1,2*c.y-1),r.camera)}),[]);return o.useImperativeHandle(b,(()=>g.texture),[g]),o.createElement(o.Fragment,null,n.createPortal(o.createElement(f,{renderPriority:l,frames:m,fbo:g},e),h,{events:{compute:r||j,priority:d}}),o.createElement("primitive",c.default({object:g.texture},p)))}));function f({frames:e,renderPriority:r,children:t,fbo:a}){let u=0;return n.useFrame((r=>{(e===1/0||u<e)&&(r.gl.setRenderTarget(a),r.gl.render(r.scene,r.camera),r.gl.setRenderTarget(null),u++)}),r),o.createElement(o.Fragment,null,t)}exports.RenderTexture=l;
@@ -7,5 +7,6 @@ export declare const RenderTexture: React.ForwardRefExoticComponent<Pick<import(
7
7
  renderPriority?: number | undefined;
8
8
  eventPriority?: number | undefined;
9
9
  frames?: number | undefined;
10
+ compute?: ((event: any, state: any, previous: any) => false | undefined) | undefined;
10
11
  children: React.ReactNode;
11
- }, "attach" | "args" | "children" | "key" | "onUpdate" | "rotation" | "matrix" | "dispose" | "type" | "id" | "uuid" | "name" | "matrixAutoUpdate" | "userData" | "updateMatrix" | "toJSON" | "clone" | "copy" | "addEventListener" | "hasEventListener" | "removeEventListener" | "dispatchEvent" | "center" | "source" | "repeat" | "image" | "needsUpdate" | "version" | "offset" | "width" | "height" | "sourceFile" | "mipmaps" | "mapping" | "wrapS" | "wrapT" | "magFilter" | "minFilter" | "anisotropy" | "format" | "internalFormat" | "generateMipmaps" | "premultiplyAlpha" | "flipY" | "unpackAlignment" | "encoding" | "isRenderTargetTexture" | "needsPMREMUpdate" | "isTexture" | "transformUv" | "samples" | "frames" | "renderPriority" | "eventPriority"> & React.RefAttributes<unknown>>;
12
+ }, "attach" | "args" | "children" | "key" | "onUpdate" | "rotation" | "matrix" | "dispose" | "type" | "id" | "uuid" | "name" | "matrixAutoUpdate" | "userData" | "updateMatrix" | "toJSON" | "clone" | "copy" | "addEventListener" | "hasEventListener" | "removeEventListener" | "dispatchEvent" | "center" | "source" | "repeat" | "image" | "needsUpdate" | "version" | "offset" | "width" | "height" | "sourceFile" | "mipmaps" | "mapping" | "wrapS" | "wrapT" | "magFilter" | "minFilter" | "anisotropy" | "format" | "internalFormat" | "generateMipmaps" | "premultiplyAlpha" | "flipY" | "unpackAlignment" | "encoding" | "isRenderTargetTexture" | "needsPMREMUpdate" | "isTexture" | "transformUv" | "compute" | "samples" | "frames" | "renderPriority" | "eventPriority"> & React.RefAttributes<unknown>>;
@@ -6,6 +6,7 @@ import { useFBO } from './useFBO.js';
6
6
 
7
7
  const RenderTexture = /*#__PURE__*/React.forwardRef(({
8
8
  children,
9
+ compute,
9
10
  width,
10
11
  height,
11
12
  samples = 8,
@@ -22,7 +23,7 @@ const RenderTexture = /*#__PURE__*/React.forwardRef(({
22
23
  samples
23
24
  });
24
25
  const [vScene] = React.useState(() => new THREE.Scene());
25
- const compute = React.useCallback((event, state, previous) => {
26
+ const uvCompute = React.useCallback((event, state, previous) => {
26
27
  var _fbo$texture, _previous$previousRoo;
27
28
 
28
29
  // Since this is only a texture it does not have an easy way to obtain the parent, which we
@@ -52,7 +53,7 @@ const RenderTexture = /*#__PURE__*/React.forwardRef(({
52
53
  fbo: fbo
53
54
  }, children), vScene, {
54
55
  events: {
55
- compute,
56
+ compute: compute || uvCompute,
56
57
  priority: eventPriority
57
58
  }
58
59
  }), /*#__PURE__*/React.createElement("primitive", _extends({