11import { useCallback , useEffect , useRef , useState } from "react" ;
22import { Canvas , useCanvasEffect } from "react-native-wgpu" ;
3- import { PixelRatio , useWindowDimensions } from "react-native" ;
3+ import { useWindowDimensions } from "react-native" ;
4+ import { SharedValue , useSharedValue } from "react-native-reanimated" ;
5+ import { Gesture , GestureDetector } from "react-native-gesture-handler" ;
46
57import { ComputeEngine } from "./engine" ;
68
@@ -44,6 +46,7 @@ export interface ComputeToyProps {
4446}
4547
4648export const ComputeToy = ( { toy : { shader, uniforms } } : ComputeToyProps ) => {
49+ const mouse = useSharedValue ( { pos : { x : 0 , y : 0 } , click : false } ) ;
4750 const { width, height } = useWindowDimensions ( ) ;
4851 const [ engine , setEngine ] = useState < ComputeEngine | null > ( null ) ;
4952 const animationRef = useRef < number | null > ( null ) ;
@@ -62,8 +65,8 @@ export const ComputeToy = ({ toy: { shader, uniforms } }: ComputeToyProps) => {
6265 eng . setSurface ( canvasRef . current ! ) ;
6366
6467 // Set the canvas size based on your CANVAS constants
65- // TODO: use PixelRatio.get()
66- eng . resize ( width , height , PixelRatio . get ( ) ) ;
68+ // TODO: use PixelRatio.get()?
69+ eng . resize ( width , height , 1 ) ;
6770
6871 // Initialize render state
6972 eng . reset ( ) ;
@@ -121,18 +124,46 @@ export const ComputeToy = ({ toy: { shader, uniforms } }: ComputeToyProps) => {
121124 // Update time uniforms
122125 engine . setTimeElapsed ( timestamp / 1000 ) ;
123126 engine . setTimeDelta ( delta ) ;
127+ if ( mouse ) {
128+ engine . setMousePos ( mouse . value . pos . x , mouse . value . pos . y ) ;
129+ engine . setMouseClick ( mouse . value . click ) ;
130+ }
124131 // Render frame
125132
126133 engine . render ( ) ;
127134 // Schedule next frame
128135 animationRef . current = requestAnimationFrame ( renderLoop ) ;
129136 } ,
130- [ engine ] ,
137+ [ engine , mouse ] ,
131138 ) ;
132139
133140 useEffect ( ( ) => {
134141 renderLoop ( new Date ( ) . getTime ( ) ) ;
135142 } , [ renderLoop ] ) ;
136143
137- return < Canvas ref = { canvasRef } style = { { width, height } } /> ;
144+ const gesture = Gesture . Pan ( )
145+ . onChange ( ( e ) => {
146+ mouse . value = {
147+ pos : {
148+ x : e . absoluteX / width ,
149+ y : e . absoluteY / height ,
150+ } ,
151+ click : true ,
152+ } ;
153+ } )
154+ . onEnd ( ( e ) => {
155+ mouse . value = {
156+ pos : {
157+ x : e . absoluteX / width ,
158+ y : e . absoluteY / height ,
159+ } ,
160+ click : false ,
161+ } ;
162+ } ) ;
163+
164+ return (
165+ < GestureDetector gesture = { gesture } >
166+ < Canvas ref = { canvasRef } style = { { width, height } } />
167+ </ GestureDetector >
168+ ) ;
138169} ;
0 commit comments