File size: 12,532 Bytes
fdb3169 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 |
"""
SDF Primitives - Core geometric shape representations as Signed Distance Fields.
Following GeoSDF paper methodology.
This module contains:
- Math utilities for quartic solving (Appendix B)
- SDF primitive classes (Circle, Ellipse, Hyperbola, Parabola, Line, etc.)
"""
import torch
import torch.nn as nn
from typing import Tuple
# Device configuration
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# =============================================================================
# Quartic Solver Utilities (Following Paper Appendix B)
# =============================================================================
def solve_cubic_one_real_batch(a: torch.Tensor, b: torch.Tensor, c: torch.Tensor,
d: torch.Tensor) -> torch.Tensor:
"""Find one real root of cubic equation using Cardano's formula."""
a_safe = a + 1e-10 * torch.sign(a + 1e-20)
p = b / a_safe
q = c / a_safe
r = d / a_safe
alpha = q - p**2 / 3
beta = 2 * p**3 / 27 - p * q / 3 + r
discriminant = (beta / 2)**2 + (alpha / 3)**3
sqrt_disc = torch.sqrt(torch.clamp(discriminant, min=0) + 1e-12)
term1 = -beta / 2 + sqrt_disc
term2 = -beta / 2 - sqrt_disc
def safe_cbrt(x):
return torch.sign(x) * torch.pow(torch.abs(x) + 1e-12, 1/3)
u = safe_cbrt(term1)
v = safe_cbrt(term2)
return u + v - p / 3
def hyperbola_distance_quartic(px: torch.Tensor, py: torch.Tensor,
a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
"""Compute exact distance from point to hyperbola using Newton iteration."""
px_abs = torch.abs(px)
py_abs = torch.abs(py)
t = torch.asinh(py_abs / (b + 1e-8))
t = torch.clamp(t, 0.01, 10.0)
for _ in range(15):
cosh_t = torch.cosh(t)
sinh_t = torch.sinh(t)
hx = a * cosh_t
hy = b * sinh_t
dx = px_abs - hx
dy = py_abs - hy
grad = -2 * (dx * a * sinh_t + dy * b * cosh_t)
hess = 2 * (a**2 * sinh_t**2 + b**2 * cosh_t**2 - dx * a * cosh_t - dy * b * sinh_t) + 1e-6
step = grad / torch.abs(hess)
t = t - torch.clamp(step, -0.3, 0.3)
t = torch.clamp(t, 0.001, 20.0)
cosh_t = torch.cosh(t)
sinh_t = torch.sinh(t)
return torch.sqrt((px_abs - a * cosh_t)**2 + (py_abs - b * sinh_t)**2 + 1e-10)
def ellipse_distance_quartic(px: torch.Tensor, py: torch.Tensor,
a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
"""Compute exact distance from point to ellipse using Newton iteration."""
px_abs = torch.abs(px)
py_abs = torch.abs(py)
a_use = torch.max(a, b)
b_use = torch.min(a, b)
needs_swap = a < b
if needs_swap:
px_use, py_use = py_abs, px_abs
else:
px_use, py_use = px_abs, py_abs
at_origin = (px_use < 1e-10) & (py_use < 1e-10)
on_x_axis = py_use < 1e-10
on_y_axis = px_use < 1e-10
theta = torch.atan2(a_use * py_use, b_use * px_use)
for _ in range(12):
cos_t = torch.cos(theta)
sin_t = torch.sin(theta)
ex = a_use * cos_t
ey = b_use * sin_t
dx = px_use - ex
dy = py_use - ey
grad = 2 * (dx * a_use * sin_t - dy * b_use * cos_t)
hess = 2 * (a_use**2 * sin_t**2 + b_use**2 * cos_t**2 + dx * a_use * cos_t + dy * b_use * sin_t) + 1e-6
theta = theta - torch.clamp(grad / torch.abs(hess), -0.3, 0.3)
cos_t = torch.cos(theta)
sin_t = torch.sin(theta)
dist = torch.sqrt((px_use - a_use * cos_t)**2 + (py_use - b_use * sin_t)**2 + 1e-10)
dist = torch.where(at_origin, b_use, dist)
dist = torch.where(on_x_axis & ~at_origin, torch.where(px_use > a_use, px_use - a_use, torch.sqrt((px_use - a_use)**2 + 1e-10)), dist)
dist = torch.where(on_y_axis & ~at_origin, torch.abs(py_use - b_use), dist)
return dist
# =============================================================================
# SDF Primitives Base Class
# =============================================================================
class SDFPrimitive(nn.Module):
"""Base class for SDF primitives - all shapes represented as distance functions."""
def forward(self, p: torch.Tensor) -> torch.Tensor:
"""Compute signed distance from points p to the shape boundary."""
raise NotImplementedError
class PointSDF(SDFPrimitive):
"""SDF for a point: f(p; c) = ||p - c||₂"""
def __init__(self, center: torch.Tensor):
super().__init__()
self.center = nn.Parameter(center.clone())
def forward(self, p: torch.Tensor) -> torch.Tensor:
return torch.norm(p - self.center, dim=-1)
class CircleSDF(SDFPrimitive):
"""SDF for circle: f(p; c, r) = ||p - c||₂ - r"""
def __init__(self, center: torch.Tensor, radius: torch.Tensor):
super().__init__()
self.center = nn.Parameter(center.clone())
self.radius = nn.Parameter(radius.clone())
def forward(self, p: torch.Tensor) -> torch.Tensor:
dist_to_center = torch.norm(p - self.center, dim=-1)
return dist_to_center - self.radius
class EllipseSDF(SDFPrimitive):
"""SDF for ellipse: x²/a² + y²/b² = 1"""
def __init__(self, center: torch.Tensor, a: torch.Tensor, b: torch.Tensor):
super().__init__()
self.center = nn.Parameter(center.clone())
self.a = nn.Parameter(a.clone())
self.b = nn.Parameter(b.clone())
def forward(self, p: torch.Tensor) -> torch.Tensor:
p_local = p - self.center
px = p_local[..., 0]
py = p_local[..., 1]
a = torch.abs(self.a) + 1e-8
b = torch.abs(self.b) + 1e-8
dist = ellipse_distance_quartic(px, py, a, b)
ellipse_val = px**2 / (a**2) + py**2 / (b**2)
inside = ellipse_val < 1
return torch.where(inside, -dist, dist)
class HyperbolaSDF(SDFPrimitive):
"""SDF for hyperbola: x²/a² - y²/b² = 1"""
def __init__(self, center: torch.Tensor, a: torch.Tensor, b: torch.Tensor):
super().__init__()
self.center = nn.Parameter(center.clone())
self.a = nn.Parameter(a.clone())
self.b = nn.Parameter(b.clone())
def forward(self, p: torch.Tensor) -> torch.Tensor:
p_local = p - self.center
px = p_local[..., 0]
py = p_local[..., 1]
a = torch.abs(self.a) + 1e-8
b = torch.abs(self.b) + 1e-8
dist = hyperbola_distance_quartic(px, py, a, b)
hyperbola_val = px**2 / (a**2) - py**2 / (b**2)
is_between_branches = hyperbola_val < 1
return torch.where(is_between_branches, -dist, dist)
class ParabolaSDF(SDFPrimitive):
"""SDF for parabola: y² = 4px (rightward) or x² = 4py (upward)"""
def __init__(self, vertex: torch.Tensor, p: torch.Tensor, direction: str = 'right'):
super().__init__()
self.vertex = nn.Parameter(vertex.clone())
self.p = nn.Parameter(p.clone())
self.direction = direction
def forward(self, pts: torch.Tensor) -> torch.Tensor:
p_local = pts - self.vertex
px = p_local[..., 0]
py = p_local[..., 1]
p_param = torch.abs(self.p) + 1e-6
if self.direction == 'right':
return self._compute_distance_right(px, py, p_param)
elif self.direction == 'left':
return self._compute_distance_right(-px, py, p_param)
elif self.direction == 'up':
return self._compute_distance_right(py, px, p_param)
elif self.direction == 'down':
return self._compute_distance_right(-py, px, p_param)
return self._compute_distance_right(px, py, p_param)
def _compute_distance_right(self, px: torch.Tensor, py: torch.Tensor, p: torch.Tensor) -> torch.Tensor:
t = py.clone()
for _ in range(12):
para_x = t**2 / (4 * p)
para_y = t
dx = px - para_x
dy = py - para_y
dpara_x = t / (2 * p)
dpara_y = torch.ones_like(t)
grad = -2 * (dx * dpara_x + dy * dpara_y)
ddpara_x = 1 / (2 * p)
hess = 2 * (dpara_x**2 + dpara_y**2 - dx * ddpara_x) + 1e-8
t = t - torch.clamp(grad / torch.abs(hess), -1.0, 1.0)
para_x = t**2 / (4 * p)
para_y = t
dist = torch.sqrt((px - para_x)**2 + (py - para_y)**2 + 1e-10)
at_vertex = (torch.abs(px) < 1e-6) & (torch.abs(py) < 1e-6)
dist = torch.where(at_vertex, torch.zeros_like(dist), dist)
on_concave_side = (px >= 0) & (py**2 < 4 * p * px)
return torch.where(on_concave_side, -dist, dist)
class LineSDF(SDFPrimitive):
"""SDF for infinite line passing through point with direction."""
def __init__(self, point: torch.Tensor, direction: torch.Tensor):
super().__init__()
self.point = nn.Parameter(point.clone())
self.direction = nn.Parameter(direction / (torch.norm(direction) + 1e-8))
def forward(self, p: torch.Tensor) -> torch.Tensor:
v = p - self.point
normal = torch.tensor([-self.direction[1], self.direction[0]], device=p.device)
return (v * normal).sum(dim=-1)
class LineSegmentSDF(SDFPrimitive):
"""SDF for line segment from point a to point b."""
def __init__(self, a: torch.Tensor, b: torch.Tensor):
super().__init__()
self.a = nn.Parameter(a.clone())
self.b = nn.Parameter(b.clone())
def forward(self, p: torch.Tensor) -> torch.Tensor:
v_ab = self.b - self.a
v_ap = p - self.a
h = (v_ap * v_ab).sum(dim=-1) / (torch.norm(v_ab)**2 + 1e-8)
h_clamped = torch.clamp(h, 0, 1)
closest = self.a + h_clamped.unsqueeze(-1) * v_ab
return torch.norm(p - closest, dim=-1)
class TriangleEdgesSDF(SDFPrimitive):
"""SDF for triangle edges (boundary only)."""
def __init__(self, v0: torch.Tensor, v1: torch.Tensor, v2: torch.Tensor,
line_thickness: float = 0.02):
super().__init__()
self.edge0 = LineSegmentSDF(v0, v1)
self.edge1 = LineSegmentSDF(v1, v2)
self.edge2 = LineSegmentSDF(v2, v0)
self.thickness = line_thickness
def forward(self, p: torch.Tensor) -> torch.Tensor:
d0 = self.edge0(p)
d1 = self.edge1(p)
d2 = self.edge2(p)
return torch.min(torch.min(d0, d1), d2) - self.thickness
class TriangleFillSDF(SDFPrimitive):
"""SDF for filled triangle region."""
def __init__(self, v0: torch.Tensor, v1: torch.Tensor, v2: torch.Tensor):
super().__init__()
self.v0 = nn.Parameter(v0.clone())
self.v1 = nn.Parameter(v1.clone())
self.v2 = nn.Parameter(v2.clone())
self.edge0 = LineSegmentSDF(v0, v1)
self.edge1 = LineSegmentSDF(v1, v2)
self.edge2 = LineSegmentSDF(v2, v0)
def _sign(self, p: torch.Tensor, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
return (p[..., 0] - a[0]) * (b[1] - a[1]) - (b[0] - a[0]) * (p[..., 1] - a[1])
def forward(self, p: torch.Tensor) -> torch.Tensor:
d0 = self.edge0(p)
d1 = self.edge1(p)
d2 = self.edge2(p)
dist = torch.min(torch.min(d0, d1), d2)
s0 = self._sign(p, self.v0, self.v1)
s1 = self._sign(p, self.v1, self.v2)
s2 = self._sign(p, self.v2, self.v0)
inside = ((s0 >= 0) & (s1 >= 0) & (s2 >= 0)) | ((s0 <= 0) & (s1 <= 0) & (s2 <= 0))
return torch.where(inside, -dist, dist)
class RightAngleSDF(SDFPrimitive):
"""SDF for right angle marker."""
def __init__(self, vertex: torch.Tensor, dir1: torch.Tensor, dir2: torch.Tensor,
size: float = 0.25, thickness: float = 0.015):
super().__init__()
dir1_norm = dir1 / (torch.norm(dir1) + 1e-8)
dir2_norm = dir2 / (torch.norm(dir2) + 1e-8)
p1 = vertex + dir1_norm * size
p2 = vertex + dir2_norm * size
p3 = vertex + dir1_norm * size + dir2_norm * size
self.seg1 = LineSegmentSDF(p1, p3)
self.seg2 = LineSegmentSDF(p2, p3)
self.thickness = thickness
def forward(self, p: torch.Tensor) -> torch.Tensor:
return torch.min(self.seg1(p), self.seg2(p)) - self.thickness
|