react-three-gpu-pathtracer

repository·main·Indexed 42 days ago

https://github.com/pmndrs/react-three-gpu-pathtracer

A React abstraction for the three-gpu-pathtracer library that enables high-quality path tracing in react-three-fiber scenes. It provides the <Pathtracer /> component for rendering, the usePathtracer hook for lifecycle control, and specialized components including PhysicalCamera, PhysicalSpotLight, ShapedAreaLight, and FogVolumeMaterial.

Tokens
3.3K
Snippets
13
Records
19
Agent score
53%

What's inside react-three-gpu-pathtracer

  1. Render scenes with Path Tracing using <Pathtracer />

    main

    To enable path tracing in a react-three-fiber scene, wrap your scene content with the <Pathtracer /> component. This component intercepts the scene and renders it using the path tracing algorithm instead of standard rasterization.

    import { Pathtracer } from "@react-three/gpu-pathtracer";
    
    function GradientSphere() {
      return (
        <Canvas>
          <Pathtracer>{/* Your scene */}</Pathtracer>
        </Canvas>
      );
    }
  2. Use the Pathtracer component

    main

    The Pathtracer component is the main provider for the rendering engine. It wraps your scene and manages the path-tracing lifecycle, including sample accumulation and scene synchronization. When enabled is true, it performs path-tracing; when false, it falls back to standard WebGL rendering.

    Key Props

    • enabled: Boolean to toggle between path-tracing and standard WebGL rendering. Defaults to true.
    • samples: The target number of samples to accumulate. Defaults to 32.
    • minSamples: The minimum samples required before rendering starts. Defaults to 1.
    • bounces: Number of light bounces. Defaults to 4.
    • resolutionFactor: Scales the render resolution. Defaults to 1.
    • tiles: Defines the tile size for progressive rendering (e.g., [3, 3]).
    • textureSize: The resolution of the internal render textures (e.g., [1024, 1024]).
    • rasterizeScene: Boolean to enable scene rasterization. Defaults to false.
    • dynamicLowRes: Enables dynamic low-resolution rendering. Defaults to true.
    • lowResScale: Scale used for dynamic low-res rendering. Defaults to 0.25.
    • filteredGlossyFactor: Controls the filtering of glossy reflections. Defaults to 0.
    <Pathtracer 
      samples={64} 
      bounces={8} 
      resolutionFactor={0.5}
    >
      <Scene />
    </Pathtracer>
  3. Use Environment maps with <Pathtracer />

    main

    You can add environment maps to your path-traced scene using the <Environment /> component from @react-three/drei. Place the <Environment /> component inside the <Pathtracer /> wrapper.

    <Pathtracer>
      <Environment
        preset="..."
        background // Optional, set as scene background
        backgroundBlurriness={0.5}
        backgroundIntensity={1}
      />
    </Pathtracer>
  4. Configure <Pathtracer /> props

    main

    The <Pathtracer /> component accepts several props to control the quality, performance, and lifecycle of the path tracing process:

    PropTypeDefaultDescription
    minSamplesnumber1Min number of samples before blending the base scene with the pathtraced one.
    samplesnumber1Max number of samples before the pathtracer stops.
    framesnumberInfinityNumber of frames to path trace. Will pause rendering once this number is reached.
    tiles[number, number] / THREE.Vector2 / { x: number; y: number } / number2Number of tiles. Can be used to improve responsiveness while rendering high resolution.
    bouncesnumber1The number of ray bounces to test. Higher is better quality but slower performance.
    enabledbooleantrueWhether to enable pathtracing.
  5. Access the renderer and lifecycle with usePathtracer

    main

    The usePathtracer hook provides access to the internal renderer and lifecycle controls. Note: This hook must be used within a component that is a child of the <Pathtracer /> component.

    Return valueTypeDescription
    pathtracerWebGLPathTracerInternal renderer. Can be used to access/edit internal properties.
    reset() => voidFlushes the rendered scene and resets the samples count.
    update() => voidTells the pathtracer that the scene has been updated.
    const { pathtracer, update, reset } = usePathtracer();
  6. Implement a custom post-processing pass with the Pass class

    main

    The Pass class serves as a base class for creating custom post-processing effects. To create a functional pass, you must extend this class and implement the render method.

    Key properties for controlling pass behavior:

    • enabled: If true, the pass is processed by the composer.
    • needsSwap: If true, the pass indicates that the read and write buffers should be swapped after rendering.
    • clear: If true, the pass clears its buffer before rendering.
    • renderToScreen: If true, the result is rendered directly to the screen (usually managed automatically by EffectComposer).

    When implementing render, you must provide the following signature: render(renderer: WebGLRenderer, writeBuffer: WebGLRenderTarget, readBuffer: WebGLRenderTarget, deltaTime: number, maskActive?: unknown): void

    import { Pass, WebGLRenderer, WebGLRenderTarget } from "@react-three/gpu-pathtracer";
    
    class MyCustomPass extends Pass {
      constructor() {
        super();
        this.clear = true;
      }
    
      render(
        renderer: WebGLRenderer, 
        writeBuffer: WebGLRenderTarget, 
        readBuffer: WebGLRenderTarget, 
        deltaTime: number
      ) {
        // Implementation of your post-processing effect
      }
    }
  7. Use FullScreenQuad for full-viewport rendering

    main

    The FullScreenQuad class is a helper designed for post-processing passes that need to fill the entire viewport with a single quad (a plane covering the screen). It manages an OrthographicCamera and a PlaneGeometry internally.

    Usage:

    • Initialize it with a Material (e.g., a shader material).
    • Use the .render(renderer) method to draw the quad using the provided WebGL renderer.
    • Access or update the material via the .material property.
    • Call .dispose() to clean up the underlying geometry and prevent memory leaks.
    import { FullScreenQuad } from "@react-three/gpu-pathtracer";
    import { ShaderMaterial } from "three";
    
    const material = new ShaderMaterial({ /* ... */ });
    const quad = new FullScreenQuad(material);
    
    // In your render loop:
    quad.render(renderer);
    
    // Cleanup:
    quad.dispose();
  8. Use the FogVolumeMaterial component

    main

    The FogVolumeMaterial component allows you to render volumetric fog within a scene using the GPU pathtracer. It is a React wrapper around the FogVolumeMaterial implementation from three-gpu-pathtracer.

    To use it, ensure you have a Pathtracer context provider active in your component tree, as the material automatically calls pathtracer.updateMaterials() whenever it mounts to ensure the GPU state is synchronized.

    import { FogVolumeMaterial } from '@react-three/gpu-pathtracer';
    
    // Inside your Canvas/Pathtracer context
    <fogVolumeMaterial 
      args={[{ color: 'white', density: 0.1 }]} 
      // ... other FogVolumeMaterialImpl props
    />
  9. Use the ShapedAreaLight component

    main

    The ShapedAreaLight component allows you to create area lights with custom shapes for use with the GPU Pathtracer. It is a wrapper around the three-gpu-pathtracer implementation that automatically triggers a pathtracer.updateLights() call whenever the component is mounted, ensuring the light is registered with the pathtracer instance.

    To use it, ensure you have a Pathtracer context provider in your scene tree, as the component relies on the usePathtracer hook to access the pathtracer instance.

    <Pathtracer>
      <ShapedAreaLight 
        args={["path/to/geometry/or/shape"]}
        /* other ShapedAreaLightImpl props */ 
      />
    </Pathtracer>
  10. Use the PhysicalCamera component for realistic rendering

    main

    The PhysicalCamera component provides a Three.js PhysicalCamera implementation integrated with @react-three/fiber and the GPU Pathtracer. It automatically handles aspect ratio calculations (unless manual mode is enabled), updates the projection matrix, and sets itself as the active camera in the R3F state. Crucially, it automatically triggers pathtracer.updateCamera() whenever the camera changes, ensuring the path tracer stays in sync with the camera's properties.

    To use it, simply include the <physicalCamera /> element within your R3F scene. It accepts all standard PhysicalCamera properties from three-gpu-pathtracer.

    <PhysicalCamera 
      fov={50} 
      near={0.1} 
      far={1000} 
      // manual={true} // Set to true if you want to manage aspect ratio yourself
    />
  11. Configure Pathtracer via Ref

    main

    The Pathtracer component supports a ref that exposes the underlying WebGLPathTracer instance. This allows you to access the low-level engine directly for advanced configurations or manual control.

    const pathtracerRef = useRef<WebGLPathTracer>(null);
    
    <Pathtracer ref={pathtracerRef} />
    
    // Later in code:
    // pathtracerRef.current.someMethod();