WUT_Computer_Science/Programming/TRAK/code/photonmapping/python/geometry.py
Krzysztof kuhy Rudnicki 24f800d15a TRAK: zero findings, and a byte-identical render proving it
494 ruff findings to 0, and mypy --strict is clean too -- the first course in
this campaign where that is true of both.

Two real bugs turned up on the way, neither of which ruff can see:

- `main.py` passed `args.environment_map` to `ray_trace`, and argparse only
  ever defined `--environment`. Every `--algorithm ray_tracing0` run died with
  AttributeError before rendering a pixel, so `rendering.py` -- the largest
  file in the course -- had no way to be exercised at all.
- `mouse_button` in the environment-map viewer assigned `mouse_last_x/y`
  without declaring them `global`, so the drag origin went to locals and was
  thrown away. Measured against HEAD: a 10x5 px drag turned the camera by
  11.0/20.5 degrees because it measured from (0, 0); it is 1.0/0.5 now, which
  is what the 0.1 degrees-per-pixel constant says it should be.

Fixing the first one is what made the rest safe. `ray_tracing0` has no RNG
anywhere in it, so it renders byte-identically every time, and the whole
refactor of `rendering.py` is verified by one md5 comparison:
02484bdb6b6c1ddeff317d7e5566580f, 248619 rays, before and after. The
cornell_box path cannot do that -- its ray count drifts by ~20 between
identical runs.

Three files were over the 250-line cap and are now split, geometry away from
the algorithm that uses it: rendering.py 462 -> 137 + raytracer.py,
photon_mapping.py 261 -> 160 + photon_geometry.py, and
code/photonmapping/python/main.py 257 -> 203 + geometry.py. No TRAK source
file is over the cap now.

The two photon mappers do use numpy's legacy global RNG, so NPY002 could not
be bit-identical. Each was done in two steps: restructure first, verified
identical under an external seed (digests 7220370f60206a62 and
21b4771504ab2351, and an identical 828 photon traces), then the swap to
`default_rng` on its own, checked against the before/after distributions.

Verified by running, not by reading:

- cornell_box through `./run.sh run Programming/TRAK`: 24.27s, 13294 rays
- all five scenes build after `from sightpy import *` became explicit imports
- the standalone photon mapper end to end: 81.4s, 38742 photon traces
- the EXR loader byte for byte: a0c3890350ce6101247c6948, 6291456 bytes
- the GLUT viewer under xvfb-run, which drew a real 1024x512 frame

`pyproject.toml` gains a mypy override for Imath, OpenEXR, OpenGL and
matplotlib. Those four ship neither stubs nor py.typed, and without it mypy
cannot import them at all and so reports nothing else about the file.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-29 07:54:51 +02:00

120 lines
4.0 KiB
Python
Executable File

#!/usr/bin/env python3
"""Vectors, photons and the two surfaces the standalone photon mapper traces.
Split out of `main.py` so each file stays under this repo's 250-line cap; the
classes are unchanged.
"""
from __future__ import annotations
import numpy as np
# A ray whose direction is this close to parallel with a plane never hits it.
_PARALLEL_EPSILON = 1e-6
# Define basic vector operations
class Vector3:
"""A 3D vector, with just the operations this renderer needs."""
def __init__(self, x: float, y: float, z: float) -> None:
"""Store the three components."""
self.x = x
self.y = y
self.z = z
def __add__(self, other: Vector3) -> Vector3:
"""Return the component-wise sum."""
return Vector3(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other: Vector3) -> Vector3:
"""Return the component-wise difference."""
return Vector3(self.x - other.x, self.y - other.y, self.z - other.z)
def __mul__(self, scalar: float) -> Vector3:
"""Return this vector scaled by `scalar`."""
return Vector3(self.x * scalar, self.y * scalar, self.z * scalar)
def dot(self, other: Vector3) -> float:
"""Return the dot product with `other`."""
return self.x * other.x + self.y * other.y + self.z * other.z
def norm(self) -> float:
"""Return the length of this vector."""
return float(np.sqrt(self.dot(self)))
def normalize(self) -> Vector3:
"""Return a new vector of unit length pointing the same way."""
n = self.norm()
return Vector3(self.x / n, self.y / n, self.z / n)
# Define the photon
class Photon:
"""A packet of light energy travelling in a straight line."""
def __init__(
self, position: Vector3, direction: Vector3, power: np.ndarray
) -> None:
"""Store where the photon is, where it is going, and what it carries."""
self.position = position
self.direction = direction
self.power = power
# Define a simple sphere
class Sphere:
"""A sphere of uniform colour."""
def __init__(self, center: Vector3, radius: float, color: np.ndarray) -> None:
"""Store the sphere's geometry and colour."""
self.center = center
self.radius = radius
self.color = color
def intersect(
self, ray_origin: Vector3, ray_direction: Vector3
) -> tuple[float, Vector3, Vector3] | None:
"""Return the nearest hit as (distance, point, normal), or None."""
# Solve quadratic equation for intersection
oc = ray_origin - self.center
a = ray_direction.dot(ray_direction)
b = 2.0 * oc.dot(ray_direction)
c = oc.dot(oc) - self.radius * self.radius
discriminant = b * b - 4 * a * c
if discriminant < 0:
return None # No intersection
t = (-b - np.sqrt(discriminant)) / (2.0 * a)
if t < 0:
t = (-b + np.sqrt(discriminant)) / (2.0 * a)
if t < 0:
return None
hit_point = ray_origin + ray_direction * t
normal = (hit_point - self.center).normalize()
return (t, hit_point, normal)
# Define a simple plane
class Plane:
"""An infinite plane of uniform colour."""
def __init__(self, point: Vector3, normal: Vector3, color: np.ndarray) -> None:
"""Store a point on the plane, its (normalised) normal, and its colour."""
self.point = point
self.normal = normal.normalize()
self.color = color
def intersect(
self, ray_origin: Vector3, ray_direction: Vector3
) -> tuple[float, Vector3, Vector3] | None:
"""Return the nearest hit as (distance, point, normal), or None."""
denom = self.normal.dot(ray_direction)
if abs(denom) > _PARALLEL_EPSILON:
t = (self.point - ray_origin).dot(self.normal) / denom
if t >= 0:
hit_point = ray_origin + ray_direction * t
return (t, hit_point, self.normal)
return None
Surface = Sphere | Plane