Skip to content

Instantly share code, notes, and snippets.

@luigidenora
Created April 23, 2025 16:01
Show Gist options
  • Save luigidenora/f4e238bbc3f00e8b9a1d89b6f0b4c4af to your computer and use it in GitHub Desktop.
Save luigidenora/f4e238bbc3f00e8b9a1d89b6f0b4c4af to your computer and use it in GitHub Desktop.
DepthTexture plane
private createRenderTarget(): WebGLRenderTarget {
const width = window.innerWidth;
const height = window.innerHeight;
const target = new WebGLRenderTarget(width, height);
target.texture.minFilter = NearestFilter;
target.texture.magFilter = NearestFilter;
target.texture.generateMipmaps = false;
target.stencilBuffer = false;
target.samples = 4;
target.depthTexture = new DepthTexture(width, height);
if (DEBUG) {
const debugMaterial = new ShaderMaterial({
uniforms: {
tDepth: { value: target.depthTexture },
cameraNear: { value: this.camera.near },
cameraFar: { value: this.camera.far },
},
vertexShader: `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
uniform sampler2D tDepth;
uniform float cameraNear;
uniform float cameraFar;
varying vec2 vUv;
float linearizeDepth(float z) {
float n = cameraNear;
float f = cameraFar;
return (2.0 * n) / (f + n - z * (f - n));
}
void main() {
float depth = texture2D(tDepth, vUv).x;
float gray = linearizeDepth(depth);
gl_FragColor = vec4(vec3(gray), 1.0);
}
`,
});
const debugPlane = new Mesh(new PlaneGeometry(0.64, 0.36), debugMaterial);
debugPlane.visible = true;
const debugFolder = DEBUG.addFolder({ title: "Renderer Debug" });
debugFolder?.addBinding(debugPlane, "visible");
this.on("animate", () => {
debugPlane.position.copy(this.camera.position);
debugPlane.rotation.copy(this.camera.rotation);
debugPlane.translateZ(-1);
debugPlane.translateX(-1);
debugPlane.translateY(-0.5);
});
this.add(debugPlane);
}
this.on("viewportresize", (e) => {
if (e) target.setSize(e.width, e.height);
});
return target;
}
@luigidenora
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment