def _racines(a, b, c):
"""Racines reelles de a t^2 + b t + c = 0 (cas lineaire inclus). NaN si aucune."""
eps = 1e-12
quad = a.abs() > eps
disc = b * b - 4 * a * c
sq = torch.sqrt(torch.clamp(disc, min=0.0))
den = torch.where(quad, 2 * a, torch.ones_like(a))
lin = torch.where(b.abs() > eps, -c / torch.where(b.abs() > eps, b, torch.ones_like(b)),
torch.full_like(a, float("nan")))
t1 = torch.where(quad, (-b - sq) / den, lin)
t2 = torch.where(quad, (-b + sq) / den, lin)
ok = torch.where(quad, disc > 0, b.abs() > eps)
nan = torch.full_like(a, float("nan"))
return torch.where(ok, torch.minimum(t1, t2), nan), torch.where(ok, torch.maximum(t1, t2), nan)
M0_ANN = torch.stack([c["m0"] for c in CANDIDATS[1:]]) # (12, 3)
M1_ANN = torch.stack([c["m1"] for c in CANDIDATS[1:]])
M0_PAD = torch.cat([torch.zeros(1, 3), M0_ANN], dim=0) # (13, 3) : colonne 0 = sphere
M1_PAD = torch.cat([torch.zeros(1, 3), M1_ANN], dim=0)
EST_SPHERE = torch.zeros(M_CAND, dtype=torch.bool); EST_SPHERE[0] = True
def _decoupe(o, d, ts_list, predicat, near, far):
"""o, d : (n, 3). ts_list : tenseurs (n, C). Rend (longueurs, lo, hi) en (n, C, K)."""
n = o.shape[0]
C = ts_list[0].shape[1]
ts = torch.stack([torch.full((n, C), near), torch.full((n, C), far)] + list(ts_list), dim=-1)
ts = torch.nan_to_num(ts, nan=float("inf"))
ts = torch.clamp(ts, near, far)
ts, _ = torch.sort(ts, dim=-1)
lo, hi = ts[..., :-1], ts[..., 1:]
mil = 0.5 * (lo + hi)
pts = o[:, None, None, :] + d[:, None, None, :] * mil.unsqueeze(-1)
ok = predicat(pts) & (hi > lo + 1e-9)
return (hi - lo) * ok, lo, hi
def _col0(x):
"""(n,) -> (n, M_CAND) : x en colonne 0, NaN ailleurs (sphere seule)."""
out = torch.full((x.shape[0], M_CAND), float("nan"))
out[:, 0] = x
return out
def _cols112(x):
"""(n,) ou (n, 12) -> (n, M_CAND) : NaN en colonne 0, x ensuite (anneau)."""
n = x.shape[0]
if x.dim() == 1:
x = x.unsqueeze(1).expand(n, M_CAND - 1)
return torch.cat([torch.full((n, 1), float("nan")), x], dim=1)
def _t_plan(o, d, M, c=0.0):
"""M : (C, 3). t tel que M . (o + t d) = c -> (n, C)."""
den = d @ M.T
num = c - (o @ M.T)
sur = den.abs() > 1e-12
return torch.where(sur, num / torch.where(sur, den, torch.ones_like(den)), torch.full_like(den, float("nan")))
def _pred_mixte(pts):
"""pts (n, M_CAND, K, 3). Colonne 0 = sphere, colonnes 1.. = secteurs de l'anneau."""
sph = (pts ** 2).sum(-1) < RAYON_SPHERE ** 2
r2p = pts[..., 0] ** 2 + pts[..., 1] ** 2
zp = (pts * NORMALE_ANNEAU).sum(-1)
ann = (zp.abs() < H_ANNEAU) & (r2p > R_MIN ** 2) & (r2p < R_MAX ** 2)
ann = ann & ((pts * M0_PAD[None, :, None, :]).sum(-1) >= 0) & ((pts * M1_PAD[None, :, None, :]).sum(-1) <= 0)
return torch.where(EST_SPHERE.view(1, M_CAND, 1), sph, ann)
def _geometrie(o, d, near, far):
"""Toutes les primitives d'un coup : longueurs/lo/hi en (n, M_CAND, K), 12 tranches critiques."""
n = o.shape[0]
a = (d * d).sum(-1); b = 2 * (o * d).sum(-1); c = (o * o).sum(-1) - RAYON_SPHERE ** 2
t1, t2 = _racines(a, b, c)
tp1 = _t_plan(o, d, NORMALE_ANNEAU.unsqueeze(0), -H_ANNEAU).squeeze(-1)
tp2 = _t_plan(o, d, NORMALE_ANNEAU.unsqueeze(0), H_ANNEAU).squeeze(-1)
ax = d[..., 0] ** 2 + d[..., 1] ** 2
bx = 2 * (o[..., 0] * d[..., 0] + o[..., 1] * d[..., 1])
cmin = o[..., 0] ** 2 + o[..., 1] ** 2 - R_MIN ** 2
cmax = o[..., 0] ** 2 + o[..., 1] ** 2 - R_MAX ** 2
r1, r2 = _racines(ax, bx, cmin)
r3, r4 = _racines(ax, bx, cmax)
w0 = _t_plan(o, d, M0_ANN)
w1 = _t_plan(o, d, M1_ANN)
ts = [_col0(t1), _col0(t2)] + [_cols112(t) for t in (tp1, tp2, r1, r2, r3, r4, w0, w1)]
return _decoupe(o, d, ts, _pred_mixte, near, far)
def _points_gauss(n):
"""Points et poids pour la MOYENNE sur [-1, 1] : les poids somment a 1."""
if n == 1:
return torch.tensor([0.0]), torch.tensor([1.0])
u = torch.tensor([-math.sqrt(3 / 5), 0.0, math.sqrt(3 / 5)])
return u, torch.tensor([5 / 18, 8 / 18, 5 / 18])
def _couleur_paires(o, d, lg, lo, hi, paires, n_gauss=3):
"""Couleur moyenne par paire (rayon, candidat) active, sur les DEUX segments les plus longs."""
oi, ci = paires[:, 0], paires[:, 1]
lg_p, lo_p, hi_p = lg[oi, ci], lo[oi, ci], hi[oi, ci] # (P, K)
Lp = lg_p.sum(-1) # (P,)
top, idx = lg_p.topk(2, dim=-1) # (P, 2)
lo2 = torch.gather(lo_p, -1, idx); hi2 = torch.gather(hi_p, -1, idx)
u, w = _points_gauss(n_gauss)
tg = lo2.unsqueeze(-1) + (hi2 - lo2).unsqueeze(-1) * ((u + 1) / 2)
pts = o[oi][:, None, None, :] + d[oi][:, None, None, :] * tg.unsqueeze(-1)
cc = couleur_analytique(pts) # (P, 2, G, 3)
wt = top.unsqueeze(-1) * w # (P, 2, G), somme = lg_k
return (cc * wt.unsqueeze(-1)).sum((1, 2)) / Lp.clamp_min(1e-12).unsqueeze(-1)
def rendu_analytique(theta, H=80, W=80, near=1.8, far=4.8, focal=90.0, n_gauss=3, culling=True):
"""Rendu exact : tau par decomposition en segments, couleur par Gauss sur les segments actifs."""
o, d = rayons(pose_spherique(theta), H, W, focal)
n = o.shape[0]
t_cam = torch.linalg.norm(o, dim=-1)
garde = torch.ones(n, M_CAND, dtype=torch.bool)
if culling:
pi = spineur_direction(d)
w_ = omega_rayon(o, pi, t=None)
s_c = ((CENTRES.unsqueeze(0) - o.unsqueeze(1)) * d.unsqueeze(1)).sum(-1)
r_c = residu(CENTRES.unsqueeze(0).expand(n, M_CAND, 3), w_.unsqueeze(1), pi.unsqueeze(1),
t=(t_cam.unsqueeze(1) + s_c))
garde = (r_c.norm(dim=-1) / pi.abs().norm(dim=-1).unsqueeze(1)) <= RAYONS_CAND.unsqueeze(0)
lg, lo, hi = _geometrie(o, d, near, far) # (n, M_CAND, K)
if culling:
lg = lg * garde.unsqueeze(-1)
# Seules les paires (rayon, candidat) qui traversent reellement quelque chose paient la couleur.
paires = (lg > 1e-9).any(-1).nonzero() # (P, 2)
coul = _couleur_paires(o, d, lg, lo, hi, paires, n_gauss) # (P, 3)
poids = lg[paires[:, 0], paires[:, 1]].sum(-1) # (P,)
sur_sphere = paires[:, 1] == 0
num_s = torch.zeros(n, 3).index_add_(0, paires[sur_sphere, 0],
coul[sur_sphere] * poids[sur_sphere].unsqueeze(-1))
num_r = torch.zeros(n, 3).index_add_(0, paires[~sur_sphere, 0],
coul[~sur_sphere] * poids[~sur_sphere].unsqueeze(-1))
L_s = lg[:, 0, :].sum(-1)
L_r = lg.sum((-1, -2)) - L_s
Col_s = num_s / L_s.clamp_min(1e-12).unsqueeze(-1)
Col_r = num_r / L_r.clamp_min(1e-12).unsqueeze(-1)
inf = float("inf")
Tin_s = torch.where(lg[:, 0] > 1e-9, lo[:, 0], torch.full_like(lo[:, 0], inf)).min(-1).values
Tin_r = torch.where(lg[:, 1:] > 1e-9, lo[:, 1:], torch.full_like(lo[:, 1:], inf)).min(-1).values.min(-1).values
a_s = 1 - torch.exp(-SIGMA_SPHERE * L_s)
a_r = 1 - torch.exp(-SIGMA_ANNEAU * L_r)
sphere_devant = Tin_s <= Tin_r
a1 = torch.where(sphere_devant, a_s, a_r)
c1 = torch.where(sphere_devant.unsqueeze(-1), Col_s, Col_r)
a2 = torch.where(sphere_devant, a_r, a_s)
c2 = torch.where(sphere_devant.unsqueeze(-1), Col_r, Col_s)
img = a1.unsqueeze(-1) * c1 + (1 - a1).unsqueeze(-1) * a2.unsqueeze(-1) * c2
stats = {"gardes": int(garde.sum()), "possibles": int(n * M_CAND),
"pieces_max": int((lg > 1e-9).sum(-1).max())}
return img.clamp(0, 1), stats
def psnr(a, b):
a, b = a.detach(), b.detach()
mse = float(((a - b) ** 2).mean())
return 10 * math.log10(1.0 / max(mse, 1e-12))
t0 = time.perf_counter()
vue_exacte, stats_exact = rendu_analytique(ANGLES_CIBLES[0])
duree_exacte = time.perf_counter() - t0
fig, axes = plt.subplots(1, 3, figsize=(10, 3.4))
axes[0].imshow(vue_exacte.reshape(80, 80, 3).numpy()); axes[0].set_title("forme close, 3 pts de Gauss"); axes[0].axis('off')
axes[1].imshow(vues_cibles[0].reshape(80, 80, 3).numpy()); axes[1].set_title("reference, 64 echantillons"); axes[1].axis('off')
diff = (vue_exacte - vues_cibles[0]).abs().reshape(80, 80, 3).max(-1).values
im = axes[2].imshow(diff.numpy(), cmap="inferno"); axes[2].set_title("ecart absolu (max canal)"); axes[2].axis('off')
plt.colorbar(im, ax=axes[2], fraction=0.046)
plt.tight_layout(); plt.show()
print(f"PSNR forme close contre reference : {psnr(vue_exacte, vues_cibles[0]):.2f} dB")
print(f"temps d'un rendu exact : {duree_exacte * 1000:.1f} ms")
print(f"culling : {stats_exact['gardes']} candidats gardes sur {stats_exact['possibles']} tests "
f"({100 * (1 - stats_exact['gardes'] / stats_exact['possibles']):.1f} % rejetes)")
print(f"segments non vides par rayon (max observe) : {stats_exact['pieces_max']} (le rendu en suit 2 au plus)")