Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

crt renderer init #46

Open
wants to merge 21 commits into
base: main
Choose a base branch
from
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
20 changes: 19 additions & 1 deletion public/experiments.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,30 @@
[
{
"filename": "78.crt-renderer",
"title": "Crt renderer.",
"href": "/experiments/78.crt-renderer",
"tags": [],
"og": null,
"number": 78,
"contributors": []
},
{
"filename": "77.instanced-grass",
"title": "Instanced grass.",
"href": "/experiments/77.instanced-grass",
"tags": [],
"og": null,
"number": 77,
"contributors": []
"contributors": [
{
"id": "MDQ6VXNlcjgyODQ0NDQ4",
"url": "https://github.com/git-chad",
"name": "Tobi Moccagatta",
"avatarUrl": "https://avatars.githubusercontent.com/u/82844448?u=c71fc101623e8d32861d8512f379b06a3378606f&v=4",
"email": "[email protected]",
"company": "@basementstudio"
}
]
},
{
"filename": "76.butterfly-particle-sphere",
Expand Down
192 changes: 192 additions & 0 deletions src/experiments/78.crt-renderer/_components/scene.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
import { OrbitControls, PerspectiveCamera, useGLTF } from '@react-three/drei'
import { useFrame } from '@react-three/fiber'
import {
ChromaticAberration,
EffectComposer,
wrapEffect
} from '@react-three/postprocessing'
import { folder, useControls } from 'leva'
import { Effect } from 'postprocessing'
import { useCallback, useRef } from 'react'
import * as THREE from 'three'

import { fragment } from '../shaders/shaders'

class CrtEffectImpl extends Effect {
constructor() {
super('CrtEffect', fragment, {
uniforms: new Map<
string,
THREE.Uniform<number | boolean | THREE.Vector3>
>([
['uColorNum', new THREE.Uniform(4.0)],
['uPixelSize', new THREE.Uniform(4.0)],
['uThresholdOffset', new THREE.Uniform(8)],
['uTime', new THREE.Uniform(0)],
['uNoiseIntensity', new THREE.Uniform(0.0)],
['uWarpStrength', new THREE.Uniform(0.75)],
['uScanlineIntensity', new THREE.Uniform(0.25)],
['uScanlineFrequency', new THREE.Uniform(1024.0)],
['uIsMonochrome', new THREE.Uniform(false)],
[
'uMonochromeColor',
new THREE.Uniform(new THREE.Vector3(1.0, 0.5, 0.0))
]
])
})
}

update(renderer: any, inputBuffer: any, deltaTime: number) {
// @ts-expect-error
this.uniforms.get('uTime').value += deltaTime
}
}

export const CrtEffect = wrapEffect(CrtEffectImpl)

export function Scene() {
const crtEffect = useRef<CrtEffectImpl>(null)
const { scene } = useGLTF('/models/monitor.glb')

const {
colorNum,
pixelSize,
thresholdOffset,
isMonochrome,
monochromeColor,
noiseIntensity,
warpStrength,
scanlineIntensity,
scanlineFrequency
} = useControls({
Pixelation: folder({
colorNum: {
value: 2.0,
min: 2.0,
max: 8.0,
step: 1.0,
label: 'Color Numbers'
},
pixelSize: {
value: 3.0,
min: 1.0,
max: 16.0,
step: 1.0,
label: 'Pixel Size'
},
thresholdOffset: {
value: 8,
min: 0,
max: 16.0,
step: 1.0,
label: 'Threshold Offset'
}
}),

'CRT Effects': folder({
noiseIntensity: {
value: 0.15,
min: 0,
max: 1,
step: 0.01,
label: 'Noise Intensity'
},
warpStrength: {
value: 0.75,
min: 0,
max: 2,
step: 0.01,
label: 'Screen Warp'
}
}),

Scanlines: folder({
scanlineIntensity: {
value: 0.25,
min: 0,
max: 1,
step: 0.01,
label: 'Intensity'
},
scanlineFrequency: {
value: 1024,
min: 100,
max: 2048,
step: 1,
label: 'Frequency'
}
}),

'Color Mode': folder({
isMonochrome: {
value: false,
label: 'Monochrome'
},
monochromeColor: {
value: '#ff8000',
render: (get) => get('Color Mode.isMonochrome'),
label: 'Color'
}
})
})

const updateUniforms = useCallback(() => {
if (!crtEffect.current) return

const uniforms = crtEffect.current.uniforms
// @ts-expect-error
uniforms.get('uColorNum').value = colorNum
// @ts-expect-error
uniforms.get('uPixelSize').value = pixelSize
// @ts-expect-error
uniforms.get('uThresholdOffset').value = thresholdOffset
// @ts-expect-error
uniforms.get('uIsMonochrome').value = isMonochrome
// @ts-expect-error
uniforms.get('uNoiseIntensity').value = noiseIntensity
// @ts-expect-error
uniforms.get('uWarpStrength').value = warpStrength
// @ts-expect-error
uniforms.get('uScanlineIntensity').value = scanlineIntensity
// @ts-expect-error
uniforms.get('uScanlineFrequency').value = scanlineFrequency

const color = new THREE.Color(monochromeColor)
// @ts-expect-error
uniforms.get('uMonochromeColor').value.set(color.r, color.g, color.b)
}, [
colorNum,
pixelSize,
thresholdOffset,
isMonochrome,
noiseIntensity,
warpStrength,
scanlineIntensity,
scanlineFrequency,
monochromeColor
])

useFrame(() => {
updateUniforms()
})

return (
<>
<OrbitControls />

<PerspectiveCamera makeDefault position={[1, 1, 2]} fov={65} />

<ambientLight intensity={1} />
<directionalLight position={10} intensity={3} />

<primitive object={scene} position={[0, -0.5, 0]} />

<EffectComposer>
{/* @ts-expect-error */}
<ChromaticAberration offset={[0.0025, 0.0025]} />
{/* @ts-expect-error */}
<CrtEffect ref={crtEffect} />
</EffectComposer>
</>
)
}
44 changes: 44 additions & 0 deletions src/experiments/78.crt-renderer/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
'use client'

import { Environment, PerspectiveCamera } from '@react-three/drei'
import { Suspense } from 'react'
import { SRGBColorSpace } from 'three'

import { R3FCanvasLayout } from '~/components/layout/r3f-canvas-layout'

import { Scene } from './_components/scene'

function CrtRenderer() {
return (
<>
<PerspectiveCamera makeDefault position={[0, 2, 6]} fov={65} />
<Suspense fallback={null}>
<Environment
files="/textures/grass/illus_sky.hdr"
backgroundIntensity={2}
environmentIntensity={1}
background
/>
<Scene />
</Suspense>
</>
)
}

CrtRenderer.Title = 'CRT Renderer'
CrtRenderer.Description = 'CRT Renderer'

CrtRenderer.Layout = (props: any) => (
<R3FCanvasLayout
gl={{
antialias: false,
autoClear: false,
powerPreference: 'high-performance',
outputColorSpace: SRGBColorSpace,
pixelRatio: 1
}}
{...props}
/>
)

export default CrtRenderer
113 changes: 113 additions & 0 deletions src/experiments/78.crt-renderer/shaders/shaders.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
export const fragment = /* glsl */ `
precision highp float;

uniform float uColorNum;
uniform float uPixelSize;
uniform int uThresholdOffset;

uniform float uTime;

uniform float uNoiseIntensity;

uniform float uWarpStrength;

uniform float uScanlineIntensity;
uniform float uScanlineFrequency;

uniform bool uIsMonochrome;
uniform vec3 uMonochromeColor;

float random(vec2 c) {
return fract(sin(dot(c.xy, vec2(12.9898, 78.233))) * 43758.5453);
}

// 2D Noise based on Morgan McGuire @morgan3d
// https://www.shadertoy.com/view/4dS3Wd
float noise (in vec2 st) {
vec2 i = floor(st);
vec2 f = fract(st);

float a = random(i);
float b = random(i + vec2(1.0, 0.0));
float c = random(i + vec2(0.0, 1.0));
float d = random(i + vec2(1.0, 1.0));

vec2 u = f*f*(3.0-2.0*f);

return mix(a, b, u.x) +
(c - a)* u.y * (1.0 - u.x) +
(d - b) * u.x * u.y;
}


void mainUv(inout vec2 uv) {
float shake = (noise(vec2(uv.y) * sin(time * 400.0) * 100.0) - 0.5) * 0.0025;
uv.x += shake * 0.5;
}

const float bayerMatrix8x8[64] = float[64](
0.0/ 64.0, 48.0/ 64.0, 12.0/ 64.0, 60.0/ 64.0, 3.0/ 64.0, 51.0/ 64.0, 15.0/ 64.0, 63.0/ 64.0,
32.0/ 64.0, 16.0/ 64.0, 44.0/ 64.0, 28.0/ 64.0, 35.0/ 64.0, 19.0/ 64.0, 47.0/ 64.0, 31.0/ 64.0,
8.0/ 64.0, 56.0/ 64.0, 4.0/ 64.0, 52.0/ 64.0, 11.0/ 64.0, 59.0/ 64.0, 7.0/ 64.0, 55.0/ 64.0,
40.0/ 64.0, 24.0/ 64.0, 36.0/ 64.0, 20.0/ 64.0, 43.0/ 64.0, 27.0/ 64.0, 39.0/ 64.0, 23.0/ 64.0,
2.0/ 64.0, 50.0/ 64.0, 14.0/ 64.0, 62.0/ 64.0, 1.0/ 64.0, 49.0/ 64.0, 13.0/ 64.0, 61.0/ 64.0,
34.0/ 64.0, 18.0/ 64.0, 46.0/ 64.0, 30.0/ 64.0, 33.0/ 64.0, 17.0/ 64.0, 45.0/ 64.0, 29.0/ 64.0,
10.0/ 64.0, 58.0/ 64.0, 6.0/ 64.0, 54.0/ 64.0, 9.0/ 64.0, 57.0/ 64.0, 5.0/ 64.0, 53.0/ 64.0,
42.0/ 64.0, 26.0/ 64.0, 38.0/ 64.0, 22.0/ 64.0, 41.0/ 64.0, 25.0/ 64.0, 37.0/ 64.0, 21.0 / 64.0
);

vec3 dither(vec2 uv, vec3 color) {
int x = int(uv.x * resolution.x) % 8;
int y = int(uv.y * resolution.y) % 8;
float threshold = bayerMatrix8x8[y * uThresholdOffset + x] - 1.0;

color.rgb += threshold;

if (uIsMonochrome) {
float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));
gray = floor(gray * (uColorNum - 1.0) + 0.5) / (uColorNum - 1.0);
color.rgb = gray * uMonochromeColor;
} else {
color.r = floor(color.r * (uColorNum - 1.0) + 0.5) / (uColorNum - 1.0);
color.g = floor(color.g * (uColorNum - 1.0) + 0.5) / (uColorNum - 1.0);
color.b = floor(color.b * (uColorNum - 1.0) + 0.5) / (uColorNum - 1.0);
}

return color;
}

const float curve = 0.25;

void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor) {
vec2 curveUV = uv * 2.0 - 1.0;
vec2 offset = curveUV.yx * curve;
curveUV += curveUV * offset * offset;
curveUV = curveUV * 0.5 + 0.5;


vec2 normalizeduPixelSize = uPixelSize / resolution;
vec2 uvPixel = normalizeduPixelSize * floor(curveUV / normalizeduPixelSize);

vec4 color = texture2D(inputBuffer, uvPixel);
color.rgb = dither(uvPixel, color.rgb);

// Add scanlines
float scanLine = sin(curveUV.y * uScanlineFrequency) * uScanlineIntensity;
color.rgb *= (1.0 - scanLine);

// Add noise
float noise = random(curveUV + uTime) * uNoiseIntensity;
color.rgb = mix(color.rgb, vec3(1.0), noise);

// Add vignette
vec2 vignetteUV = curveUV * (1.0 - curveUV.yx);
float vignette = vignetteUV.x * vignetteUV.y * 15.0;
vignette = pow(vignette, 0.25);
color.rgb *= vignette;

vec2 edge = smoothstep(0., 0.005, curveUV)*(1.-smoothstep(1.-0.005, 1., curveUV));
color.rgb *= edge.x * edge.y;

outputColor = color;
}
`