@react-three/drei 9.51.20 → 9.51.22
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
|
@@ -1525,6 +1525,20 @@ type MeshTransmissionMaterialProps = JSX.IntrinsicElements['meshPhysicalMaterial
|
|
|
1525
1525
|
distortionScale: number
|
|
1526
1526
|
/* Temporal distortion (speed of movement), default: 0.0 */
|
|
1527
1527
|
temporalDistortion: number
|
|
1528
|
+
/** The scene rendered into a texture (use it to share a texture between materials), default: null */
|
|
1529
|
+
buffer?: THREE.Texture
|
|
1530
|
+
/** transmissionSampler, you can use the threejs transmission sampler texture that is
|
|
1531
|
+
* generated once for all transmissive materials. The upside is that it can be faster if you
|
|
1532
|
+
* use multiple MeshPhysical and Transmission materials, the downside is that transmissive materials
|
|
1533
|
+
* using this can't see other transparent or transmissive objects nor do you have control over the
|
|
1534
|
+
* buffer and its resolution, default: false */
|
|
1535
|
+
transmissionSampler?: boolean
|
|
1536
|
+
/** Resolution of the local buffer, default: undefined (fullscreen) */
|
|
1537
|
+
resolution?: number
|
|
1538
|
+
/** Refraction samples, default: 6 */
|
|
1539
|
+
samples?: number
|
|
1540
|
+
/** Buffer scene background (can be a texture, a cubetexture or a color), default: null */
|
|
1541
|
+
background?: THREE.Texture
|
|
1528
1542
|
}
|
|
1529
1543
|
```
|
|
1530
1544
|
|
|
@@ -1534,7 +1548,37 @@ return (
|
|
|
1534
1548
|
<MeshTransmissionMaterial />
|
|
1535
1549
|
```
|
|
1536
1550
|
|
|
1537
|
-
If each material rendering the scene on its own is too much expensense you can share a buffer texture
|
|
1551
|
+
If each material rendering the scene on its own is too much expensense you can share a buffer texture. Either by enabling `transmissionSampler` which would use the threejs-internal buffer that MeshPhysicalMaterials use. This might be faster, the downside is that no transmissive material can "see" other transparent or transmissive objects.
|
|
1552
|
+
|
|
1553
|
+
```jsx
|
|
1554
|
+
<mesh geometry={torus}>
|
|
1555
|
+
<MeshTransmissionMaterial transmissionSampler />
|
|
1556
|
+
</mesh>
|
|
1557
|
+
<mesh geometry={sphere}>
|
|
1558
|
+
<MeshTransmissionMaterial transmissionSampler />
|
|
1559
|
+
</mesh>
|
|
1560
|
+
```
|
|
1561
|
+
|
|
1562
|
+
Or, by passing a texture to `buffer` manually, for instance using useFBO.
|
|
1563
|
+
|
|
1564
|
+
```jsx
|
|
1565
|
+
const buffer = useFBO()
|
|
1566
|
+
useFrame((state) => {
|
|
1567
|
+
state.gl.setRenderTarget(buffer)
|
|
1568
|
+
state.gl.render(state.scene, state.camera)
|
|
1569
|
+
state.gl.setRenderTarget(null)
|
|
1570
|
+
})
|
|
1571
|
+
return (
|
|
1572
|
+
<>
|
|
1573
|
+
<mesh geometry={torus}>
|
|
1574
|
+
<MeshTransmissionMaterial buffer={buffer.texture} />
|
|
1575
|
+
</mesh>
|
|
1576
|
+
<mesh geometry={sphere}>
|
|
1577
|
+
<MeshTransmissionMaterial buffer={buffer.texture} />
|
|
1578
|
+
</mesh>
|
|
1579
|
+
```
|
|
1580
|
+
|
|
1581
|
+
Or a PerspectiveCamera.
|
|
1538
1582
|
|
|
1539
1583
|
```jsx
|
|
1540
1584
|
<PerspectiveCamera makeDefault fov={75} position={[10, 0, 15]} resolution={1024}>
|
|
@@ -1550,6 +1594,8 @@ If each material rendering the scene on its own is too much expensense you can s
|
|
|
1550
1594
|
)}
|
|
1551
1595
|
```
|
|
1552
1596
|
|
|
1597
|
+
This would mimic the default MeshPhysicalMaterial behaviour, these materials won't "see" one another, but at least they would pick up on everything else, including transmissive or transparent objects.
|
|
1598
|
+
|
|
1553
1599
|
#### PointMaterial
|
|
1554
1600
|
|
|
1555
1601
|
<p>
|
|
@@ -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"),o=require("./useFBO.cjs.js");function r(n){return n&&"object"==typeof n&&"default"in n?n:{default:n}}function i(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)}var s=r(n),l=i(e),c=i(t);class m extends l.MeshPhysicalMaterial{constructor(n=6){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 l.Color("white")},anisotropy:{value:.1},time:{value:0},distortion:{value:0},distortionScale:{value:.5},temporalDistortion:{value:0},buffer:{value:null},resolution:{value:new l.Vector2}},this.onBeforeCompile=e=>{e.uniforms={...e.uniforms,...this.uniforms},e.defines.USE_TRANSMISSION="",e.fragmentShader="\n uniform float chromaticAberration;\n uniform vec2 resolution; \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"+e.fragmentShader,e.fragmentShader=e.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 return texture2D(buffer, fragCoord.xy);\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"),e.fragmentShader=e.fragmentShader.replace("#include <transmission_fragment>",`\n vec2 uv = gl_FragCoord.xy / resolution.xy; \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 u=c.forwardRef((({buffer:n,transmission:e=1,samples:t=10,resolution:r,background:i,...u},f)=>{a.extend({MeshTransmissionMaterial:m});const d=c.useRef(null),{size:v,viewport:h}=a.useThree(),p=o.useFBO(r);let x,g,C,M;return a.useFrame((e=>{d.current.time=e.clock.getElapsedTime(),n||(M=d.current.__r3f.parent,M&&(C=e.gl.toneMapping,g=M.visible,e.gl.toneMapping=l.NoToneMapping,M.visible=!1,e.gl.setRenderTarget(p),x=e.scene.background,i&&(e.scene.background=i),e.gl.render(e.scene,e.camera),e.scene.background=x,e.gl.setRenderTarget(null),M.visible=g,e.gl.toneMapping=C))})),c.useImperativeHandle(f,(()=>d.current),[]),c.createElement("meshTransmissionMaterial",s.default({args:[t],ref:d},u,{buffer:n||p.texture,_transmission:e,transmission:0,resolution:[v.width*h.dpr,v.height*h.dpr]}))}));exports.MeshTransmissionMaterial=u;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var n=require("@babel/runtime/helpers/extends"),e=require("three"),t=require("react"),o=require("@react-three/fiber"),a=require("./useFBO.cjs.js");function r(n){return n&&"object"==typeof n&&"default"in n?n:{default:n}}function i(n){if(n&&n.__esModule)return n;var e=Object.create(null);return n&&Object.keys(n).forEach((function(t){if("default"!==t){var o=Object.getOwnPropertyDescriptor(n,t);Object.defineProperty(e,t,o.get?o:{enumerable:!0,get:function(){return n[t]}})}})),e.default=n,Object.freeze(e)}var s=r(n),l=i(e),c=i(t);class m extends l.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 l.Color("white")},anisotropy:{value:.1},time:{value:0},distortion:{value:0},distortionScale:{value:.5},temporalDistortion:{value:0},buffer:{value:null},resolution:{value:new l.Vector2}},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 vec2 resolution; \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 vec2 uv = gl_FragCoord.xy / resolution.xy; \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 u=c.forwardRef((({buffer:n,transmissionSampler:e=!1,transmission:t=1,samples:r=10,resolution:i,background:u,...f},d)=>{o.extend({MeshTransmissionMaterial:m});const v=c.useRef(null),{size:h,viewport:p}=o.useThree(),x=a.useFBO(i);let g,M,S,C;return o.useFrame((t=>{v.current.time=t.clock.getElapsedTime(),n||e||(C=v.current.__r3f.parent,C&&(S=t.gl.toneMapping,M=C.visible,t.gl.toneMapping=l.NoToneMapping,C.visible=!1,t.gl.setRenderTarget(x),g=t.scene.background,u&&(t.scene.background=u),t.gl.render(t.scene,t.camera),t.scene.background=g,t.gl.setRenderTarget(null),C.visible=M,t.gl.toneMapping=S))})),c.useImperativeHandle(d,(()=>v.current),[]),c.createElement("meshTransmissionMaterial",s.default({args:[r,e],ref:v},f,{buffer:n||x.texture,_transmission:t,transmission:e?t:0,resolution:[h.width*p.dpr,h.height*p.dpr]}))}));exports.MeshTransmissionMaterial=u;
|
|
@@ -10,10 +10,10 @@ declare type MeshTransmissionMaterialType = Omit<JSX.IntrinsicElements['meshPhys
|
|
|
10
10
|
distortion?: number;
|
|
11
11
|
distortionScale: number;
|
|
12
12
|
temporalDistortion: number;
|
|
13
|
+
buffer?: THREE.Texture;
|
|
13
14
|
time?: number;
|
|
14
15
|
resolution?: ReactThreeFiber.Vector2;
|
|
15
|
-
|
|
16
|
-
args?: [samples: number];
|
|
16
|
+
args?: [samples: number, transmissionSampler: boolean];
|
|
17
17
|
};
|
|
18
18
|
declare global {
|
|
19
19
|
namespace JSX {
|
|
@@ -23,8 +23,9 @@ declare global {
|
|
|
23
23
|
}
|
|
24
24
|
}
|
|
25
25
|
export declare const MeshTransmissionMaterial: React.ForwardRefExoticComponent<Pick<Omit<MeshTransmissionMaterialType, "args" | "resolution"> & {
|
|
26
|
+
transmissionSampler?: boolean | undefined;
|
|
26
27
|
resolution?: number | undefined;
|
|
27
28
|
samples?: number | undefined;
|
|
28
29
|
background?: THREE.Texture | undefined;
|
|
29
|
-
}, "visible" | "attach" | "children" | "key" | "onUpdate" | "dispose" | "type" | "id" | "uuid" | "name" | "userData" | "toJSON" | "clone" | "copy" | "addEventListener" | "hasEventListener" | "removeEventListener" | "dispatchEvent" | "color" | "blending" | "map" | "time" | "transparent" | "fog" | "alphaTest" | "alphaToCoverage" | "blendDst" | "blendDstAlpha" | "blendEquation" | "blendEquationAlpha" | "blendSrc" | "blendSrcAlpha" | "clipIntersection" | "clippingPlanes" | "clipShadows" | "colorWrite" | "defines" | "depthFunc" | "depthTest" | "depthWrite" | "stencilWrite" | "stencilFunc" | "stencilRef" | "stencilWriteMask" | "stencilFuncMask" | "stencilFail" | "stencilZFail" | "stencilZPass" | "isMaterial" | "needsUpdate" | "opacity" | "polygonOffset" | "polygonOffsetFactor" | "polygonOffsetUnits" | "precision" | "premultipliedAlpha" | "dithering" | "side" | "shadowSide" | "toneMapped" | "vertexColors" | "version" | "onBeforeCompile" | "customProgramCacheKey" | "setValues" | "background" | "buffer" | "alphaMap" | "wireframe" | "wireframeLinewidth" | "clearcoat" | "clearcoatMap" | "clearcoatRoughness" | "clearcoatRoughnessMap" | "clearcoatNormalScale" | "clearcoatNormalMap" | "reflectivity" | "ior" | "sheen" | "sheenColor" | "sheenColorMap" | "sheenRoughness" | "sheenRoughnessMap" | "transmission" | "transmissionMap" | "thickness" | "thicknessMap" | "attenuationDistance" | "attenuationColor" | "specularIntensity" | "specularColor" | "specularIntensityMap" | "specularColorMap" | "roughness" | "metalness" | "lightMap" | "lightMapIntensity" | "aoMap" | "aoMapIntensity" | "emissive" | "emissiveIntensity" | "emissiveMap" | "bumpMap" | "bumpScale" | "normalMap" | "normalMapType" | "normalScale" | "displacementMap" | "displacementScale" | "displacementBias" | "roughnessMap" | "metalnessMap" | "envMap" | "envMapIntensity" | "wireframeLinecap" | "wireframeLinejoin" | "flatShading" | "isMeshStandardMaterial" | "anisotropy" | "resolution" | "samples" | "distortion" | "chromaticAberration" | "distortionScale" | "temporalDistortion"> & React.RefAttributes<unknown>>;
|
|
30
|
+
}, "visible" | "attach" | "children" | "key" | "onUpdate" | "dispose" | "type" | "id" | "uuid" | "name" | "userData" | "toJSON" | "clone" | "copy" | "addEventListener" | "hasEventListener" | "removeEventListener" | "dispatchEvent" | "color" | "blending" | "map" | "time" | "transparent" | "fog" | "alphaTest" | "alphaToCoverage" | "blendDst" | "blendDstAlpha" | "blendEquation" | "blendEquationAlpha" | "blendSrc" | "blendSrcAlpha" | "clipIntersection" | "clippingPlanes" | "clipShadows" | "colorWrite" | "defines" | "depthFunc" | "depthTest" | "depthWrite" | "stencilWrite" | "stencilFunc" | "stencilRef" | "stencilWriteMask" | "stencilFuncMask" | "stencilFail" | "stencilZFail" | "stencilZPass" | "isMaterial" | "needsUpdate" | "opacity" | "polygonOffset" | "polygonOffsetFactor" | "polygonOffsetUnits" | "precision" | "premultipliedAlpha" | "dithering" | "side" | "shadowSide" | "toneMapped" | "vertexColors" | "version" | "onBeforeCompile" | "customProgramCacheKey" | "setValues" | "background" | "buffer" | "alphaMap" | "wireframe" | "wireframeLinewidth" | "clearcoat" | "clearcoatMap" | "clearcoatRoughness" | "clearcoatRoughnessMap" | "clearcoatNormalScale" | "clearcoatNormalMap" | "reflectivity" | "ior" | "sheen" | "sheenColor" | "sheenColorMap" | "sheenRoughness" | "sheenRoughnessMap" | "transmission" | "transmissionMap" | "thickness" | "thicknessMap" | "attenuationDistance" | "attenuationColor" | "specularIntensity" | "specularColor" | "specularIntensityMap" | "specularColorMap" | "roughness" | "metalness" | "lightMap" | "lightMapIntensity" | "aoMap" | "aoMapIntensity" | "emissive" | "emissiveIntensity" | "emissiveMap" | "bumpMap" | "bumpScale" | "normalMap" | "normalMapType" | "normalScale" | "displacementMap" | "displacementScale" | "displacementBias" | "roughnessMap" | "metalnessMap" | "envMap" | "envMapIntensity" | "wireframeLinecap" | "wireframeLinejoin" | "flatShading" | "isMeshStandardMaterial" | "anisotropy" | "resolution" | "samples" | "distortion" | "chromaticAberration" | "distortionScale" | "temporalDistortion" | "transmissionSampler"> & React.RefAttributes<unknown>>;
|
|
30
31
|
export {};
|
|
@@ -5,13 +5,13 @@ import { extend, useThree, useFrame } from '@react-three/fiber';
|
|
|
5
5
|
import { useFBO } from './useFBO.js';
|
|
6
6
|
|
|
7
7
|
class MeshTransmissionMaterialImpl extends THREE.MeshPhysicalMaterial {
|
|
8
|
-
constructor(samples = 6) {
|
|
8
|
+
constructor(samples = 6, transmissionSampler = false) {
|
|
9
9
|
super();
|
|
10
10
|
this.uniforms = {
|
|
11
11
|
chromaticAberration: {
|
|
12
12
|
value: 0.05
|
|
13
13
|
},
|
|
14
|
-
// Transmission must always be 0
|
|
14
|
+
// Transmission must always be 0, unless transmissionSampler is being used
|
|
15
15
|
transmission: {
|
|
16
16
|
value: 0
|
|
17
17
|
},
|
|
@@ -64,8 +64,11 @@ class MeshTransmissionMaterialImpl extends THREE.MeshPhysicalMaterial {
|
|
|
64
64
|
this.onBeforeCompile = shader => {
|
|
65
65
|
shader.uniforms = { ...shader.uniforms,
|
|
66
66
|
...this.uniforms
|
|
67
|
-
};
|
|
68
|
-
|
|
67
|
+
}; // If the transmission sampler is active inject a flag
|
|
68
|
+
|
|
69
|
+
if (transmissionSampler) shader.defines.USE_SAMPLER = ''; // Otherwise we do use use .transmission and must therefore force USE_TRANSMISSION
|
|
70
|
+
// because threejs won't inject it for us
|
|
71
|
+
else shader.defines.USE_TRANSMISSION = ''; // Head
|
|
69
72
|
|
|
70
73
|
shader.fragmentShader =
|
|
71
74
|
/*glsl*/
|
|
@@ -201,7 +204,16 @@ class MeshTransmissionMaterialImpl extends THREE.MeshPhysicalMaterial {
|
|
|
201
204
|
return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );
|
|
202
205
|
}
|
|
203
206
|
vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {
|
|
204
|
-
|
|
207
|
+
float framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );
|
|
208
|
+
#ifdef USE_SAMPLER
|
|
209
|
+
#ifdef texture2DLodEXT
|
|
210
|
+
return texture2DLodEXT(transmissionSamplerMap, fragCoord.xy, framebufferLod);
|
|
211
|
+
#else
|
|
212
|
+
return texture2D(transmissionSamplerMap, fragCoord.xy, framebufferLod);
|
|
213
|
+
#endif
|
|
214
|
+
#else
|
|
215
|
+
return texture2D(buffer, fragCoord.xy);
|
|
216
|
+
#endif
|
|
205
217
|
}
|
|
206
218
|
vec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {
|
|
207
219
|
if ( isinf( attenuationDistance ) ) {
|
|
@@ -298,6 +310,7 @@ class MeshTransmissionMaterialImpl extends THREE.MeshPhysicalMaterial {
|
|
|
298
310
|
|
|
299
311
|
const MeshTransmissionMaterial = /*#__PURE__*/React.forwardRef(({
|
|
300
312
|
buffer,
|
|
313
|
+
transmissionSampler = false,
|
|
301
314
|
transmission = 1,
|
|
302
315
|
samples = 10,
|
|
303
316
|
resolution,
|
|
@@ -320,7 +333,7 @@ const MeshTransmissionMaterial = /*#__PURE__*/React.forwardRef(({
|
|
|
320
333
|
useFrame(state => {
|
|
321
334
|
ref.current.time = state.clock.getElapsedTime();
|
|
322
335
|
|
|
323
|
-
if (!buffer) {
|
|
336
|
+
if (!buffer && !transmissionSampler) {
|
|
324
337
|
parent = ref.current.__r3f.parent;
|
|
325
338
|
|
|
326
339
|
if (parent) {
|
|
@@ -351,15 +364,16 @@ const MeshTransmissionMaterial = /*#__PURE__*/React.forwardRef(({
|
|
|
351
364
|
React.useImperativeHandle(fref, () => ref.current, []);
|
|
352
365
|
return /*#__PURE__*/React.createElement("meshTransmissionMaterial", _extends({
|
|
353
366
|
// Samples must re-compile the shader so we memoize it
|
|
354
|
-
args: [samples],
|
|
367
|
+
args: [samples, transmissionSampler],
|
|
355
368
|
ref: ref
|
|
356
369
|
}, props, {
|
|
357
370
|
buffer: buffer || fbo.texture // @ts-ignore
|
|
358
371
|
,
|
|
359
372
|
_transmission: transmission // In order for this to not incur extra cost "transmission" must be set to 0 and treated as a reserved prop.
|
|
360
373
|
// This is because THREE.WebGLRenderer will check for transmission > 0 and execute extra renders.
|
|
374
|
+
// The exception is when transmissionSampler is set, in which case we are using three's built in sampler.
|
|
361
375
|
,
|
|
362
|
-
transmission: 0,
|
|
376
|
+
transmission: transmissionSampler ? transmission : 0,
|
|
363
377
|
resolution: [size.width * viewport.dpr, size.height * viewport.dpr]
|
|
364
378
|
}));
|
|
365
379
|
});
|