Source code for lsurf.surfaces.protocol

# The Clear BSD License
#
# Copyright (c) 2026 Tobias Heibges
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted (subject to the limitations in the disclaimer
# below) provided that the following conditions are met:
#
#      * Redistributions of source code must retain the above copyright notice,
#      this list of conditions and the following disclaimer.
#
#      * Redistributions in binary form must reproduce the above copyright
#      notice, this list of conditions and the following disclaimer in the
#      documentation and/or other materials provided with the distribution.
#
#      * Neither the name of the copyright holder nor the names of its
#      contributors may be used to endorse or promote products derived from this
#      software without specific prior written permission.
#
# NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
# THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
# CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

"""
Unified Surface Protocol

Defines the base class and enums for all surfaces in the ray tracing framework.
All surfaces follow this protocol regardless of GPU capability.

GPU-capable surfaces additionally provide signed_distance() and get_gpu_parameters()
for accelerated computation. CPU fallback (intersect, normal_at) is always available.

See registry.py for the geometry type registry.
"""

from __future__ import annotations

from abc import ABC, abstractmethod
from enum import IntEnum
from typing import TYPE_CHECKING, Any

import numpy as np
from numpy.typing import NDArray

if TYPE_CHECKING:
    from ..materials import MaterialField
    from ..propagation.kernels.registry import IntersectionKernelID


[docs] class SurfaceRole(IntEnum): """What happens when a ray hits this surface.""" DETECTOR = 1 # Record ray data and deactivate OPTICAL = 2 # Reflect/refract based on Fresnel equations ABSORBER = 3 # Apply absorption coefficient, possibly deactivate
[docs] class Surface(ABC): """ Abstract base class for all surfaces. All surfaces provide CPU-based ray intersection and normal computation. GPU-capable surfaces additionally provide signed_distance() and get_gpu_parameters() for accelerated GPU computation. Parameters ---------- role : SurfaceRole What happens when a ray hits (DETECTOR, OPTICAL, ABSORBER). name : str Human-readable identifier for the surface. material_front : MaterialField, optional Material on the front side (direction of normal). Required for OPTICAL. material_back : MaterialField, optional Material on the back side. Required for OPTICAL. Attributes ---------- role : SurfaceRole Surface role. name : str Surface identifier. material_front : MaterialField or None Front-side material. material_back : MaterialField or None Back-side material. gpu_capable : bool Whether this surface supports GPU acceleration. geometry_id : int GPU geometry type ID (0 for CPU-only surfaces). Examples -------- >>> # Check if surface can use GPU >>> if surface.gpu_capable: ... params = surface.get_gpu_parameters() ... sd = surface.signed_distance(positions) >>> else: ... distances, hits = surface.intersect(origins, directions) """ # Subclasses should override these class attributes _gpu_capable: bool = False _geometry_id: int = 0 # 0 = CPU-only, no GPU geometry # Intersection kernel compatibility declarations _supported_kernels: list[IntersectionKernelID] = [] _default_kernel: IntersectionKernelID | None = None
[docs] def __init__( self, role: SurfaceRole, name: str, material_front: "MaterialField | None" = None, material_back: "MaterialField | None" = None, kernel: "IntersectionKernelID | None" = None, ): self.role = role self.name = name self.material_front = material_front self.material_back = material_back # Validate kernel selection if kernel is None: self._kernel_id = self._default_kernel else: if self._supported_kernels and kernel not in self._supported_kernels: raise ValueError( f"{self.__class__.__name__} does not support kernel {kernel}. " f"Supported: {self._supported_kernels}" ) self._kernel_id = kernel
@property def gpu_capable(self) -> bool: """Whether this surface supports GPU acceleration.""" return self._gpu_capable @property def geometry_id(self) -> int: """ GPU geometry type ID. Returns 0 for CPU-only surfaces. GPU-capable surfaces return a positive integer registered in the geometry registry. """ return self._geometry_id # Backwards compatibility alias @property def geometry(self) -> int: """Deprecated: use geometry_id instead.""" return self._geometry_id # ========================================================================= # COMPATIBILITY QUERY METHODS # =========================================================================
[docs] @classmethod def supported_kernels(cls) -> list[IntersectionKernelID]: """ Return list of intersection kernels supported by this surface type. Returns ------- list[IntersectionKernelID] List of kernel IDs this surface supports. Examples -------- >>> from lsurf.surfaces import PlaneSurface >>> PlaneSurface.supported_kernels() [<IntersectionKernelID.PLANE_ANALYTICAL: ...>] """ return list(cls._supported_kernels)
[docs] @classmethod def default_kernel(cls) -> IntersectionKernelID | None: """ Return the default intersection kernel for this surface type. Returns ------- IntersectionKernelID or None The default kernel ID, or None if no GPU kernels are supported. """ return cls._default_kernel
@property def kernel_id(self) -> IntersectionKernelID | None: """ Return the kernel ID configured for this surface instance. Returns ------- IntersectionKernelID or None The kernel ID selected for this instance. """ return self._kernel_id
[docs] @abstractmethod def intersect( self, origins: NDArray[np.float32], directions: NDArray[np.float32], min_distance: float = 1e-6, ) -> tuple[NDArray[np.float32], NDArray[np.bool_]]: """ Compute ray-surface intersections (CPU). Parameters ---------- origins : ndarray, shape (N, 3) Ray origin positions. directions : ndarray, shape (N, 3) Ray direction unit vectors. min_distance : float, optional Minimum valid intersection distance. Default is 1e-6. Returns ------- distances : ndarray, shape (N,) Distance to intersection (inf if no hit). hit_mask : ndarray, shape (N,), dtype=bool True for rays that hit the surface. """ ...
[docs] @abstractmethod def normal_at( self, positions: NDArray[np.float32], incoming_directions: NDArray[np.float32] | None = None, ) -> NDArray[np.float32]: """ Compute surface normal at given positions. Parameters ---------- positions : ndarray, shape (N, 3) Points on the surface. incoming_directions : ndarray, shape (N, 3), optional Incoming ray directions (for orienting normals). Returns ------- normals : ndarray, shape (N, 3) Unit normal vectors. """ ...
[docs] def get_materials(self) -> tuple[Any, Any] | None: """ Return (material_front, material_back) for Fresnel calculation. Returns ------- tuple or None (material_front, material_back) for OPTICAL surfaces, None otherwise. """ if self.role == SurfaceRole.OPTICAL: return (self.material_front, self.material_back) return None
# --- GPU-specific methods (override in GPU-capable surfaces) ---
[docs] def signed_distance( self, positions: NDArray[np.float32], ) -> NDArray[np.float32]: """ Compute signed distance from positions to surface. Only available for GPU-capable surfaces. Raises NotImplementedError for CPU-only surfaces. Parameters ---------- positions : ndarray, shape (N, 3) Points to compute distance for. Returns ------- ndarray, shape (N,) Signed distance (positive on front side, negative on back side). Raises ------ NotImplementedError If surface is not GPU-capable. """ raise NotImplementedError( f"{self.__class__.__name__} does not support GPU acceleration. " "Use intersect() for CPU-based ray tracing." )
[docs] def get_gpu_parameters(self) -> tuple: """ Return parameters for GPU kernel. Only available for GPU-capable surfaces. Raises NotImplementedError for CPU-only surfaces. Returns ------- tuple Geometry-dependent parameters for GPU signed distance calculation. Raises ------ NotImplementedError If surface is not GPU-capable. """ raise NotImplementedError( f"{self.__class__.__name__} does not support GPU acceleration." )
[docs] def __repr__(self) -> str: """Return string representation.""" gpu_str = "GPU" if self.gpu_capable else "CPU" return f"{self.__class__.__name__}(name='{self.name}', role={self.role.name}, {gpu_str})"
# For backwards compatibility, also export as GPUSurface GPUSurface = Surface