Scene color
Last updated
Last updated
You can access the color in the scene behind object for certain effects like screen space refraction. This is especially useful in visual effects to create the effects like shockwaves or heat distortion.
The code below shows how we can get the color from the scene behind the fragment we render. By using the screenUV coordinate, we get the color immediately behind the object from the direction of the camera. If we output this color, the object would appear completely transparent.
import { sampleSceneColor, screenUV, RgbaNode } from "@hology/core/shader-nodes";
const color: RgbaNode = sampleSceneColor(screenUV)
To create various effects like heat distortions of shockwaves, you would simply add an offset to this coordinate which is demonstrated in the example below.
We can create the effect shown in the image below using a sprite and sample the color behind it with an animated offset.
import { SpriteNodeShader } from '@hology/core';
import { distance, normalize, oneMinus, particleUniforms, sampleSceneColor, screenUV, sin, smoothstep, timeUniforms, varyingAttributes, vec2 } from "@hology/core/shader-nodes";
import { NodeShaderOutput, Parameter } from "@hology/core/shader/shader";
export default class ShockwaveShader extends SpriteNodeShader {
@Parameter()
distortionStrength: number = 0.05
@Parameter()
waveScale: number = 20
@Parameter()
waveSpeed: number = 0.2
@Parameter()
fadeDistance: number = 0.1
output(): NodeShaderOutput {
const center = vec2(0.5)
const dir = normalize(varyingAttributes.uv.subtract(center))
const dist = distance(varyingAttributes.uv, center)
const alpha = smoothstep(0.5, 0.5 + this.fadeDistance, oneMinus(dist))
const wave = sin(
dist.subtract(timeUniforms.elapsed.multiply(this.waveSpeed)).multiply(this.waveScale)
).multiply(this.distortionStrength).multiply(alpha)
const offset = dir.multiplyScalar(wave)
const sample = sampleSceneColor(screenUV.add(offset)).rgb
return {
color: sample.rgba(alpha.multiply(particleUniforms.opacity)),
transparent: false
}
}
}