How to calculate focus for bokeh

Hi. I have perspective camera and a scene with some 3D objects on different depth.
The idea is to focus on a selected object on the scene. For it I use bokeh. The question is: how to automaticaly calculate a focus on some object?
Thanks in advance.

Are you using the code of one of the official bokeh shaders of three.js or a custom implementation?

I’m using Bokeh from here:

For test, I’m changing focus with a slider. And it works.
But how to calculate it automatically?

You can try to study the following example:

The focal depth is calculated based on the distance from the camera to a certain object in the scene. This object is determined by a simple raycast. The following code shows this approach:

Yes, I was trying this sample, but the result was the same - all objects are blurred.
‘ldistance’ that is using here:

postprocessing.bokeh_uniforms[ 'focalDepth' ].value = ldistance;

is to big

Maybe there is a problem in your shader code. Try it with BokehShader2.

I’m not sure that a problem with the shader, because when I change the focus value with slider(I’ve attached 2 screenshots above), it works good.
And the focus is about: 0.014.
And when I tried to use code from the sample, the focus value is about 50

It seems that the parameterization of both shaders is different. I can only recommend to use BokehShader2. Otherwise you should raise an issue at:

1 Like

Ok, so you are saying, that the code that you have attached above(from the sample), works on 100%

Well, I think it works in our example :wink:

Ok. One more question: could you please clarify what is the “distance = 100”?

It’s the initial value of distance used for calculating the focal depth. This process is somewhat animated what you can see at this line.

Do you have TypeScript definitions for DoF?

Sry, I’m not using TypeScript.

Sad, very sad