Files
ViewDesignEngine/include/vde/sdf/sdf_gradient.h
T
茂之钳 08b5854c56
CI / Build & Test (push) Failing after 16m59s
CI / Release Build (push) Failing after 42s
feat(sdf): S12-C PyTorch integration + Python bindings
Add batch evaluation/gradient functions for SDF trees (sdf_torch.h/cpp).
Add sdf_gradient.h with finite-difference gradient utilities.
Add Python modules vde.sdf (high-level SDF API) and vde.torch_sdf (PyTorch autograd).
Add test_sdf_torch_bridge.cpp with batch eval/gradient tests.
Integrate into vde_sdf library and test suite.
2026-07-24 07:20:45 +00:00

39 lines
1.3 KiB
C++

#pragma once
#include "vde/core/point.h"
#include <functional>
#include <tuple>
namespace vde::sdf {
using core::Point3D;
using core::Vector3D;
/// Compute numerical gradient of a scalar field f at point p
/// Uses central finite differences with step size h
template <typename Fn>
[[nodiscard]] Vector3D gradient(Fn&& f, const Point3D& p, double h = 1e-6) {
double fx = f(p);
const double eps_x = h * (1.0 + std::abs(p.x()));
const double eps_y = h * (1.0 + std::abs(p.y()));
const double eps_z = h * (1.0 + std::abs(p.z()));
double dfdx = (f(Point3D(p.x() + eps_x, p.y(), p.z())) -
f(Point3D(p.x() - eps_x, p.y(), p.z()))) / (2.0 * eps_x);
double dfdy = (f(Point3D(p.x(), p.y() + eps_y, p.z())) -
f(Point3D(p.x(), p.y() - eps_y, p.z()))) / (2.0 * eps_y);
double dfdz = (f(Point3D(p.x(), p.y(), p.z() + eps_z)) -
f(Point3D(p.x(), p.y(), p.z() - eps_z))) / (2.0 * eps_z);
return Vector3D(dfdx, dfdy, dfdz);
}
/// Evaluate scalar field and its gradient at point p (joint pass)
/// Returns (value, gradient)
template <typename Fn>
[[nodiscard]] std::tuple<double, Vector3D> evaluate_with_gradient(
Fn&& f, const Point3D& p, double h = 1e-6) {
return {f(p), gradient(std::forward<Fn>(f), p, h)};
}
} // namespace vde::sdf