Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
120 changes: 84 additions & 36 deletions examples/jsm/lighting/ReflectionProbes.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
Box3,
Color,
CubeArrayTexture,
CubeReflectionMapping,
HalfFloatType,
Expand All @@ -15,6 +16,7 @@ const _position = /*@__PURE__*/ new Vector3();
const _size = /*@__PURE__*/ new Vector3();
const _region = /*@__PURE__*/ new Box3();
const _destination = /*@__PURE__*/ new Vector3();
const _black = /*@__PURE__*/ new Color( 0x000000 );

/**
* A local reflection volume. Add it to a {@link ReflectionProbes} container.
Expand Down Expand Up @@ -163,6 +165,13 @@ class ReflectionProbes extends Object3D {
this.capturing = false;

this._renderTarget = null;
this._pmrem = null;
this._generator = null;
this._environment = new Scene();

this._environmentTexture = undefined;
this._environmentVersion = - 1;
this._environmentPMREMVersion = - 1;

}

Expand All @@ -189,71 +198,106 @@ class ReflectionProbes extends Object3D {
const probes = this.children.filter( ( child ) => child.isReflectionProbe ).sort( ( a, b ) => volume( a ) - volume( b ) );
const maxLod = Math.log2( resolution ) - 3;

const renderTarget = new RenderTarget( resolution, resolution, {
depth: ( probes.length + 1 ) * 6,
type: HalfFloatType,
depthBuffer: false,
generateMipmaps: false,
minFilter: LinearMipmapLinearFilter,
mapping: CubeReflectionMapping
} );
const depth = ( probes.length + 1 ) * 6;

// Reuse the cube array and the PMREM between bakes of the same layout, so that
// re-baking every frame neither allocates nor changes the texture materials sample.

let renderTarget = this._renderTarget;
let previousRenderTarget = null;

const layoutChanged = renderTarget === null || renderTarget.width !== resolution || renderTarget.depth !== depth;

if ( layoutChanged ) {

// Materials sample the previous cube array while the probes are captured.

previousRenderTarget = renderTarget;

renderTarget.texture = new CubeArrayTexture().copy( renderTarget.texture );
renderTarget.texture.name = 'ReflectionProbes';
if ( this._pmrem !== null ) this._pmrem.dispose();
this._pmrem = null;

renderTarget = new RenderTarget( resolution, resolution, {
depth,
type: HalfFloatType,
depthBuffer: false,
generateMipmaps: false,
minFilter: LinearMipmapLinearFilter,
mapping: CubeReflectionMapping
} );

renderTarget.texture = new CubeArrayTexture().copy( renderTarget.texture );
renderTarget.texture.name = 'ReflectionProbes';

for ( let lod = 0; lod <= maxLod; lod ++ ) {

renderTarget.texture.mipmaps.push( { width: resolution >> lod, height: resolution >> lod } );

}

for ( let lod = 0; lod <= maxLod; lod ++ ) {
renderer.initRenderTarget( renderTarget );

renderTarget.texture.mipmaps.push( { width: resolution >> lod, height: resolution >> lod } );
if ( this._generator === null ) this._generator = new PMREMGenerator( renderer );

}

renderer.initRenderTarget( renderTarget );
// The environment is captured again only when it changed. A new cube array starts black,
// which is what no environment looks like.

const generator = new PMREMGenerator( renderer );
const environment = new Scene();
environment.background = scene.environment;
const environmentTexture = scene.environment;

let pmrem = null;
const environmentChanged = environmentTexture !== this._environmentTexture ||
( environmentTexture !== null && ( environmentTexture.version !== this._environmentVersion || environmentTexture.pmremVersion !== this._environmentPMREMVersion ) );

this.capturing = true;
const captureEnvironment = layoutChanged ? environmentTexture !== null : environmentChanged;

try {
const generator = this._generator;
const environment = this._environment;
environment.background = environmentTexture !== null ? environmentTexture : _black;

const captureSlot = ( source, position, slot ) => {

this._pmrem = generator.fromScene( source, 0, near, far, { size: resolution, position, renderTarget: this._pmrem } );

for ( let lod = 0; lod <= maxLod; lod ++ ) {

const size = resolution >> lod;

// Unfilled cubes stay black, so an empty environment needs no capture.
_region.min.set( 0, 0, 0 );
_region.max.set( size, size, 6 );
_destination.set( 0, 0, slot * 6 );

const count = scene.environment !== null ? probes.length + 1 : probes.length;
renderer.copyTextureToTexture( this._pmrem.texture, renderTarget.texture, _region, _destination, lod, lod );

for ( let i = 0; i < count; i ++ ) {
}

const probe = probes[ i ];
const position = probe !== undefined ? probe.getWorldPosition( _position ) : _position.set( 0, 0, 0 );
};

pmrem = generator.fromScene( probe !== undefined ? scene : environment, 0, near, far, { size: resolution, position, renderTarget: pmrem } );
this.capturing = true;

for ( let lod = 0; lod <= maxLod; lod ++ ) {
try {

const size = resolution >> lod;
// The environment goes first, as the probe captures reflect it.

_region.min.set( 0, 0, 0 );
_region.max.set( size, size, 6 );
_destination.set( 0, 0, i * 6 );
if ( captureEnvironment ) captureSlot( environment, _position.set( 0, 0, 0 ), probes.length );

renderer.copyTextureToTexture( pmrem.texture, renderTarget.texture, _region, _destination, lod, lod );
for ( let slot = 0; slot < probes.length; slot ++ ) {

}
captureSlot( scene, probes[ slot ].getWorldPosition( _position ), slot );

}

} finally {

this.capturing = false;

if ( pmrem !== null ) pmrem.dispose();
generator.dispose();

}

if ( this._renderTarget !== null ) this._renderTarget.dispose();
this._environmentTexture = environmentTexture;
this._environmentVersion = environmentTexture !== null ? environmentTexture.version : - 1;
this._environmentPMREMVersion = environmentTexture !== null ? environmentTexture.pmremVersion : - 1;

if ( previousRenderTarget !== null ) previousRenderTarget.dispose();

this._renderTarget = renderTarget;
this.texture = renderTarget.texture;
Expand All @@ -267,8 +311,12 @@ class ReflectionProbes extends Object3D {
dispose() {

if ( this._renderTarget !== null ) this._renderTarget.dispose();
if ( this._pmrem !== null ) this._pmrem.dispose();
if ( this._generator !== null ) this._generator.dispose();

this._renderTarget = null;
this._pmrem = null;
this._generator = null;
this.texture = null;

}
Expand Down
52 changes: 42 additions & 10 deletions examples/webgpu_reflection_probes.html
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,11 @@
import { reflectionProbes } from 'three/addons/tsl/lighting/ReflectionProbesNode.js';
import { ReflectionProbesHelper } from 'three/addons/helpers/ReflectionProbesHelper.js';

const params = { showProbes: false, dynamicObject: 'Bunny', pause: false, showGrid: false, gridResolution: 6, gridSize: 0.12, resolution: 128, boxProjection: true, capture: capture };
const params = { showProbes: false, dynamicObject: 'Bunny', pause: false, showGrid: false, gridResolution: 6, gridSize: 0.12, resolution: 128, boxProjection: true, liveCapture: true, animateRoom: true, includeInCapture: false, capture: capture };
const grid = new THREE.Group();
const timer = new THREE.Timer();
let camera, scene, renderer, controls, probes, probesHelper, gridMaterial, dynamicObject;
let animationTime = 0;
let camera, scene, renderer, controls, probes, probesHelper, gridMaterial, dynamicObject, warmLight, coolLight, torusKnot;
let animationTime = 0, roomTime = 0;

init();

Expand Down Expand Up @@ -214,7 +214,7 @@
pedestal.receiveShadow = true;
scene.add( pedestal );

const torusKnot = new THREE.Mesh(
torusKnot = new THREE.Mesh(
new THREE.TorusKnotGeometry( 0.3, 0.1, 64, 16 ),
new THREE.MeshStandardMaterial( { color: 0xff44aa, metalness: 0.2, roughness: 0.5 } )
);
Expand All @@ -236,7 +236,7 @@
// Lights

// Warm point light in left room
const warmLight = new THREE.PointLight( 0xffaa44, 30 );
warmLight = new THREE.PointLight( 0xffaa44, 30 );
warmLight.position.set( - 4, 4.5, 0 );
warmLight.castShadow = true;
warmLight.shadow.mapSize.setScalar( 256 );
Expand All @@ -245,7 +245,7 @@
scene.add( warmLight );

// Cool point light in right room
const coolLight = new THREE.PointLight( 0x88bbff, 30 );
coolLight = new THREE.PointLight( 0x88bbff, 30 );
coolLight.position.set( 4, 4.5, 0 );
coolLight.castShadow = true;
coolLight.shadow.mapSize.setScalar( 256 );
Expand Down Expand Up @@ -329,6 +329,8 @@
const gui = renderer.inspector.createParameters( 'Reflection Probes' );
gui.add( params, 'resolution', [ 64, 128, 256, 512, 1024 ] ).name( 'Capture Resolution' );
gui.add( params, 'capture' ).name( 'Capture' );
gui.add( params, 'liveCapture' ).name( 'Live Capture' );
gui.add( params, 'animateRoom' ).name( 'Animate Room' );
gui.add( params, 'boxProjection' ).name( 'Box Projection' ).onChange( ( value ) => probes.boxProjection = value );

const dynamicTest = gui.addFolder( 'Dynamic Test' );
Expand All @@ -339,6 +341,7 @@

} );
dynamicTest.add( params, 'pause' ).name( 'Pause' );
dynamicTest.add( params, 'includeInCapture' ).name( 'Include in Capture' );
dynamicTest.add( dynamicMaterial, 'roughness', 0, 1, 0.01 ).name( 'Roughness' );

const staticTest = gui.addFolder( 'Static Test' );
Expand All @@ -365,17 +368,39 @@

timer.update();

const delta = timer.getDelta();

if ( ! params.pause && params.dynamicObject !== 'None' ) {

animationTime += timer.getDelta();
animationTime += delta;
updateDynamicObject( animationTime );

}

if ( params.animateRoom ) {

roomTime += delta;
updateRoom( roomTime );

}

if ( params.liveCapture ) capture( true );

renderer.render( scene, camera );

}

function updateRoom( time ) {

// The lights drift slowly through the hues, half a cycle apart, and the knot turns.
// With Live Capture off, the reflections keep showing the room as it was captured.

warmLight.color.setHSL( ( 0.08 + time * 0.02 ) % 1, 1, 0.63 );
coolLight.color.setHSL( ( 0.6 + time * 0.02 ) % 1, 1, 0.77 );
torusKnot.rotation.y = time * 0.5;

}

function updateDynamicObject( time ) {

// A figure eight around both room centers, crossing x=0 at the doorway.
Expand Down Expand Up @@ -426,12 +451,19 @@

}

function capture() {
function capture( live = false ) {

// Keep helpers and test objects out of the reflections. Moving objects are usually
// left out of probes, as the probes only see them from a few fixed points. A mirror
// shows the lights' highlights as a few very bright texels, which appear and disappear
// as it moves and make the prefiltered reflections flicker. Turn on "Include in Capture"
// to see this.

// Keep helpers and test objects out of the reflections.
probesHelper.visible = grid.visible = false;
dynamicObject.visible = live === true && params.includeInCapture && params.dynamicObject !== 'None';

probesHelper.visible = grid.visible = dynamicObject.visible = false;
probes.bake( renderer, scene, { resolution: Number( params.resolution ), near: 0.05, far: 30 } );

probesHelper.visible = params.showProbes;
grid.visible = params.showGrid;
dynamicObject.visible = params.dynamicObject !== 'None';
Expand Down
41 changes: 23 additions & 18 deletions src/nodes/pmrem/PMREMUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,26 @@ export const ggxConvolution = /*@__PURE__*/ Fn( ( { roughness, lodBias, envMap,

} );

// Weighted radiance of one texel pair of the ggxIntegration() source mip, as vec4( color * weight, weight ).
export const ggxIntegrationTexel = /*@__PURE__*/ Fn( ( { N, alpha2, face, x, y, texelSize, sourceLod, envMap } ) => {

const uv = vec2( x, y ).add( 0.5 ).mul( texelSize ).sub( 1.0 ).toConst();
const texelDirection = select( face.equal( 0 ), vec3( 1.0, uv ), select( face.equal( 1 ), vec3( uv.x, 1.0, uv.y ), vec3( uv, 1.0 ) ) ).toVar();

const invDistance = inverseSqrt( dot( uv, uv ).add( 1.0 ) ).toConst();
const NdotL = dot( N, texelDirection ).toVar();
texelDirection.mulAssign( select( NdotL.lessThan( 0.0 ), - 1.0, 1.0 ) );
NdotL.assign( abs( NdotL ).mul( invDistance ) );

// With V = N, NdotH squared is ( 1 + NdotL ) / 2. Common factors
// in the GGX distribution and texel solid angle cancel when normalized.
const d = alpha2.add( 1.0 ).add( alpha2.sub( 1.0 ).mul( NdotL ) );
const weight = NdotL.mul( invDistance ).mul( invDistance ).mul( invDistance ).div( d.mul( d ) ).toConst();

return vec4( envMap.sample( texelDirection ).level( sourceLod ).rgb.mul( weight ), weight );

} );

// GGX convolution that weights every texel of a small source mip. Noise free and,
// for the wide lobes of the rough mip levels, cheaper than importance sampling.
export const ggxIntegration = /*@__PURE__*/ Fn( ( { roughness, sourceLod, sourceSize, envMap, direction } ) => {
Expand All @@ -153,8 +173,7 @@ export const ggxIntegration = /*@__PURE__*/ Fn( ( { roughness, sourceLod, source

const texelSize = float( 2.0 ).div( float( sourceSize ) ).toConst();

const prefilteredColor = vec3( 0.0 ).toVar();
const totalWeight = float( 0.0 ).toVar();
const prefilteredColor = vec4( 0.0 ).toVar();

// Pair opposite texels: only the one in N's hemisphere contributes.
Loop( { start: int( 0 ), end: int( 3 ), name: 'face' }, ( { face } ) => {
Expand All @@ -163,28 +182,14 @@ export const ggxIntegration = /*@__PURE__*/ Fn( ( { roughness, sourceLod, source

Loop( { start: int( 0 ), end: sourceSize, name: 'x' }, ( { x } ) => {

const uv = vec2( x, y ).add( 0.5 ).mul( texelSize ).sub( 1.0 ).toConst();
const texelDirection = select( face.equal( 0 ), vec3( 1.0, uv ), select( face.equal( 1 ), vec3( uv.x, 1.0, uv.y ), vec3( uv, 1.0 ) ) ).toVar();

const invDistance = inverseSqrt( dot( uv, uv ).add( 1.0 ) ).toConst();
const NdotL = dot( N, texelDirection ).toVar();
texelDirection.mulAssign( select( NdotL.lessThan( 0.0 ), - 1.0, 1.0 ) );
NdotL.assign( abs( NdotL ).mul( invDistance ) );

// With V = N, NdotH squared is ( 1 + NdotL ) / 2. Common factors
// in the GGX distribution and texel solid angle cancel when normalized.
const d = alpha2.add( 1.0 ).add( alpha2.sub( 1.0 ).mul( NdotL ) );
const weight = NdotL.mul( invDistance ).mul( invDistance ).mul( invDistance ).div( d.mul( d ) ).toConst();

prefilteredColor.addAssign( envMap.sample( texelDirection ).level( sourceLod ).rgb.mul( weight ) );
totalWeight.addAssign( weight );
prefilteredColor.addAssign( ggxIntegrationTexel( { N, alpha2, face, x, y, texelSize, sourceLod, envMap } ) );

} );

} );

} );

return vec4( prefilteredColor.div( totalWeight ), 1.0 );
return vec4( prefilteredColor.rgb.div( prefilteredColor.a ), 1.0 );

} );
Loading
Loading