|
| 1 | +import { BlendFunction, Effect, EffectAttribute } from 'postprocessing' |
| 2 | +import type { Ref } from 'react' |
| 3 | +import { Uniform } from 'three' |
| 4 | +import { createEffectComponent } from '../createEffectComponent' |
| 5 | + |
| 6 | +const SharpnessShader = { |
| 7 | + fragmentShader: /* glsl */ ` |
| 8 | + uniform float sharpness; |
| 9 | + uniform float radius; |
| 10 | +
|
| 11 | + void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor) { |
| 12 | + vec2 dx = vec2(texelSize.x * radius, 0.0); |
| 13 | + vec2 dy = vec2(0.0, texelSize.y * radius); |
| 14 | +
|
| 15 | + vec3 center = texture2D(inputBuffer, uv).rgb; |
| 16 | + vec3 neighbors = texture2D(inputBuffer, uv - dx).rgb |
| 17 | + + texture2D(inputBuffer, uv + dx).rgb |
| 18 | + + texture2D(inputBuffer, uv - dy).rgb |
| 19 | + + texture2D(inputBuffer, uv + dy).rgb; |
| 20 | +
|
| 21 | + // Laplacian sharpen, sharpness 1 is the classic 5 / -1 kernel |
| 22 | + vec3 color = center + sharpness * (4.0 * center - neighbors); |
| 23 | + outputColor = vec4(max(color, 0.0), inputColor.a); |
| 24 | + } |
| 25 | + `, |
| 26 | +} |
| 27 | + |
| 28 | +export class SharpnessEffect extends Effect { |
| 29 | + constructor({ blendFunction = BlendFunction.NORMAL, sharpness = 1, radius = 1 } = {}) { |
| 30 | + super('SharpnessEffect', SharpnessShader.fragmentShader, { |
| 31 | + blendFunction, |
| 32 | + attributes: EffectAttribute.CONVOLUTION, |
| 33 | + uniforms: new Map<string, Uniform<number>>([ |
| 34 | + ['sharpness', new Uniform(sharpness)], |
| 35 | + ['radius', new Uniform(radius)], |
| 36 | + ]), |
| 37 | + }) |
| 38 | + } |
| 39 | + |
| 40 | + /** Sharpening strength, 0 disables it. */ |
| 41 | + get sharpness(): number { |
| 42 | + return this.uniforms.get('sharpness')!.value |
| 43 | + } |
| 44 | + |
| 45 | + set sharpness(value: number) { |
| 46 | + this.uniforms.get('sharpness')!.value = value |
| 47 | + } |
| 48 | + |
| 49 | + /** Distance to the sampled neighbors in pixels. */ |
| 50 | + get radius(): number { |
| 51 | + return this.uniforms.get('radius')!.value |
| 52 | + } |
| 53 | + |
| 54 | + set radius(value: number) { |
| 55 | + this.uniforms.get('radius')!.value = value |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +export type SharpnessProps = { |
| 60 | + blendFunction?: BlendFunction |
| 61 | + opacity?: number |
| 62 | + sharpness?: number |
| 63 | + radius?: number |
| 64 | + ref?: Ref<SharpnessEffect> |
| 65 | +} |
| 66 | + |
| 67 | +export const Sharpness = /* @__PURE__ */ createEffectComponent<typeof SharpnessEffect, SharpnessProps>(SharpnessEffect) |
0 commit comments