Image_SDF / src /sdf_geo /renderer.py
WendingGao's picture
Upload 22 files
fdb3169 verified
"""
SDF Renderer Module
Visualization utilities for SDF fields and zero-level sets.
"""
import torch
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from typing import Tuple, Optional
class SDFRenderer:
"""
Renderer for SDF fields and zero-level sets.
Creates visualization grids and renders SDF values.
"""
def __init__(self, resolution: int = 512,
xlim: Tuple[float, float] = (-5, 5),
ylim: Tuple[float, float] = (-5, 5)):
self.resolution = resolution
self.xlim = xlim
self.ylim = ylim
# Create evaluation grid
x = torch.linspace(xlim[0], xlim[1], resolution)
y = torch.linspace(ylim[0], ylim[1], resolution)
self.xx, self.yy = torch.meshgrid(x, y, indexing='xy')
self.grid = torch.stack([self.xx, self.yy], dim=-1)
# Custom colormap for SDF visualization
self.sdf_cmap = LinearSegmentedColormap.from_list(
'sdf', ['#2E86AB', '#FFFFFF', '#E74C3C'], N=256
)
def render_sdf_field(self, sdf, ax: plt.Axes,
show_field: bool = True,
field_alpha: float = 0.3) -> np.ndarray:
"""
Render SDF field and zero-level set.
Args:
sdf: SDF primitive to render
ax: Matplotlib axes
show_field: Show background SDF field
field_alpha: Alpha for background field
Returns:
SDF values as numpy array
"""
with torch.no_grad():
# Evaluate SDF on grid
grid_flat = self.grid.reshape(-1, 2)
distances = sdf(grid_flat).reshape(self.resolution, self.resolution)
distances_np = distances.cpu().numpy()
# Show SDF field as background
if show_field:
max_val = min(np.abs(distances_np).max(), 10)
ax.contourf(self.xx.numpy(), self.yy.numpy(), distances_np,
levels=50, cmap=self.sdf_cmap, alpha=field_alpha,
vmin=-max_val, vmax=max_val)
# Draw zero-level set (the curve)
ax.contour(self.xx.numpy(), self.yy.numpy(), distances_np,
levels=[0], colors=['#2E86AB'], linewidths=2.5)
return distances_np
def render_multiple(self, sdfs: list, ax: plt.Axes,
colors: Optional[list] = None) -> None:
"""Render multiple SDFs on the same axes."""
if colors is None:
colors = ['#2E86AB', '#E74C3C', '#27AE60', '#9B59B6', '#F39C12']
with torch.no_grad():
grid_flat = self.grid.reshape(-1, 2)
for i, sdf in enumerate(sdfs):
distances = sdf(grid_flat).reshape(self.resolution, self.resolution)
distances_np = distances.cpu().numpy()
color = colors[i % len(colors)]
ax.contour(self.xx.numpy(), self.yy.numpy(), distances_np,
levels=[0], colors=[color], linewidths=2.5)