ソースを参照

TSL: Introduce Chromatic Aberration (#31236)

* Chromatic aberration TSL node

Example page for ca node

* Fix comma

* Remove unused delta from render loop in ca example

* Rename CANode.js to ChromaticAberrationNode.js

Add nodeObject in ca params, for ability to use a procedural node

Update example gui to toggle procedural / static

* Fix the gui in example

* cleanup code style

* use nodeObject()

* Update webgpu_postprocessing_ca.html

* cleanup

---------

Co-authored-by: PashaDev2 <pasha.yakubovsky@lynksen.com>
Pasha Yakubovsky 1 年間 前
コミット
e9f3ce4731

+ 1 - 0
examples/files.json

@@ -405,6 +405,7 @@
 		"webgpu_postprocessing_fxaa",
 		"webgpu_postprocessing_lensflare",
 		"webgpu_postprocessing_masking",
+		"webgpu_postprocessing_ca",
 		"webgpu_postprocessing_motion_blur",
 		"webgpu_postprocessing_outline",
 		"webgpu_postprocessing_smaa",

+ 206 - 0
examples/jsm/tsl/display/ChromaticAberrationNode.js

@@ -0,0 +1,206 @@
+import { Vector2, TempNode } from 'three/webgpu';
+import {
+	nodeObject,
+	Fn,
+	uniform,
+	convertToTexture,
+	float,
+	vec4,
+	uv,
+	NodeUpdateType,
+} from 'three/tsl';
+
+/**
+ * Post processing node for applying chromatic aberration effect.
+ * This effect simulates the color fringing that occurs in real camera lenses
+ * by separating and offsetting the red, green, and blue channels.
+ *
+ * @augments TempNode
+ * @three_import import { chromaticAberration } from 'three/addons/tsl/display/ChromaticAberrationNode.js';
+ */
+class ChromaticAberrationNode extends TempNode {
+
+	static get type() {
+
+		return 'ChromaticAberrationNode';
+
+	}
+
+	/**
+	 * Constructs a new chromatic aberration node.
+	 *
+	 * @param {TextureNode} textureNode - The texture node that represents the input of the effect.
+	 * @param {Node} strengthNode - The strength of the chromatic aberration effect as a node.
+	 * @param {Node} centerNode - The center point of the effect as a node.
+	 * @param {Node} scaleNode - The scale factor for stepped scaling from center as a node.
+	 */
+	constructor( textureNode, strengthNode, centerNode, scaleNode ) {
+
+		super( 'vec4' );
+
+		/**
+		 * The texture node that represents the input of the effect.
+		 *
+		 * @type {texture}
+		 */
+		this.textureNode = textureNode;
+
+		/**
+		 * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node updates
+		 * its internal uniforms once per frame in `updateBefore()`.
+		 *
+		 * @type {string}
+		 * @default 'frame'
+		 */
+		this.updateBeforeType = NodeUpdateType.FRAME;
+
+		/**
+		 * A node holding the strength of the effect.
+		 *
+		 * @type {Node}
+		 */
+		this.strengthNode = strengthNode;
+
+		/**
+		 * A node holding the center point of the effect.
+		 *
+		 * @type {Node}
+		 */
+		this.centerNode = centerNode;
+
+		/**
+		 * A node holding the scale factor for stepped scaling.
+		 *
+		 * @type {Node}
+		 */
+		this.scaleNode = scaleNode;
+
+		/**
+		 * A uniform node holding the inverse resolution value.
+		 *
+		 * @private
+		 * @type {UniformNode<vec2>}
+		 */
+		this._invSize = uniform( new Vector2() );
+
+	}
+
+	/**
+	 * This method is used to update the effect's uniforms once per frame.
+	 *
+	 * @param {NodeFrame} frame - The current node frame.
+	 */
+	updateBefore( /* frame */ ) {
+
+		const map = this.textureNode.value;
+		this._invSize.value.set( 1 / map.image.width, 1 / map.image.height );
+
+	}
+
+	/**
+	 * This method is used to setup the effect's TSL code.
+	 *
+	 * @param {NodeBuilder} builder - The current node builder.
+	 * @return {ShaderCallNodeInternal}
+	 */
+	setup( /* builder */ ) {
+
+		const textureNode = this.textureNode;
+		const uvNode = textureNode.uvNode || uv();
+
+		const ApplyChromaticAberration = Fn( ( [ uv, strength, center, scale ] ) => {
+
+			// Calculate distance from center
+			const offset = uv.sub( center );
+			const distance = offset.length();
+
+			// Create stepped scaling zones based on distance
+			// Each channel gets different scaling steps
+			const redScale = float( 1.0 ).add( scale.mul( 0.02 ).mul( strength ) ); // Red channel scaled outward
+			const greenScale = float( 1.0 ); // Green stays at original scale
+			const blueScale = float( 1.0 ).sub( scale.mul( 0.02 ).mul( strength ) ); // Blue channel scaled inward
+
+			// Create radial distortion based on distance from center
+			const aberrationStrength = strength.mul( distance );
+
+			// Calculate scaled UV coordinates for each channel
+			const redUV = center.add( offset.mul( redScale ) );
+			const greenUV = center.add( offset.mul( greenScale ) );
+			const blueUV = center.add( offset.mul( blueScale ) );
+
+			// Apply additional chromatic offset based on aberration strength
+			const rOffset = offset.mul( aberrationStrength ).mul( float( 0.01 ) );
+			const gOffset = offset.mul( aberrationStrength ).mul( float( 0.0 ) );
+			const bOffset = offset.mul( aberrationStrength ).mul( float( - 0.01 ) );
+
+			// Final UV coordinates combining scale and chromatic aberration
+			const finalRedUV = redUV.add( rOffset );
+			const finalGreenUV = greenUV.add( gOffset );
+			const finalBlueUV = blueUV.add( bOffset );
+
+			// Sample texture for each channel
+			const r = textureNode.sample( finalRedUV ).r;
+			const g = textureNode.sample( finalGreenUV ).g;
+			const b = textureNode.sample( finalBlueUV ).b;
+
+			// Get original alpha
+			const a = textureNode.sample( uv ).a;
+
+			return vec4( r, g, b, a );
+
+		} ).setLayout( {
+			name: 'ChromaticAberrationShader',
+			type: 'vec4',
+			inputs: [
+				{ name: 'uv', type: 'vec2' },
+				{ name: 'strength', type: 'float' },
+				{ name: 'center', type: 'vec2' },
+				{ name: 'scale', type: 'float' },
+				{ name: 'invSize', type: 'vec2' }
+			]
+		} );
+
+		const chromaticAberrationFn = Fn( () => {
+
+			return ApplyChromaticAberration(
+				uvNode,
+				this.strengthNode,
+				this.centerNode,
+				this.scaleNode,
+				this._invSize
+			);
+
+		} );
+
+		const outputNode = chromaticAberrationFn();
+
+		return outputNode;
+
+	}
+
+}
+
+export default ChromaticAberrationNode;
+
+/**
+ * TSL function for creating a chromatic aberration node for post processing.
+ *
+ * @tsl
+ * @function
+ * @param {Node<vec4>} node - The node that represents the input of the effect.
+ * @param {Node|number} [strength=1.0] - The strength of the chromatic aberration effect as a node or value.
+ * @param {Node|Vector2} [center=null] - The center point of the effect as a node or value. If null, uses screen center (0.5, 0.5).
+ * @param {Node|number} [scale=1.1] - The scale factor for stepped scaling from center as a node or value.
+ * @returns {ChromaticAberrationNode}
+ */
+export const chromaticAberration = ( node, strength = 1.0, center = null, scale = 1.1 ) => {
+
+	return nodeObject(
+		new ChromaticAberrationNode(
+			convertToTexture( node ),
+			nodeObject( strength ),
+			nodeObject( center ),
+			nodeObject( scale )
+		)
+	);
+};

BIN
examples/screenshots/webgpu_postprocessing_ca.jpg


+ 1 - 0
examples/tags.json

@@ -148,6 +148,7 @@
 	"webgpu_postprocessing_dof": [ "bokeh" ],
 	"webgpu_postprocessing_fxaa": [ "msaa", "multisampled" ],
 	"webgpu_postprocessing_motion_blur": [ "mrt" ],
+	"webgpu_postprocessing_ca": [ "chromatic aberration" ],
 	"webgpu_postprocessing_sobel": [ "filter", "edge detection" ],
 	"webgpu_postprocessing_ssaa": [ "msaa", "multisampled" ],
 	"webgpu_refraction": [ "water" ],

+ 346 - 0
examples/webgpu_postprocessing_ca.html

@@ -0,0 +1,346 @@
+<!DOCTYPE html>
+<html lang="en">
+	<head>
+		<title>three.js webgpu - chromatic aberration</title>
+		<meta charset="utf-8">
+		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
+		<link type="text/css" rel="stylesheet" href="main.css">
+	</head>
+
+	<body>
+
+		<div id="info">
+			<a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> webgpu - chromatic aberration
+		</div>
+
+		<script type="importmap">
+			{
+				"imports": {
+					"three": "../build/three.webgpu.js",
+					"three/webgpu": "../build/three.webgpu.js",
+					"three/tsl": "../build/three.tsl.js",
+					"three/addons/": "./jsm/"
+				}
+			}
+		</script>
+
+		<script type="module">
+
+			import * as THREE from 'three';
+			import { pass, renderOutput, uniform } from 'three/tsl';
+
+			import { chromaticAberration } from 'three/addons/tsl/display/ChromaticAberrationNode.js';
+
+			import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
+
+			const params = {
+				enabled: true,
+				animated: true,
+				strength: 1.5,
+				center: new THREE.Vector2(0.5, 0.5),
+				scale: 1.2,
+				autoRotate: true,
+				cameraDistance: 40
+			};
+
+			let camera, scene, renderer, clock, mainGroup;
+			let postProcessing;
+
+			init();
+
+			async function init() {
+
+				camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1, 200 );
+				camera.position.set( 0, 15, params.cameraDistance );
+				camera.lookAt( 0, 0, 0 );
+
+				scene = new THREE.Scene();
+				scene.background = new THREE.Color( 0x0a0a0a );
+
+				clock = new THREE.Clock();
+
+				// Lighting
+				const ambientLight = new THREE.AmbientLight( 0xffffff, 0.3 );
+				scene.add( ambientLight );
+
+				const dirLight1 = new THREE.DirectionalLight( 0xffffff, 1.5 );
+				dirLight1.position.set( 10, 20, 10 );
+				scene.add( dirLight1 );
+
+				const dirLight2 = new THREE.DirectionalLight( 0x4080ff, 0.5 );
+				dirLight2.position.set( -10, 20, -10 );
+				scene.add( dirLight2 );
+
+				const pointLight = new THREE.PointLight( 0xff4080, 1, 50 );
+				pointLight.position.set( 0, 10, 0 );
+				scene.add( pointLight );
+
+				// Create main group
+				mainGroup = new THREE.Group();
+				scene.add( mainGroup );
+
+				// Create shapes
+				createShapes();
+
+				// Add a grid for reference
+				const gridHelper = new THREE.GridHelper( 40, 20, 0x444444, 0x222222 );
+				gridHelper.position.y = -10;
+				scene.add( gridHelper );
+
+				renderer = new THREE.WebGPURenderer();
+				renderer.setPixelRatio( window.devicePixelRatio );
+				renderer.setSize( window.innerWidth, window.innerHeight );
+				renderer.setAnimationLoop( animate );
+				document.body.appendChild( renderer.domElement );
+
+				// post processing
+				postProcessing = new THREE.PostProcessing( renderer );
+				postProcessing.outputColorTransform = false;
+
+				// scene pass
+				const scenePass = pass( scene, camera );
+				const outputPass = renderOutput( scenePass );
+
+				// Create uniform nodes for the static version that can be updated
+				const staticStrength = uniform( params.strength );
+				const staticCenter = uniform( new THREE.Vector2( params.center.x, params.center.y ) );
+				const staticScale = uniform( params.scale );
+
+				// With static values (using uniform nodes)
+				const caPass = chromaticAberration( outputPass, staticStrength, staticCenter, staticScale );
+
+				// Set initial output based on params
+				postProcessing.outputNode = params.enabled ? caPass : outputPass;
+
+				window.addEventListener( 'resize', onWindowResize );
+
+				// GUI
+
+				const gui = new GUI();
+				gui.title( 'Chromatic Aberration' );
+
+				gui.add( params, 'enabled' ).onChange( ( value ) => {
+
+					postProcessing.outputNode = value ? caPass : outputPass;
+					postProcessing.needsUpdate = true;
+
+				} );
+
+				const staticFolder = gui.addFolder( 'Static Parameters' );
+
+				staticFolder.add( staticStrength, 'value', 0, 3 ).name( 'Strength' );
+				staticFolder.add( staticCenter.value, 'x', - 1, 1 ).name( 'Center X' );
+				staticFolder.add( staticCenter.value, 'y', - 1, 1 ).name( 'Center Y' );
+				staticFolder.add( staticScale, 'value', 0.5, 2 ).name( 'Scale' );
+
+				const animationFolder = gui.addFolder( 'Animation' );
+				animationFolder.add( params, 'animated' );
+				animationFolder.add( params, 'autoRotate' );
+				animationFolder.add( params, 'cameraDistance', 20, 60 ).onChange( ( value ) => {
+
+				    camera.position.z = value;
+
+				} );
+
+			}
+
+			function createShapes() {
+
+				const shapes = [];
+				const materials = [];
+
+				// Define colors for different materials
+				const colors = [
+					0xff0000, // Red
+					0x00ff00, // Green
+					0x0000ff, // Blue
+					0xffff00, // Yellow
+					0xff00ff, // Magenta
+					0x00ffff, // Cyan
+					0xffffff, // White
+					0xff8800  // Orange
+				];
+
+				// Create materials
+				colors.forEach( color => {
+
+					materials.push( new THREE.MeshStandardMaterial( {
+						color: color,
+						roughness: 0.2,
+						metalness: 0.8
+					} ) );
+
+				});
+
+				// Create geometries
+				const geometries = [
+					new THREE.BoxGeometry( 3, 3, 3 ),
+					new THREE.SphereGeometry( 2, 32, 16 ),
+					new THREE.ConeGeometry( 2, 4, 8 ),
+					new THREE.CylinderGeometry( 1.5, 1.5, 4, 8 ),
+					new THREE.TorusGeometry( 2, 0.8, 8, 16 ),
+					new THREE.OctahedronGeometry( 2.5 ),
+					new THREE.IcosahedronGeometry( 2.5 ),
+					new THREE.TorusKnotGeometry( 1.5, 0.5, 64, 8 )
+				];
+
+				// Create central showcase
+				const centralGroup = new THREE.Group();
+
+				// Large central torus
+				const centralTorus = new THREE.Mesh(
+					new THREE.TorusGeometry( 5, 1.5, 16, 32 ),
+					new THREE.MeshStandardMaterial( {
+						color: 0xffffff,
+						roughness: 0.1,
+						metalness: 1,
+						emissive: 0x222222
+					} )
+				);
+				centralGroup.add( centralTorus );
+
+				// Inner rotating shapes
+				for ( let i = 0; i < 6; i++ ) {
+
+					const angle = ( i / 6 ) * Math.PI * 2;
+					const radius = 3;
+
+					const mesh = new THREE.Mesh(
+						geometries[ i % geometries.length ],
+						materials[ i % materials.length ]
+					);
+
+					mesh.position.set(
+						Math.cos( angle ) * radius,
+						0,
+						Math.sin( angle ) * radius
+					);
+
+					mesh.scale.setScalar( 0.5 );
+					centralGroup.add( mesh );
+					shapes.push( mesh );
+
+				}
+
+				mainGroup.add( centralGroup );
+				shapes.push( centralGroup );
+
+				// Create outer ring of shapes
+				const numShapes = 12;
+				const outerRadius = 15;
+
+				for ( let i = 0; i < numShapes; i++ ) {
+
+					const angle = ( i / numShapes ) * Math.PI * 2;
+					const shapesGroup = new THREE.Group();
+
+					const geometry = geometries[ i % geometries.length ];
+					const material = materials[ i % materials.length ];
+
+					const mesh = new THREE.Mesh( geometry, material );
+					mesh.castShadow = true;
+					mesh.receiveShadow = true;
+
+					shapesGroup.add( mesh );
+					shapesGroup.position.set(
+						Math.cos( angle ) * outerRadius,
+						Math.sin( i * 0.5 ) * 2,
+						Math.sin( angle ) * outerRadius
+					);
+
+					mainGroup.add( shapesGroup );
+					shapes.push( shapesGroup );
+
+				}
+
+				// Add floating particles
+				const particlesGeometry = new THREE.BufferGeometry();
+				const particlesCount = 200;
+				const positions = new Float32Array( particlesCount * 3 );
+
+				for ( let i = 0; i < particlesCount * 3; i += 3 ) {
+
+					const radius = 25 + Math.random() * 10;
+					const theta = Math.random() * Math.PI * 2;
+					const phi = Math.random() * Math.PI;
+
+					positions[ i ] = radius * Math.sin( phi ) * Math.cos( theta );
+					positions[ i + 1 ] = radius * Math.cos( phi );
+					positions[ i + 2 ] = radius * Math.sin( phi ) * Math.sin( theta );
+
+				}
+
+				particlesGeometry.setAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
+
+				const particlesMaterial = new THREE.PointsMaterial( {
+					color: 0xffffff,
+					size: 0.5,
+					sizeAttenuation: true
+				} );
+
+				const particles = new THREE.Points( particlesGeometry, particlesMaterial );
+				mainGroup.add( particles );
+
+			}
+
+			function onWindowResize() {
+
+				camera.aspect = window.innerWidth / window.innerHeight;
+				camera.updateProjectionMatrix();
+				renderer.setSize( window.innerWidth, window.innerHeight );
+
+			}
+
+			function animate() {
+
+				const time = clock.getElapsedTime();
+
+				if ( params.animated ) {
+
+					// Animate individual shapes
+					mainGroup.children.forEach( ( child, index ) => {
+
+						if ( child.children.length > 0 ) {
+
+							// Central group
+							child.rotation.y = time * 0.5;
+							child.children.forEach( ( subChild, subIndex ) => {
+
+								if ( subChild.geometry ) {
+
+									subChild.rotation.x = time * ( 1 + subIndex * 0.1 );
+									subChild.rotation.z = time * ( 1 - subIndex * 0.1 );
+
+								}
+
+							} );
+
+						} else if ( child.type === 'Group' ) {
+
+							// Outer shapes
+							child.rotation.x = time * 0.5 + index;
+							child.rotation.y = time * 0.3 + index;
+							child.position.y = Math.sin( time + index ) * 2;
+
+						}
+
+					} );
+
+				}
+
+				if ( params.autoRotate ) {
+
+					const radius = params.cameraDistance;
+					camera.position.x = Math.sin( time * 0.1 ) * radius;
+					camera.position.z = Math.cos( time * 0.1 ) * radius;
+					camera.lookAt( 0, 0, 0 );
+
+				}
+
+				postProcessing.render();
+			}
+
+		</script>
+
+	</body>
+</html>

+ 1 - 0
test/e2e/puppeteer.js

@@ -170,6 +170,7 @@ const exceptionList = [
 	'webgpu_postprocessing_3dlut',
 	'webgpu_postprocessing_fxaa',
 	'webgpu_postprocessing_afterimage',
+	'webgpu_postprocessing_ca',
 	'webgpu_xr_native_layers',
 	'webgpu_volume_caustics',
 

粤ICP备19079148号