user8475519
user8475519

Reputation:

Is there a way to read depth value from WebGLRenderTarget to buffer( js)?

I'm trying to read depth values from framebuffer/WebGLRenderTarget into an array. I can find information to render depth to depth Texture, but could not read the depth to a buffer. With readpixels i could only get rbga values. Ideally i am trying to get worldposition from depth and ray.

I have tried reading pixels, but dont know how to read depth in threejs.

Upvotes: 0

Views: 1912

Answers (1)

user128511
user128511

Reputation:

Off the top of my head it's not possible to read depth values directly.

You can set a DepthTexture to your WebGLRenderTarget's depthTexture property. You can then render all or part of that depth texture to another render target and read the result.

'use strict';

/* global THREE */

const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({canvas});

const fov = 75;
const aspect = 2;  // the canvas default
const near = 0.01;
const far = 5;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.z = 0.7;

const scene = new THREE.Scene();
const geometry = new THREE.BoxBufferGeometry();
const material = new THREE.MeshBasicMaterial({color: 'red'});
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
cube.position.x = 0.25;
cube.rotation.y = Math.PI * 0.25;
 
const depthTexture = new THREE.DepthTexture(canvas.width, canvas.height);
const rt = new THREE.WebGLRenderTarget(canvas.width, canvas.height, {
  depthTexture,
});

renderer.setRenderTarget(rt);
renderer.render(scene, camera);

const planeScene = new THREE.Scene();
const planeGeo = new THREE.PlaneBufferGeometry(2, 2);
const planeMat = new THREE.MeshBasicMaterial({map: depthTexture});
const plane = new THREE.Mesh(planeGeo, planeMat);
planeScene.add(plane);
const ortho = new THREE.OrthographicCamera(-1, 1, 1, -1, -1, 1)
const planeRT = new THREE.WebGLRenderTarget(canvas.width, canvas.height, {type: THREE.FloatType});
renderer.setRenderTarget(planeRT);
renderer.render(planeScene, ortho);

const depths = new Float32Array(canvas.width * canvas.height * 4);
renderer.readRenderTargetPixels(planeRT, 0, 0, canvas.width, canvas.height, depths);

console.log(depths);
<canvas id="c" width="4" height="4"></canvas>
<script src="https://threejsfundamentals.org/threejs/resources/threejs/r105/three.min.js"></script>

Upvotes: 5

Related Questions