Monday, January 6, 2025

Now the Guru and his disciple are looking together at the same direction... A discussion on Ray Tracing...

I must admit that when my young son Ridit used to exclaim,"Baba, you know Blender's Cycles rendering engine uses Ray Tracing" - i was absolutely blank, as I didn't possess any knowledge about the details of Computer Graphics. But I am happy that those days are over. Now I am going through the nitty gritty of Computer Graphics and trying to get into their application in real-life open source projects.

This is my today's update on Ray Tracing.

Here is the Python code for FreeCAD ray tracing example.

import FreeCAD

import Part

def create_sphere(center, radius):

    """Creates a sphere in FreeCAD and makes it visible."""

    sphere = Part.makeSphere(radius, center)

    obj = App.ActiveDocument.addObject("Part::Feature", "Sphere")

    obj.Shape = sphere

    obj.ViewObject.Visibility = True  # Ensure visibility

    return sphere


def create_ray(origin, direction, length=100):

    """Creates a ray as a visual line."""

    start = origin

    end = FreeCAD.Vector(

        origin.x + direction.x * length,

        origin.y + direction.y * length,

        origin.z + direction.z * length

    )

    ray = Part.LineSegment(start, end)

    obj = App.ActiveDocument.addObject("Part::Feature", "Ray")

    obj.Shape = ray.toShape()

    obj.ViewObject.Visibility = True  # Ensure visibility

    return ray


def ray_sphere_intersection(ray_origin, ray_dir, sphere_center, sphere_radius):

    """Computes the intersection of a ray and a sphere."""

    oc = ray_origin - sphere_center

    a = ray_dir.dot(ray_dir)

    b = 2.0 * oc.dot(ray_dir)

    c = oc.dot(oc) - sphere_radius ** 2

    discriminant = b * b - 4 * a * c

    

    if discriminant < 0:

        return None  # No intersection

    else:

        t = (-b - discriminant ** 0.5) / (2.0 * a)

        if t < 0:

            return None  # Intersection is behind the ray origin

        intersection = ray_origin + ray_dir * t

        return intersection


# Clear existing objects and start a new document

App.newDocument("RayTracing")

doc = App.ActiveDocument

doc.clearAllObjects()


# Scene setup

sphere_center = FreeCAD.Vector(0, 0, 0)

sphere_radius = 10

create_sphere(sphere_center, sphere_radius)


ray_origin = FreeCAD.Vector(-20, 0, 0)

ray_direction = FreeCAD.Vector(1, 0, 0).normalize()

create_ray(ray_origin, ray_direction)


# Ray tracing

intersection = ray_sphere_intersection(ray_origin, ray_direction, sphere_center, sphere_radius)

if intersection:

    print("Ray intersects the sphere at:", intersection)

    # Add a visual point at the intersection

    intersection_point = Part.Vertex(intersection)

    obj = App.ActiveDocument.addObject("Part::Feature", "IntersectionPoint")

    obj.Shape = intersection_point

    obj.ViewObject.Visibility = True

else:

    print("Ray does not intersect the sphere.")


# Recompute the FreeCAD document to display objects

doc.recompute()


If you run the above code in the Python console of FreeCAD, the result will be as shown in the image.




Ray Tracing is a rendering technique in computer graphics used to simulate the way light interacts with objects to produce realistic images. It traces the path of rays of light as they travel through a scene, capturing their interactions with surfaces, such as reflection, refraction, and shadows. This technique is widely used for generating high-quality and photorealistic images.

How Ray Tracing Works

  1. Ray Generation:

    • Rays are cast from the camera (or eye) through each pixel on the image plane into the scene.
  2. Intersection Testing:

    • For each ray, the algorithm determines whether it intersects any object in the scene.
    • The closest intersection point is considered the point of interaction.
  3. Shading:

    • At the intersection point, calculations are performed to determine the color and intensity of light, taking into account:
      • Surface properties (e.g., texture, reflectivity, transparency).
      • Light sources and their contributions (e.g., diffuse and specular reflection).
  4. Secondary Rays:

    • Reflection Rays: For shiny surfaces, rays are traced in the mirror direction.
    • Refraction Rays: For transparent objects, rays are bent based on the material's refractive index.
    • Shadow Rays: Rays are cast toward light sources to determine if the point is in shadow.
  5. Recursive Tracing:

    • Secondary rays are recursively traced to simulate global illumination effects like multiple reflections and refractions.
  6. Image Formation:

    • The final color of each pixel is determined by combining the contributions of all rays.

Advantages of Ray Tracing

  1. Realism:

    • Accurately simulates lighting effects such as shadows, reflections, refractions, and caustics.
  2. Global Illumination:

    • Captures indirect lighting, making scenes look more natural and photorealistic.
  3. Flexibility:

    • Works well with complex geometries and materials.

Disadvantages

  1. Performance:
    • Computationally expensive due to the large number of rays and recursive tracing.
  2. Real-Time Challenges:
    • Historically unsuitable for real-time rendering (like games) until advancements in GPU technology.

Applications

  1. Movies and Visual Effects:

    • Used in rendering high-quality frames for animated movies and CGI.
  2. Architecture:

    • Simulates realistic lighting for architectural visualizations.
  3. Games:

    • Modern GPUs (e.g., NVIDIA RTX series) enable real-time ray tracing for improved visual fidelity in games.
  4. Product Design:

    • Used in CAD software for rendering photorealistic previews of designs.

Simplified Example of Ray Tracing Algorithm

Vector3 rayDirection = normalize(pixelPosition - cameraPosition);
Intersection hit = trace(rayOrigin, rayDirection);

if (hit) {
    Color pixelColor = computeLighting(hit.position, hit.normal, hit.material);
    image.setPixel(x, y, pixelColor);
} else {
    image.setPixel(x, y, backgroundColor);
}

Recent Advances

  1. Real-Time Ray Tracing:

    • Technologies like NVIDIA's RTX and DirectX Raytracing (DXR) enable real-time ray tracing in games and interactive applications.
  2. Hybrid Techniques:

    • Combines ray tracing and rasterization for optimal performance and quality.
  3. Path Tracing:

    • An extension of ray tracing that simulates global illumination by averaging multiple rays for more realistic results.

Ray tracing is at the forefront of rendering innovation, bridging the gap between realism and interactivity.

I hope you like this post.

Fatherhood is one of my best phases of life. I have learnt many aspects of software to train my son...

Jai Hind...

No comments: