three#UniformsUtils JavaScript Examples

The following examples show how to use three#UniformsUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FilmPass.js    From Computer-Graphics with MIT License 6 votes vote down vote up
constructor( noiseIntensity, scanlinesIntensity, scanlinesCount, grayscale ) {

		super();

		if ( FilmShader === undefined ) console.error( 'THREE.FilmPass relies on FilmShader' );

		const shader = FilmShader;

		this.uniforms = UniformsUtils.clone( shader.uniforms );

		this.material = new ShaderMaterial( {

			uniforms: this.uniforms,
			vertexShader: shader.vertexShader,
			fragmentShader: shader.fragmentShader

		} );

		if ( grayscale !== undefined )	this.uniforms.grayscale.value = grayscale;
		if ( noiseIntensity !== undefined ) this.uniforms.nIntensity.value = noiseIntensity;
		if ( scanlinesIntensity !== undefined ) this.uniforms.sIntensity.value = scanlinesIntensity;
		if ( scanlinesCount !== undefined ) this.uniforms.sCount.value = scanlinesCount;

		this.fsQuad = new FullScreenQuad( this.material );

	}
Example #2
Source File: Waterpass.js    From r3f-website with MIT License 6 votes vote down vote up
WaterPass = function(dt_size) {
  Pass.call(this)
  if (WaterShader === undefined) console.error('THREE.WaterPass relies on THREE.WaterShader')
  var shader = WaterShader
  this.uniforms = UniformsUtils.clone(shader.uniforms)
  if (dt_size === undefined) dt_size = 64
  this.uniforms['resolution'].value = new Vector2(dt_size, dt_size)
  this.material = new ShaderMaterial({
    uniforms: this.uniforms,
    vertexShader: shader.vertexShader,
    fragmentShader: shader.fragmentShader
  })
  this.camera = new OrthographicCamera(-1, 1, 1, -1, 0, 1)
  this.scene = new Scene()
  this.quad = new Mesh(new PlaneBufferGeometry(2, 2), null)
  this.quad.frustumCulled = false // Avoid getting clipped
  this.scene.add(this.quad)
  this.factor = 0
  this.time = 0
}
Example #3
Source File: Glitchpass.js    From r3f-website with MIT License 6 votes vote down vote up
GlitchPass = function(dt_size) {
  Pass.call(this)
  if (DigitalGlitch === undefined) console.error('THREE.GlitchPass relies on THREE.DigitalGlitch')
  var shader = DigitalGlitch
  this.uniforms = UniformsUtils.clone(shader.uniforms)
  if (dt_size === undefined) dt_size = 64
  this.uniforms['tDisp'].value = this.generateHeightmap(dt_size)
  this.material = new ShaderMaterial({
    uniforms: this.uniforms,
    vertexShader: shader.vertexShader,
    fragmentShader: shader.fragmentShader
  })
  this.camera = new OrthographicCamera(-1, 1, 1, -1, 0, 1)
  this.scene = new Scene()
  this.quad = new Mesh(new PlaneBufferGeometry(2, 2), null)
  this.quad.frustumCulled = false // Avoid getting clipped
  this.scene.add(this.quad)
  this.factor = 0
}
Example #4
Source File: TexturePass.js    From Computer-Graphics with MIT License 6 votes vote down vote up
constructor( map, opacity ) {

		super();

		if ( CopyShader === undefined ) console.error( 'THREE.TexturePass relies on CopyShader' );

		const shader = CopyShader;

		this.map = map;
		this.opacity = ( opacity !== undefined ) ? opacity : 1.0;

		this.uniforms = UniformsUtils.clone( shader.uniforms );

		this.material = new ShaderMaterial( {

			uniforms: this.uniforms,
			vertexShader: shader.vertexShader,
			fragmentShader: shader.fragmentShader,
			depthTest: false,
			depthWrite: false

		} );

		this.needsSwap = false;

		this.fsQuad = new FullScreenQuad( null );

	}
Example #5
Source File: SavePass.js    From Computer-Graphics with MIT License 6 votes vote down vote up
constructor( renderTarget ) {

		super();

		if ( CopyShader === undefined ) console.error( 'THREE.SavePass relies on CopyShader' );

		const shader = CopyShader;

		this.textureID = 'tDiffuse';

		this.uniforms = UniformsUtils.clone( shader.uniforms );

		this.material = new ShaderMaterial( {

			uniforms: this.uniforms,
			vertexShader: shader.vertexShader,
			fragmentShader: shader.fragmentShader

		} );

		this.renderTarget = renderTarget;

		if ( this.renderTarget === undefined ) {

			this.renderTarget = new WebGLRenderTarget( window.innerWidth, window.innerHeight );
			this.renderTarget.texture.name = 'SavePass.rt';

		}

		this.needsSwap = false;

		this.fsQuad = new FullScreenQuad( this.material );

	}
Example #6
Source File: SSAARenderPass.js    From Computer-Graphics with MIT License 6 votes vote down vote up
constructor( scene, camera, clearColor, clearAlpha ) {

		super();

		this.scene = scene;
		this.camera = camera;

		this.sampleLevel = 4; // specified as n, where the number of samples is 2^n, so sampleLevel = 4, is 2^4 samples, 16.
		this.unbiased = true;

		// as we need to clear the buffer in this pass, clearColor must be set to something, defaults to black.
		this.clearColor = ( clearColor !== undefined ) ? clearColor : 0x000000;
		this.clearAlpha = ( clearAlpha !== undefined ) ? clearAlpha : 0;
		this._oldClearColor = new Color();

		if ( CopyShader === undefined ) console.error( 'THREE.SSAARenderPass relies on CopyShader' );

		const copyShader = CopyShader;
		this.copyUniforms = UniformsUtils.clone( copyShader.uniforms );

		this.copyMaterial = new ShaderMaterial(	{
			uniforms: this.copyUniforms,
			vertexShader: copyShader.vertexShader,
			fragmentShader: copyShader.fragmentShader,
			premultipliedAlpha: true,
			transparent: true,
			blending: AdditiveBlending,
			depthTest: false,
			depthWrite: false
		} );

		this.fsQuad = new FullScreenQuad( this.copyMaterial );

	}
Example #7
Source File: HalftonePass.js    From Computer-Graphics with MIT License 6 votes vote down vote up
constructor( width, height, params ) {

		super();

	 	if ( HalftoneShader === undefined ) {

	 		console.error( 'THREE.HalftonePass requires HalftoneShader' );

	 	}

	 	this.uniforms = UniformsUtils.clone( HalftoneShader.uniforms );
	 	this.material = new ShaderMaterial( {
	 		uniforms: this.uniforms,
	 		fragmentShader: HalftoneShader.fragmentShader,
	 		vertexShader: HalftoneShader.vertexShader
	 	} );

		// set params
		this.uniforms.width.value = width;
		this.uniforms.height.value = height;

		for ( const key in params ) {

			if ( params.hasOwnProperty( key ) && this.uniforms.hasOwnProperty( key ) ) {

				this.uniforms[ key ].value = params[ key ];

			}

		}

		this.fsQuad = new FullScreenQuad( this.material );

	}
Example #8
Source File: GlitchPass.js    From Computer-Graphics with MIT License 6 votes vote down vote up
constructor( dt_size = 64 ) {

		super();

		if ( DigitalGlitch === undefined ) console.error( 'THREE.GlitchPass relies on DigitalGlitch' );

		const shader = DigitalGlitch;

		this.uniforms = UniformsUtils.clone( shader.uniforms );

		this.uniforms[ 'tDisp' ].value = this.generateHeightmap( dt_size );

		this.material = new ShaderMaterial( {
			uniforms: this.uniforms,
			vertexShader: shader.vertexShader,
			fragmentShader: shader.fragmentShader
		} );

		this.fsQuad = new FullScreenQuad( this.material );

		this.goWild = false;
		this.curF = 0;
		this.generateTrigger();

	}
Example #9
Source File: DotScreenPass.js    From Computer-Graphics with MIT License 6 votes vote down vote up
constructor( center, angle, scale ) {

		super();

		if ( DotScreenShader === undefined ) console.error( 'THREE.DotScreenPass relies on DotScreenShader' );

		const shader = DotScreenShader;

		this.uniforms = UniformsUtils.clone( shader.uniforms );

		if ( center !== undefined ) this.uniforms[ 'center' ].value.copy( center );
		if ( angle !== undefined ) this.uniforms[ 'angle' ].value = angle;
		if ( scale !== undefined ) this.uniforms[ 'scale' ].value = scale;

		this.material = new ShaderMaterial( {

			uniforms: this.uniforms,
			vertexShader: shader.vertexShader,
			fragmentShader: shader.fragmentShader

		} );

		this.fsQuad = new FullScreenQuad( this.material );

	}
Example #10
Source File: CubeTexturePass.js    From Computer-Graphics with MIT License 6 votes vote down vote up
constructor( camera, envMap, opacity = 1 ) {

		super();

		this.camera = camera;

		this.needsSwap = false;

		this.cubeShader = ShaderLib[ 'cube' ];
		this.cubeMesh = new Mesh(
			new BoxGeometry( 10, 10, 10 ),
			new ShaderMaterial( {
				uniforms: UniformsUtils.clone( this.cubeShader.uniforms ),
				vertexShader: this.cubeShader.vertexShader,
				fragmentShader: this.cubeShader.fragmentShader,
				depthTest: false,
				depthWrite: false,
				side: BackSide
			} )
		);

		Object.defineProperty( this.cubeMesh.material, 'envMap', {

			get: function () {

				return this.uniforms.envMap.value;

			}

		} );

		this.envMap = envMap;
		this.opacity = opacity;

		this.cubeScene = new Scene();
		this.cubeCamera = new PerspectiveCamera();
		this.cubeScene.add( this.cubeMesh );

	}
Example #11
Source File: ShaderPass.js    From threejs-tutorial with MIT License 6 votes vote down vote up
ShaderPass = function (shader, textureID) {
    Pass.call(this);

    this.textureID = textureID !== undefined ? textureID : "tDiffuse";

    if (shader instanceof ShaderMaterial) {
        this.uniforms = shader.uniforms;

        this.material = shader;
    } else if (shader) {
        this.uniforms = UniformsUtils.clone(shader.uniforms);

        this.material = new ShaderMaterial({
            defines: Object.assign({}, shader.defines),
            uniforms: this.uniforms,
            vertexShader: shader.vertexShader,
            fragmentShader: shader.fragmentShader,
        });
    }

    this.fsQuad = new Pass.FullScreenQuad(this.material);
}
Example #12
Source File: SavePass.js    From threejs-tutorial with MIT License 6 votes vote down vote up
SavePass = function (renderTarget) {
    Pass.call(this);

    if (CopyShader === undefined)
        console.error("SavePass relies on CopyShader");

    var shader = CopyShader;

    this.textureID = "tDiffuse";

    this.uniforms = UniformsUtils.clone(shader.uniforms);

    this.material = new ShaderMaterial({
        uniforms: this.uniforms,
        vertexShader: shader.vertexShader,
        fragmentShader: shader.fragmentShader,
    });

    this.renderTarget = renderTarget;

    if (this.renderTarget === undefined) {
        this.renderTarget = new WebGLRenderTarget(
            window.innerWidth,
            window.innerHeight,
            {
                minFilter: LinearFilter,
                magFilter: LinearFilter,
                format: RGBFormat,
                stencilBuffer: false,
            }
        );
        this.renderTarget.texture.name = "SavePass.rt";
    }

    this.needsSwap = false;

    this.fsQuad = new Pass.FullScreenQuad(this.material);
}
Example #13
Source File: ShaderPass.js    From AudioPlayer with MIT License 6 votes vote down vote up
ShaderPass = function (shader, textureID) {
  Pass.call(this);

  this.textureID = textureID !== undefined ? textureID : "tDiffuse";

  if (shader instanceof ShaderMaterial) {
    this.uniforms = shader.uniforms;

    this.material = shader;
  } else if (shader) {
    this.uniforms = UniformsUtils.clone(shader.uniforms);

    this.material = new ShaderMaterial({
      defines: Object.assign({}, shader.defines),
      uniforms: this.uniforms,
      vertexShader: shader.vertexShader,
      fragmentShader: shader.fragmentShader,
    });
  }

  this.fsQuad = new Pass.FullScreenQuad(this.material);
}
Example #14
Source File: Sky.js    From canvas with Apache License 2.0 6 votes vote down vote up
Sky = function () {

	var shader = Sky.SkyShader;

	var material = new ShaderMaterial( {
		fragmentShader: shader.fragmentShader,
		vertexShader: shader.vertexShader,
		uniforms: UniformsUtils.clone( shader.uniforms ),
		side: BackSide,
		depthWrite: false
	} );

	Mesh.call( this, new BoxBufferGeometry( 1, 1, 1 ), material );

}
Example #15
Source File: AfterimagePass.js    From Computer-Graphics with MIT License 5 votes vote down vote up
constructor( damp = 0.96 ) {

		super();

		if ( AfterimageShader === undefined ) console.error( 'THREE.AfterimagePass relies on AfterimageShader' );

		this.shader = AfterimageShader;

		this.uniforms = UniformsUtils.clone( this.shader.uniforms );

		this.uniforms[ 'damp' ].value = damp;

		this.textureComp = new WebGLRenderTarget( window.innerWidth, window.innerHeight, {

			minFilter: LinearFilter,
			magFilter: NearestFilter,
			format: RGBAFormat

		} );

		this.textureOld = new WebGLRenderTarget( window.innerWidth, window.innerHeight, {

			minFilter: LinearFilter,
			magFilter: NearestFilter,
			format: RGBAFormat

		} );

		this.shaderMaterial = new ShaderMaterial( {

			uniforms: this.uniforms,
			vertexShader: this.shader.vertexShader,
			fragmentShader: this.shader.fragmentShader

		} );

		this.compFsQuad = new FullScreenQuad( this.shaderMaterial );

		const material = new MeshBasicMaterial();
		this.copyFsQuad = new FullScreenQuad( material );

	}
Example #16
Source File: BloomPass.js    From Computer-Graphics with MIT License 5 votes vote down vote up
constructor( strength = 1, kernelSize = 25, sigma = 4, resolution = 256 ) {

		super();

		// render targets

		const pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat };

		this.renderTargetX = new WebGLRenderTarget( resolution, resolution, pars );
		this.renderTargetX.texture.name = 'BloomPass.x';
		this.renderTargetY = new WebGLRenderTarget( resolution, resolution, pars );
		this.renderTargetY.texture.name = 'BloomPass.y';

		// copy material

		if ( CopyShader === undefined ) console.error( 'THREE.BloomPass relies on CopyShader' );

		const copyShader = CopyShader;

		this.copyUniforms = UniformsUtils.clone( copyShader.uniforms );

		this.copyUniforms[ 'opacity' ].value = strength;

		this.materialCopy = new ShaderMaterial( {

			uniforms: this.copyUniforms,
			vertexShader: copyShader.vertexShader,
			fragmentShader: copyShader.fragmentShader,
			blending: AdditiveBlending,
			transparent: true

		} );

		// convolution material

		if ( ConvolutionShader === undefined ) console.error( 'THREE.BloomPass relies on ConvolutionShader' );

		const convolutionShader = ConvolutionShader;

		this.convolutionUniforms = UniformsUtils.clone( convolutionShader.uniforms );

		this.convolutionUniforms[ 'uImageIncrement' ].value = BloomPass.blurX;
		this.convolutionUniforms[ 'cKernel' ].value = ConvolutionShader.buildKernel( sigma );

		this.materialConvolution = new ShaderMaterial( {

			uniforms: this.convolutionUniforms,
			vertexShader: convolutionShader.vertexShader,
			fragmentShader: convolutionShader.fragmentShader,
			defines: {
				'KERNEL_SIZE_FLOAT': kernelSize.toFixed( 1 ),
				'KERNEL_SIZE_INT': kernelSize.toFixed( 0 )
			}

		} );

		this.needsSwap = false;

		this.fsQuad = new FullScreenQuad( null );

	}
Example #17
Source File: BokehPass.js    From Computer-Graphics with MIT License 5 votes vote down vote up
constructor( scene, camera, params ) {

		super();

		this.scene = scene;
		this.camera = camera;

		const focus = ( params.focus !== undefined ) ? params.focus : 1.0;
		const aspect = ( params.aspect !== undefined ) ? params.aspect : camera.aspect;
		const aperture = ( params.aperture !== undefined ) ? params.aperture : 0.025;
		const maxblur = ( params.maxblur !== undefined ) ? params.maxblur : 1.0;

		// render targets

		const width = params.width || window.innerWidth || 1;
		const height = params.height || window.innerHeight || 1;

		this.renderTargetDepth = new WebGLRenderTarget( width, height, {
			minFilter: NearestFilter,
			magFilter: NearestFilter
		} );

		this.renderTargetDepth.texture.name = 'BokehPass.depth';

		// depth material

		this.materialDepth = new MeshDepthMaterial();
		this.materialDepth.depthPacking = RGBADepthPacking;
		this.materialDepth.blending = NoBlending;

		// bokeh material

		if ( BokehShader === undefined ) {

			console.error( 'THREE.BokehPass relies on BokehShader' );

		}

		const bokehShader = BokehShader;
		const bokehUniforms = UniformsUtils.clone( bokehShader.uniforms );

		bokehUniforms[ 'tDepth' ].value = this.renderTargetDepth.texture;

		bokehUniforms[ 'focus' ].value = focus;
		bokehUniforms[ 'aspect' ].value = aspect;
		bokehUniforms[ 'aperture' ].value = aperture;
		bokehUniforms[ 'maxblur' ].value = maxblur;
		bokehUniforms[ 'nearClip' ].value = camera.near;
		bokehUniforms[ 'farClip' ].value = camera.far;

		this.materialBokeh = new ShaderMaterial( {
			defines: Object.assign( {}, bokehShader.defines ),
			uniforms: bokehUniforms,
			vertexShader: bokehShader.vertexShader,
			fragmentShader: bokehShader.fragmentShader
		} );

		this.uniforms = bokehUniforms;
		this.needsSwap = false;

		this.fsQuad = new FullScreenQuad( this.materialBokeh );

		this._oldClearColor = new Color();

	}
Example #18
Source File: BlurPass.js    From threejs-tutorial with MIT License 5 votes vote down vote up
BlurPass = function (blur, resolution) {
    Pass.call(this);

    this.downSampleRatio = 2;
    this.blur = blur !== undefined ? blur : 0.8;
    this.resolution =
        resolution !== undefined
            ? new Vector2(resolution.x, resolution.y)
            : new Vector2(256, 256);
    var pars = {
        minFilter: LinearFilter,
        magFilter: LinearFilter,
        format: RGBAFormat,
    };
    var resx = Math.round(this.resolution.x / this.downSampleRatio);
    var resy = Math.round(this.resolution.y / this.downSampleRatio);

    this.renderTargetBlurBuffer1 = new WebGLRenderTarget(resx, resy, pars);
    this.renderTargetBlurBuffer1.texture.name = "BlurPass.blur1";
    this.renderTargetBlurBuffer1.texture.generateMipmaps = false;
    this.renderTargetBlurBuffer2 = new WebGLRenderTarget(
        Math.round(resx / 2),
        Math.round(resy / 2),
        pars
    );
    this.renderTargetBlurBuffer2.texture.name = "BlurPass.blur2";
    this.renderTargetBlurBuffer2.texture.generateMipmaps = false;

    this.separableBlurMaterial1 = this.getSeperableBlurMaterial(16);
    this.separableBlurMaterial1.uniforms["texSize"].value = new Vector2(
        resx,
        resy
    );
    this.separableBlurMaterial1.uniforms["kernelRadius"].value = 1;
    this.separableBlurMaterial2 = this.getSeperableBlurMaterial(16);
    this.separableBlurMaterial2.uniforms["texSize"].value = new Vector2(
        Math.round(resx / 2),
        Math.round(resy / 2)
    );
    this.separableBlurMaterial2.uniforms["kernelRadius"].value = 1;

    var copyShader = CopyShader;
    this.copyUniforms = UniformsUtils.clone(copyShader.uniforms);
    this.materialCopy = new ShaderMaterial({
        uniforms: this.copyUniforms,
        vertexShader: copyShader.vertexShader,
        fragmentShader: copyShader.fragmentShader,
        depthTest: false,
        depthWrite: false,
        transparent: true,
    });

    //this.needsSwap = false;
    this.fsQuad = new Pass.FullScreenQuad(null);
}
Example #19
Source File: SubsurfaceScatteringShader.js    From Computer-Graphics with MIT License 5 votes vote down vote up
SubsurfaceScatteringShader = {

	uniforms: UniformsUtils.merge( [
		ShaderLib[ 'phong' ].uniforms,
		{
			'thicknessMap': { value: null },
			'thicknessColor': { value: new Color( 0xffffff ) },
			'thicknessDistortion': { value: 0.1 },
			'thicknessAmbient': { value: 0.0 },
			'thicknessAttenuation': { value: 0.1 },
			'thicknessPower': { value: 2.0 },
			'thicknessScale': { value: 10.0 }
		}

	] ),

	vertexShader: [
		'#define USE_UV',
		ShaderChunk[ 'meshphong_vert' ],
	].join( '\n' ),

	fragmentShader: [
		'#define USE_UV',
		'#define SUBSURFACE',

		meshphong_frag_head,

		'uniform sampler2D thicknessMap;',
		'uniform float thicknessPower;',
		'uniform float thicknessScale;',
		'uniform float thicknessDistortion;',
		'uniform float thicknessAmbient;',
		'uniform float thicknessAttenuation;',
		'uniform vec3 thicknessColor;',

		'void RE_Direct_Scattering(const in IncidentLight directLight, const in vec2 uv, const in GeometricContext geometry, inout ReflectedLight reflectedLight) {',
		'	vec3 thickness = thicknessColor * texture2D(thicknessMap, uv).r;',
		'	vec3 scatteringHalf = normalize(directLight.direction + (geometry.normal * thicknessDistortion));',
		'	float scatteringDot = pow(saturate(dot(geometry.viewDir, -scatteringHalf)), thicknessPower) * thicknessScale;',
		'	vec3 scatteringIllu = (scatteringDot + thicknessAmbient) * thickness;',
		'	reflectedLight.directDiffuse += scatteringIllu * thicknessAttenuation * directLight.color;',
		'}',

		meshphong_frag_body.replace( '#include <lights_fragment_begin>',

			replaceAll(
				ShaderChunk[ 'lights_fragment_begin' ],
				'RE_Direct( directLight, geometry, material, reflectedLight );',
				[
					'RE_Direct( directLight, geometry, material, reflectedLight );',

					'#if defined( SUBSURFACE ) && defined( USE_UV )',
					' RE_Direct_Scattering(directLight, vUv, geometry, reflectedLight);',
					'#endif',
				].join( '\n' )
			),

		),

	].join( '\n' ),

}
Example #20
Source File: MMDToonShader.js    From Computer-Graphics with MIT License 5 votes vote down vote up
MMDToonShader = {

	defines: {
		TOON: true,
		MATCAP: true,
		MATCAP_BLENDING_ADD: true,
	},

	uniforms: UniformsUtils.merge( [
		ShaderLib.toon.uniforms,
		ShaderLib.phong.uniforms,
		ShaderLib.matcap.uniforms,
	] ),

	vertexShader: ShaderLib.phong.vertexShader,

	fragmentShader:
		ShaderLib.phong.fragmentShader
			.replace(
				'#include <common>',
				`
					#ifdef USE_MATCAP
						uniform sampler2D matcap;
					#endif

					#include <common>
				`
			)
			.replace(
				'#include <envmap_common_pars_fragment>',
				`
					#include <gradientmap_pars_fragment>
					#include <envmap_common_pars_fragment>
				`
			)
			.replace(
				'#include <lights_phong_pars_fragment>',
				lights_mmd_toon_pars_fragment
			)
			.replace(
				'#include <envmap_fragment>',
				`
					#include <envmap_fragment>
					${mmd_toon_matcap_fragment}
				`
			),

}
Example #21
Source File: b3dmExample.js    From 3DTilesRendererJS with Apache License 2.0 5 votes vote down vote up
// Adjusts the three.js standard shader to include batchid highlight
function batchIdHighlightShaderMixin( shader ) {

	const newShader = { ...shader };
	newShader.uniforms = {
		highlightedBatchId: { value: - 1 },
		highlightColor: { value: new Color( 0xFFC107 ).convertSRGBToLinear() },
		...UniformsUtils.clone( shader.uniforms ),
	};
	newShader.extensions = {
		derivatives: true,
	};
	newShader.lights = true;
	newShader.vertexShader =
		`
			attribute float _batchid;
			varying float batchid;
		` +
		newShader.vertexShader.replace(
			/#include <uv_vertex>/,
			`
			#include <uv_vertex>
			batchid = _batchid;
			`
		);
	newShader.fragmentShader =
		`
			varying float batchid;
			uniform float highlightedBatchId;
			uniform vec3 highlightColor;
		` +
		newShader.fragmentShader.replace(
			/vec4 diffuseColor = vec4\( diffuse, opacity \);/,
			`
			vec4 diffuseColor =
				abs( batchid - highlightedBatchId ) < 0.5 ?
				vec4( highlightColor, opacity ) :
				vec4( diffuse, opacity );
			`
		);

	return newShader;

}
Example #22
Source File: LineMaterial.js    From BlueMapWeb with MIT License 4 votes vote down vote up
ShaderLib[ 'line' ] = {

	uniforms: UniformsUtils.merge( [
		UniformsLib.common,
		UniformsLib.fog,
		UniformsLib.line
	] ),

	vertexShader:
		`
		#include <common>
		#include <color_pars_vertex>
		#include <fog_pars_vertex>
		#include <logdepthbuf_pars_vertex>
		#include <clipping_planes_pars_vertex>

		uniform float linewidth;
		uniform vec2 resolution;

		attribute vec3 instanceStart;
		attribute vec3 instanceEnd;

		attribute vec3 instanceColorStart;
		attribute vec3 instanceColorEnd;

		varying vec2 vUv;
		
		varying float vDistance;

		#ifdef USE_DASH

			uniform float dashScale;
			attribute float instanceDistanceStart;
			attribute float instanceDistanceEnd;
			varying float vLineDistance;

		#endif

		void trimSegment( const in vec4 start, inout vec4 end ) {

			// trim end segment so it terminates between the camera plane and the near plane

			// conservative estimate of the near plane
			float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column
			float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column
			float nearEstimate = - 0.5 * b / a;

			float alpha = ( nearEstimate - start.z ) / ( end.z - start.z );

			end.xyz = mix( start.xyz, end.xyz, alpha );

		}

		void main() {

			#ifdef USE_COLOR

				vColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd;

			#endif

			#ifdef USE_DASH

				vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd;

			#endif

			float aspect = resolution.x / resolution.y;

			vUv = uv;

			// camera space
			vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );
			vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );

			// special case for perspective projection, and segments that terminate either in, or behind, the camera plane
			// clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
			// but we need to perform ndc-space calculations in the shader, so we must address this issue directly
			// perhaps there is a more elegant solution -- WestLangley

			bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column

			if ( perspective ) {

				if ( start.z < 0.0 && end.z >= 0.0 ) {

					trimSegment( start, end );

				} else if ( end.z < 0.0 && start.z >= 0.0 ) {

					trimSegment( end, start );

				}

			}

			// clip space
			vec4 clipStart = projectionMatrix * start;
			vec4 clipEnd = projectionMatrix * end;

			// ndc space
			vec2 ndcStart = clipStart.xy / clipStart.w;
			vec2 ndcEnd = clipEnd.xy / clipEnd.w;

			// direction
			vec2 dir = ndcEnd - ndcStart;

			// account for clip-space aspect ratio
			dir.x *= aspect;
			dir = normalize( dir );

			// perpendicular to dir
			vec2 offset = vec2( dir.y, - dir.x );

			// undo aspect ratio adjustment
			dir.x /= aspect;
			offset.x /= aspect;

			// sign flip
			if ( position.x < 0.0 ) offset *= - 1.0;

			// endcaps
			if ( position.y < 0.0 ) {

				offset += - dir;

			} else if ( position.y > 1.0 ) {

				offset += dir;

			}

			// adjust for linewidth
			offset *= linewidth;

			// adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
			offset /= resolution.y;

			// select end
			vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd;

			// back to clip space
			offset *= clip.w;

			clip.xy += offset;

			gl_Position = clip;

			vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation
			
			vDistance = -mvPosition.z;

			#include <logdepthbuf_vertex>
			#include <clipping_planes_vertex>
			#include <fog_vertex>

		}
		`,

	fragmentShader:
		`
		#define FLT_MAX 3.402823466e+38

		uniform vec3 diffuse;
		uniform float opacity;
		
		uniform float fadeDistanceMax;
		uniform float fadeDistanceMin;

		#ifdef USE_DASH

			uniform float dashSize;
			uniform float gapSize;

		#endif

		varying float vLineDistance;

		#include <common>
		#include <color_pars_fragment>
		#include <fog_pars_fragment>
		#include <logdepthbuf_pars_fragment>
		#include <clipping_planes_pars_fragment>

		varying vec2 vUv;
		
		varying float vDistance;

		void main() {

			#include <clipping_planes_fragment>

			#ifdef USE_DASH

				if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps

				if ( mod( vLineDistance, dashSize + gapSize ) > dashSize ) discard; // todo - FIX

			#endif

			if ( abs( vUv.y ) > 1.0 ) {

				float a = vUv.x;
				float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
				float len2 = a * a + b * b;

				if ( len2 > 1.0 ) discard;

			}

			// distance fading
			float fdMax = FLT_MAX;
			if ( fadeDistanceMax > 0.0 ) fdMax = fadeDistanceMax;
			
			float minDelta = (vDistance - fadeDistanceMin) / fadeDistanceMin;
			float maxDelta = (vDistance - fadeDistanceMax) / (fadeDistanceMax * 0.5);
			float distanceOpacity = min(
				clamp(minDelta, 0.0, 1.0),
				1.0 - clamp(maxDelta + 1.0, 0.0, 1.0)
			);

			vec4 diffuseColor = vec4( diffuse, opacity * distanceOpacity );

			#include <logdepthbuf_fragment>
			#include <color_fragment>

			gl_FragColor = vec4( diffuseColor.rgb, diffuseColor.a );

			#include <tonemapping_fragment>
			#include <encodings_fragment>
			#include <fog_fragment>
			#include <premultiplied_alpha_fragment>

		}
		`
};
Example #23
Source File: AdaptiveToneMappingPass.js    From Computer-Graphics with MIT License 4 votes vote down vote up
constructor( adaptive, resolution ) {

		super();

		this.resolution = ( resolution !== undefined ) ? resolution : 256;
		this.needsInit = true;
		this.adaptive = adaptive !== undefined ? !! adaptive : true;

		this.luminanceRT = null;
		this.previousLuminanceRT = null;
		this.currentLuminanceRT = null;

		if ( CopyShader === undefined ) console.error( 'THREE.AdaptiveToneMappingPass relies on CopyShader' );

		const copyShader = CopyShader;

		this.copyUniforms = UniformsUtils.clone( copyShader.uniforms );

		this.materialCopy = new ShaderMaterial( {

			uniforms: this.copyUniforms,
			vertexShader: copyShader.vertexShader,
			fragmentShader: copyShader.fragmentShader,
			blending: NoBlending,
			depthTest: false

		} );

		if ( LuminosityShader === undefined )
			console.error( 'THREE.AdaptiveToneMappingPass relies on LuminosityShader' );

		this.materialLuminance = new ShaderMaterial( {

			uniforms: UniformsUtils.clone( LuminosityShader.uniforms ),
			vertexShader: LuminosityShader.vertexShader,
			fragmentShader: LuminosityShader.fragmentShader,
			blending: NoBlending
		} );

		this.adaptLuminanceShader = {
			defines: {
				'MIP_LEVEL_1X1': ( Math.log( this.resolution ) / Math.log( 2.0 ) ).toFixed( 1 )
			},
			uniforms: {
				'lastLum': { value: null },
				'currentLum': { value: null },
				'minLuminance': { value: 0.01 },
				'delta': { value: 0.016 },
				'tau': { value: 1.0 }
			},
			vertexShader:
				`varying vec2 vUv;

				void main() {

					vUv = uv;
					gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

				}`,

			fragmentShader:
				`varying vec2 vUv;

				uniform sampler2D lastLum;
				uniform sampler2D currentLum;
				uniform float minLuminance;
				uniform float delta;
				uniform float tau;

				void main() {

					vec4 lastLum = texture2D( lastLum, vUv, MIP_LEVEL_1X1 );
					vec4 currentLum = texture2D( currentLum, vUv, MIP_LEVEL_1X1 );

					float fLastLum = max( minLuminance, lastLum.r );
					float fCurrentLum = max( minLuminance, currentLum.r );

					//The adaption seems to work better in extreme lighting differences
					//if the input luminance is squared.
					fCurrentLum *= fCurrentLum;

					// Adapt the luminance using Pattanaik's technique
					float fAdaptedLum = fLastLum + (fCurrentLum - fLastLum) * (1.0 - exp(-delta * tau));
					// "fAdaptedLum = sqrt(fAdaptedLum);
					gl_FragColor.r = fAdaptedLum;
				}`

		};

		this.materialAdaptiveLum = new ShaderMaterial( {

			uniforms: UniformsUtils.clone( this.adaptLuminanceShader.uniforms ),
			vertexShader: this.adaptLuminanceShader.vertexShader,
			fragmentShader: this.adaptLuminanceShader.fragmentShader,
			defines: Object.assign( {}, this.adaptLuminanceShader.defines ),
			blending: NoBlending
		} );

		if ( ToneMapShader === undefined )
			console.error( 'THREE.AdaptiveToneMappingPass relies on ToneMapShader' );

		this.materialToneMap = new ShaderMaterial( {

			uniforms: UniformsUtils.clone( ToneMapShader.uniforms ),
			vertexShader: ToneMapShader.vertexShader,
			fragmentShader: ToneMapShader.fragmentShader,
			blending: NoBlending
		} );

		this.fsQuad = new FullScreenQuad( null );

	}
Example #24
Source File: DisplacementSphere.js    From personal-website-react with MIT License 4 votes vote down vote up
DisplacementSphere = (props) => {
    const { theme } = useContext(ThemeContext);
    const rgbBackground = theme === "light" ? "250 250 250" : "17 17 17";
    const width = useRef(window.innerWidth);
    const height = useRef(window.innerHeight);
    const start = useRef(Date.now());
    const canvasRef = useRef();
    const mouse = useRef();
    const renderer = useRef();
    const camera = useRef();
    const scene = useRef();
    const lights = useRef();
    const uniforms = useRef();
    const material = useRef();
    const geometry = useRef();
    const sphere = useRef();
    const tweenRef = useRef();
    const sphereSpring = useRef();
    const prefersReducedMotion = Boolean(usePrefersReducedMotion() && false); //disabled until switching themes fixed
    const isInViewport = useInViewport(canvasRef);

    useEffect(() => {
        mouse.current = new Vector2(0.8, 0.5);
        renderer.current = new WebGLRenderer({
            canvas: canvasRef.current,
            powerPreference: "high-performance",
        });
        renderer.current.setSize(width.current, height.current);
        renderer.current.setPixelRatio(1);
        renderer.current.outputEncoding = sRGBEncoding;

        camera.current = new PerspectiveCamera(
            55,
            width.current / height.current,
            0.1,
            200
        );
        camera.current.position.z = 52;

        scene.current = new Scene();

        material.current = new MeshPhongMaterial();
        material.current.onBeforeCompile = (shader) => {
            uniforms.current = UniformsUtils.merge([
                UniformsLib["ambient"],
                UniformsLib["lights"],
                shader.uniforms,
                { time: { type: "f", value: 0 } },
            ]);

            shader.uniforms = uniforms.current;
            shader.vertexShader = vertShader;
            shader.fragmentShader = fragShader;
            shader.lights = true;
        };

        geometry.current = new SphereBufferGeometry(32, 128, 128);

        sphere.current = new Mesh(geometry.current, material.current);
        sphere.current.position.z = 0;
        sphere.current.modifier = Math.random();
        scene.current.add(sphere.current);

        return () => {
            cleanScene(scene.current);
            cleanRenderer(renderer.current);
        };
    }, []);

    useEffect(() => {
        const dirLight = new DirectionalLight(
            rgbToThreeColor("250 250 250"),
            0.6
        );
        const ambientLight = new AmbientLight(
            rgbToThreeColor("250 250 250"),
            theme === "light" ? 0.8 : 0.1
        );

        dirLight.position.z = 200;
        dirLight.position.x = 100;
        dirLight.position.y = 100;

        lights.current = [dirLight, ambientLight];
        scene.current.background = rgbToThreeColor(rgbBackground);
        lights.current.forEach((light) => scene.current.add(light));

        return () => {
            removeLights(lights.current);
        };
    }, [rgbBackground, theme]);

    useEffect(() => {
        const handleResize = () => {
            const canvasHeight = innerHeight();
            const windowWidth = window.innerWidth;
            const fullHeight = canvasHeight + canvasHeight * 0.3;
            canvasRef.current.style.height = fullHeight;
            renderer.current.setSize(windowWidth, fullHeight);
            camera.current.aspect = windowWidth / fullHeight;
            camera.current.updateProjectionMatrix();

            // Render a single frame on resize when not animating
            if (prefersReducedMotion) {
                renderer.current.render(scene.current, camera.current);
            }

            if (windowWidth <= media.mobile) {
                sphere.current.position.x = 14;
                sphere.current.position.y = 10;
            } else if (windowWidth <= media.tablet) {
                sphere.current.position.x = 18;
                sphere.current.position.y = 14;
            } else {
                sphere.current.position.x = 22;
                sphere.current.position.y = 16;
            }
        };

        window.addEventListener("resize", handleResize);
        handleResize();

        return () => {
            window.removeEventListener("resize", handleResize);
        };
    }, [prefersReducedMotion]);

    useEffect(() => {
        const onMouseMove = (event) => {
            const { rotation } = sphere.current;

            const position = {
                x: event.clientX / window.innerWidth,
                y: event.clientY / window.innerHeight,
            };

            if (!sphereSpring.current) {
                sphereSpring.current = value(rotation.toArray(), (values) =>
                    rotation.set(
                        values[0],
                        values[1],
                        sphere.current.rotation.z
                    )
                );
            }

            tweenRef.current = spring({
                from: sphereSpring.current.get(),
                to: [position.y / 2, position.x / 2],
                stiffness: 30,
                damping: 20,
                velocity: sphereSpring.current.getVelocity(),
                mass: 2,
                restSpeed: 0.0001,
            }).start(sphereSpring.current);
        };

        if (!prefersReducedMotion && isInViewport) {
            window.addEventListener("mousemove", onMouseMove);
        }

        return () => {
            window.removeEventListener("mousemove", onMouseMove);

            if (tweenRef.current) {
                tweenRef.current.stop();
            }
        };
    }, [isInViewport, prefersReducedMotion]);

    useEffect(() => {
        let animation;

        const animate = () => {
            animation = requestAnimationFrame(animate);

            if (uniforms.current !== undefined) {
                uniforms.current.time.value =
                    0.00005 * (Date.now() - start.current);
            }

            sphere.current.rotation.z += 0.001;
            renderer.current.render(scene.current, camera.current);
        };

        if (!prefersReducedMotion && isInViewport) {
            animate();
        } else {
            renderer.current.render(scene.current, camera.current);
        }

        return () => {
            cancelAnimationFrame(animation);
        };
    }, [isInViewport, prefersReducedMotion]);

    return (
        <Transition appear in onEnter={reflow} timeout={3000}>
            {(status) => (
                <canvas
                    aria-hidden
                    className={classNames(
                        "displacement-sphere",
                        `displacement-sphere--${status}`
                    )}
                    ref={canvasRef}
                    {...props}
                />
            )}
        </Transition>
    );
}
Example #25
Source File: SSRrPass.js    From Computer-Graphics with MIT License 4 votes vote down vote up
constructor( { renderer, scene, camera, width, height, selects } ) {

		super();

		this.width = ( width !== undefined ) ? width : 512;
		this.height = ( height !== undefined ) ? height : 512;

		this.clear = true;

		this.renderer = renderer;
		this.scene = scene;
		this.camera = camera;

		this.output = 0;
		// this.output = 1;

		this.ior = SSRrShader.uniforms.ior.value;
		this.maxDistance = SSRrShader.uniforms.maxDistance.value;
		this.surfDist = SSRrShader.uniforms.surfDist.value;

		this.tempColor = new Color();

		this.selects = selects;

		this._specular = SSRrShader.defines.SPECULAR;
		Object.defineProperty( this, 'specular', {
			get() {

				return this._specular;

			},
			set( val ) {

				if ( this._specular === val ) return;
				this._specular = val;
				this.ssrrMaterial.defines.SPECULAR = val;
				this.ssrrMaterial.needsUpdate = true;

			}
		} );

		this._fillHole = SSRrShader.defines.FILL_HOLE;
		Object.defineProperty( this, 'fillHole', {
			get() {

				return this._fillHole;

			},
			set( val ) {

				if ( this._fillHole === val ) return;
				this._fillHole = val;
				this.ssrrMaterial.defines.FILL_HOLE = val;
				this.ssrrMaterial.needsUpdate = true;

			}
		} );

		this._infiniteThick = SSRrShader.defines.INFINITE_THICK;
		Object.defineProperty( this, 'infiniteThick', {
			get() {

				return this._infiniteThick;

			},
			set( val ) {

				if ( this._infiniteThick === val ) return;
				this._infiniteThick = val;
				this.ssrrMaterial.defines.INFINITE_THICK = val;
				this.ssrrMaterial.needsUpdate = true;

			}
		} );

		// beauty render target with depth buffer

		const depthTexture = new DepthTexture();
		depthTexture.type = UnsignedShortType;
		depthTexture.minFilter = NearestFilter;
		depthTexture.magFilter = NearestFilter;

		this.beautyRenderTarget = new WebGLRenderTarget( this.width, this.height, {
			minFilter: NearestFilter,
			magFilter: NearestFilter,
			format: RGBAFormat,
			depthTexture: depthTexture,
			depthBuffer: true
		} );

		this.specularRenderTarget = new WebGLRenderTarget( this.width, this.height, { // TODO: Can merge with refractiveRenderTarget?
			minFilter: NearestFilter,
			magFilter: NearestFilter,
			format: RGBAFormat,
		} );

		// normalSelects render target

		const depthTextureSelects = new DepthTexture();
		depthTextureSelects.type = UnsignedShortType;
		depthTextureSelects.minFilter = NearestFilter;
		depthTextureSelects.magFilter = NearestFilter;

		this.normalSelectsRenderTarget = new WebGLRenderTarget( this.width, this.height, {
			minFilter: NearestFilter,
			magFilter: NearestFilter,
			format: RGBAFormat,
			type: HalfFloatType,
			depthTexture: depthTextureSelects,
			depthBuffer: true
		} );

		// refractive render target

		this.refractiveRenderTarget = new WebGLRenderTarget( this.width, this.height, {
			minFilter: NearestFilter,
			magFilter: NearestFilter,
			format: RGBAFormat
		} );

		// ssrr render target

		this.ssrrRenderTarget = new WebGLRenderTarget( this.width, this.height, {
			minFilter: NearestFilter,
			magFilter: NearestFilter,
			format: RGBAFormat
		} );

		// ssrr material

		if ( SSRrShader === undefined ) {

			console.error( 'THREE.SSRrPass: The pass relies on SSRrShader.' );

		}

		this.ssrrMaterial = new ShaderMaterial( {
			defines: Object.assign( {}, SSRrShader.defines, {
				MAX_STEP: Math.sqrt( this.width * this.width + this.height * this.height )
			} ),
			uniforms: UniformsUtils.clone( SSRrShader.uniforms ),
			vertexShader: SSRrShader.vertexShader,
			fragmentShader: SSRrShader.fragmentShader,
			blending: NoBlending
		} );

		this.ssrrMaterial.uniforms[ 'tDiffuse' ].value = this.beautyRenderTarget.texture;
		this.ssrrMaterial.uniforms[ 'tSpecular' ].value = this.specularRenderTarget.texture;
		this.ssrrMaterial.uniforms[ 'tNormalSelects' ].value = this.normalSelectsRenderTarget.texture;
		this.ssrrMaterial.needsUpdate = true;
		this.ssrrMaterial.uniforms[ 'tRefractive' ].value = this.refractiveRenderTarget.texture;
		this.ssrrMaterial.uniforms[ 'tDepth' ].value = this.beautyRenderTarget.depthTexture;
		this.ssrrMaterial.uniforms[ 'tDepthSelects' ].value = this.normalSelectsRenderTarget.depthTexture;
		this.ssrrMaterial.uniforms[ 'cameraNear' ].value = this.camera.near;
		this.ssrrMaterial.uniforms[ 'cameraFar' ].value = this.camera.far;
		this.ssrrMaterial.uniforms[ 'resolution' ].value.set( this.width, this.height );
		this.ssrrMaterial.uniforms[ 'cameraProjectionMatrix' ].value.copy( this.camera.projectionMatrix );
		this.ssrrMaterial.uniforms[ 'cameraInverseProjectionMatrix' ].value.copy( this.camera.projectionMatrixInverse );

		// normal material

		this.normalMaterial = new MeshNormalMaterial();
		this.normalMaterial.blending = NoBlending;

		// refractiveOn material

		this.refractiveOnMaterial = new MeshBasicMaterial( {
			color: 'white'
		} );

		// refractiveOff material

		this.refractiveOffMaterial = new MeshBasicMaterial( {
			color: 'black'
		} );

		// specular material
		this.specularMaterial = new MeshStandardMaterial( {
			color: 'black',
			metalness: 0,
			roughness: .2,
		} );

		// material for rendering the depth

		this.depthRenderMaterial = new ShaderMaterial( {
			defines: Object.assign( {}, SSRrDepthShader.defines ),
			uniforms: UniformsUtils.clone( SSRrDepthShader.uniforms ),
			vertexShader: SSRrDepthShader.vertexShader,
			fragmentShader: SSRrDepthShader.fragmentShader,
			blending: NoBlending
		} );
		this.depthRenderMaterial.uniforms[ 'tDepth' ].value = this.beautyRenderTarget.depthTexture;
		this.depthRenderMaterial.uniforms[ 'cameraNear' ].value = this.camera.near;
		this.depthRenderMaterial.uniforms[ 'cameraFar' ].value = this.camera.far;

		// material for rendering the content of a render target

		this.copyMaterial = new ShaderMaterial( {
			uniforms: UniformsUtils.clone( CopyShader.uniforms ),
			vertexShader: CopyShader.vertexShader,
			fragmentShader: CopyShader.fragmentShader,
			transparent: true,
			depthTest: false,
			depthWrite: false,
			blendSrc: SrcAlphaFactor,
			blendDst: OneMinusSrcAlphaFactor,
			blendEquation: AddEquation,
			blendSrcAlpha: SrcAlphaFactor,
			blendDstAlpha: OneMinusSrcAlphaFactor,
			blendEquationAlpha: AddEquation,
			// premultipliedAlpha:true,
		} );

		this.fsQuad = new FullScreenQuad( null );

		this.originalClearColor = new Color();

	}
Example #26
Source File: SSRPass.js    From Computer-Graphics with MIT License 4 votes vote down vote up
constructor( { renderer, scene, camera, width, height, selects, bouncing = false, groundReflector } ) {

		super();

		this.width = ( width !== undefined ) ? width : 512;
		this.height = ( height !== undefined ) ? height : 512;

		this.clear = true;

		this.renderer = renderer;
		this.scene = scene;
		this.camera = camera;
		this.groundReflector = groundReflector;

		this.opacity = SSRShader.uniforms.opacity.value;
		this.output = 0;

		this.maxDistance = SSRShader.uniforms.maxDistance.value;
		this.thickness = SSRShader.uniforms.thickness.value;

		this.tempColor = new Color();

		this._selects = selects;
		this.selective = Array.isArray( this._selects );
		Object.defineProperty( this, 'selects', {
			get() {

				return this._selects;

			},
			set( val ) {

				if ( this._selects === val ) return;
				this._selects = val;
				if ( Array.isArray( val ) ) {

					this.selective = true;
					this.ssrMaterial.defines.SELECTIVE = true;
					this.ssrMaterial.needsUpdate = true;

				} else {

					this.selective = false;
					this.ssrMaterial.defines.SELECTIVE = false;
					this.ssrMaterial.needsUpdate = true;

				}

			}
		} );

		this._bouncing = bouncing;
		Object.defineProperty( this, 'bouncing', {
			get() {

				return this._bouncing;

			},
			set( val ) {

				if ( this._bouncing === val ) return;
				this._bouncing = val;
				if ( val ) {

					this.ssrMaterial.uniforms[ 'tDiffuse' ].value = this.prevRenderTarget.texture;

				} else {

					this.ssrMaterial.uniforms[ 'tDiffuse' ].value = this.beautyRenderTarget.texture;

				}

			}
		} );

		this.blur = true;

		this._distanceAttenuation = SSRShader.defines.DISTANCE_ATTENUATION;
		Object.defineProperty( this, 'distanceAttenuation', {
			get() {

				return this._distanceAttenuation;

			},
			set( val ) {

				if ( this._distanceAttenuation === val ) return;
				this._distanceAttenuation = val;
				this.ssrMaterial.defines.DISTANCE_ATTENUATION = val;
				this.ssrMaterial.needsUpdate = true;

			}
		} );


		this._fresnel = SSRShader.defines.FRESNEL;
		Object.defineProperty( this, 'fresnel', {
			get() {

				return this._fresnel;

			},
			set( val ) {

				if ( this._fresnel === val ) return;
				this._fresnel = val;
				this.ssrMaterial.defines.FRESNEL = val;
				this.ssrMaterial.needsUpdate = true;

			}
		} );

		this._infiniteThick = SSRShader.defines.INFINITE_THICK;
		Object.defineProperty( this, 'infiniteThick', {
			get() {

				return this._infiniteThick;

			},
			set( val ) {

				if ( this._infiniteThick === val ) return;
				this._infiniteThick = val;
				this.ssrMaterial.defines.INFINITE_THICK = val;
				this.ssrMaterial.needsUpdate = true;

			}
		} );

		// beauty render target with depth buffer

		const depthTexture = new DepthTexture();
		depthTexture.type = UnsignedShortType;
		depthTexture.minFilter = NearestFilter;
		depthTexture.magFilter = NearestFilter;

		this.beautyRenderTarget = new WebGLRenderTarget( this.width, this.height, {
			minFilter: NearestFilter,
			magFilter: NearestFilter,
			format: RGBAFormat,
			depthTexture: depthTexture,
			depthBuffer: true
		} );

		//for bouncing
		this.prevRenderTarget = new WebGLRenderTarget( this.width, this.height, {
			minFilter: NearestFilter,
			magFilter: NearestFilter,
			format: RGBAFormat,
		} );

		// normal render target

		this.normalRenderTarget = new WebGLRenderTarget( this.width, this.height, {
			minFilter: NearestFilter,
			magFilter: NearestFilter,
			format: RGBAFormat,
			type: HalfFloatType,
		} );

		// metalness render target

		this.metalnessRenderTarget = new WebGLRenderTarget( this.width, this.height, {
			minFilter: NearestFilter,
			magFilter: NearestFilter,
			format: RGBAFormat
		} );



		// ssr render target

		this.ssrRenderTarget = new WebGLRenderTarget( this.width, this.height, {
			minFilter: NearestFilter,
			magFilter: NearestFilter,
			format: RGBAFormat
		} );

		this.blurRenderTarget = this.ssrRenderTarget.clone();
		this.blurRenderTarget2 = this.ssrRenderTarget.clone();
		// this.blurRenderTarget3 = this.ssrRenderTarget.clone();

		// ssr material

		if ( SSRShader === undefined ) {

			console.error( 'THREE.SSRPass: The pass relies on SSRShader.' );

		}

		this.ssrMaterial = new ShaderMaterial( {
			defines: Object.assign( {}, SSRShader.defines, {
				MAX_STEP: Math.sqrt( this.width * this.width + this.height * this.height )
			} ),
			uniforms: UniformsUtils.clone( SSRShader.uniforms ),
			vertexShader: SSRShader.vertexShader,
			fragmentShader: SSRShader.fragmentShader,
			blending: NoBlending
		} );

		this.ssrMaterial.uniforms[ 'tDiffuse' ].value = this.beautyRenderTarget.texture;
		this.ssrMaterial.uniforms[ 'tNormal' ].value = this.normalRenderTarget.texture;
		this.ssrMaterial.defines.SELECTIVE = this.selective;
		this.ssrMaterial.needsUpdate = true;
		this.ssrMaterial.uniforms[ 'tMetalness' ].value = this.metalnessRenderTarget.texture;
		this.ssrMaterial.uniforms[ 'tDepth' ].value = this.beautyRenderTarget.depthTexture;
		this.ssrMaterial.uniforms[ 'cameraNear' ].value = this.camera.near;
		this.ssrMaterial.uniforms[ 'cameraFar' ].value = this.camera.far;
		this.ssrMaterial.uniforms[ 'thickness' ].value = this.thickness;
		this.ssrMaterial.uniforms[ 'resolution' ].value.set( this.width, this.height );
		this.ssrMaterial.uniforms[ 'cameraProjectionMatrix' ].value.copy( this.camera.projectionMatrix );
		this.ssrMaterial.uniforms[ 'cameraInverseProjectionMatrix' ].value.copy( this.camera.projectionMatrixInverse );

		// normal material

		this.normalMaterial = new MeshNormalMaterial();
		this.normalMaterial.blending = NoBlending;

		// metalnessOn material

		this.metalnessOnMaterial = new MeshBasicMaterial( {
			color: 'white'
		} );

		// metalnessOff material

		this.metalnessOffMaterial = new MeshBasicMaterial( {
			color: 'black'
		} );

		// blur material

		this.blurMaterial = new ShaderMaterial( {
			defines: Object.assign( {}, SSRBlurShader.defines ),
			uniforms: UniformsUtils.clone( SSRBlurShader.uniforms ),
			vertexShader: SSRBlurShader.vertexShader,
			fragmentShader: SSRBlurShader.fragmentShader
		} );
		this.blurMaterial.uniforms[ 'tDiffuse' ].value = this.ssrRenderTarget.texture;
		this.blurMaterial.uniforms[ 'resolution' ].value.set( this.width, this.height );

		// blur material 2

		this.blurMaterial2 = new ShaderMaterial( {
			defines: Object.assign( {}, SSRBlurShader.defines ),
			uniforms: UniformsUtils.clone( SSRBlurShader.uniforms ),
			vertexShader: SSRBlurShader.vertexShader,
			fragmentShader: SSRBlurShader.fragmentShader
		} );
		this.blurMaterial2.uniforms[ 'tDiffuse' ].value = this.blurRenderTarget.texture;
		this.blurMaterial2.uniforms[ 'resolution' ].value.set( this.width, this.height );

		// // blur material 3

		// this.blurMaterial3 = new ShaderMaterial({
		//   defines: Object.assign({}, SSRBlurShader.defines),
		//   uniforms: UniformsUtils.clone(SSRBlurShader.uniforms),
		//   vertexShader: SSRBlurShader.vertexShader,
		//   fragmentShader: SSRBlurShader.fragmentShader
		// });
		// this.blurMaterial3.uniforms['tDiffuse'].value = this.blurRenderTarget2.texture;
		// this.blurMaterial3.uniforms['resolution'].value.set(this.width, this.height);

		// material for rendering the depth

		this.depthRenderMaterial = new ShaderMaterial( {
			defines: Object.assign( {}, SSRDepthShader.defines ),
			uniforms: UniformsUtils.clone( SSRDepthShader.uniforms ),
			vertexShader: SSRDepthShader.vertexShader,
			fragmentShader: SSRDepthShader.fragmentShader,
			blending: NoBlending
		} );
		this.depthRenderMaterial.uniforms[ 'tDepth' ].value = this.beautyRenderTarget.depthTexture;
		this.depthRenderMaterial.uniforms[ 'cameraNear' ].value = this.camera.near;
		this.depthRenderMaterial.uniforms[ 'cameraFar' ].value = this.camera.far;

		// material for rendering the content of a render target

		this.copyMaterial = new ShaderMaterial( {
			uniforms: UniformsUtils.clone( CopyShader.uniforms ),
			vertexShader: CopyShader.vertexShader,
			fragmentShader: CopyShader.fragmentShader,
			transparent: true,
			depthTest: false,
			depthWrite: false,
			blendSrc: SrcAlphaFactor,
			blendDst: OneMinusSrcAlphaFactor,
			blendEquation: AddEquation,
			blendSrcAlpha: SrcAlphaFactor,
			blendDstAlpha: OneMinusSrcAlphaFactor,
			blendEquationAlpha: AddEquation,
			// premultipliedAlpha:true,
		} );

		this.fsQuad = new FullScreenQuad( null );

		this.originalClearColor = new Color();

	}
Example #27
Source File: SSAOPass.js    From Computer-Graphics with MIT License 4 votes vote down vote up
constructor( scene, camera, width, height ) {

		super();

		this.width = ( width !== undefined ) ? width : 512;
		this.height = ( height !== undefined ) ? height : 512;

		this.clear = true;

		this.camera = camera;
		this.scene = scene;

		this.kernelRadius = 8;
		this.kernelSize = 32;
		this.kernel = [];
		this.noiseTexture = null;
		this.output = 0;

		this.minDistance = 0.005;
		this.maxDistance = 0.1;

		this._visibilityCache = new Map();

		//

		this.generateSampleKernel();
		this.generateRandomKernelRotations();

		// beauty render target

		const depthTexture = new DepthTexture();
		depthTexture.format = DepthStencilFormat;
		depthTexture.type = UnsignedInt248Type;

		this.beautyRenderTarget = new WebGLRenderTarget( this.width, this.height );

		// normal render target with depth buffer

		this.normalRenderTarget = new WebGLRenderTarget( this.width, this.height, {
			minFilter: NearestFilter,
			magFilter: NearestFilter,
			depthTexture: depthTexture
		} );

		// ssao render target

		this.ssaoRenderTarget = new WebGLRenderTarget( this.width, this.height );

		this.blurRenderTarget = this.ssaoRenderTarget.clone();

		// ssao material

		if ( SSAOShader === undefined ) {

			console.error( 'THREE.SSAOPass: The pass relies on SSAOShader.' );

		}

		this.ssaoMaterial = new ShaderMaterial( {
			defines: Object.assign( {}, SSAOShader.defines ),
			uniforms: UniformsUtils.clone( SSAOShader.uniforms ),
			vertexShader: SSAOShader.vertexShader,
			fragmentShader: SSAOShader.fragmentShader,
			blending: NoBlending
		} );

		this.ssaoMaterial.uniforms[ 'tDiffuse' ].value = this.beautyRenderTarget.texture;
		this.ssaoMaterial.uniforms[ 'tNormal' ].value = this.normalRenderTarget.texture;
		this.ssaoMaterial.uniforms[ 'tDepth' ].value = this.normalRenderTarget.depthTexture;
		this.ssaoMaterial.uniforms[ 'tNoise' ].value = this.noiseTexture;
		this.ssaoMaterial.uniforms[ 'kernel' ].value = this.kernel;
		this.ssaoMaterial.uniforms[ 'cameraNear' ].value = this.camera.near;
		this.ssaoMaterial.uniforms[ 'cameraFar' ].value = this.camera.far;
		this.ssaoMaterial.uniforms[ 'resolution' ].value.set( this.width, this.height );
		this.ssaoMaterial.uniforms[ 'cameraProjectionMatrix' ].value.copy( this.camera.projectionMatrix );
		this.ssaoMaterial.uniforms[ 'cameraInverseProjectionMatrix' ].value.copy( this.camera.projectionMatrixInverse );

		// normal material

		this.normalMaterial = new MeshNormalMaterial();
		this.normalMaterial.blending = NoBlending;

		// blur material

		this.blurMaterial = new ShaderMaterial( {
			defines: Object.assign( {}, SSAOBlurShader.defines ),
			uniforms: UniformsUtils.clone( SSAOBlurShader.uniforms ),
			vertexShader: SSAOBlurShader.vertexShader,
			fragmentShader: SSAOBlurShader.fragmentShader
		} );
		this.blurMaterial.uniforms[ 'tDiffuse' ].value = this.ssaoRenderTarget.texture;
		this.blurMaterial.uniforms[ 'resolution' ].value.set( this.width, this.height );

		// material for rendering the depth

		this.depthRenderMaterial = new ShaderMaterial( {
			defines: Object.assign( {}, SSAODepthShader.defines ),
			uniforms: UniformsUtils.clone( SSAODepthShader.uniforms ),
			vertexShader: SSAODepthShader.vertexShader,
			fragmentShader: SSAODepthShader.fragmentShader,
			blending: NoBlending
		} );
		this.depthRenderMaterial.uniforms[ 'tDepth' ].value = this.normalRenderTarget.depthTexture;
		this.depthRenderMaterial.uniforms[ 'cameraNear' ].value = this.camera.near;
		this.depthRenderMaterial.uniforms[ 'cameraFar' ].value = this.camera.far;

		// material for rendering the content of a render target

		this.copyMaterial = new ShaderMaterial( {
			uniforms: UniformsUtils.clone( CopyShader.uniforms ),
			vertexShader: CopyShader.vertexShader,
			fragmentShader: CopyShader.fragmentShader,
			transparent: true,
			depthTest: false,
			depthWrite: false,
			blendSrc: DstColorFactor,
			blendDst: ZeroFactor,
			blendEquation: AddEquation,
			blendSrcAlpha: DstAlphaFactor,
			blendDstAlpha: ZeroFactor,
			blendEquationAlpha: AddEquation
		} );

		this.fsQuad = new FullScreenQuad( null );

		this.originalClearColor = new Color();

	}
Example #28
Source File: SMAAPass.js    From Computer-Graphics with MIT License 4 votes vote down vote up
constructor( width, height ) {

		super();

		// render targets

		this.edgesRT = new WebGLRenderTarget( width, height, {
			depthBuffer: false
		} );
		this.edgesRT.texture.name = 'SMAAPass.edges';

		this.weightsRT = new WebGLRenderTarget( width, height, {
			depthBuffer: false
		} );
		this.weightsRT.texture.name = 'SMAAPass.weights';

		// textures
		const scope = this;

		const areaTextureImage = new Image();
		areaTextureImage.src = this.getAreaTexture();
		areaTextureImage.onload = function () {

			// assigning data to HTMLImageElement.src is asynchronous (see #15162)
			scope.areaTexture.needsUpdate = true;

		};

		this.areaTexture = new Texture();
		this.areaTexture.name = 'SMAAPass.area';
		this.areaTexture.image = areaTextureImage;
		this.areaTexture.minFilter = LinearFilter;
		this.areaTexture.generateMipmaps = false;
		this.areaTexture.flipY = false;

		const searchTextureImage = new Image();
		searchTextureImage.src = this.getSearchTexture();
		searchTextureImage.onload = function () {

			// assigning data to HTMLImageElement.src is asynchronous (see #15162)
			scope.searchTexture.needsUpdate = true;

		};

		this.searchTexture = new Texture();
		this.searchTexture.name = 'SMAAPass.search';
		this.searchTexture.image = searchTextureImage;
		this.searchTexture.magFilter = NearestFilter;
		this.searchTexture.minFilter = NearestFilter;
		this.searchTexture.generateMipmaps = false;
		this.searchTexture.flipY = false;

		// materials - pass 1

		if ( SMAAEdgesShader === undefined ) {

			console.error( 'THREE.SMAAPass relies on SMAAShader' );

		}

		this.uniformsEdges = UniformsUtils.clone( SMAAEdgesShader.uniforms );

		this.uniformsEdges[ 'resolution' ].value.set( 1 / width, 1 / height );

		this.materialEdges = new ShaderMaterial( {
			defines: Object.assign( {}, SMAAEdgesShader.defines ),
			uniforms: this.uniformsEdges,
			vertexShader: SMAAEdgesShader.vertexShader,
			fragmentShader: SMAAEdgesShader.fragmentShader
		} );

		// materials - pass 2

		this.uniformsWeights = UniformsUtils.clone( SMAAWeightsShader.uniforms );

		this.uniformsWeights[ 'resolution' ].value.set( 1 / width, 1 / height );
		this.uniformsWeights[ 'tDiffuse' ].value = this.edgesRT.texture;
		this.uniformsWeights[ 'tArea' ].value = this.areaTexture;
		this.uniformsWeights[ 'tSearch' ].value = this.searchTexture;

		this.materialWeights = new ShaderMaterial( {
			defines: Object.assign( {}, SMAAWeightsShader.defines ),
			uniforms: this.uniformsWeights,
			vertexShader: SMAAWeightsShader.vertexShader,
			fragmentShader: SMAAWeightsShader.fragmentShader
		} );

		// materials - pass 3

		this.uniformsBlend = UniformsUtils.clone( SMAABlendShader.uniforms );

		this.uniformsBlend[ 'resolution' ].value.set( 1 / width, 1 / height );
		this.uniformsBlend[ 'tDiffuse' ].value = this.weightsRT.texture;

		this.materialBlend = new ShaderMaterial( {
			uniforms: this.uniformsBlend,
			vertexShader: SMAABlendShader.vertexShader,
			fragmentShader: SMAABlendShader.fragmentShader
		} );

		this.needsSwap = false;

		this.fsQuad = new FullScreenQuad( null );

	}
Example #29
Source File: SAOPass.js    From Computer-Graphics with MIT License 4 votes vote down vote up
constructor( scene, camera, useDepthTexture = false, useNormals = false, resolution = new Vector2( 256, 256 ) ) {

		super();

		this.scene = scene;
		this.camera = camera;

		this.clear = true;
		this.needsSwap = false;

		this.supportsDepthTextureExtension = useDepthTexture;
		this.supportsNormalTexture = useNormals;

		this.originalClearColor = new Color();
		this._oldClearColor = new Color();
		this.oldClearAlpha = 1;

		this.params = {
			output: 0,
			saoBias: 0.5,
			saoIntensity: 0.18,
			saoScale: 1,
			saoKernelRadius: 100,
			saoMinResolution: 0,
			saoBlur: true,
			saoBlurRadius: 8,
			saoBlurStdDev: 4,
			saoBlurDepthCutoff: 0.01
		};

		this.resolution = new Vector2( resolution.x, resolution.y );

		this.saoRenderTarget = new WebGLRenderTarget( this.resolution.x, this.resolution.y, {
			minFilter: LinearFilter,
			magFilter: LinearFilter,
			format: RGBAFormat
		} );
		this.blurIntermediateRenderTarget = this.saoRenderTarget.clone();
		this.beautyRenderTarget = this.saoRenderTarget.clone();

		this.normalRenderTarget = new WebGLRenderTarget( this.resolution.x, this.resolution.y, {
			minFilter: NearestFilter,
			magFilter: NearestFilter,
			format: RGBAFormat
		} );
		this.depthRenderTarget = this.normalRenderTarget.clone();

		let depthTexture;

		if ( this.supportsDepthTextureExtension ) {

			depthTexture = new DepthTexture();
			depthTexture.type = UnsignedShortType;

			this.beautyRenderTarget.depthTexture = depthTexture;
			this.beautyRenderTarget.depthBuffer = true;

		}

		this.depthMaterial = new MeshDepthMaterial();
		this.depthMaterial.depthPacking = RGBADepthPacking;
		this.depthMaterial.blending = NoBlending;

		this.normalMaterial = new MeshNormalMaterial();
		this.normalMaterial.blending = NoBlending;

		if ( SAOShader === undefined ) {

			console.error( 'THREE.SAOPass relies on SAOShader' );

		}

		this.saoMaterial = new ShaderMaterial( {
			defines: Object.assign( {}, SAOShader.defines ),
			fragmentShader: SAOShader.fragmentShader,
			vertexShader: SAOShader.vertexShader,
			uniforms: UniformsUtils.clone( SAOShader.uniforms )
		} );
		this.saoMaterial.extensions.derivatives = true;
		this.saoMaterial.defines[ 'DEPTH_PACKING' ] = this.supportsDepthTextureExtension ? 0 : 1;
		this.saoMaterial.defines[ 'NORMAL_TEXTURE' ] = this.supportsNormalTexture ? 1 : 0;
		this.saoMaterial.defines[ 'PERSPECTIVE_CAMERA' ] = this.camera.isPerspectiveCamera ? 1 : 0;
		this.saoMaterial.uniforms[ 'tDepth' ].value = ( this.supportsDepthTextureExtension ) ? depthTexture : this.depthRenderTarget.texture;
		this.saoMaterial.uniforms[ 'tNormal' ].value = this.normalRenderTarget.texture;
		this.saoMaterial.uniforms[ 'size' ].value.set( this.resolution.x, this.resolution.y );
		this.saoMaterial.uniforms[ 'cameraInverseProjectionMatrix' ].value.copy( this.camera.projectionMatrixInverse );
		this.saoMaterial.uniforms[ 'cameraProjectionMatrix' ].value = this.camera.projectionMatrix;
		this.saoMaterial.blending = NoBlending;

		if ( DepthLimitedBlurShader === undefined ) {

			console.error( 'THREE.SAOPass relies on DepthLimitedBlurShader' );

		}

		this.vBlurMaterial = new ShaderMaterial( {
			uniforms: UniformsUtils.clone( DepthLimitedBlurShader.uniforms ),
			defines: Object.assign( {}, DepthLimitedBlurShader.defines ),
			vertexShader: DepthLimitedBlurShader.vertexShader,
			fragmentShader: DepthLimitedBlurShader.fragmentShader
		} );
		this.vBlurMaterial.defines[ 'DEPTH_PACKING' ] = this.supportsDepthTextureExtension ? 0 : 1;
		this.vBlurMaterial.defines[ 'PERSPECTIVE_CAMERA' ] = this.camera.isPerspectiveCamera ? 1 : 0;
		this.vBlurMaterial.uniforms[ 'tDiffuse' ].value = this.saoRenderTarget.texture;
		this.vBlurMaterial.uniforms[ 'tDepth' ].value = ( this.supportsDepthTextureExtension ) ? depthTexture : this.depthRenderTarget.texture;
		this.vBlurMaterial.uniforms[ 'size' ].value.set( this.resolution.x, this.resolution.y );
		this.vBlurMaterial.blending = NoBlending;

		this.hBlurMaterial = new ShaderMaterial( {
			uniforms: UniformsUtils.clone( DepthLimitedBlurShader.uniforms ),
			defines: Object.assign( {}, DepthLimitedBlurShader.defines ),
			vertexShader: DepthLimitedBlurShader.vertexShader,
			fragmentShader: DepthLimitedBlurShader.fragmentShader
		} );
		this.hBlurMaterial.defines[ 'DEPTH_PACKING' ] = this.supportsDepthTextureExtension ? 0 : 1;
		this.hBlurMaterial.defines[ 'PERSPECTIVE_CAMERA' ] = this.camera.isPerspectiveCamera ? 1 : 0;
		this.hBlurMaterial.uniforms[ 'tDiffuse' ].value = this.blurIntermediateRenderTarget.texture;
		this.hBlurMaterial.uniforms[ 'tDepth' ].value = ( this.supportsDepthTextureExtension ) ? depthTexture : this.depthRenderTarget.texture;
		this.hBlurMaterial.uniforms[ 'size' ].value.set( this.resolution.x, this.resolution.y );
		this.hBlurMaterial.blending = NoBlending;

		if ( CopyShader === undefined ) {

			console.error( 'THREE.SAOPass relies on CopyShader' );

		}

		this.materialCopy = new ShaderMaterial( {
			uniforms: UniformsUtils.clone( CopyShader.uniforms ),
			vertexShader: CopyShader.vertexShader,
			fragmentShader: CopyShader.fragmentShader,
			blending: NoBlending
		} );
		this.materialCopy.transparent = true;
		this.materialCopy.depthTest = false;
		this.materialCopy.depthWrite = false;
		this.materialCopy.blending = CustomBlending;
		this.materialCopy.blendSrc = DstColorFactor;
		this.materialCopy.blendDst = ZeroFactor;
		this.materialCopy.blendEquation = AddEquation;
		this.materialCopy.blendSrcAlpha = DstAlphaFactor;
		this.materialCopy.blendDstAlpha = ZeroFactor;
		this.materialCopy.blendEquationAlpha = AddEquation;

		if ( UnpackDepthRGBAShader === undefined ) {

			console.error( 'THREE.SAOPass relies on UnpackDepthRGBAShader' );

		}

		this.depthCopy = new ShaderMaterial( {
			uniforms: UniformsUtils.clone( UnpackDepthRGBAShader.uniforms ),
			vertexShader: UnpackDepthRGBAShader.vertexShader,
			fragmentShader: UnpackDepthRGBAShader.fragmentShader,
			blending: NoBlending
		} );

		this.fsQuad = new FullScreenQuad( null );

	}