@react-three/drei 9.51.8 → 9.51.10

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
@@ -1480,30 +1480,24 @@ return (
1480
1480
  <a href="https://codesandbox.io/s/hmgdjq"><img width="20%" src="https://codesandbox.io/api/v1/sandboxes/hmgdjq/screenshot.png" alt="Demo"/></a>
1481
1481
  </p>
1482
1482
 
1483
- A more convincing transmission shader with RGB shift (based on THREE.MeshPhysicalMaterial). This material can be expensive as it causes an additional render pass of the scene. Low samples and low resolution will make it faster. It will temporarily make the mesh that uses it invisible for that pass, this is better for performance and also improves visuals. If you have other objects that you don't want to see reflected in the material just add them to the parent mesh as children.
1483
+ An improved THREE.MeshPhysicalMaterial. It acts like a normal PhysicalMaterial in terms of transmission support, thickness, ior, roughness, etc., but has chromatic aberration, noise-based roughness blur, (primitive) anisotropy support, and unlike the original it can "see" other transmissive or transparent objects which leads to improved visuals.
1484
+
1485
+ Keep in mind that it can be expensive as it causes an additional render pass of the scene, minus the host mesh which gets removed from the render-stack temporarily. If you have other objects that you don't want to see reflected in the material just add them to the parent mesh as children. Low samples and low resolution will make it faster.
1486
+
1487
+ If you use roughness consider using a tiny resolution, for instance 32x32 pixels, it will still look good but perform much faster.
1484
1488
 
1485
1489
  ```tsx
1486
- type MeshTransmissionMaterialProps = {
1487
- /** Refraction shift, default: 0 */
1488
- refraction?: number
1489
- /** White noise roughness, default: 0 */
1490
- roughness?: number
1491
- /** RGB color shift, default: 0.3 */
1492
- rgbShift?: number
1493
- /** Noise, default: 0.03 */
1494
- noise?: number
1495
- /** Color saturation, default: 1 */
1496
- saturation?: number
1497
- /** Color contrast, default: 1 */
1498
- contrast?: number
1499
- /** Resolution of the local buffer, default: 1024 */
1500
- resolution?: number
1501
- /** Refraction samples, default: 10 */
1502
- samples?: number
1503
- /** Buffer scene background (can be a texture, a cubetexture or a color), default: null */
1504
- background?: THREE.Texture
1505
- /** The scene rendered into a texture (use it to share a texture between materials), default: null */
1506
- buffer?: THREE.Texture
1490
+ type MeshTransmissionMaterialProps = JSX.IntrinsicElements['meshPhysicalMaterial'] & {
1491
+ /* Chromatic aberration, default: 0.03 */
1492
+ chromaticAberration?: number
1493
+ /* Anisotropy, default: 0.1 */
1494
+ anisotropy?: number
1495
+ /* Distortion, default: 0 */
1496
+ distortion?: number
1497
+ /* Distortion scale, default: 0.5 */
1498
+ distortionScale?: number
1499
+ /* Temporal distortion, default: 0.5 */
1500
+ temporalDistortion?: number
1507
1501
  }
1508
1502
  ```
1509
1503
 
@@ -1513,7 +1507,7 @@ return (
1513
1507
  <MeshTransmissionMaterial />
1514
1508
  ```
1515
1509
 
1516
- If each material rendering the scene on its own is too much expensense you can share the buffer, for instance using drei/PerspectiveCamera.
1510
+ If each material rendering the scene on its own is too much expensense you can share a buffer texture, for instance using drei/PerspectiveCamera. This would mimic the default THREE.MeshPhysicalMaterial behaviour, the upside is that it's faster if you have multiple materials, the downside is that one transmissive material now can't "see" the other.
1517
1511
 
1518
1512
  ```jsx
1519
1513
  <PerspectiveCamera makeDefault fov={75} position={[10, 0, 15]} resolution={1024}>
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),r=require("@react-three/fiber"),t=require("three"),n=require("./OrthographicCamera.cjs.js"),u=require("./useCamera.cjs.js");function a(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)}require("@babel/runtime/helpers/extends"),require("react-merge-refs"),require("./useFBO.cjs.js");var o=a(e);const c=o.createContext({}),i=2*Math.PI,s=new t.Object3D,l=new t.Matrix4,[p,d]=[new t.Quaternion,new t.Quaternion],f=new t.Vector3,h=new t.Vector3;exports.GizmoHelper=({alignment:e="bottom-right",margin:a=[80,80],renderPriority:m=0,autoClear:g=!0,onUpdate:b,onTarget:y,children:w})=>{const j=r.useThree((({size:e})=>e)),q=r.useThree((({camera:e})=>e)),v=r.useThree((({controls:e})=>e)),C=r.useThree((({gl:e})=>e)),O=r.useThree((({scene:e})=>e)),x=r.useThree((({invalidate:e})=>e)),T=o.useRef(),k=o.useRef(),P=o.useRef(null),[R]=o.useState((()=>new t.Scene)),E=o.useRef(!1),M=o.useRef(0),z=o.useRef(new t.Vector3(0,0,0)),Q=o.useRef(new t.Vector3(0,0,0));o.useEffect((()=>{Q.current.copy(q.up)}),[q]);const S=o.useCallback((e=>{E.current=!0,(v||y)&&(z.current=(null==v?void 0:v.target)||(null==y?void 0:y())),M.current=q.position.distanceTo(f),p.copy(q.quaternion),h.copy(e).multiplyScalar(M.current).add(f),s.lookAt(h),d.copy(s.quaternion),x()}),[v,q,y,x]);o.useEffect((()=>(O.background&&(T.current=O.background,O.background=null,R.background=T.current),()=>{T.current&&(O.background=T.current)})),[]),r.useFrame(((e,r)=>{if(P.current&&k.current){var t;if(E.current)if(p.angleTo(d)<.01)E.current=!1,"minPolarAngle"in v&&q.up.copy(Q.current);else{const e=r*i;p.rotateTowards(d,e),q.position.set(0,0,1).applyQuaternion(p).multiplyScalar(M.current).add(z.current),q.up.set(0,1,0).applyQuaternion(p).normalize(),q.quaternion.copy(p),b?b():v&&v.update(),x()}l.copy(q.matrix).invert(),null==(t=k.current)||t.quaternion.setFromRotationMatrix(l),g&&(C.autoClear=!1),C.clearDepth(),C.render(R,P.current)}}),m);const V=u.useCamera(P),W=o.useMemo((()=>({tweenCamera:S,raycast:V})),[S]),[_,D]=a,F=e.endsWith("-center")?0:e.endsWith("-left")?-j.width/2+_:j.width/2-_,A=e.startsWith("center-")?0:e.startsWith("top-")?j.height/2-D:-j.height/2+D;return r.createPortal(o.createElement(c.Provider,{value:W},o.createElement(n.OrthographicCamera,{ref:P,position:[0,0,200]}),o.createElement("group",{ref:k,position:[F,A,0]},w)),R)},exports.useGizmoContext=()=>o.useContext(c);
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),r=require("@react-three/fiber"),t=require("three"),n=require("./OrthographicCamera.cjs.js"),o=require("./Hud.cjs.js");function u(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)}require("@babel/runtime/helpers/extends"),require("react-merge-refs"),require("./useFBO.cjs.js");var i=u(e);const a=i.createContext({}),c=2*Math.PI,s=new t.Object3D,l=new t.Matrix4,[p,d]=[new t.Quaternion,new t.Quaternion],f=new t.Vector3,h=new t.Vector3;exports.GizmoHelper=({alignment:e="bottom-right",margin:u=[80,80],renderPriority:m=1,onUpdate:y,onTarget:g,children:b})=>{const j=r.useThree((e=>e.size)),w=r.useThree((e=>e.camera)),q=r.useThree((e=>e.controls)),v=r.useThree((e=>e.invalidate)),O=i.useRef(),x=i.useRef(null),P=i.useRef(!1),T=i.useRef(0),C=i.useRef(new t.Vector3(0,0,0)),R=i.useRef(new t.Vector3(0,0,0));i.useEffect((()=>{R.current.copy(w.up)}),[w]);const E=i.useCallback((e=>{P.current=!0,(q||g)&&(C.current=(null==q?void 0:q.target)||(null==g?void 0:g())),T.current=w.position.distanceTo(f),p.copy(w.quaternion),h.copy(e).multiplyScalar(T.current).add(f),s.lookAt(h),d.copy(s.quaternion),v()}),[q,w,g,v]);r.useFrame(((e,r)=>{if(x.current&&O.current){var t;if(P.current)if(p.angleTo(d)<.01)P.current=!1,"minPolarAngle"in q&&w.up.copy(R.current);else{const e=r*c;p.rotateTowards(d,e),w.position.set(0,0,1).applyQuaternion(p).multiplyScalar(T.current).add(C.current),w.up.set(0,1,0).applyQuaternion(p).normalize(),w.quaternion.copy(p),y?y():q&&q.update(),v()}l.copy(w.matrix).invert(),null==(t=O.current)||t.quaternion.setFromRotationMatrix(l)}}));const M=i.useMemo((()=>({tweenCamera:E})),[E]),[z,k]=u,Q=e.endsWith("-center")?0:e.endsWith("-left")?-j.width/2+z:j.width/2-z,V=e.startsWith("center-")?0:e.startsWith("top-")?j.height/2-k:-j.height/2+k;return i.createElement(o.Hud,{renderPriority:m},i.createElement(a.Provider,{value:M},i.createElement(n.OrthographicCamera,{makeDefault:!0,ref:x,position:[0,0,200]}),i.createElement("group",{ref:O,position:[Q,V,0]},b)))},exports.useGizmoContext=()=>i.useContext(a);
@@ -1,7 +1,6 @@
1
- import { Intersection, Raycaster, Vector3 } from 'three';
1
+ import { Vector3 } from 'three';
2
2
  declare type GizmoHelperContext = {
3
3
  tweenCamera: (direction: Vector3) => void;
4
- raycast: (raycaster: Raycaster, intersects: Intersection[]) => void;
5
4
  };
6
5
  export declare const useGizmoContext: () => GizmoHelperContext;
7
6
  export declare type GizmoHelperProps = JSX.IntrinsicElements['group'] & {
@@ -12,5 +11,5 @@ export declare type GizmoHelperProps = JSX.IntrinsicElements['group'] & {
12
11
  onUpdate?: () => void;
13
12
  onTarget?: () => Vector3;
14
13
  };
15
- export declare const GizmoHelper: ({ alignment, margin, renderPriority, autoClear, onUpdate, onTarget, children: GizmoHelperComponent, }: GizmoHelperProps) => any;
14
+ export declare const GizmoHelper: ({ alignment, margin, renderPriority, onUpdate, onTarget, children, }: GizmoHelperProps) => any;
16
15
  export {};
@@ -1,8 +1,8 @@
1
1
  import * as React from 'react';
2
- import { useThree, useFrame, createPortal } from '@react-three/fiber';
3
- import { Object3D, Matrix4, Quaternion, Vector3, Scene } from 'three';
2
+ import { useThree, useFrame } from '@react-three/fiber';
3
+ import { Object3D, Matrix4, Quaternion, Vector3 } from 'three';
4
4
  import { OrthographicCamera } from './OrthographicCamera.js';
5
- import { useCamera } from './useCamera.js';
5
+ import { Hud } from './Hud.js';
6
6
 
7
7
  const Context = /*#__PURE__*/React.createContext({});
8
8
  const useGizmoContext = () => {
@@ -23,35 +23,18 @@ const isOrbitControls = controls => {
23
23
  const GizmoHelper = ({
24
24
  alignment = 'bottom-right',
25
25
  margin = [80, 80],
26
- renderPriority = 0,
27
- autoClear = true,
26
+ renderPriority = 1,
28
27
  onUpdate,
29
28
  onTarget,
30
- children: GizmoHelperComponent
29
+ children
31
30
  }) => {
32
- const size = useThree(({
33
- size
34
- }) => size);
35
- const mainCamera = useThree(({
36
- camera
37
- }) => camera); // @ts-expect-error new in @react-three/fiber@7.0.5
31
+ const size = useThree(state => state.size);
32
+ const mainCamera = useThree(state => state.camera); // @ts-ignore
38
33
 
39
- const defaultControls = useThree(({
40
- controls
41
- }) => controls);
42
- const gl = useThree(({
43
- gl
44
- }) => gl);
45
- const scene = useThree(({
46
- scene
47
- }) => scene);
48
- const invalidate = useThree(({
49
- invalidate
50
- }) => invalidate);
51
- const backgroundRef = React.useRef();
34
+ const defaultControls = useThree(state => state.controls);
35
+ const invalidate = useThree(state => state.invalidate);
52
36
  const gizmoRef = React.useRef();
53
37
  const virtualCam = React.useRef(null);
54
- const [virtualScene] = React.useState(() => new Scene());
55
38
  const animating = React.useRef(false);
56
39
  const radius = React.useRef(0);
57
40
  const focusPoint = React.useRef(new Vector3(0, 0, 0));
@@ -71,19 +54,6 @@ const GizmoHelper = ({
71
54
  q2.copy(dummy.quaternion);
72
55
  invalidate();
73
56
  }, [defaultControls, mainCamera, onTarget, invalidate]);
74
- React.useEffect(() => {
75
- if (scene.background) {
76
- //Interchange the actual scene background with the virtual scene
77
- backgroundRef.current = scene.background;
78
- scene.background = null;
79
- virtualScene.background = backgroundRef.current;
80
- }
81
-
82
- return () => {
83
- // reset on unmount
84
- if (backgroundRef.current) scene.background = backgroundRef.current;
85
- };
86
- }, []);
87
57
  useFrame((_, delta) => {
88
58
  if (virtualCam.current && gizmoRef.current) {
89
59
  var _gizmoRef$current;
@@ -113,31 +83,28 @@ const GizmoHelper = ({
113
83
 
114
84
 
115
85
  matrix.copy(mainCamera.matrix).invert();
116
- (_gizmoRef$current = gizmoRef.current) == null ? void 0 : _gizmoRef$current.quaternion.setFromRotationMatrix(matrix); // Render virtual camera
117
-
118
- if (autoClear) gl.autoClear = false;
119
- gl.clearDepth();
120
- gl.render(virtualScene, virtualCam.current);
86
+ (_gizmoRef$current = gizmoRef.current) == null ? void 0 : _gizmoRef$current.quaternion.setFromRotationMatrix(matrix);
121
87
  }
122
- }, renderPriority);
123
- const raycast = useCamera(virtualCam);
88
+ });
124
89
  const gizmoHelperContext = React.useMemo(() => ({
125
- tweenCamera,
126
- raycast
90
+ tweenCamera
127
91
  }), [tweenCamera]); // Position gizmo component within scene
128
92
 
129
93
  const [marginX, marginY] = margin;
130
94
  const x = alignment.endsWith('-center') ? 0 : alignment.endsWith('-left') ? -size.width / 2 + marginX : size.width / 2 - marginX;
131
95
  const y = alignment.startsWith('center-') ? 0 : alignment.startsWith('top-') ? size.height / 2 - marginY : -size.height / 2 + marginY;
132
- return createPortal( /*#__PURE__*/React.createElement(Context.Provider, {
96
+ return /*#__PURE__*/React.createElement(Hud, {
97
+ renderPriority: renderPriority
98
+ }, /*#__PURE__*/React.createElement(Context.Provider, {
133
99
  value: gizmoHelperContext
134
100
  }, /*#__PURE__*/React.createElement(OrthographicCamera, {
101
+ makeDefault: true,
135
102
  ref: virtualCam,
136
103
  position: [0, 0, 200]
137
104
  }), /*#__PURE__*/React.createElement("group", {
138
105
  ref: gizmoRef,
139
106
  position: [x, y, 0]
140
- }, GizmoHelperComponent)), virtualScene);
107
+ }, children)));
141
108
  };
142
109
 
143
110
  export { GizmoHelper, useGizmoContext };
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@babel/runtime/helpers/extends"),t=require("react"),r=require("@react-three/fiber"),o=require("./GizmoHelper.cjs.js"),a=require("three");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function i(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,o.get?o:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}require("./OrthographicCamera.cjs.js"),require("react-merge-refs"),require("./useFBO.cjs.js"),require("./useCamera.cjs.js");var s=n(e),c=i(t);const l="#f0f0f0",u="#999",p="black",m="black",f=["Right","Left","Top","Bottom","Front","Back"],h=e=>new a.Vector3(...e).multiplyScalar(.38),y=[[1,1,1],[1,1,-1],[1,-1,1],[1,-1,-1],[-1,1,1],[-1,1,-1],[-1,-1,1],[-1,-1,-1]].map(h),d=[.25,.25,.25],g=[[1,1,0],[1,0,1],[1,0,-1],[1,-1,0],[0,1,1],[0,1,-1],[0,-1,1],[0,-1,-1],[-1,1,0],[-1,0,1],[-1,0,-1],[-1,-1,0]].map(h),b=g.map((e=>e.toArray().map((e=>0==e?.5:.25)))),x=({hover:e,index:t,font:o="20px Inter var, Arial, sans-serif",faces:n=f,color:i=l,hoverColor:s=u,textColor:h=p,strokeColor:y=m,opacity:d=1})=>{const g=r.useThree((e=>e.gl)),b=c.useMemo((()=>{const e=document.createElement("canvas");e.width=128,e.height=128;const r=e.getContext("2d");return r.fillStyle=i,r.fillRect(0,0,e.width,e.height),r.strokeStyle=y,r.strokeRect(0,0,e.width,e.height),r.font=o,r.textAlign="center",r.fillStyle=h,r.fillText(n[t].toUpperCase(),64,76),new a.CanvasTexture(e)}),[t,n,o,i,h,y]);return c.createElement("meshLambertMaterial",{map:b,"map-encoding":g.outputEncoding,"map-anisotropy":g.capabilities.getMaxAnisotropy()||1,attach:`material-${t}`,color:e?s:"white",transparent:!0,opacity:d})},C=e=>{const{tweenCamera:t,raycast:r}=o.useGizmoContext(),[a,n]=c.useState(null);return c.createElement("mesh",{raycast:r,onPointerOut:e=>{e.stopPropagation(),n(null)},onPointerMove:e=>{e.stopPropagation(),n(Math.floor(e.faceIndex/2))},onClick:e.onClick||(e=>{e.stopPropagation(),t(e.face.normal)})},[...Array(6)].map(((t,r)=>c.createElement(x,s.default({key:r,index:r,hover:a===r},e)))),c.createElement("boxGeometry",null))},E=({onClick:e,dimensions:t,position:r,hoverColor:a=u})=>{const{tweenCamera:n,raycast:i}=o.useGizmoContext(),[s,l]=c.useState(!1);return c.createElement("mesh",{scale:1.01,position:r,raycast:i,onPointerOver:e=>{e.stopPropagation(),l(!0)},onPointerOut:e=>{e.stopPropagation(),l(!1)},onClick:e||(e=>{e.stopPropagation(),n(r)})},c.createElement("meshBasicMaterial",{color:s?a:"white",transparent:!0,opacity:.6,visible:s}),c.createElement("boxGeometry",{args:t}))};exports.GizmoViewcube=e=>c.createElement("group",{scale:[60,60,60]},c.createElement(C,e),g.map(((t,r)=>c.createElement(E,s.default({key:r,position:t,dimensions:b[r]},e)))),y.map(((t,r)=>c.createElement(E,s.default({key:r,position:t,dimensions:d},e)))),c.createElement("ambientLight",{intensity:.5}),c.createElement("pointLight",{position:[10,10,10],intensity:.5}));
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@babel/runtime/helpers/extends"),t=require("react"),r=require("@react-three/fiber"),o=require("./GizmoHelper.cjs.js"),n=require("three");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function i(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,o.get?o:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}require("./OrthographicCamera.cjs.js"),require("react-merge-refs"),require("./useFBO.cjs.js"),require("./Hud.cjs.js");var l=a(e),s=i(t);const c="#f0f0f0",u="#999",p="black",m="black",f=["Right","Left","Top","Bottom","Front","Back"],h=e=>new n.Vector3(...e).multiplyScalar(.38),d=[[1,1,1],[1,1,-1],[1,-1,1],[1,-1,-1],[-1,1,1],[-1,1,-1],[-1,-1,1],[-1,-1,-1]].map(h),g=[.25,.25,.25],y=[[1,1,0],[1,0,1],[1,0,-1],[1,-1,0],[0,1,1],[0,1,-1],[0,-1,1],[0,-1,-1],[-1,1,0],[-1,0,1],[-1,0,-1],[-1,-1,0]].map(h),b=y.map((e=>e.toArray().map((e=>0==e?.5:.25)))),x=({hover:e,index:t,font:o="20px Inter var, Arial, sans-serif",faces:a=f,color:i=c,hoverColor:l=u,textColor:h=p,strokeColor:d=m,opacity:g=1})=>{const y=r.useThree((e=>e.gl)),b=s.useMemo((()=>{const e=document.createElement("canvas");e.width=128,e.height=128;const r=e.getContext("2d");return r.fillStyle=i,r.fillRect(0,0,e.width,e.height),r.strokeStyle=d,r.strokeRect(0,0,e.width,e.height),r.font=o,r.textAlign="center",r.fillStyle=h,r.fillText(a[t].toUpperCase(),64,76),new n.CanvasTexture(e)}),[t,a,o,i,h,d]);return s.createElement("meshLambertMaterial",{map:b,"map-encoding":y.outputEncoding,"map-anisotropy":y.capabilities.getMaxAnisotropy()||1,attach:`material-${t}`,color:e?l:"white",transparent:!0,opacity:g})},C=e=>{const{tweenCamera:t}=o.useGizmoContext(),[r,n]=s.useState(null);return s.createElement("mesh",{onPointerOut:e=>{e.stopPropagation(),n(null)},onPointerMove:e=>{e.stopPropagation(),n(Math.floor(e.faceIndex/2))},onClick:e.onClick||(e=>{e.stopPropagation(),t(e.face.normal)})},[...Array(6)].map(((t,o)=>s.createElement(x,l.default({key:o,index:o,hover:r===o},e)))),s.createElement("boxGeometry",null))},E=({onClick:e,dimensions:t,position:r,hoverColor:n=u})=>{const{tweenCamera:a}=o.useGizmoContext(),[i,l]=s.useState(!1);return s.createElement("mesh",{scale:1.01,position:r,onPointerOver:e=>{e.stopPropagation(),l(!0)},onPointerOut:e=>{e.stopPropagation(),l(!1)},onClick:e||(e=>{e.stopPropagation(),a(r)})},s.createElement("meshBasicMaterial",{color:i?n:"white",transparent:!0,opacity:.6,visible:i}),s.createElement("boxGeometry",{args:t}))};exports.GizmoViewcube=e=>s.createElement("group",{scale:[60,60,60]},s.createElement(C,e),y.map(((t,r)=>s.createElement(E,l.default({key:r,position:t,dimensions:b[r]},e)))),d.map(((t,r)=>s.createElement(E,l.default({key:r,position:t,dimensions:g},e)))),s.createElement("ambientLight",{intensity:.5}),s.createElement("pointLight",{position:[10,10,10],intensity:.5}));
@@ -59,8 +59,7 @@ const FaceMaterial = ({
59
59
 
60
60
  const FaceCube = props => {
61
61
  const {
62
- tweenCamera,
63
- raycast
62
+ tweenCamera
64
63
  } = useGizmoContext();
65
64
  const [hover, setHover] = React.useState(null);
66
65
 
@@ -80,7 +79,6 @@ const FaceCube = props => {
80
79
  };
81
80
 
82
81
  return /*#__PURE__*/React.createElement("mesh", {
83
- raycast: raycast,
84
82
  onPointerOut: handlePointerOut,
85
83
  onPointerMove: handlePointerMove,
86
84
  onClick: props.onClick || handleClick
@@ -98,8 +96,7 @@ const EdgeCube = ({
98
96
  hoverColor = colors.hover
99
97
  }) => {
100
98
  const {
101
- tweenCamera,
102
- raycast
99
+ tweenCamera
103
100
  } = useGizmoContext();
104
101
  const [hover, setHover] = React.useState(false);
105
102
 
@@ -121,7 +118,6 @@ const EdgeCube = ({
121
118
  return /*#__PURE__*/React.createElement("mesh", {
122
119
  scale: 1.01,
123
120
  position: position,
124
- raycast: raycast,
125
121
  onPointerOver: handlePointerOver,
126
122
  onPointerOut: handlePointerOut,
127
123
  onClick: onClick || handleClick
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@babel/runtime/helpers/extends"),t=require("react"),r=require("@react-three/fiber"),a=require("three"),o=require("./GizmoHelper.cjs.js");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function l(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var a=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,a.get?a:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}require("./OrthographicCamera.cjs.js"),require("react-merge-refs"),require("./useFBO.cjs.js"),require("./useCamera.cjs.js");var i=n(e),c=l(t);function s({scale:e=[.8,.05,.05],color:t,rotation:r}){return c.createElement("group",{rotation:r},c.createElement("mesh",{position:[.4,0,0]},c.createElement("boxGeometry",{args:e}),c.createElement("meshBasicMaterial",{color:t,toneMapped:!1})))}function u({onClick:e,font:t,disabled:o,arcStyle:n,label:l,labelColor:s,axisHeadScale:u=1,...p}){const f=r.useThree((e=>e.gl)),m=c.useMemo((()=>{const e=document.createElement("canvas");e.width=64,e.height=64;const r=e.getContext("2d");return r.beginPath(),r.arc(32,32,16,0,2*Math.PI),r.closePath(),r.fillStyle=n,r.fill(),l&&(r.font=t,r.textAlign="center",r.fillStyle=s,r.fillText(l,32,41)),new a.CanvasTexture(e)}),[n,l,s,t]),[d,b]=c.useState(!1),g=(l?1:.75)*(d?1.2:1)*u;return c.createElement("sprite",i.default({scale:g,onPointerOver:o?void 0:e=>{e.stopPropagation(),b(!0)},onPointerOut:o?void 0:e||(e=>{e.stopPropagation(),b(!1)})},p),c.createElement("spriteMaterial",{map:m,"map-encoding":f.outputEncoding,"map-anisotropy":f.capabilities.getMaxAnisotropy()||1,alphaTest:.3,opacity:l?1:.75,toneMapped:!1}))}exports.GizmoViewport=({hideNegativeAxes:e,hideAxisHeads:t,disabled:r,font:a="18px Inter var, Arial, sans-serif",axisColors:n=["#ff2060","#20df80","#2080ff"],axisHeadScale:l=1,axisScale:p,labels:f=["X","Y","Z"],labelColor:m="#000",onClick:d,...b})=>{const[g,E,h]=n,{tweenCamera:y,raycast:x}=o.useGizmoContext(),j={font:a,disabled:r,labelColor:m,raycast:x,onClick:d,axisHeadScale:l,onPointerDown:r?void 0:e=>{y(e.object.position),e.stopPropagation()}};return c.createElement("group",i.default({scale:40},b),c.createElement(s,{color:g,rotation:[0,0,0],scale:p}),c.createElement(s,{color:E,rotation:[0,0,Math.PI/2],scale:p}),c.createElement(s,{color:h,rotation:[0,-Math.PI/2,0],scale:p}),!t&&c.createElement(c.Fragment,null,c.createElement(u,i.default({arcStyle:g,position:[1,0,0],label:f[0]},j)),c.createElement(u,i.default({arcStyle:E,position:[0,1,0],label:f[1]},j)),c.createElement(u,i.default({arcStyle:h,position:[0,0,1],label:f[2]},j)),!e&&c.createElement(c.Fragment,null,c.createElement(u,i.default({arcStyle:g,position:[-1,0,0]},j)),c.createElement(u,i.default({arcStyle:E,position:[0,-1,0]},j)),c.createElement(u,i.default({arcStyle:h,position:[0,0,-1]},j)))),c.createElement("ambientLight",{intensity:.5}),c.createElement("pointLight",{position:[10,10,10],intensity:.5}))};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@babel/runtime/helpers/extends"),t=require("react"),r=require("@react-three/fiber"),a=require("three"),o=require("./GizmoHelper.cjs.js");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function l(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var a=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,a.get?a:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}require("./OrthographicCamera.cjs.js"),require("react-merge-refs"),require("./useFBO.cjs.js"),require("./Hud.cjs.js");var i=n(e),c=l(t);function s({scale:e=[.8,.05,.05],color:t,rotation:r}){return c.createElement("group",{rotation:r},c.createElement("mesh",{position:[.4,0,0]},c.createElement("boxGeometry",{args:e}),c.createElement("meshBasicMaterial",{color:t,toneMapped:!1})))}function u({onClick:e,font:t,disabled:o,arcStyle:n,label:l,labelColor:s,axisHeadScale:u=1,...p}){const d=r.useThree((e=>e.gl)),f=c.useMemo((()=>{const e=document.createElement("canvas");e.width=64,e.height=64;const r=e.getContext("2d");return r.beginPath(),r.arc(32,32,16,0,2*Math.PI),r.closePath(),r.fillStyle=n,r.fill(),l&&(r.font=t,r.textAlign="center",r.fillStyle=s,r.fillText(l,32,41)),new a.CanvasTexture(e)}),[n,l,s,t]),[m,b]=c.useState(!1),g=(l?1:.75)*(m?1.2:1)*u;return c.createElement("sprite",i.default({scale:g,onPointerOver:o?void 0:e=>{e.stopPropagation(),b(!0)},onPointerOut:o?void 0:e||(e=>{e.stopPropagation(),b(!1)})},p),c.createElement("spriteMaterial",{map:f,"map-encoding":d.outputEncoding,"map-anisotropy":d.capabilities.getMaxAnisotropy()||1,alphaTest:.3,opacity:l?1:.75,toneMapped:!1}))}exports.GizmoViewport=({hideNegativeAxes:e,hideAxisHeads:t,disabled:r,font:a="18px Inter var, Arial, sans-serif",axisColors:n=["#ff2060","#20df80","#2080ff"],axisHeadScale:l=1,axisScale:p,labels:d=["X","Y","Z"],labelColor:f="#000",onClick:m,...b})=>{const[g,E,h]=n,{tweenCamera:y}=o.useGizmoContext(),x={font:a,disabled:r,labelColor:f,onClick:m,axisHeadScale:l,onPointerDown:r?void 0:e=>{y(e.object.position),e.stopPropagation()}};return c.createElement("group",i.default({scale:40},b),c.createElement(s,{color:g,rotation:[0,0,0],scale:p}),c.createElement(s,{color:E,rotation:[0,0,Math.PI/2],scale:p}),c.createElement(s,{color:h,rotation:[0,-Math.PI/2,0],scale:p}),!t&&c.createElement(c.Fragment,null,c.createElement(u,i.default({arcStyle:g,position:[1,0,0],label:d[0]},x)),c.createElement(u,i.default({arcStyle:E,position:[0,1,0],label:d[1]},x)),c.createElement(u,i.default({arcStyle:h,position:[0,0,1],label:d[2]},x)),!e&&c.createElement(c.Fragment,null,c.createElement(u,i.default({arcStyle:g,position:[-1,0,0]},x)),c.createElement(u,i.default({arcStyle:E,position:[0,-1,0]},x)),c.createElement(u,i.default({arcStyle:h,position:[0,0,-1]},x)))),c.createElement("ambientLight",{intensity:.5}),c.createElement("pointLight",{position:[10,10,10],intensity:.5}))};
@@ -94,14 +94,12 @@ const GizmoViewport = ({
94
94
  }) => {
95
95
  const [colorX, colorY, colorZ] = axisColors;
96
96
  const {
97
- tweenCamera,
98
- raycast
97
+ tweenCamera
99
98
  } = useGizmoContext();
100
99
  const axisHeadProps = {
101
100
  font,
102
101
  disabled,
103
102
  labelColor,
104
- raycast,
105
103
  onClick,
106
104
  axisHeadScale,
107
105
  onPointerDown: !disabled ? e => {
package/core/Hud.cjs.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("three"),r=require("react"),t=require("@react-three/fiber");function n(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 a=n(e),u=n(r);function c({defaultScene:e,defaultCamera:r,renderPriority:n=1}){const{gl:a,scene:c,camera:l}=t.useThree();return t.useFrame((()=>{1===n&&(a.autoClear=!0,a.render(e,r)),a.autoClear=!1,a.clearDepth(),a.render(c,l)}),n),u.createElement(u.Fragment,null)}exports.Hud=function({children:e,renderPriority:r=1}){const{scene:n,camera:l}=t.useThree(),[i]=u.useState((()=>new a.Scene));return u.createElement(u.Fragment,null,t.createPortal(u.createElement(u.Fragment,null,e,u.createElement(c,{defaultScene:n,defaultCamera:l,renderPriority:r})),i,{events:{priority:r+1}}))};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("three"),r=require("react"),t=require("@react-three/fiber");function n(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 a=n(e),u=n(r);function c({defaultScene:e,defaultCamera:r,renderPriority:n=1}){const{gl:a,scene:c,camera:l}=t.useThree();let o;return t.useFrame((()=>{o=a.autoClear,1===n&&(a.autoClear=!0,a.render(e,r)),a.autoClear=!1,a.clearDepth(),a.render(c,l),a.autoClear=o}),n),u.createElement(u.Fragment,null)}exports.Hud=function({children:e,renderPriority:r=1}){const{scene:n,camera:l}=t.useThree(),[o]=u.useState((()=>new a.Scene));return u.createElement(u.Fragment,null,t.createPortal(u.createElement(u.Fragment,null,e,u.createElement(c,{defaultScene:n,defaultCamera:l,renderPriority:r})),o,{events:{priority:r+1}}))};
package/core/Hud.js CHANGED
@@ -12,7 +12,10 @@ function RenderHud({
12
12
  scene,
13
13
  camera
14
14
  } = useThree();
15
+ let oldCLear;
15
16
  useFrame(() => {
17
+ oldCLear = gl.autoClear;
18
+
16
19
  if (renderPriority === 1) {
17
20
  // Clear scene and render the default scene
18
21
  gl.autoClear = true;
@@ -22,7 +25,9 @@ function RenderHud({
22
25
 
23
26
  gl.autoClear = false;
24
27
  gl.clearDepth();
25
- gl.render(scene, camera);
28
+ gl.render(scene, camera); // Restore default
29
+
30
+ gl.autoClear = oldCLear;
26
31
  }, renderPriority);
27
32
  return /*#__PURE__*/React.createElement(React.Fragment, null);
28
33
  }
@@ -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"),o=require("./useFBO.cjs.js");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function s(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 i=a(e),u=s(r),l=s(t);class f extends u.MeshPhysicalMaterial{constructor({samples:e=5,...r}={}){super(r),this.uniforms={refraction:{value:0},rgbShift:{value:.3},noise:{value:.03},saturation:{value:1},contrast:{value:1},buffer:{value:null},resolution:{value:new u.Vector2}},this.onBeforeCompile=r=>{r.uniforms={...r.uniforms,...this.uniforms},r.fragmentShader="uniform float rgbShift;\n uniform vec2 resolution;\n uniform vec3 refractionColor;\n uniform float refraction;\n uniform float noise;\n uniform float saturation;\n uniform float contrast;\n uniform sampler2D buffer;\n \n vec3 sat(vec3 rgb, float adjustment) {\n const vec3 W = vec3(0.2125, 0.7154, 0.0721);\n vec3 intensity = vec3(dot(rgb, W));\n return mix(intensity, rgb, adjustment);\n }\n"+r.fragmentShader,r.fragmentShader=r.fragmentShader.replace("#include <transmission_pars_fragment>",""),r.fragmentShader=r.fragmentShader.replace("#include <transmission_fragment>",""),r.fragmentShader=r.fragmentShader.replace("vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;",`vec2 uv = gl_FragCoord.xy / resolution.xy;\n vec2 refractNormal = vNormal.xy * (1.0 - vNormal.z * 0.85);\n vec3 refractCol = vec3(0.0); \n float randomCoords = rand(uv);\n vec2 randomCoords2;\n float roughBlur = roughness * roughness;\n float slide;\n #pragma unroll_loop_start\n for (int i = 0; i < ${e}; i ++) {\n slide = float(UNROLLED_LOOP_INDEX) / float(${e}) * 0.1 + randomCoords * noise;\n randomCoords2 = vec2(rand(uv + randomCoords + 0.1 * float(UNROLLED_LOOP_INDEX)), rand(uv - randomCoords - 0.1 * float(UNROLLED_LOOP_INDEX))) - 0.5;\n randomCoords2 = normalize(randomCoords2) * sqrt(rand(uv + 0.12 * float(UNROLLED_LOOP_INDEX)));\n refractCol.r += texture2D(buffer, uv - refractNormal * (refraction + slide * 1.0) * rgbShift + randomCoords2 * roughBlur).r;\n refractCol.g += texture2D(buffer, uv - refractNormal * (refraction + slide * 2.0) * rgbShift + randomCoords2 * roughBlur).g;\n refractCol.b += texture2D(buffer, uv - refractNormal * (refraction + slide * 3.0) * rgbShift + randomCoords2 * roughBlur).b;\n refractCol = sat(refractCol, saturation);\n }\n #pragma unroll_loop_end\n refractCol /= float(${e});\n vec3 outgoingLight = (refractCol * totalDiffuse * contrast) + totalSpecular + totalEmissiveRadiance;`)},Object.keys(this.uniforms).forEach((e=>Object.defineProperty(this,e,{get:()=>this.uniforms[e].value,set:r=>this.uniforms[e].value=r})))}}const c=l.forwardRef((({buffer:e,samples:r=10,resolution:t=1024,background:a,...s},u)=>{n.extend({MeshTransmissionMaterial:f});const c=l.useRef(null),{size:d,viewport:m}=n.useThree(),g=o.useFBO(t),v=l.useMemo((()=>({samples:r})),[r]);let h,b,p;return n.useFrame((r=>{e||(p=c.current.__r3f.parent,p&&(b=p.visible,p.visible=!1,r.gl.setRenderTarget(g),h=r.scene.background,a&&(r.scene.background=a),r.gl.render(r.scene,r.camera),r.scene.background=h,r.gl.setRenderTarget(null),p.visible=b))})),l.useImperativeHandle(u,(()=>c.current),[]),l.createElement("meshTransmissionMaterial",i.default({args:[v],ref:c,buffer:e||g.texture,resolution:[d.width*m.dpr,d.height*m.dpr]},s))}));exports.MeshTransmissionMaterial=c;
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({samples:n=6,...e}={}){super(e),this.uniforms={chromaticAberration:{value:.05},transmission:{value:1},thickness:{value:1},anisotropy:{value:.1},time:{value:0},distortion:{value:0},distortionScale:{value:.5},temporalDistortion:{value:.5},buffer:{value:null},resolution:{value:new l.Vector2}},this.onBeforeCompile=e=>{e.uniforms={...e.uniforms,...this.uniforms},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 sat(vec3 rgb, float adjustment) {\n const vec3 W = vec3(0.2125, 0.7154, 0.0721);\n vec3 intensity = vec3(dot(rgb, W));\n return mix(intensity, rgb, adjustment);\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\n m &= ieeeMantissa; // Keep only mantissa bits (fractional part)\n m |= ieeeOne; // Add fractional part to 1.0\n\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 material.transmissionAlpha = 1.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,distortionSpeed:e=1,samples:t=10,resolution:r,background:i,...l},u)=>{o.extend({MeshTransmissionMaterial:m});const f=c.useRef(null),{size:d,viewport:v}=o.useThree(),h=a.useFBO(r);let p,x,g;return o.useFrame((t=>{n||(g=f.current.__r3f.parent,f.current.time=t.clock.getElapsedTime()*e,g&&(x=g.visible,g.visible=!1,t.gl.setRenderTarget(h),p=t.scene.background,i&&(t.scene.background=i),t.gl.render(t.scene,t.camera),t.scene.background=p,t.gl.setRenderTarget(null),g.visible=x))})),c.useImperativeHandle(u,(()=>f.current),[]),c.createElement("meshTransmissionMaterial",s.default({args:[c.useMemo((()=>({samples:t})),[t])],ref:f,buffer:n||h.texture,resolution:[d.width*v.dpr,d.height*v.dpr]},l))}));exports.MeshTransmissionMaterial=u;
@@ -1,13 +1,13 @@
1
1
  import * as THREE from 'three';
2
2
  import * as React from 'react';
3
3
  import { ReactThreeFiber } from '@react-three/fiber';
4
- declare type MeshTransmissionMaterialType = Omit<JSX.IntrinsicElements['meshPhysicalMaterial'], 'args' | 'roughness' | 'transmission' | 'transmissionMap' | 'thickness'> & {
5
- refraction?: number;
6
- roughness?: number;
7
- rgbShift?: number;
8
- noise?: number;
9
- saturation?: number;
10
- contrast?: number;
4
+ declare type MeshTransmissionMaterialType = Omit<JSX.IntrinsicElements['meshPhysicalMaterial'], 'args'> & {
5
+ chromaticAberration?: number;
6
+ anisotropy?: number;
7
+ distortion?: number;
8
+ distortionScale?: number;
9
+ temporalDistortion?: number;
10
+ time?: number;
11
11
  resolution?: ReactThreeFiber.Vector2;
12
12
  buffer?: THREE.Texture;
13
13
  args?: [{
@@ -22,8 +22,9 @@ declare global {
22
22
  }
23
23
  }
24
24
  export declare const MeshTransmissionMaterial: React.ForwardRefExoticComponent<Pick<Omit<MeshTransmissionMaterialType, "args" | "resolution"> & {
25
+ distortionSpeed?: number | undefined;
25
26
  resolution?: number | undefined;
26
27
  samples?: number | undefined;
27
28
  background?: THREE.Texture | undefined;
28
- }, "visible" | "attach" | "children" | "key" | "onUpdate" | "dispose" | "type" | "id" | "uuid" | "name" | "userData" | "toJSON" | "clone" | "copy" | "addEventListener" | "hasEventListener" | "removeEventListener" | "dispatchEvent" | "color" | "blending" | "map" | "transparent" | "saturation" | "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" | "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" | "resolution" | "samples" | "refraction" | "rgbShift" | "noise" | "contrast"> & React.RefAttributes<unknown>>;
29
+ }, "attach" | "children" | "key" | "onUpdate" | "time" | "background" | "buffer" | keyof THREE.MeshPhysicalMaterial | "anisotropy" | "resolution" | "samples" | "distortion" | "chromaticAberration" | "distortionScale" | "temporalDistortion" | "distortionSpeed"> & React.RefAttributes<unknown>>;
29
30
  export {};