使用vertexShader求深度值。

This commit is contained in:
tengge1 2019-11-23 21:48:50 +08:00
parent 5439ae5da8
commit b28666a2fb
3 changed files with 14 additions and 10 deletions

View File

@ -163,7 +163,7 @@ GPUPickEvent.prototype.onAfterRender = function () {
hex = -hex;
}
let depth = hex * (camera.far - camera.near) + camera.near;
let depth = hex * camera.far;
this.world.set(
this.offsetX / width * 2 - 1,
@ -172,7 +172,7 @@ GPUPickEvent.prototype.onAfterRender = function () {
);
this.world.unproject(camera);
console.log(`${hex},${depth}, ${this.world.x}, ${this.world.y}, ${this.world.z}`);
console.log(`(${this.pixel[0]},${this.pixel[1]},${this.pixel[2]}),${depth}, ${this.world.x}, ${this.world.y}, ${this.world.z}`);
// 还原原来的属性
scene.background = oldBackground;

View File

@ -1,20 +1,18 @@
precision highp float;
uniform float near;
uniform float far;
varying float depth;
void main() {
// 参考1https://stackoverflow.com/questions/6408851/draw-the-depth-value-in-opengl-using-shaders
// 参考2https://gamedev.stackexchange.com/questions/93055/getting-the-real-fragment-depth-in-glsl
float ndcDepth = (gl_FragCoord.z - near) / (far - near);
float clipDepth = ndcDepth / gl_FragCoord.w;
// 参考https://gamedev.stackexchange.com/questions/93055/getting-the-real-fragment-depth-in-glsl
// float ndcDepth = (gl_FragCoord.z - near) / (far - near);
// float clipDepth = ndcDepth / gl_FragCoord.w;
float hex = abs(clamp(clipDepth, -1.0, 1.0)) * 16777215.0; // 0xffffff
float hex = abs(clamp(depth, -1.0, 1.0)) * 16777215.0; // 0xffffff
float r = floor(hex / 65535.0);
float g = floor((hex - r * 65535.0) / 255.0);
float b = floor(hex - r * 65535.0 - g * 255.0);
float a = sign(clipDepth) >= 0.0 ? 1.0 : 0.0; // depth大于等于0为1.0小于0为0.0。
float a = sign(depth) >= 0.0 ? 1.0 : 0.0; // depth大于等于0为1.0小于0为0.0。
gl_FragColor = vec4(r / 255.0, g / 255.0, b / 255.0, a);
}

View File

@ -1,5 +1,11 @@
precision highp float;
uniform float far;
varying float depth;
void main() {
// 参考https://stackoverflow.com/questions/6408851/draw-the-depth-value-in-opengl-using-shaders
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
depth = gl_Position.z / far;
}