# Theoretical basis of Raycaster

Hi, I’m new here using threejs to develop.I would like to know which literatures the algorithm of class raycaster corresponds to. How is the accuracy of the current algorithm?

Tbh, the built-in raycasting is as basic as it gets (optimisation of the raycasting makes sense mostly only on per-project basis, so it’s dev responsibility to extend it as they see fit.)

1. Instance of Ray is created when creating a Raycaster. Raycaster re-uses just a single ray over and over.

2. Usually, you call Raycaster.intersectObjects - which is just a looped version of a singular Raycaster.intersectObject.

3. intersectObject is an external function that just calls Object3D.raycast method on every object you passed as possible targets (every class extending Object3D can have it’s own way of determining whether the ray hit the object or not.)

4. For Mesh objects (which extend Object3D) - first, method checks if the ray is within a bounding sphere of the object. If it’s not, it doesn’t make sense to continue calculations, since the ray is likely far away.

5. The method then loops through faces of the geometry assigned to the Mesh (for example here, depending on properties of the geometry, another if may trigger.) It uses external checkBufferGeometryIntersection to check the intersections between a ray and a face.

6. You can skip this and this part. It’s just calculating morph target and current animation frame influence on the face. This line jumps to the actual collision testing here.

7. Three tests only faces that point in the opposite direction of the rays direction - hence the Three.BackFace check.

8. The checkIntersection method calls Ray.intersectTriangle - a copy-paste mathemagical formula to determine whether a line intersects a triangle (source fork, if for some reason you prefer C to JS )

9. Afterwards, if the collision occurs, the chain goes all the way back - collecting the exact intersection point (pixel-perfect precision, if that’s what you asked about), the face details, face index, material information, object reference etc.

(If what you are looking is specific theory behind something-to-something intersection, these are the authors of the triangle-to-ray intersection math three uses - and they do seem to have tons of books for sale on the topic Mind, it’s mostly theory and in practice you don’t really need that knowledge to create stuff.)

2 Likes