Files
ViewDesignEngine/src/mesh/point_cloud.cpp
T
hm d2f0a40d10 fix(brep,mesh): entity diagnostics/ref validation + robust polygon triangulation (VDE-1342..1345, 1.0.176)
- VDE-1345 mesh: to_mcm ear-clips n>3 faces (Newell normal + 2D ear clipping,
  fallback to fan on degeneracy) and maps local triangle indices back to face
  vertices; empty HalfedgeMesh/PointCloud bounds return a finite zero box;
  faces_range()/vertex_one_ring() implemented (FaceRange iterator, adjacency
  from vertex outgoing half-edges).
- VDE-1342 FeatureNode: last_error()/last_evaluate_ok() diagnostics, stronger
  boolean success predicate, invalid primitive/edit parameters throw
  std::invalid_argument instead of being silently clamped.
- VDE-1343 edit_feature: face_ids range validation before the no-op early
  return, analytic hole location first, warnings on geometric fallback,
  15% radial consistency check between reference faces and matched hole.
- VDE-1344 rebind_entity: id hit now verified against the anchor distance
  (vertex/edge/face), falls back to nearest-anchor match, returns -1 when
  still mismatched; Body rebinds through anchor's nearest face.
- Tests: test_mesh_1177_fixes 11 cases, test_entity_1177_fixes 12 cases;
  registry 8,339 -> 8,362; full CTest 8,362/8,362 passed, 0 failed, 35 SKIP,
  635.55 s; release checks 14/14 PASS, report-check latest=224.
- Docs: report 224 (self-verification), verifier report 223 (1.0.175 PASS)
  included, RegressionExtreme count corrected to 10/10 (P3-1).
  Mesh VDE id renumbered 1341 -> 1345 to avoid collision with upstream
  docs/feedback/VDE-1341 (shell_multi).
2026-11-07 03:53:07 +08:00

3795 lines
158 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* @file point_cloud.cpp
* @brief 点云数据结构与处理算法实现(降采样、去噪、法线估计等)
*/
#include "vde/mesh/point_cloud.h"
#include <fstream>
#include <iomanip>
#include <cstdio>
#include <functional>
#include <sstream>
#include <algorithm>
#include <cmath>
#include <map>
#include <numeric>
#include <unordered_set>
#include <cstring>
// ───────────────────────────────────────────────────────────
// GPU 加速:点云 kNN 法线 / SOR 统计(VDE-1278)
// ───────────────────────────────────────────────────────────
#if defined(VDE_HAVE_COMPUTE)
#include "vde/compute/compute_backend.h"
#include <cstdlib>
#include <memory>
#include <mutex>
#endif
namespace vde::mesh {
#if defined(VDE_HAVE_COMPUTE)
namespace {
constexpr std::size_t kGpuCloudDefaultMinPoints = 20000;
constexpr std::size_t kGpuCloudMaxPoints = 4000000;
constexpr int kGpuCloudMaxK = 16;
std::mutex& gpu_cloud_init_mutex() {
static std::mutex m;
return m;
}
std::mutex& gpu_cloud_call_mutex() {
static std::mutex m;
return m;
}
/// OpenCL 后端单例(首次使用时创建;无 GPU 设备时为 cpu-fallback,info().gpu=false)。
vde::compute::ComputeBackend* gpu_cloud_backend() {
static std::unique_ptr<vde::compute::ComputeBackend> backend;
static bool tried = false;
std::lock_guard<std::mutex> lock(gpu_cloud_init_mutex());
if (!tried) {
tried = true;
backend = vde::compute::create_backend(vde::compute::BackendType::OpenCl);
}
return backend.get();
}
/// 一次真实小批核探测(缓存):确认设备可用且点云核能正确产出单位法线与有限距离。
bool gpu_cloud_probe() {
static std::mutex probe_mutex;
static bool done = false;
static bool available = false;
std::lock_guard<std::mutex> lock(probe_mutex);
if (done) return available;
done = true;
auto* backend = gpu_cloud_backend();
if (!backend || !backend->info().gpu) return available = false;
const double xs[5] = {0.0, 1.0, 0.0, 0.0, 0.5};
const double ys[5] = {0.0, 0.0, 1.0, 0.0, 0.5};
const double zs[5] = {0.0, 0.0, 0.0, 1.0, 0.5};
const double bbox_min[3] = {0.0, 0.0, 0.0};
double nx[5] = {0, 0, 0, 0, 0};
double ny[5] = {0, 0, 0, 0, 0};
double nz[5] = {0, 0, 0, 0, 0};
double md[5] = {0, 0, 0, 0, 0};
if (!backend->point_normal_stats_batch(xs, ys, zs, 5, 1, 1.0, bbox_min,
nx, ny, nz, md))
return available = false;
for (int i = 0; i < 5; ++i) {
const double len = std::sqrt(nx[i] * nx[i] + ny[i] * ny[i] + nz[i] * nz[i]);
if (!std::isfinite(len) || std::abs(len - 1.0) > 1e-6)
return available = false;
if (!std::isfinite(md[i])) return available = false;
}
return available = true;
}
/// GPU 点云统计:成功时写满 normals(可选)与 mean_dists;任何前置条件不满足
/// 或后端返回不支持/失败时返回 false,由调用方走原有 CPU 实现。
bool gpu_cloud_stats(const std::vector<Point3D>& vertices, int k,
std::vector<Vector3D>* normals,
std::vector<double>* mean_dists) {
const std::size_t n = vertices.size();
if (n == 0 || n < point_cloud_gpu_min_points()) return false;
if (n > kGpuCloudMaxPoints) return false;
std::size_t knn = (k < 0) ? n - 1 : static_cast<std::size_t>(k);
if (knn >= n) knn = n - 1;
if (n > 1 && knn < 1) knn = 1;
if (knn < 1 || knn > static_cast<std::size_t>(kGpuCloudMaxK)) return false;
AABB3D bb;
for (const auto& p : vertices) bb.expand(p);
const Vector3D ext = bb.extent();
const double avg_spacing = std::cbrt(
(ext.x() * ext.y() * ext.z()) / static_cast<double>(n));
const double cell = avg_spacing * 3.0;
if (!(cell > 0.0) || !std::isfinite(cell)) return false;
constexpr double kMaxCell = 1048575.0; // 2^21 - 1(64 位 key 三轴各 21 bit)
if (std::floor(ext.x() / cell) > kMaxCell ||
std::floor(ext.y() / cell) > kMaxCell ||
std::floor(ext.z() / cell) > kMaxCell)
return false;
auto* backend = gpu_cloud_backend();
if (!backend || !backend->info().gpu) return false;
std::vector<double> xs(n), ys(n), zs(n);
for (std::size_t i = 0; i < n; ++i) {
xs[i] = vertices[i].x();
ys[i] = vertices[i].y();
zs[i] = vertices[i].z();
}
const double bbox_min[3] = {bb.min().x(), bb.min().y(), bb.min().z()};
std::vector<double> out_nx(n), out_ny(n), out_nz(n), out_md(n);
{
std::lock_guard<std::mutex> lock(gpu_cloud_call_mutex());
if (!backend->point_normal_stats_batch(
xs.data(), ys.data(), zs.data(), n, static_cast<int>(knn),
cell, bbox_min, out_nx.data(), out_ny.data(), out_nz.data(),
out_md.data()))
return false;
}
if (normals) {
normals->resize(n);
for (std::size_t i = 0; i < n; ++i)
(*normals)[i] = Vector3D(out_nx[i], out_ny[i], out_nz[i]);
}
if (mean_dists) *mean_dists = std::move(out_md);
return true;
}
} // namespace
#endif
// ───────────────────────────────────────────────────────────
// bounds
// ───────────────────────────────────────────────────────────
AABB3D PointCloud::bounds() const {
if (vertices.empty()) {
// VDE-1345:空点云返回原点退化盒(避免 extent=-inf 参与容差计算)。
return AABB3D(Point3D::Zero(), Point3D::Zero());
}
AABB3D bbox;
for (const auto& p : vertices) bbox.expand(p);
return bbox;
}
// ───────────────────────────────────────────────────────────
// PLY I/O
// ───────────────────────────────────────────────────────────
PointCloud PointCloud::load_ply(const std::string& path) {
std::ifstream in(path, std::ios::binary);
if (!in) throw std::runtime_error("Cannot open PLY file: " + path);
std::string line;
size_t num_vertices = 0;
bool ascii = true;
struct Prop { std::string name; bool is_uchar = false; };
std::vector<Prop> props;
int x_idx = -1, y_idx = -1, z_idx = -1;
int nx_idx = -1, ny_idx = -1, nz_idx = -1;
int r_idx = -1, g_idx = -1, b_idx = -1;
// Normal indices tracked but extracted in binary mode below; suppress unused warning
(void)nx_idx; (void)ny_idx; (void)nz_idx;
// Read header
while (std::getline(in, line)) {
if (line.rfind("format ascii", 0) == 0) { ascii = true; }
else if (line.rfind("format binary_little_endian", 0) == 0) { ascii = false; }
else if (line.rfind("element vertex ", 0) == 0) {
num_vertices = std::stoul(line.substr(15));
}
else if (line.rfind("property ", 0) == 0) {
std::istringstream iss(line.substr(9));
std::string type, name;
iss >> type >> name;
if (type == "float" || type == "float32" || type == "double") {
props.push_back({name, false});
} else if (type == "uchar" || type == "uint8") {
props.push_back({name, true});
} else {
props.push_back({name, false});
}
}
else if (line == "end_header") break;
}
// Map properties
for (size_t i = 0; i < props.size(); ++i) {
if (props[i].name == "x") x_idx = static_cast<int>(i);
if (props[i].name == "y") y_idx = static_cast<int>(i);
if (props[i].name == "z") z_idx = static_cast<int>(i);
if (props[i].name == "nx") nx_idx = static_cast<int>(i);
if (props[i].name == "ny") ny_idx = static_cast<int>(i);
if (props[i].name == "nz") nz_idx = static_cast<int>(i);
if (props[i].name == "red" || props[i].name == "r" || props[i].name == "diffuse_red") r_idx = static_cast<int>(i);
if (props[i].name == "green" || props[i].name == "g" || props[i].name == "diffuse_green") g_idx = static_cast<int>(i);
if (props[i].name == "blue" || props[i].name == "b" || props[i].name == "diffuse_blue") b_idx = static_cast<int>(i);
}
PointCloud cloud;
cloud.vertices.reserve(num_vertices);
if (ascii) {
for (size_t i = 0; i < num_vertices; ++i) {
std::getline(in, line);
std::istringstream iss(line);
std::vector<double> vals(props.size());
for (size_t j = 0; j < props.size(); ++j) iss >> vals[j];
if (x_idx >= 0 && y_idx >= 0 && z_idx >= 0)
cloud.vertices.emplace_back(vals[x_idx], vals[y_idx], vals[z_idx]);
}
} else {
// Binary little-endian
// Calculate per-vertex byte size
size_t vertex_size = 0;
for (const auto& p : props) vertex_size += p.is_uchar ? 1 : 4;
std::vector<char> buf(vertex_size * num_vertices);
in.read(buf.data(), static_cast<std::streamsize>(buf.size()));
for (size_t i = 0; i < num_vertices; ++i) {
const char* base = buf.data() + i * vertex_size;
size_t off = 0;
float x = 0, y = 0, z = 0;
for (size_t j = 0; j < props.size(); ++j) {
if (props[j].is_uchar) {
off += 1;
if (static_cast<int>(j) == r_idx) { /* store color later */ }
if (static_cast<int>(j) == g_idx) { /* store color later */ }
if (static_cast<int>(j) == b_idx) { /* store color later */ }
} else {
float val;
std::memcpy(&val, base + off, 4);
off += 4;
if (static_cast<int>(j) == x_idx) x = val;
if (static_cast<int>(j) == y_idx) y = val;
if (static_cast<int>(j) == z_idx) z = val;
}
}
cloud.vertices.emplace_back(x, y, z);
}
}
return cloud;
}
bool PointCloud::save_ply(const std::string& path) const {
// 可选属性数组必须与顶点数等长:否则逐顶点索引 normals/colors 会越界读。
if (!normals.empty() && normals.size() != vertices.size()) return false;
if (!colors.empty() && colors.size() != vertices.size()) return false;
std::ofstream out(path);
if (!out) return false;
out << "ply\nformat ascii 1.0\n";
out << "element vertex " << vertices.size() << "\n";
out << "property float x\nproperty float y\nproperty float z\n";
if (has_normals()) {
out << "property float nx\nproperty float ny\nproperty float nz\n";
}
if (has_colors()) {
out << "property uchar red\nproperty uchar green\nproperty uchar blue\n";
}
out << "end_header\n";
for (size_t i = 0; i < vertices.size(); ++i) {
const auto& v = vertices[i];
out << v.x() << " " << v.y() << " " << v.z();
if (has_normals()) {
out << " " << normals[i].x() << " " << normals[i].y() << " " << normals[i].z();
}
if (has_colors()) {
out << " " << static_cast<int>(colors[i][0])
<< " " << static_cast<int>(colors[i][1])
<< " " << static_cast<int>(colors[i][2]);
}
out << "\n";
}
return true;
}
// ───────────────────────────────────────────────────────────
// Point cloud writers (VDE data-exchange completion, A-9)
// ───────────────────────────────────────────────────────────
namespace {
// little-endian primitive writers (all supported targets are LE x86/x64)
template <typename T>
void w_raw(std::ostream& out, const T& v) {
out.write(reinterpret_cast<const char*>(&v), sizeof(T));
}
void w_u8(std::ostream& out, uint8_t v) { w_raw(out, v); }
void w_u16(std::ostream& out, uint16_t v) { w_raw(out, v); }
void w_u32(std::ostream& out, uint32_t v) { w_raw(out, v); }
void w_u64(std::ostream& out, uint64_t v) { w_raw(out, v); }
void w_i32(std::ostream& out, int32_t v) { w_raw(out, v); }
void w_f64(std::ostream& out, double v) { w_raw(out, v); }
void w_str(std::ostream& out, const std::string& s, size_t field_len) {
std::string t = s.substr(0, field_len);
t.resize(field_len, '\0');
out.write(t.data(), static_cast<std::streamsize>(field_len));
}
} // namespace
PointCloudIoResult PointCloud::save_las(const std::string& path) const {
PointCloudIoResult r;
if (vertices.empty()) {
r.status = PointCloudIoStatus::Error;
r.message = "save_las: empty point cloud";
return r;
}
// bounding box + quantization. 1e-6 gives max round-trip error 5e-7.
double minx = vertices[0].x(), maxx = minx;
double miny = vertices[0].y(), maxy = miny;
double minz = vertices[0].z(), maxz = minz;
for (const auto& v : vertices) {
minx = std::min(minx, v.x()); maxx = std::max(maxx, v.x());
miny = std::min(miny, v.y()); maxy = std::max(maxy, v.y());
minz = std::min(minz, v.z()); maxz = std::max(maxz, v.z());
}
auto pick_scale = [](double span) {
constexpr double kMaxInt32 = 2147483647.0;
double s = 1e-6;
if (span / s > kMaxInt32) s = span / kMaxInt32;
return s;
};
const double sx = pick_scale(maxx - minx);
const double sy = pick_scale(maxy - miny);
const double sz = pick_scale(maxz - minz);
const uint64_t n = static_cast<uint64_t>(vertices.size());
const bool with_rgb = has_colors();
const uint8_t pdrf = with_rgb ? 2 : 0;
const uint16_t rec_len = with_rgb ? 26 : 20;
const uint16_t header_size = 375;
const uint32_t legacy_count = (n < 0xFFFFFFFFull) ? static_cast<uint32_t>(n) : 0u;
std::ofstream out(path, std::ios::binary);
if (!out) {
r.status = PointCloudIoStatus::Error;
r.message = "save_las: cannot open output file: " + path;
return r;
}
// ── Public Header Block (LAS 1.4, 375 bytes) ──
out.write("LASF", 4);
w_u16(out, 0); // file source id
w_u16(out, 0); // global encoding
w_u32(out, 0); // guid1
w_u16(out, 0); w_u16(out, 0); // guid2/3
for (int i = 0; i < 8; ++i) w_u8(out, 0); // guid4
w_u8(out, 1); w_u8(out, 4); // version 1.4
w_str(out, "VDE", 32); // system identifier
w_str(out, "ViewDesignEngine", 32); // generating software
w_u16(out, 0); // creation day
w_u16(out, 2026); // creation year
w_u16(out, header_size);
w_u32(out, header_size); // offset to point data
w_u32(out, 0); // number of VLRs
w_u8(out, pdrf);
w_u16(out, rec_len);
w_u32(out, legacy_count);
for (int i = 0; i < 5; ++i) w_u32(out, i == 0 ? legacy_count : 0u);
w_f64(out, sx); w_f64(out, sy); w_f64(out, sz);
w_f64(out, minx); w_f64(out, miny); w_f64(out, minz);
w_f64(out, maxx); w_f64(out, minx);
w_f64(out, maxy); w_f64(out, miny);
w_f64(out, maxz); w_f64(out, minz);
w_u64(out, 0); // start of waveform data
w_u64(out, 0); // start of first EVLR
w_u32(out, 0); // number of EVLRs
w_u64(out, n); // 64-bit point count
for (int i = 0; i < 15; ++i) w_u64(out, i == 0 ? n : 0ull);
auto quant = [](double v, double off, double scale) {
const double q = std::round((v - off) / scale);
const double hi = 2147483647.0, lo = -2147483648.0;
return static_cast<int32_t>(std::max(lo, std::min(hi, q)));
};
for (size_t i = 0; i < vertices.size(); ++i) {
const auto& v = vertices[i];
w_i32(out, quant(v.x(), minx, sx));
w_i32(out, quant(v.y(), miny, sy));
w_i32(out, quant(v.z(), minz, sz));
double inten = has_intensity() ? intensities[i] : 0.0;
inten = std::max(0.0, std::min(65535.0, std::round(inten)));
w_u16(out, static_cast<uint16_t>(inten));
w_u8(out, static_cast<uint8_t>((1u & 0x7u) | ((1u & 0x7u) << 3))); // return 1 of 1
w_u8(out, 0); // classification
w_u8(out, 0); // scan angle rank
w_u8(out, 0); // user data
w_u16(out, 0); // point source id
if (with_rgb) {
w_u16(out, static_cast<uint16_t>(colors[i][0]) << 8);
w_u16(out, static_cast<uint16_t>(colors[i][1]) << 8);
w_u16(out, static_cast<uint16_t>(colors[i][2]) << 8);
}
}
out.flush();
if (!out.good()) {
r.status = PointCloudIoStatus::Error;
r.message = "save_las: write failure: " + path;
return r;
}
r.status = PointCloudIoStatus::Ok;
r.message = "LAS 1.4 PDRF " + std::to_string(static_cast<int>(pdrf)) +
", " + std::to_string(n) + " points, scale=" + std::to_string(sx);
return r;
}
PointCloudIoResult PointCloud::save_ptx(const std::string& path) const {
PointCloudIoResult r;
if (vertices.empty()) {
r.status = PointCloudIoStatus::Error;
r.message = "save_ptx: empty point cloud";
return r;
}
std::ofstream out(path);
if (!out) {
r.status = PointCloudIoStatus::Error;
r.message = "save_ptx: cannot open output file: " + path;
return r;
}
out << vertices.size() << " 1\n";
out << "1 0 0 0\n0 1 0 0\n0 0 1 0\n";
out << std::setprecision(17);
for (size_t i = 0; i < vertices.size(); ++i) {
const auto& v = vertices[i];
const double intensity = has_intensity() ? intensities[i] : 0.0;
int cr = 0, cg = 0, cb = 0;
if (has_colors()) { cr = colors[i][0]; cg = colors[i][1]; cb = colors[i][2]; }
out << v.x() << ' ' << v.y() << ' ' << v.z() << ' ' << intensity
<< ' ' << cr << ' ' << cg << ' ' << cb << '\n';
}
out.flush();
if (!out.good()) {
r.status = PointCloudIoStatus::Error;
r.message = "save_ptx: write failure: " + path;
return r;
}
r.status = PointCloudIoStatus::Ok;
r.message = "PTX single scan, " + std::to_string(vertices.size()) + " points";
return r;
}
PointCloudIoResult PointCloud::save_e57(const std::string& path) const {
PointCloudIoResult r;
if (vertices.empty()) {
r.status = PointCloudIoStatus::Error;
r.message = "save_e57: empty point cloud";
return r;
}
const size_t n = vertices.size();
const bool has_normals = normals.size() == n;
const bool has_colors = colors.size() == n;
const bool has_intensity = intensities.size() == n;
auto build_xml = [&](uint64_t file_offset) {
std::ostringstream x;
x << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
x << "<e57Root type=\"Structure\">\n";
x << " <data3D type=\"Vector\">\n";
x << " <points type=\"Structure\" prototype=\"VdePointProto\">\n";
x << " <pointCount type=\"Integer\">" << n << "</pointCount>\n";
x << " <fileOffset type=\"Integer\">" << file_offset
<< "</fileOffset>\n";
x << " </points>\n";
x << " </data3D>\n";
x << " <vectorChild type=\"Vector\"/>\n";
x << "</e57Root>\n";
// 原型:字段顺序 = 二进制记录顺序(load_e57 按此顺序解析)
x << "<VdePointProto type=\"Structure\">\n";
x << " <Float name=\"cartesianX\" precision=\"double\"/>\n";
x << " <Float name=\"cartesianY\" precision=\"double\"/>\n";
x << " <Float name=\"cartesianZ\" precision=\"double\"/>\n";
if (has_normals) {
x << " <Float name=\"nor:normalX\" precision=\"double\"/>\n";
x << " <Float name=\"nor:normalY\" precision=\"double\"/>\n";
x << " <Float name=\"nor:normalZ\" precision=\"double\"/>\n";
}
if (has_colors) {
x << " <Integer name=\"colorRed\" minimum=\"0\" maximum=\"255\"/>\n";
x << " <Integer name=\"colorGreen\" minimum=\"0\" maximum=\"255\"/>\n";
x << " <Integer name=\"colorBlue\" minimum=\"0\" maximum=\"255\"/>\n";
}
if (has_intensity) {
x << " <Float name=\"intensity\" precision=\"double\"/>\n";
}
x << "</VdePointProto>\n";
return x.str();
};
// 二进制段紧跟 XML:fileOffset 依赖 XML 长度,迭代收敛(数字位数变化)
uint64_t binary_offset = 48;
std::string xml_data;
for (int iter = 0; iter < 8; ++iter) {
xml_data = build_xml(binary_offset);
const uint64_t next = 48u + static_cast<uint64_t>(xml_data.size());
if (next == binary_offset) break;
binary_offset = next;
}
xml_data = build_xml(binary_offset);
std::ofstream out(path, std::ios::binary);
if (!out) {
r.status = PointCloudIoStatus::Error;
r.message = "save_e57: cannot open output file: " + path;
return r;
}
auto write_le64 = [&](uint64_t v) {
char b[8];
for (int i = 0; i < 8; ++i) b[i] = static_cast<char>((v >> (i * 8)) & 0xFF);
out.write(b, 8);
};
auto write_f64 = [&](double v) {
uint64_t u = 0;
std::memcpy(&u, &v, sizeof(u));
write_le64(u);
};
// 48 字节头:magic + 版本 + phys + xml(与 load_e57 的读取布局一致)
char header[48] = {};
std::memcpy(header, "ASTM-E57", 8);
const uint32_t major = 1, minor = 0;
std::memcpy(header + 8, &major, 4);
std::memcpy(header + 12, &minor, 4);
const uint64_t phys_off = 48;
const uint64_t phys_len = xml_data.size();
const uint64_t xml_off = 48;
const uint64_t xml_len = xml_data.size();
std::memcpy(header + 16, &phys_off, 8);
std::memcpy(header + 24, &phys_len, 8);
std::memcpy(header + 32, &xml_off, 8);
std::memcpy(header + 40, &xml_len, 8);
out.write(header, 48);
out.write(xml_data.data(), static_cast<std::streamsize>(xml_data.size()));
for (size_t i = 0; i < n; ++i) {
write_f64(vertices[i].x());
write_f64(vertices[i].y());
write_f64(vertices[i].z());
if (has_normals) {
write_f64(normals[i].x());
write_f64(normals[i].y());
write_f64(normals[i].z());
}
if (has_colors) {
const char rgb[3] = {static_cast<char>(colors[i][0]),
static_cast<char>(colors[i][1]),
static_cast<char>(colors[i][2])};
out.write(rgb, 3);
}
if (has_intensity) write_f64(intensities[i]);
}
if (!out.good()) {
r.status = PointCloudIoStatus::Error;
r.message = "save_e57: write failure: " + path;
return r;
}
r.status = PointCloudIoStatus::Ok;
r.message = "E57 minimal write (ASTM-E57 header + XML prototype + raw binary "
"point records; VDE reader round-trip). Note: standard E57 "
"CompressedVector section packing is not emitted.";
return r;
}
// ═══════════════════════════════════════════════════════════════════
// FMT-12: standard E57 CompressedVector writer (bitPack codec, first increment)
// ═══════════════════════════════════════════════════════════════════
namespace {
struct StdE57Field {
enum class Kind { Float64, Integer8 };
std::string name;
Kind kind = Kind::Float64;
};
void append_u16(std::vector<std::uint8_t>& out, std::uint16_t value) {
out.push_back(static_cast<std::uint8_t>(value & 0xFF));
out.push_back(static_cast<std::uint8_t>((value >> 8) & 0xFF));
}
void append_u64(std::vector<std::uint8_t>& out, std::uint64_t value) {
for (int i = 0; i < 8; ++i) out.push_back(static_cast<std::uint8_t>((value >> (i * 8)) & 0xFF));
}
void append_f64(std::vector<std::uint8_t>& out, double value) {
std::uint64_t bits = 0;
std::memcpy(&bits, &value, sizeof(bits));
append_u64(out, bits);
}
void set_u16(std::vector<std::uint8_t>& out, std::size_t offset, std::uint16_t value) {
out[offset] = static_cast<std::uint8_t>(value & 0xFF);
out[offset + 1] = static_cast<std::uint8_t>((value >> 8) & 0xFF);
}
void set_u64(std::vector<std::uint8_t>& out, std::size_t offset, std::uint64_t value) {
for (int i = 0; i < 8; ++i) {
out[offset + static_cast<std::size_t>(i)] =
static_cast<std::uint8_t>((value >> (i * 8)) & 0xFF);
}
}
std::string build_std_e57_xml(const std::vector<StdE57Field>& fields, std::size_t point_count,
std::uint64_t section_offset) {
std::ostringstream x;
x << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
x << "<e57Root type=\"Structure\" xmlns=\"http://www.astm.org/COMMIT/E57/2010-e57-v1.0\">\n";
x << " <data3D type=\"Vector\">\n";
x << " <vectorChild type=\"Structure\">\n";
x << " <points type=\"CompressedVector\" fileOffset=\"" << section_offset
<< "\" recordCount=\"" << point_count << "\">\n";
x << " <prototype type=\"Structure\">\n";
for (const auto& field : fields) {
if (field.kind == StdE57Field::Kind::Float64) {
x << " <" << field.name << " type=\"Float\" precision=\"double\"/>\n";
} else {
x << " <" << field.name << " type=\"Integer\" minimum=\"0\" maximum=\"255\"/>\n";
}
}
x << " </prototype>\n";
x << " <codecs type=\"Structure\"><bitPackCodec type=\"Structure\"/></codecs>\n";
x << " </points>\n";
x << " </vectorChild>\n";
x << " </data3D>\n";
x << " <images2D type=\"Vector\"/>\n";
x << "</e57Root>\n";
return x.str();
}
std::vector<std::uint8_t> make_data_packet(
const std::vector<std::vector<std::uint8_t>>& streams) {
std::vector<std::uint8_t> packet;
const std::uint16_t stream_count = static_cast<std::uint16_t>(streams.size());
packet.push_back(1); // DATA_PACKET
packet.push_back(0); // flags
packet.push_back(0); // packetLogicalLengthMinus1 placeholder
packet.push_back(0);
append_u16(packet, stream_count);
for (const auto& stream : streams) {
if (stream.size() > 0xFFFFu) throw std::runtime_error("E57 data packet bytestream too large");
append_u16(packet, static_cast<std::uint16_t>(stream.size()));
}
for (const auto& stream : streams) packet.insert(packet.end(), stream.begin(), stream.end());
while ((packet.size() % 4u) != 0u) packet.push_back(0);
if (packet.size() > 0x10000u) throw std::runtime_error("E57 data packet exceeds 64KiB");
set_u16(packet, 2, static_cast<std::uint16_t>(packet.size() - 1));
return packet;
}
// E57 physical page layer: 1024B page = 1020B data + 4B CRC-32C (Castagnoli).
constexpr std::size_t kE57PhysicalPageSize = 1024;
constexpr std::size_t kE57LogicalPageSize = 1020;
std::uint32_t crc32c(const std::uint8_t* data, std::size_t length) {
std::uint32_t crc = 0xFFFFFFFFu;
for (std::size_t i = 0; i < length; ++i) {
crc ^= data[i];
for (int bit = 0; bit < 8; ++bit) {
crc = (crc & 1u) ? ((crc >> 1) ^ 0x82F63B78u) : (crc >> 1);
}
}
return crc ^ 0xFFFFFFFFu;
}
std::uint64_t physical_to_logical(std::uint64_t physical) {
return (physical / kE57PhysicalPageSize) * kE57LogicalPageSize +
std::min<std::uint64_t>(physical % kE57PhysicalPageSize, kE57LogicalPageSize);
}
std::vector<std::uint8_t> make_index_packet(std::uint64_t data_offset) {
std::vector<std::uint8_t> packet(32, 0);
packet[0] = 0; // INDEX_PACKET
packet[1] = 0;
set_u16(packet, 2, 31); // length - 1
set_u16(packet, 4, 1); // entryCount
packet[6] = 0; // indexLevel
// entries: chunkRecordNumber=0, chunkPhysicalOffset=data_offset
for (int i = 0; i < 8; ++i) packet[8 + static_cast<std::size_t>(i)] = 0;
for (int i = 0; i < 8; ++i) {
packet[16 + static_cast<std::size_t>(i)] =
static_cast<std::uint8_t>((data_offset >> (i * 8)) & 0xFF);
}
return packet;
}
} // namespace
PointCloudIoResult PointCloud::save_e57(const std::string& path,
const E57WriteOptions& options) const {
if (!options.standard_compressed_vector) return save_e57(path);
if (!options.page_crc) return save_e57_standard(path);
// Build the FMT-12 standard logical stream first, then lay it into 1024B
// physical pages (1020B data + 4B CRC-32C). Offsets inside this first
// page-layer increment stay logical (self-compatible); external physical
// offset semantics are documented as not yet claimed.
const std::string logical_path = path + ".vde_e57_logical";
const auto logical_result = save_e57_standard(logical_path);
if (!logical_result.ok()) {
std::remove(logical_path.c_str());
return logical_result;
}
std::ifstream logical_in(logical_path, std::ios::binary);
std::string logical((std::istreambuf_iterator<char>(logical_in)),
std::istreambuf_iterator<char>());
logical_in.close();
std::remove(logical_path.c_str());
if (logical.size() < 48) {
PointCloudIoResult r;
r.status = PointCloudIoStatus::Error;
r.message = "save_e57: page/CRC wrap failed to read standard logical stream";
return r;
}
const std::uint64_t page_count =
(static_cast<std::uint64_t>(logical.size()) + kE57LogicalPageSize - 1) /
kE57LogicalPageSize;
const std::uint64_t physical_size = page_count * kE57PhysicalPageSize;
const std::uint64_t xml_length =
static_cast<std::uint64_t>(logical[32]) |
(static_cast<std::uint64_t>(logical[33]) << 8) |
(static_cast<std::uint64_t>(logical[34]) << 16) |
(static_cast<std::uint64_t>(logical[35]) << 24) |
(static_cast<std::uint64_t>(logical[36]) << 32) |
(static_cast<std::uint64_t>(logical[37]) << 40) |
(static_cast<std::uint64_t>(logical[38]) << 48) |
(static_cast<std::uint64_t>(logical[39]) << 56);
char header[48];
std::memcpy(header, logical.data(), 48);
std::memcpy(header + 16, &physical_size, 8); // filePhysicalLength
const std::uint64_t page_size = 1024;
std::memcpy(header + 40, &page_size, 8);
std::memcpy(logical.data(), header, 48);
std::ofstream out(path, std::ios::binary);
if (!out) {
PointCloudIoResult r;
r.status = PointCloudIoStatus::Error;
r.message = "save_e57: cannot open page/CRC output file: " + path;
return r;
}
for (std::uint64_t page = 0; page < page_count; ++page) {
char page_data[kE57PhysicalPageSize] = {};
const std::uint64_t begin = page * kE57LogicalPageSize;
const std::uint64_t remaining = static_cast<std::uint64_t>(logical.size()) - begin;
const std::size_t bytes = static_cast<std::size_t>(
std::min<std::uint64_t>(remaining, kE57LogicalPageSize));
std::memcpy(page_data, logical.data() + begin, bytes);
const std::uint32_t crc =
crc32c(reinterpret_cast<const std::uint8_t*>(page_data), kE57LogicalPageSize);
// E57/libE57 stores the CRC-32C check value in big-endian byte order
// (CRCpp value is byte-swapped before the native little-endian write).
page_data[kE57LogicalPageSize + 0] = static_cast<char>((crc >> 24) & 0xFF);
page_data[kE57LogicalPageSize + 1] = static_cast<char>((crc >> 16) & 0xFF);
page_data[kE57LogicalPageSize + 2] = static_cast<char>((crc >> 8) & 0xFF);
page_data[kE57LogicalPageSize + 3] = static_cast<char>(crc & 0xFF);
out.write(page_data, kE57PhysicalPageSize);
}
if (!out.good()) {
PointCloudIoResult r;
r.status = PointCloudIoStatus::Error;
r.message = "save_e57: page/CRC write failure: " + path;
return r;
}
PointCloudIoResult r;
r.status = PointCloudIoStatus::Ok;
std::ostringstream msg;
msg << "E57 standard CompressedVector + 1024B page/CRC layer (" << page_count
<< " pages, " << physical_size << " physical bytes, logical XML length " << xml_length
<< "); self-compatible first increment (logical offsets, CRC-32C big-endian page trailer)";
r.message = msg.str();
return r;
}
PointCloudIoResult PointCloud::save_e57_standard(const std::string& path) const {
PointCloudIoResult r;
if (vertices.empty()) {
r.status = PointCloudIoStatus::Error;
r.message = "save_e57_standard: empty point cloud";
return r;
}
const std::size_t n = vertices.size();
const bool has_normals = normals.size() == n;
const bool has_colors = colors.size() == n;
const bool has_intensity = intensities.size() == n;
std::vector<StdE57Field> fields;
fields.push_back({"cartesianX", StdE57Field::Kind::Float64});
fields.push_back({"cartesianY", StdE57Field::Kind::Float64});
fields.push_back({"cartesianZ", StdE57Field::Kind::Float64});
if (has_normals) {
fields.push_back({"normalX", StdE57Field::Kind::Float64});
fields.push_back({"normalY", StdE57Field::Kind::Float64});
fields.push_back({"normalZ", StdE57Field::Kind::Float64});
}
if (has_colors) {
fields.push_back({"colorRed", StdE57Field::Kind::Integer8});
fields.push_back({"colorGreen", StdE57Field::Kind::Integer8});
fields.push_back({"colorBlue", StdE57Field::Kind::Integer8});
}
if (has_intensity) fields.push_back({"intensity", StdE57Field::Kind::Float64});
std::uint64_t section_offset = 48;
std::string xml;
for (int iter = 0; iter < 8; ++iter) {
xml = build_std_e57_xml(fields, n, section_offset);
const std::uint64_t next = 48u + static_cast<std::uint64_t>(xml.size());
if (next == section_offset) break;
section_offset = next;
}
xml = build_std_e57_xml(fields, n, section_offset);
constexpr std::size_t kRecordsPerPacket = 512;
std::vector<std::vector<std::uint8_t>> streams(fields.size());
std::vector<std::uint8_t> data_bytes;
std::size_t packet_count = 0;
for (std::size_t start = 0; start < n; start += kRecordsPerPacket) {
const std::size_t end = std::min(start + kRecordsPerPacket, n);
for (auto& stream : streams) stream.clear();
for (std::size_t i = start; i < end; ++i) {
for (std::size_t f = 0; f < fields.size(); ++f) {
switch (fields[f].kind) {
case StdE57Field::Kind::Float64: {
double value = 0.0;
if (f == 0) value = vertices[i].x();
else if (f == 1) value = vertices[i].y();
else if (f == 2) value = vertices[i].z();
else if (has_normals && f >= 3 && f <= 5) {
value = (f == 3 ? normals[i].x() : (f == 4 ? normals[i].y() : normals[i].z()));
} else if (has_intensity && f + 1 == fields.size()) {
value = intensities[i];
}
append_f64(streams[f], value);
break;
}
case StdE57Field::Kind::Integer8: {
int value = 0;
if (has_colors) {
const std::size_t base = has_normals ? 6u : 3u;
const std::size_t c = f - base;
if (c < 3) value = colors[i][c];
}
streams[f].push_back(static_cast<std::uint8_t>(value & 0xFF));
break;
}
}
}
}
const auto packet = make_data_packet(streams);
data_bytes.insert(data_bytes.end(), packet.begin(), packet.end());
++packet_count;
}
const std::uint64_t data_offset =
section_offset + 32u + 0u; // section header 32 bytes; data begins there
(void)data_offset;
const std::uint64_t absolute_data_offset =
static_cast<std::uint64_t>(48 + xml.size()) + 32u;
const std::uint64_t index_offset = absolute_data_offset + data_bytes.size();
const auto index_packet = make_index_packet(absolute_data_offset);
const std::uint64_t section_length =
32u + data_bytes.size() + index_packet.size();
std::vector<std::uint8_t> section(32, 0);
section[0] = 1; // COMPRESSED_VECTOR_SECTION
set_u64(section, 8, section_length);
set_u64(section, 16, absolute_data_offset);
set_u64(section, 24, index_offset);
for (std::uint8_t byte : data_bytes) section.push_back(byte);
section.insert(section.end(), index_packet.begin(), index_packet.end());
const std::uint64_t file_size = 48u + xml.size() + section.size();
char header[48] = {};
std::memcpy(header, "ASTM-E57", 8);
const std::uint32_t major = 1, minor = 0;
std::memcpy(header + 8, &major, 4);
std::memcpy(header + 12, &minor, 4);
std::memcpy(header + 16, &file_size, 8);
const std::uint64_t xml_offset = 48;
std::memcpy(header + 24, &xml_offset, 8);
const std::uint64_t xml_length = xml.size();
std::memcpy(header + 32, &xml_length, 8);
// 无页标准流(FMT-12 首增量):pageSize=0 明确标记无 page/CRC 层。
const std::uint64_t page_size = 0;
std::memcpy(header + 40, &page_size, 8);
std::ofstream out(path, std::ios::binary);
if (!out) {
r.status = PointCloudIoStatus::Error;
r.message = "save_e57_standard: cannot open output file: " + path;
return r;
}
out.write(header, 48);
out.write(xml.data(), static_cast<std::streamsize>(xml.size()));
out.write(reinterpret_cast<const char*>(section.data()),
static_cast<std::streamsize>(section.size()));
if (!out.good()) {
r.status = PointCloudIoStatus::Error;
r.message = "save_e57_standard: write failure: " + path;
return r;
}
r.status = PointCloudIoStatus::Ok;
std::ostringstream msg;
msg << "E57 standard CompressedVector (bitPack, " << n << " records, " << packet_count
<< " data packet(s), section@" << section_offset << ", data@" << absolute_data_offset
<< ", index@" << index_offset
<< "); first increment: no page/CRC layer, self-roundtrip only";
r.message = msg.str();
return r;
}
// ═══════════════════════════════════════════════════════════════════
// LAZ 1.2 codec (compressor 2 = pointwise + chunked, item version 2).
//
// 自包含实现,零外部依赖;算术编码 / 模型 / 整数压缩器 / POINT10 v2 /
// RGB12 v2 / chunk table 均按 OGC LAZ 1.4 规范(Clause 8、9、12.1、12.3)
// 与 LASzip 3.x 兼容语义实现(write→read 往返 + 第三方 laspy/lazrs 互验)。
// 只覆盖本项目写出所需子集:LAS 点格式 0/2、POINT10 v2(+RGB12 v2)。
// ═══════════════════════════════════════════════════════════════════
namespace laz {
constexpr uint32_t kAcMinLength = 0x01000000u;
constexpr uint32_t kAcMaxLength = 0xFFFFFFFFu;
constexpr uint32_t kDmShift = 15;
constexpr uint32_t kDmMaxCount = 1u << kDmShift;
constexpr uint32_t kBmShift = 13;
constexpr uint32_t kBmMaxCount = 1u << kBmShift;
/// 自适应符号模型(编码/解码共用的分布更新,与 LASzip ArithmeticModel 等价)
struct SymbolModel {
uint32_t symbols = 0;
std::vector<uint32_t> dist, counts;
uint32_t total = 0, update_cycle = 0, until_update = 0;
void init(uint32_t n) {
symbols = n;
dist.assign(n, 0);
counts.assign(n, 1);
total = 0;
update_cycle = n;
update();
update_cycle = (n + 6) >> 1;
until_update = update_cycle;
}
void update() {
if ((total += update_cycle) > kDmMaxCount) {
total = 0;
for (uint32_t i = 0; i < symbols; ++i) {
counts[i] = (counts[i] + 1) >> 1;
total += counts[i];
}
}
uint32_t sum = 0;
const uint32_t scale = 0x80000000u / total;
for (uint32_t i = 0; i < symbols; ++i) {
dist[i] = (scale * sum) >> (31 - kDmShift);
sum += counts[i];
}
update_cycle = (5 * update_cycle) >> 2;
const uint32_t max_cycle = (symbols + 6) << 3;
if (update_cycle > max_cycle) update_cycle = max_cycle;
until_update = update_cycle;
}
};
/// 自适应单比特模型
struct BitModel {
uint32_t bit_0_prob = 1u << (kBmShift - 1);
uint32_t bit_0_count = 1, bit_count = 2;
uint32_t update_cycle = 4, until_update = 4;
void init() {
bit_0_prob = 1u << (kBmShift - 1);
bit_0_count = 1;
bit_count = 2;
update_cycle = until_update = 4;
}
void update() {
if ((bit_count += update_cycle) > kBmMaxCount) {
bit_count = (bit_count + 1) >> 1;
bit_0_count = (bit_0_count + 1) >> 1;
if (bit_0_count == bit_count) ++bit_count;
}
const uint32_t scale = 0x80000000u / bit_count;
bit_0_prob = (bit_0_count * scale) >> (31 - kBmShift);
update_cycle = (5 * update_cycle) >> 2;
if (update_cycle > 64) update_cycle = 64;
until_update = update_cycle;
}
};
/// 32 位算术编码器(输出到内存缓冲;语义同 LASzip ArithmeticEncoder)
struct Encoder {
uint32_t base = 0;
uint32_t length = kAcMaxLength;
std::vector<uint8_t> out;
void init() {
base = 0;
length = kAcMaxLength;
out.clear();
}
void propagate_carry() {
if (out.empty()) { // 规范保证不会发生;防御性处理
out.push_back(1);
return;
}
size_t i = out.size() - 1;
while (out[i] == 0xFF) {
out[i] = 0;
if (i == 0) {
out.insert(out.begin(), 1);
return;
}
--i;
}
++out[i];
}
void renorm() {
do {
out.push_back(static_cast<uint8_t>(base >> 24));
base <<= 8;
length <<= 8;
} while (length < kAcMinLength);
}
void encodeBit(BitModel& m, uint32_t sym) {
const uint32_t x = m.bit_0_prob * (length >> kBmShift);
if (sym == 0) {
length = x;
++m.bit_0_count;
} else {
const uint32_t init_base = base;
base += x;
length -= x;
if (init_base > base) propagate_carry();
}
if (length < kAcMinLength) renorm();
if (--m.until_update == 0) m.update();
}
void encodeSymbol(SymbolModel& m, uint32_t sym) {
uint32_t x;
const uint32_t init_base = base;
if (sym == m.symbols - 1) {
x = m.dist[sym] * (length >> kDmShift);
base += x;
length -= x;
} else {
x = m.dist[sym] * (length >>= kDmShift);
base += x;
length = m.dist[sym + 1] * length - x;
}
if (init_base > base) propagate_carry();
if (length < kAcMinLength) renorm();
++m.counts[sym];
if (--m.until_update == 0) m.update();
}
void writeShort(uint16_t sym) {
const uint32_t init_base = base;
base += static_cast<uint32_t>(sym) * (length >>= 16);
if (init_base > base) propagate_carry();
if (length < kAcMinLength) renorm();
}
void writeBits(uint32_t bits, uint32_t sym) {
if (bits > 19) {
writeShort(static_cast<uint16_t>(sym & 0xFFFFu));
sym >>= 16;
bits -= 16;
}
const uint32_t init_base = base;
base += sym * (length >>= bits);
if (init_base > base) propagate_carry();
if (length < kAcMinLength) renorm();
}
void writeInt(uint32_t sym) {
writeShort(static_cast<uint16_t>(sym & 0xFFFFu));
writeShort(static_cast<uint16_t>(sym >> 16));
}
void done() {
// 规范 8.5.2(与 LASzip ArithmeticEncoder::done 等价)
const uint32_t init_base = base;
bool another_byte = true;
if (length > 2 * kAcMinLength) {
base += kAcMinLength;
length = kAcMinLength >> 1;
} else {
base += kAcMinLength >> 1;
length = kAcMinLength >> 9;
another_byte = false;
}
if (init_base > base) propagate_carry();
renorm();
out.push_back(0);
out.push_back(0);
if (another_byte) out.push_back(0);
}
};
/// 32 位算术解码器(从内存缓冲读取;语义同 LASzip ArithmeticDecoder)
struct Decoder {
const uint8_t* data = nullptr;
size_t size = 0;
size_t pos = 0;
uint32_t value = 0;
uint32_t length = kAcMaxLength;
uint8_t get() { return pos < size ? data[pos++] : 0; }
void init(const uint8_t* d, size_t n) {
data = d;
size = n;
pos = 0;
length = kAcMaxLength;
value = (static_cast<uint32_t>(get()) << 24) |
(static_cast<uint32_t>(get()) << 16) |
(static_cast<uint32_t>(get()) << 8) | static_cast<uint32_t>(get());
}
void renorm() {
do {
value = (value << 8) | get();
length <<= 8;
} while (length < kAcMinLength);
}
uint32_t decodeSymbol(SymbolModel& m) {
const uint32_t ltmp = length >> kDmShift;
uint32_t s = m.symbols - 1;
while (s > 0 && m.dist[s] * ltmp > value) --s;
value -= m.dist[s] * ltmp;
if (s < m.symbols - 1) {
length = (m.dist[s + 1] * ltmp) - (m.dist[s] * ltmp);
} else {
length = length - (m.dist[s] * ltmp);
}
if (length < kAcMinLength) renorm();
++m.counts[s];
if (--m.until_update == 0) m.update();
return s;
}
uint32_t decodeBit(BitModel& m) {
uint32_t bit;
const uint32_t x = m.bit_0_prob * (length >> kBmShift);
if (value >= x) {
bit = 1;
value -= x;
length -= x;
} else {
bit = 0;
length = x;
++m.bit_0_count;
}
if (length < kAcMinLength) renorm();
if (--m.until_update == 0) m.update();
return bit;
}
uint16_t readShort() {
length >>= 16;
const uint32_t sym = value / length;
value -= length * sym;
if (length < kAcMinLength) renorm();
return static_cast<uint16_t>(sym);
}
uint32_t readBits(uint32_t bits) {
if (bits > 19) {
const uint32_t lo = readShort();
bits -= 16;
const uint32_t hi = readBits(bits);
return (hi << 16) | lo;
}
length >>= bits;
const uint32_t sym = value / length;
value -= length * sym;
if (length < kAcMinLength) renorm();
return sym;
}
uint32_t readInt() {
const uint32_t lo = readShort();
const uint32_t hi = readShort();
return (hi << 16) | lo;
}
};
/// LASzip IntegerCompressor(16/32 位,多 context / corr_bits 模型共享)
struct IntegerCompressor {
Encoder* enc = nullptr;
Decoder* dec = nullptr;
uint32_t bits = 32, contexts = 1, bits_high = 8;
uint32_t corr_bits = 32, corr_range = 0;
int32_t corr_min = 0, corr_max = 0;
uint32_t k = 0;
std::vector<SymbolModel> k_models;
std::vector<SymbolModel> corrector;
BitModel corrector0;
void setup(uint32_t bits_, uint32_t contexts_) {
bits = bits_;
contexts = contexts_;
bits_high = 8;
if (bits && bits < 32) {
corr_bits = bits;
corr_range = 1u << bits;
corr_min = -static_cast<int32_t>(corr_range / 2);
corr_max = corr_min + static_cast<int32_t>(corr_range) - 1;
} else {
corr_bits = 32;
corr_range = 0;
corr_min = static_cast<int32_t>(0x80000000u);
corr_max = 0x7FFFFFFF;
}
k_models.assign(contexts, SymbolModel());
corrector.assign(corr_bits + 1, SymbolModel());
}
void init(Encoder* e, Decoder* d) {
enc = e;
dec = d;
for (auto& m : k_models) m.init(corr_bits + 1);
corrector0.init();
for (uint32_t i = 1; i <= corr_bits; ++i) {
corrector[i].init(i <= bits_high ? (1u << i) : 256u);
}
k = 0;
}
void compress(int32_t pred, int32_t real, uint32_t context) {
int64_t c64 = static_cast<int64_t>(real) - static_cast<int64_t>(pred);
int32_t corr = static_cast<int32_t>(c64);
if (corr < corr_min) corr = static_cast<int32_t>(corr + static_cast<int32_t>(corr_range));
else if (corr > corr_max) corr = static_cast<int32_t>(corr - static_cast<int32_t>(corr_range));
write_corrector(corr, k_models[context]);
}
int32_t decompress(int32_t pred, uint32_t context) {
int32_t real = static_cast<int32_t>(static_cast<int64_t>(pred) + read_corrector(k_models[context]));
if (real < 0) real = static_cast<int32_t>(static_cast<int64_t>(real) + corr_range);
else if (static_cast<uint32_t>(real) >= corr_range) real = static_cast<int32_t>(static_cast<int64_t>(real) - corr_range);
return real;
}
uint32_t getK() const { return k; }
private:
void write_corrector(int32_t c, SymbolModel& m) {
uint32_t c1 = (c <= 0) ? static_cast<uint32_t>(-static_cast<int64_t>(c))
: static_cast<uint32_t>(c - 1);
k = 0;
while (c1) {
c1 >>= 1;
++k;
}
enc->encodeSymbol(m, k);
if (k == 0) {
enc->encodeBit(corrector0, static_cast<uint32_t>(c));
} else if (k < 32) {
if (c < 0) c = static_cast<int32_t>(static_cast<int64_t>(c) + ((int64_t(1) << k) - 1));
else c = static_cast<int32_t>(static_cast<int64_t>(c) - 1);
if (k <= bits_high) {
enc->encodeSymbol(corrector[k], static_cast<uint32_t>(c));
} else {
const int32_t k1 = static_cast<int32_t>(k - bits_high);
const uint32_t c_lo = static_cast<uint32_t>(c) & ((1u << k1) - 1u);
const uint32_t c_hi = static_cast<uint32_t>(c) >> k1;
enc->encodeSymbol(corrector[k], c_hi);
enc->writeBits(static_cast<uint32_t>(k1), c_lo);
}
}
// k == 32: 只编码 k,corrector 固定为 INT32_MIN
}
int32_t read_corrector(SymbolModel& m) {
const uint32_t kk = dec->decodeSymbol(m);
k = kk;
int32_t c = 0;
if (kk == 0) {
c = static_cast<int32_t>(dec->decodeBit(corrector0));
} else if (kk < 32) {
if (kk <= bits_high) {
c = static_cast<int32_t>(dec->decodeSymbol(corrector[kk]));
} else {
const uint32_t k1 = kk - bits_high;
const uint32_t c_hi = dec->decodeSymbol(corrector[kk]);
const uint32_t c_lo = dec->readBits(k1);
c = static_cast<int32_t>((c_hi << k1) | c_lo);
}
if (c >= (1 << (kk - 1))) c += 1;
else c = static_cast<int32_t>(static_cast<int64_t>(c) - ((int64_t(1) << kk) - 1));
} else {
c = corr_min;
}
return c;
}
};
/// 5 值流式中位数(LASzip StreamingMedian5 语义,用于 dX/dY 预测)
struct StreamingMedian5 {
int32_t values[5] = {0, 0, 0, 0, 0};
bool high = true;
void init() {
values[0] = values[1] = values[2] = values[3] = values[4] = 0;
high = true;
}
void add(int32_t v) {
if (high) {
if (v < values[2]) {
values[4] = values[3];
values[3] = values[2];
if (v < values[0]) {
values[2] = values[1];
values[1] = values[0];
values[0] = v;
} else if (v < values[1]) {
values[2] = values[1];
values[1] = v;
} else {
values[2] = v;
}
} else {
if (v < values[3]) {
values[4] = values[3];
values[3] = v;
} else {
values[4] = v;
}
high = false;
}
} else {
if (values[2] < v) {
values[0] = values[1];
values[1] = values[2];
if (values[4] < v) {
values[2] = values[3];
values[3] = values[4];
values[4] = v;
} else if (values[3] < v) {
values[2] = values[3];
values[3] = v;
} else {
values[2] = v;
}
} else {
if (values[1] < v) {
values[0] = values[1];
values[1] = v;
} else {
values[0] = v;
}
high = true;
}
}
}
int32_t get() const { return values[2]; }
};
constexpr uint8_t kNumberReturnMap[8][8] = {
{15, 14, 13, 12, 11, 10, 9, 8},
{14, 0, 1, 3, 6, 10, 10, 9},
{13, 1, 2, 4, 7, 11, 11, 10},
{12, 3, 4, 5, 8, 12, 12, 11},
{11, 6, 7, 8, 9, 13, 13, 12},
{10, 10, 11, 12, 13, 14, 14, 13},
{9, 10, 11, 12, 13, 14, 15, 14},
{8, 9, 10, 11, 12, 13, 14, 15}};
constexpr uint8_t kNumberReturnLevel[8][8] = {
{0, 1, 2, 3, 4, 5, 6, 7},
{1, 0, 1, 2, 3, 4, 5, 6},
{2, 1, 0, 1, 2, 3, 4, 5},
{3, 2, 1, 0, 1, 2, 3, 4},
{4, 3, 2, 1, 0, 1, 2, 3},
{5, 4, 3, 2, 1, 0, 1, 2},
{6, 5, 4, 3, 2, 1, 0, 1},
{7, 6, 5, 4, 3, 2, 1, 0}};
inline int32_t read_i32(const uint8_t* p) {
int32_t v;
std::memcpy(&v, p, 4);
return v;
}
inline void write_i32(uint8_t* p, int32_t v) { std::memcpy(p, &v, 4); }
inline uint16_t read_u16(const uint8_t* p) {
uint16_t v;
std::memcpy(&v, p, 2);
return v;
}
inline void write_u16(uint8_t* p, uint16_t v) { std::memcpy(p, &v, 2); }
inline int32_t fold_u8(int32_t n) {
if (n < 0) return n + 256;
if (n > 255) return n - 256;
return n;
}
inline int32_t clamp_u8(int32_t n) {
if (n <= 0) return 0;
if (n >= 255) return 255;
return n;
}
/// POINT10 v2(LAS 点格式 0 的核心 20 字节)编码/解码
struct Point10Codec {
SymbolModel changed_values;
IntegerCompressor ic_intensity;
SymbolModel scan_angle[2];
IntegerCompressor ic_point_source;
std::vector<SymbolModel> bit_byte, classification, user_data;
IntegerCompressor ic_dx, ic_dy, ic_z;
StreamingMedian5 median_x[16], median_y[16];
uint16_t last_intensity[16] = {};
int32_t last_height[8] = {};
uint8_t last_item[20] = {};
void init_models() {
changed_values.init(64);
ic_intensity.setup(16, 4);
scan_angle[0].init(256);
scan_angle[1].init(256);
ic_point_source.setup(16, 1);
bit_byte.assign(256, SymbolModel());
classification.assign(256, SymbolModel());
user_data.assign(256, SymbolModel());
for (auto& m : bit_byte) m.init(256);
for (auto& m : classification) m.init(256);
for (auto& m : user_data) m.init(256);
ic_dx.setup(32, 2);
ic_dy.setup(32, 22);
ic_z.setup(32, 20);
}
void init_chunk(const uint8_t* first, const Encoder* enc, const Decoder* dec) {
for (int i = 0; i < 16; ++i) {
median_x[i].init();
median_y[i].init();
last_intensity[i] = 0;
}
for (int i = 0; i < 8; ++i) last_height[i] = 0;
init_models();
ic_intensity.init(const_cast<Encoder*>(enc), const_cast<Decoder*>(dec));
ic_point_source.init(const_cast<Encoder*>(enc), const_cast<Decoder*>(dec));
ic_dx.init(const_cast<Encoder*>(enc), const_cast<Decoder*>(dec));
ic_dy.init(const_cast<Encoder*>(enc), const_cast<Decoder*>(dec));
ic_z.init(const_cast<Encoder*>(enc), const_cast<Decoder*>(dec));
std::memcpy(last_item, first, 20);
if (dec) { // 解码端:首点 intensity 视为 0(规范 12.1)
last_item[12] = 0;
last_item[13] = 0;
}
}
void encode(const uint8_t* item, Encoder& enc) {
const uint32_t r = item[14] & 0x7u;
const uint32_t n = (item[14] >> 3) & 0x7u;
const uint32_t m = kNumberReturnMap[n][r];
const uint32_t l = kNumberReturnLevel[n][r];
const uint16_t intensity = read_u16(item + 12);
const uint16_t last_psid = read_u16(last_item + 18);
const uint16_t psid = read_u16(item + 18);
const int32_t changed =
((last_item[14] != item[14]) << 5) |
((last_intensity[m] != intensity) << 4) |
((last_item[15] != item[15]) << 3) |
((last_item[16] != item[16]) << 2) |
((last_item[17] != item[17]) << 1) |
((last_psid != psid) ? 1 : 0);
enc.encodeSymbol(changed_values, static_cast<uint32_t>(changed));
if (changed & 32) enc.encodeSymbol(bit_byte[last_item[14]], item[14]);
if (changed & 16) {
ic_intensity.compress(static_cast<int32_t>(last_intensity[m]), static_cast<int32_t>(intensity),
m < 3 ? m : 3);
last_intensity[m] = intensity;
}
if (changed & 8) enc.encodeSymbol(classification[last_item[15]], item[15]);
if (changed & 4) {
const uint32_t scan_dir = (item[14] >> 6) & 1u;
enc.encodeSymbol(scan_angle[scan_dir],
static_cast<uint32_t>(fold_u8(static_cast<int32_t>(item[16]) -
static_cast<int32_t>(last_item[16]))));
}
if (changed & 2) enc.encodeSymbol(user_data[last_item[17]], item[17]);
if (changed & 1) {
ic_point_source.compress(static_cast<int32_t>(last_psid), static_cast<int32_t>(psid), 0);
}
// dX
const int32_t x = read_i32(item);
const int32_t last_x = read_i32(last_item);
int32_t diff = static_cast<int32_t>(static_cast<int64_t>(x) - static_cast<int64_t>(last_x));
const int32_t median = median_x[m].get();
ic_dx.compress(median, diff, n == 1 ? 1u : 0u);
median_x[m].add(diff);
// dY
const int32_t y = read_i32(item + 4);
const int32_t last_y = read_i32(last_item + 4);
diff = static_cast<int32_t>(static_cast<int64_t>(y) - static_cast<int64_t>(last_y));
const uint32_t kx = ic_dx.getK();
const uint32_t ctx_y = (n == 1 ? 1u : 0u) + (kx < 20 ? (kx & ~1u) : 20u);
ic_dy.compress(median_y[m].get(), diff, ctx_y);
median_y[m].add(diff);
// dZ
const int32_t z = read_i32(item + 8);
const uint32_t kxy = (ic_dx.getK() + ic_dy.getK()) / 2;
const uint32_t ctx_z = (n == 1 ? 1u : 0u) + (kxy < 18 ? (kxy & ~1u) : 18u);
ic_z.compress(last_height[l], z, ctx_z);
last_height[l] = z;
std::memcpy(last_item, item, 20);
}
void decode(uint8_t* item, Decoder& dec) {
const int32_t changed = static_cast<int32_t>(dec.decodeSymbol(changed_values));
if (changed) {
if (changed & 32) last_item[14] = static_cast<uint8_t>(dec.decodeSymbol(bit_byte[last_item[14]]));
const uint32_t r = last_item[14] & 0x7u;
const uint32_t n = (last_item[14] >> 3) & 0x7u;
const uint32_t m = kNumberReturnMap[n][r];
uint16_t intensity;
if (changed & 16) {
intensity = static_cast<uint16_t>(ic_intensity.decompress(last_intensity[m], m < 3 ? m : 3));
last_intensity[m] = intensity;
} else {
intensity = last_intensity[m];
}
write_u16(last_item + 12, intensity);
if (changed & 8) last_item[15] = static_cast<uint8_t>(dec.decodeSymbol(classification[last_item[15]]));
if (changed & 4) {
const uint32_t scan_dir = (last_item[14] >> 6) & 1u;
const int32_t val = static_cast<int32_t>(dec.decodeSymbol(scan_angle[scan_dir]));
last_item[16] = static_cast<uint8_t>(fold_u8(val + last_item[16]));
}
if (changed & 2) last_item[17] = static_cast<uint8_t>(dec.decodeSymbol(user_data[last_item[17]]));
if (changed & 1) {
const uint16_t psid = static_cast<uint16_t>(
ic_point_source.decompress(static_cast<int32_t>(read_u16(last_item + 18)), 0));
write_u16(last_item + 18, psid);
}
const uint32_t rr = last_item[14] & 0x7u;
const uint32_t nn = (last_item[14] >> 3) & 0x7u;
const uint32_t mm = kNumberReturnMap[nn][rr];
const uint32_t ll = kNumberReturnLevel[nn][rr];
const int32_t dx = ic_dx.decompress(median_x[mm].get(), nn == 1 ? 1u : 0u);
median_x[mm].add(dx);
write_i32(last_item, static_cast<int32_t>(static_cast<int64_t>(read_i32(last_item)) + dx));
const uint32_t kx = ic_dx.getK();
const uint32_t ctx_y = (nn == 1 ? 1u : 0u) + (kx < 20 ? (kx & ~1u) : 20u);
const int32_t dy = ic_dy.decompress(median_y[mm].get(), ctx_y);
median_y[mm].add(dy);
write_i32(last_item + 4, static_cast<int32_t>(static_cast<int64_t>(read_i32(last_item + 4)) + dy));
const uint32_t kxy = (ic_dx.getK() + ic_dy.getK()) / 2;
const uint32_t ctx_z = (nn == 1 ? 1u : 0u) + (kxy < 18 ? (kxy & ~1u) : 18u);
const int32_t z = ic_z.decompress(last_height[ll], ctx_z);
last_height[ll] = z;
write_i32(last_item + 8, z);
} else {
const uint32_t r = last_item[14] & 0x7u;
const uint32_t n = (last_item[14] >> 3) & 0x7u;
const uint32_t m = kNumberReturnMap[n][r];
const uint32_t l = kNumberReturnLevel[n][r];
write_u16(last_item + 12, last_intensity[m]);
const int32_t dx = ic_dx.decompress(median_x[m].get(), n == 1 ? 1u : 0u);
median_x[m].add(dx);
write_i32(last_item, static_cast<int32_t>(static_cast<int64_t>(read_i32(last_item)) + dx));
const uint32_t kx = ic_dx.getK();
const uint32_t ctx_y = (n == 1 ? 1u : 0u) + (kx < 20 ? (kx & ~1u) : 20u);
const int32_t dy = ic_dy.decompress(median_y[m].get(), ctx_y);
median_y[m].add(dy);
write_i32(last_item + 4, static_cast<int32_t>(static_cast<int64_t>(read_i32(last_item + 4)) + dy));
const uint32_t kxy = (ic_dx.getK() + ic_dy.getK()) / 2;
const uint32_t ctx_z = (n == 1 ? 1u : 0u) + (kxy < 18 ? (kxy & ~1u) : 18u);
const int32_t z = ic_z.decompress(last_height[l], ctx_z);
last_height[l] = z;
write_i32(last_item + 8, z);
}
std::memcpy(item, last_item, 20);
}
};
/// RGB12 v2(LAS 点格式 2 的 6 字节)编码/解码
struct Rgb12Codec {
SymbolModel byte_used;
SymbolModel diff[6];
uint8_t last_item[6] = {};
void init_models() {
byte_used.init(128);
for (auto& m : diff) m.init(256);
}
void init_chunk(const uint8_t* first) {
init_models();
std::memcpy(last_item, first, 6);
}
void encode(const uint8_t* item, Encoder& enc) {
const uint16_t r = read_u16(item);
const uint16_t g = read_u16(item + 2);
const uint16_t b = read_u16(item + 4);
const uint16_t lr = read_u16(last_item);
const uint16_t lg = read_u16(last_item + 2);
const uint16_t lb = read_u16(last_item + 4);
uint32_t sym = ((lr & 0x00FF) != (r & 0x00FF)) ? 0x01u : 0u;
sym |= ((lr & 0xFF00) != (r & 0xFF00)) ? 0x02u : 0u;
sym |= ((lg & 0x00FF) != (g & 0x00FF)) ? 0x04u : 0u;
sym |= ((lg & 0xFF00) != (g & 0xFF00)) ? 0x08u : 0u;
sym |= ((lb & 0x00FF) != (b & 0x00FF)) ? 0x10u : 0u;
sym |= ((lb & 0xFF00) != (b & 0xFF00)) ? 0x20u : 0u;
const bool same_as_red = ((r & 0x00FF) != (g & 0x00FF)) ||
((r & 0x00FF) != (b & 0x00FF)) ||
((r & 0xFF00) != (g & 0xFF00)) ||
((r & 0xFF00) != (b & 0xFF00));
if (same_as_red) sym |= 0x40u;
enc.encodeSymbol(byte_used, sym);
int32_t diff_l = 0;
int32_t diff_h = 0;
if (sym & 0x01) {
diff_l = static_cast<int32_t>(r & 255) - static_cast<int32_t>(lr & 255);
enc.encodeSymbol(diff[0], static_cast<uint32_t>(fold_u8(diff_l)));
}
if (sym & 0x02) {
diff_h = static_cast<int32_t>(r >> 8) - static_cast<int32_t>(lr >> 8);
enc.encodeSymbol(diff[1], static_cast<uint32_t>(fold_u8(diff_h)));
}
if (sym & 0x40) {
if (sym & 0x04) {
const int32_t corr = static_cast<int32_t>(g & 255) - clamp_u8(diff_l + static_cast<int32_t>(lg & 255));
enc.encodeSymbol(diff[2], static_cast<uint32_t>(fold_u8(corr)));
}
if (sym & 0x10) {
diff_l = (diff_l + static_cast<int32_t>(g & 255) - static_cast<int32_t>(lg & 255)) / 2;
const int32_t corr = static_cast<int32_t>(b & 255) - clamp_u8(diff_l + static_cast<int32_t>(lb & 255));
enc.encodeSymbol(diff[4], static_cast<uint32_t>(fold_u8(corr)));
}
if (sym & 0x08) {
const int32_t corr = static_cast<int32_t>(g >> 8) - clamp_u8(diff_h + static_cast<int32_t>(lg >> 8));
enc.encodeSymbol(diff[3], static_cast<uint32_t>(fold_u8(corr)));
}
if (sym & 0x20) {
diff_h = (diff_h + static_cast<int32_t>(g >> 8) - static_cast<int32_t>(lg >> 8)) / 2;
const int32_t corr = static_cast<int32_t>(b >> 8) - clamp_u8(diff_h + static_cast<int32_t>(lb >> 8));
enc.encodeSymbol(diff[5], static_cast<uint32_t>(fold_u8(corr)));
}
}
std::memcpy(last_item, item, 6);
}
void decode(uint8_t* item, Decoder& dec) {
const uint16_t lr = read_u16(last_item);
const uint16_t lg = read_u16(last_item + 2);
const uint16_t lb = read_u16(last_item + 4);
const uint32_t sym = dec.decodeSymbol(byte_used);
uint16_t r = 0, g = 0, b = 0;
if (sym & 0x01) {
const int32_t corr = static_cast<int32_t>(dec.decodeSymbol(diff[0]));
r = static_cast<uint16_t>(fold_u8(corr + static_cast<int32_t>(lr & 255)));
} else {
r = lr & 0xFF;
}
if (sym & 0x02) {
const int32_t corr = static_cast<int32_t>(dec.decodeSymbol(diff[1]));
r |= static_cast<uint16_t>(fold_u8(corr + static_cast<int32_t>(lr >> 8)) << 8);
} else {
r |= lr & 0xFF00;
}
if (sym & 0x40) {
int32_t d = static_cast<int32_t>(r & 0x00FF) - static_cast<int32_t>(lr & 0x00FF);
if (sym & 0x04) {
const int32_t corr = static_cast<int32_t>(dec.decodeSymbol(diff[2]));
g = static_cast<uint16_t>(fold_u8(corr + clamp_u8(d + static_cast<int32_t>(lg & 255))));
} else {
g = lg & 0xFF;
}
if (sym & 0x10) {
const int32_t corr = static_cast<int32_t>(dec.decodeSymbol(diff[4]));
d = (d + static_cast<int32_t>(g & 0x00FF) - static_cast<int32_t>(lg & 0x00FF)) / 2;
b = static_cast<uint16_t>(fold_u8(corr + clamp_u8(d + static_cast<int32_t>(lb & 255))));
} else {
b = lb & 0xFF;
}
d = static_cast<int32_t>(r >> 8) - static_cast<int32_t>(lr >> 8);
if (sym & 0x08) {
const int32_t corr = static_cast<int32_t>(dec.decodeSymbol(diff[3]));
g |= static_cast<uint16_t>(fold_u8(corr + clamp_u8(d + static_cast<int32_t>(lg >> 8))) << 8);
} else {
g |= lg & 0xFF00;
}
if (sym & 0x20) {
const int32_t corr = static_cast<int32_t>(dec.decodeSymbol(diff[5]));
d = (d + static_cast<int32_t>(g >> 8) - static_cast<int32_t>(lg >> 8)) / 2;
b |= static_cast<uint16_t>(fold_u8(corr + clamp_u8(d + static_cast<int32_t>(lb >> 8))) << 8);
} else {
b |= lb & 0xFF00;
}
} else {
g = r;
b = r;
}
write_u16(item, r);
write_u16(item + 2, g);
write_u16(item + 4, b);
std::memcpy(last_item, item, 6);
}
};
/// 一个 chunk 的编码:首点原始存储 + 其余点算术编码(POINT10 [+RGB12])
inline void encode_chunk(const uint8_t* records, uint32_t count, uint16_t rec_len,
bool has_rgb, std::vector<uint8_t>& chunk_bytes) {
const size_t chunk_start = chunk_bytes.size();
chunk_bytes.insert(chunk_bytes.end(), records, records + rec_len);
Encoder enc;
enc.init();
Point10Codec p10;
p10.init_chunk(records, &enc, nullptr);
Rgb12Codec rgb;
if (has_rgb) rgb.init_chunk(records + 20);
for (uint32_t i = 1; i < count; ++i) {
const uint8_t* rec = records + static_cast<size_t>(i) * rec_len;
p10.encode(rec, enc);
if (has_rgb) rgb.encode(rec + 20, enc);
}
enc.done();
chunk_bytes.insert(chunk_bytes.end(), enc.out.begin(), enc.out.end());
(void)chunk_start;
}
/// 一个 chunk 的解码:写入 records(count × rec_len 原始 LAS 点记录字节)
inline void decode_chunk(const uint8_t* chunk_data, size_t chunk_size, uint32_t count,
uint16_t rec_len, bool has_rgb, std::vector<uint8_t>& records) {
if (count == 0 || chunk_size < rec_len) return;
const size_t base = records.size();
records.resize(base + static_cast<size_t>(count) * rec_len);
std::memcpy(records.data() + base, chunk_data, rec_len);
if (count == 1) return;
Decoder dec;
dec.init(chunk_data + rec_len, chunk_size - rec_len);
Point10Codec p10;
p10.init_chunk(records.data() + base, nullptr, &dec);
Rgb12Codec rgb;
if (has_rgb) rgb.init_chunk(records.data() + base + 20);
for (uint32_t i = 1; i < count; ++i) {
uint8_t* rec = records.data() + base + static_cast<size_t>(i) * rec_len;
p10.decode(rec, dec);
if (has_rgb) rgb.decode(rec + 20, dec);
}
}
} // namespace laz
PointCloudIoResult PointCloud::save_laz(const std::string& path) const {
// ── 真实 LAZ 1.2 写出(LASzip 兼容,compressor 2 = pointwise + chunked)──
// 文件结构(OGC LAZ 1.4 / LASzip 3.x legacy LAZ 1.2):
// LAS 1.2 Public Header(227B) + LASzip VLR(id 22204) + 压缩数据块:
// [I64 chunk table offset][chunk 1..n][chunk table]。
// 每个 chunk = 首点原始记录 + 其余点 POINT10 v2(+RGB12 v2)算术编码数据流;
// chunk table = U32 version(0) + U32 n + IntegerCompressor(32,2) 编码的
// chunk 字节数差分。
// 量化:与 save_las 同策略(scale=1e-6,必要时按包围盒放大防 int32 溢出)。
PointCloudIoResult r;
if (vertices.empty()) {
r.status = PointCloudIoStatus::Error;
r.message = "save_laz: empty point cloud";
return r;
}
double minx = vertices[0].x(), maxx = minx;
double miny = vertices[0].y(), maxy = miny;
double minz = vertices[0].z(), maxz = minz;
for (const auto& v : vertices) {
minx = std::min(minx, v.x()); maxx = std::max(maxx, v.x());
miny = std::min(miny, v.y()); maxy = std::max(maxy, v.y());
minz = std::min(minz, v.z()); maxz = std::max(maxz, v.z());
}
auto pick_scale = [](double span) {
constexpr double kMaxInt32 = 2147483647.0;
double s = 1e-6;
if (span / s > kMaxInt32) s = span / kMaxInt32;
return s;
};
const double sx = pick_scale(maxx - minx);
const double sy = pick_scale(maxy - miny);
const double sz = pick_scale(maxz - minz);
const uint64_t n = static_cast<uint64_t>(vertices.size());
const bool with_rgb = has_colors() && colors.size() == vertices.size();
const uint8_t pdrf = with_rgb ? 2 : 0;
const uint16_t rec_len = with_rgb ? 26 : 20;
const uint16_t header_size = 227; // LAS 1.2
const uint16_t num_items = with_rgb ? 2 : 1; // POINT10 (+ RGB12)
const uint16_t vlr_payload = static_cast<uint16_t>(34 + 6 * num_items);
const uint32_t offset_to_point_data =
static_cast<uint32_t>(header_size + 54 + vlr_payload);
constexpr uint32_t kChunkSize = 50000; // LASzip 默认 chunk 点数
auto quant = [](double v, double off, double scale) {
const double q = std::round((v - off) / scale);
const double hi = 2147483647.0, lo = -2147483648.0;
return static_cast<int32_t>(std::max(lo, std::min(hi, q)));
};
// 原始点记录(POINT10 = 20B;PDRF2 追加 RGB12 = 6B)
std::vector<uint8_t> records(static_cast<size_t>(n) * rec_len, 0);
for (size_t i = 0; i < vertices.size(); ++i) {
const auto& v = vertices[i];
uint8_t* rec = records.data() + i * rec_len;
laz::write_i32(rec + 0, quant(v.x(), minx, sx));
laz::write_i32(rec + 4, quant(v.y(), miny, sy));
laz::write_i32(rec + 8, quant(v.z(), minz, sz));
double inten = has_intensity() ? intensities[i] : 0.0;
inten = std::max(0.0, std::min(65535.0, std::round(inten)));
laz::write_u16(rec + 12, static_cast<uint16_t>(inten));
rec[14] = static_cast<uint8_t>((1u & 0x7u) | ((1u & 0x7u) << 3)); // return 1 of 1
rec[15] = 0; // classification
rec[16] = 0; // scan angle rank
rec[17] = 0; // user data
laz::write_u16(rec + 18, 0); // point source id
if (with_rgb) {
laz::write_u16(rec + 20, static_cast<uint16_t>(static_cast<uint16_t>(colors[i][0]) << 8));
laz::write_u16(rec + 22, static_cast<uint16_t>(static_cast<uint16_t>(colors[i][1]) << 8));
laz::write_u16(rec + 24, static_cast<uint16_t>(static_cast<uint16_t>(colors[i][2]) << 8));
}
}
// ── 分 chunk 编码 ──
std::vector<uint8_t> chunk_stream; // 所有 chunk 的字节(首点原始 + 算术编码流)
std::vector<uint32_t> chunk_sizes;
for (uint64_t start = 0; start < n; start += kChunkSize) {
const uint32_t cnt = static_cast<uint32_t>(std::min<uint64_t>(kChunkSize, n - start));
const size_t before = chunk_stream.size();
laz::encode_chunk(records.data() + static_cast<size_t>(start) * rec_len, cnt, rec_len,
with_rgb, chunk_stream);
chunk_sizes.push_back(static_cast<uint32_t>(chunk_stream.size() - before));
}
const uint64_t chunk_table_offset = offset_to_point_data + 8 + chunk_stream.size();
// ── chunk table(算术编码的 chunk 字节数差分)──
std::vector<uint8_t> chunk_table;
{
laz::Encoder enc;
enc.init();
laz::IntegerCompressor ic;
ic.setup(32, 2);
ic.init(&enc, nullptr);
uint32_t prev = 0;
for (uint32_t sz : chunk_sizes) {
ic.compress(static_cast<int32_t>(prev), static_cast<int32_t>(sz), 1);
prev = sz;
}
enc.done();
auto push_u32 = [&chunk_table](uint32_t v) {
for (int i = 0; i < 4; ++i) chunk_table.push_back(static_cast<uint8_t>((v >> (8 * i)) & 0xFF));
};
push_u32(0); // version
push_u32(static_cast<uint32_t>(chunk_sizes.size())); // number of chunks
chunk_table.insert(chunk_table.end(), enc.out.begin(), enc.out.end());
}
std::ofstream out(path, std::ios::binary);
if (!out) {
r.status = PointCloudIoStatus::Error;
r.message = "save_laz: cannot open output file: " + path;
return r;
}
// ── LAS 1.2 Public Header Block (227 B) ──
out.write("LASF", 4);
w_u16(out, 0); // file source id
w_u16(out, 0); // global encoding
w_u32(out, 0); // guid1
w_u16(out, 0); w_u16(out, 0); // guid2/3
for (int i = 0; i < 8; ++i) w_u8(out, 0); // guid4
w_u8(out, 1); w_u8(out, 2); // version 1.2
w_str(out, "VDE", 32); // system identifier
w_str(out, "ViewDesignEngine", 32); // generating software
w_u16(out, 0); // creation day
w_u16(out, 2026); // creation year
w_u16(out, header_size);
w_u32(out, offset_to_point_data);
w_u32(out, 1); // number of VLRs (LASzip)
w_u8(out, static_cast<uint8_t>(0x80 | pdrf)); // bit7 = compressed (LASzip legacy)
w_u16(out, rec_len);
const uint32_t legacy_count = static_cast<uint32_t>(std::min<uint64_t>(n, 0xFFFFFFFFull));
w_u32(out, legacy_count);
for (int i = 0; i < 5; ++i) w_u32(out, i == 0 ? legacy_count : 0u);
w_f64(out, sx); w_f64(out, sy); w_f64(out, sz);
w_f64(out, minx); w_f64(out, miny); w_f64(out, minz);
w_f64(out, maxx); w_f64(out, minx);
w_f64(out, maxy); w_f64(out, miny);
w_f64(out, maxz); w_f64(out, minz);
// ── LASzip VLR(user_id "laszip encoded", record id 22204)──
w_u16(out, 0); // reserved
w_str(out, "laszip encoded", 16);
w_u16(out, 22204); // record id
w_u16(out, vlr_payload);
w_str(out, "VDE LASzip 1.2 pointwise-chunked", 32);
w_u16(out, 2); // compressor = pointwise chunked
w_u16(out, 0); // coder = arithmetic
w_u8(out, 3); w_u8(out, 5); // LASzip version 3.5
w_u16(out, 1); // revision 1
w_u32(out, 0); // options
w_u32(out, kChunkSize); // chunk size (points per chunk)
w_u64(out, 0); // number of special EVLRs
w_u64(out, 0); // offset to special EVLRs
w_u16(out, num_items);
w_u16(out, 6); w_u16(out, 20); w_u16(out, 2); // POINT10 v2 (20 B)
if (with_rgb) {
w_u16(out, 8); w_u16(out, 6); w_u16(out, 2); // RGB12 v2 (6 B)
}
// ── 压缩数据块:chunk table offset + chunks + chunk table ──
w_raw(out, static_cast<int64_t>(chunk_table_offset));
out.write(reinterpret_cast<const char*>(chunk_stream.data()),
static_cast<std::streamsize>(chunk_stream.size()));
out.write(reinterpret_cast<const char*>(chunk_table.data()),
static_cast<std::streamsize>(chunk_table.size()));
out.flush();
if (!out.good()) {
r.status = PointCloudIoStatus::Error;
r.message = "save_laz: write failure: " + path;
return r;
}
const uint64_t file_size = chunk_table_offset + chunk_table.size();
r.status = PointCloudIoStatus::Ok;
std::ostringstream msg;
msg << "LAZ 1.2 (LASzip VLR 22204, compressor=2 pointwise-chunked, POINT10 v2"
<< (with_rgb ? " + RGB12 v2" : "") << "), PDRF " << static_cast<int>(pdrf)
<< ", " << n << " points, " << chunk_sizes.size() << " chunk(s), file="
<< file_size << " B, chunk_table@" << chunk_table_offset;
r.message = msg.str();
return r;
}
namespace {
/// E57 field descriptor parsed from XML prototype
enum class E57FieldKind { Int, ScaledInt, Float, Double, Unsupported };
struct E57Field {
E57FieldKind kind = E57FieldKind::Unsupported;
int64_t min_val = 0, max_val = 0;
double scale = 1.0, offset = 0.0;
int byte_size = 0;
unsigned bits_per_record = 0; ///< standard bitPack 位宽
std::string name;
};
/// Parse a single <...> element: extract attribute name="value"
std::string xml_attr(const std::string& elem, const std::string& attr) {
auto key = attr + "=\"";
auto pos = elem.find(key);
if (pos == std::string::npos) return "";
pos += key.size();
auto end = elem.find('"', pos);
if (end == std::string::npos) return "";
return elem.substr(pos, end - pos);
}
/// Determine byte size from integer range (E57: ceil(log2(range)/8))
int int_byte_size(int64_t lo, int64_t hi) {
uint64_t range = static_cast<uint64_t>(hi - lo) + 1;
int bits = 0;
uint64_t v = range - 1;
while (v > 0) { v >>= 1; ++bits; }
return std::max(1, (bits + 7) / 8);
}
/// Standard bitPack integer width: ceil(log2(max-min+1)) bits.
unsigned int_bits_needed(int64_t lo, int64_t hi) {
const uint64_t range = static_cast<uint64_t>(hi - lo) + 1;
unsigned bits = 0;
uint64_t v = range - 1;
while (v > 0) { v >>= 1; ++bits; }
return bits;
}
/// Parse a legacy <Float name=.../> or standard <cartesianX type="Float".../>
/// (also Integer/ScaledInteger) element.
E57Field parse_e57_field(const std::string& elem) {
E57Field f;
f.name = xml_attr(elem, "name");
const std::string type_attr = xml_attr(elem, "type");
if (f.name.empty() && !elem.empty() && elem[0] == '<') {
const std::size_t begin = elem.find_first_not_of("</");
const std::size_t end = elem.find_first_of(" \t\r\n/>", begin);
if (begin != std::string::npos && end != std::string::npos) {
f.name = elem.substr(begin, end - begin);
}
}
const bool is_integer = type_attr == "Integer" || elem.find("<Integer") == 0;
const bool is_scaled = type_attr == "ScaledInteger" || elem.find("<ScaledInteger") == 0;
const bool is_float = type_attr == "Float" || elem.find("<Float") == 0;
const bool is_string = type_attr == "String" || elem.find("<String") == 0;
if (is_scaled) {
f.kind = E57FieldKind::ScaledInt;
const std::string lo = xml_attr(elem, "minimum");
const std::string hi = xml_attr(elem, "maximum");
if (!lo.empty()) f.min_val = std::stoll(lo);
if (!hi.empty()) f.max_val = std::stoll(hi);
f.scale = xml_attr(elem, "scale").empty() ? 1.0 : std::stod(xml_attr(elem, "scale"));
f.offset = xml_attr(elem, "offset").empty() ? 0.0 : std::stod(xml_attr(elem, "offset"));
f.byte_size = int_byte_size(f.min_val, f.max_val);
f.bits_per_record = int_bits_needed(f.min_val, f.max_val);
} else if (is_integer) {
f.kind = E57FieldKind::Int;
const std::string lo = xml_attr(elem, "minimum");
const std::string hi = xml_attr(elem, "maximum");
if (!lo.empty()) f.min_val = std::stoll(lo);
if (!hi.empty()) f.max_val = std::stoll(hi);
f.byte_size = int_byte_size(f.min_val, f.max_val);
f.bits_per_record = int_bits_needed(f.min_val, f.max_val);
} else if (is_float) {
f.kind = E57FieldKind::Float;
const std::string prec = xml_attr(elem, "precision");
f.byte_size = (prec == "single") ? 4 : 8; // E57 default is double
f.bits_per_record = static_cast<unsigned>(f.byte_size * 8);
} else if (is_string) {
f.kind = E57FieldKind::Unsupported;
f.byte_size = 0;
}
return f;
}
/// Read an integer of byte_size bytes (little-endian, optionally signed)
int64_t read_le_int(const char* buf, int byte_size, bool is_signed) {
uint64_t val = 0;
for (int i = 0; i < byte_size; ++i)
val |= (static_cast<uint64_t>(static_cast<uint8_t>(buf[i])) << (i * 8));
if (is_signed) {
// Sign-extend if high bit is set
if (byte_size < 8 && (val >> (byte_size * 8 - 1)) & 1) {
for (int i = byte_size; i < 8; ++i) val |= (0xFFULL << (i * 8));
}
}
return static_cast<int64_t>(val);
}
/// Read a little-endian float (4 or 8 bytes)
double read_le_float(const char* buf, int byte_size) {
if (byte_size == 8) {
double v;
std::memcpy(&v, buf, 8);
return v;
} else {
float v;
std::memcpy(&v, buf, 4);
return static_cast<double>(v);
}
}
/// Recursively parse a prototype subtree to extract field definitions
void parse_e57_proto(const std::string& xml, size_t start, size_t end,
std::vector<E57Field>& fields, int depth) {
size_t pos = start;
while (pos < end) {
// Skip whitespace
while (pos < end && (xml[pos] == ' ' || xml[pos] == '\n' || xml[pos] == '\r' || xml[pos] == '\t')) ++pos;
if (pos >= end) break;
if (xml[pos] != '<') { ++pos; continue; }
// Find matching >
auto gt = xml.find('>', pos);
if (gt == std::string::npos) break;
std::string elem = xml.substr(pos, gt - pos + 1);
// Check for Structure / Vector / sub-proto
bool is_structure = (elem.find("<Structure") == 0);
bool is_vector = (elem.find("<Vector") == 0);
bool is_close = (elem.rfind("</") == 0 || elem.rfind("/>") == elem.size() - 2);
if ((is_structure || is_vector) && !is_close) {
// Find matching closing tag
std::string tag = is_structure ? "Structure" : "Vector";
std::string close_tag = "</" + tag + ">";
auto close = xml.find(close_tag, gt + 1);
if (close != std::string::npos) {
parse_e57_proto(xml, gt + 1, close, fields, depth + 1);
pos = close + close_tag.size();
continue;
}
}
// Parse leaf field
auto f = parse_e57_field(elem);
if (f.kind != E57FieldKind::Unsupported && !f.name.empty()) {
fields.push_back(f);
}
pos = gt + 1;
}
}
/// Find the prototype with given name in XML
std::vector<E57Field> find_prototype(const std::string& xml, const std::string& proto_name) {
// Search for: <protoName type="Structure">
std::vector<E57Field> fields;
std::string search = "<" + proto_name;
auto pos = xml.find(search);
if (pos == std::string::npos) return fields;
auto gt = xml.find('>', pos);
if (gt == std::string::npos) return fields;
// Find closing tag
std::string close_tag = "</" + proto_name + ">";
auto close = xml.find(close_tag, gt + 1);
if (close == std::string::npos) return fields;
parse_e57_proto(xml, gt + 1, close, fields, 0);
return fields;
}
/// Recursively parse the prototype to determine byte size per record
int compute_record_size(const std::vector<E57Field>& fields) {
int size = 0;
for (const auto& f : fields) size += f.byte_size;
return size;
}
/// Read one record from binary buffer into a map of name→value
struct E57Record {
double x = 0, y = 0, z = 0;
double nx = 0, ny = 0, nz = 0;
bool has_normals = false;
uint8_t r = 128, g = 128, b = 128;
bool has_color = false;
double intensity = 0;
bool has_intensity = false;
};
E57Record read_e57_record(const char* buf, const std::vector<E57Field>& fields) {
E57Record rec;
int off = 0;
for (const auto& f : fields) {
double val = 0;
switch (f.kind) {
case E57FieldKind::Int:
val = static_cast<double>(read_le_int(buf + off, f.byte_size, false)) + static_cast<double>(f.min_val);
break;
case E57FieldKind::ScaledInt:
val = (static_cast<double>(read_le_int(buf + off, f.byte_size, false)) + static_cast<double>(f.min_val)) * f.scale + f.offset;
break;
case E57FieldKind::Float:
val = read_le_float(buf + off, f.byte_size);
break;
default:
break;
}
off += f.byte_size;
// Map known E57 field names
if (f.name == "cartesianX" || f.name == "x") rec.x = val;
else if (f.name == "cartesianY" || f.name == "y") rec.y = val;
else if (f.name == "cartesianZ" || f.name == "z") rec.z = val;
else if (f.name == "nor:normalX" || f.name == "normalX") { rec.nx = val; rec.has_normals = true; }
else if (f.name == "nor:normalY" || f.name == "normalY") { rec.ny = val; rec.has_normals = true; }
else if (f.name == "nor:normalZ" || f.name == "normalZ") { rec.nz = val; rec.has_normals = true; }
else if (f.name == "colorRed" || f.name == "red") { rec.r = static_cast<uint8_t>(std::max(0.0, std::min(255.0, val))); rec.has_color = true; }
else if (f.name == "colorGreen" || f.name == "green") { rec.g = static_cast<uint8_t>(std::max(0.0, std::min(255.0, val))); rec.has_color = true; }
else if (f.name == "colorBlue" || f.name == "blue") { rec.b = static_cast<uint8_t>(std::max(0.0, std::min(255.0, val))); rec.has_color = true; }
else if (f.name == "intensity" || f.name == "Intensity") { rec.intensity = val; rec.has_intensity = true; }
}
return rec;
}
// ── FMT-12: standard E57 CompressedVector reader (bitPack, data packets) ──
std::uint16_t le_u16(const char* p) {
return static_cast<std::uint16_t>(static_cast<std::uint8_t>(p[0]) |
(static_cast<std::uint16_t>(static_cast<std::uint8_t>(p[1])) << 8));
}
std::uint64_t le_u64(const char* p) {
std::uint64_t value = 0;
for (int i = 0; i < 8; ++i) value |= static_cast<std::uint64_t>(static_cast<std::uint8_t>(p[i])) << (i * 8);
return value;
}
std::uint64_t read_lsb_bits(const std::uint8_t* data, std::size_t byte_length,
std::size_t bit_position, unsigned bits) {
std::uint64_t value = 0;
for (unsigned i = 0; i < bits; ++i) {
const std::size_t bit = bit_position + i;
if (bit / 8 >= byte_length) break;
if ((data[bit / 8] >> (bit % 8)) & 1u) value |= (std::uint64_t(1) << i);
}
return value;
}
void map_e57_field(E57Record& rec, const E57Field& f, double val) {
if (f.name == "cartesianX" || f.name == "x") rec.x = val;
else if (f.name == "cartesianY" || f.name == "y") rec.y = val;
else if (f.name == "cartesianZ" || f.name == "z") rec.z = val;
else if (f.name == "nor:normalX" || f.name == "normalX") { rec.nx = val; rec.has_normals = true; }
else if (f.name == "nor:normalY" || f.name == "normalY") { rec.ny = val; rec.has_normals = true; }
else if (f.name == "nor:normalZ" || f.name == "normalZ") { rec.nz = val; rec.has_normals = true; }
else if (f.name == "colorRed" || f.name == "red") {
rec.r = static_cast<std::uint8_t>(std::max(0.0, std::min(255.0, val))); rec.has_color = true;
} else if (f.name == "colorGreen" || f.name == "green") {
rec.g = static_cast<std::uint8_t>(std::max(0.0, std::min(255.0, val))); rec.has_color = true;
} else if (f.name == "colorBlue" || f.name == "blue") {
rec.b = static_cast<std::uint8_t>(std::max(0.0, std::min(255.0, val))); rec.has_color = true;
} else if (f.name == "intensity" || f.name == "Intensity") {
rec.intensity = val; rec.has_intensity = true;
}
}
struct StandardE57Points {
std::uint64_t file_offset = 0;
std::size_t record_count = 0;
std::vector<E57Field> fields;
};
StandardE57Points parse_standard_e57_points(const std::string& xml) {
StandardE57Points result;
std::size_t search = 0;
std::size_t points = std::string::npos;
while ((points = xml.find("<points", search)) != std::string::npos) {
const auto gt = xml.find('>', points);
if (gt == std::string::npos) break;
const std::string tag = xml.substr(points, gt - points + 1);
if (tag.find("type=\"CompressedVector\"") != std::string::npos) break;
search = gt + 1;
}
if (points == std::string::npos) {
throw std::runtime_error("E57 standard: missing <points type=\"CompressedVector\">");
}
const auto points_gt = xml.find('>', points);
const auto points_close = xml.find("</points>", points_gt);
if (points_gt == std::string::npos || points_close == std::string::npos) {
throw std::runtime_error("E57 standard: malformed points node");
}
const std::string points_tag = xml.substr(points, points_gt - points + 1);
const std::string file_offset = xml_attr(points_tag, "fileOffset");
const std::string record_count = xml_attr(points_tag, "recordCount");
if (file_offset.empty() || record_count.empty()) {
throw std::runtime_error("E57 standard: points missing fileOffset/recordCount");
}
result.file_offset = std::stoull(file_offset);
result.record_count = static_cast<std::size_t>(std::stoull(record_count));
if (result.record_count == 0) {
throw std::runtime_error("E57 standard: recordCount=0");
}
const auto codecs = xml.find("<codecs", points_gt);
if (codecs == std::string::npos || codecs > points_close) {
throw std::runtime_error("E57 standard: missing <codecs>");
}
const auto codecs_gt = xml.find('>', codecs);
const auto codecs_close = xml.find("</codecs>", codecs_gt);
if (codecs_gt == std::string::npos || codecs_close == std::string::npos) {
throw std::runtime_error("E57 standard: malformed <codecs>");
}
const std::string codecs_body = xml.substr(codecs_gt + 1, codecs_close - codecs_gt - 1);
if (codecs_body.find('<') != std::string::npos &&
codecs_body.find("bitPackCodec") == std::string::npos) {
throw std::runtime_error("E57 standard: unsupported codec (only bitPackCodec supported)");
}
const auto proto = xml.find("<prototype", points_gt);
if (proto == std::string::npos || proto > points_close) {
throw std::runtime_error("E57 standard: missing prototype");
}
const auto proto_gt = xml.find('>', proto);
const auto proto_close = xml.find("</prototype>", proto_gt);
if (proto_gt == std::string::npos || proto_close == std::string::npos) {
throw std::runtime_error("E57 standard: malformed prototype");
}
parse_e57_proto(xml, proto_gt + 1, proto_close, result.fields, 0);
if (result.fields.empty()) {
throw std::runtime_error("E57 standard: prototype has no supported fields");
}
return result;
}
using E57ReadAt = std::function<void(std::uint64_t, char*, std::size_t)>;
PointCloud load_standard_e57(const E57ReadAt& read_at, const std::string& xml,
std::uint64_t source_size, bool page_layer) {
StandardE57Points points = parse_standard_e57_points(xml);
const auto read_byte = [&](std::uint64_t offset) -> int {
if (offset >= source_size) return -1;
char byte = 0;
read_at(offset, &byte, 1);
return static_cast<unsigned char>(byte);
};
const auto resolve_offset = [&](std::uint64_t offset, bool section) {
if (!page_layer) return offset;
const auto plausible = [&](std::uint64_t candidate) {
if (section) {
return candidate + 32 <= source_size && read_byte(candidate) == 1;
}
return candidate + 6 <= source_size && read_byte(candidate) == 1;
};
if (plausible(offset)) return offset;
const std::uint64_t logical = physical_to_logical(offset);
if (plausible(logical)) return logical;
return offset;
};
points.file_offset = resolve_offset(points.file_offset, true);
if (points.file_offset + 32 > source_size) {
throw std::runtime_error("E57 standard: compressed vector section out of range");
}
std::vector<char> section_header(32);
read_at(points.file_offset, section_header.data(), section_header.size());
if (static_cast<std::uint8_t>(section_header[0]) != 1) {
throw std::runtime_error("E57 standard: bad compressed-vector section header");
}
const std::uint64_t section_length = le_u64(section_header.data() + 8);
const std::uint64_t data_offset = resolve_offset(le_u64(section_header.data() + 16), false);
std::uint64_t index_offset = le_u64(section_header.data() + 24);
if (page_layer) {
const auto plausible_index = [&](std::uint64_t candidate) {
return candidate + 16 <= source_size && read_byte(candidate) == 0;
};
if (!plausible_index(index_offset)) {
const std::uint64_t logical = physical_to_logical(index_offset);
if (plausible_index(logical)) index_offset = logical;
}
}
if (points.file_offset + section_length > source_size || data_offset < points.file_offset ||
data_offset + 6 > source_size) {
throw std::runtime_error("E57 standard: invalid section offsets");
}
const std::uint64_t data_end =
(index_offset > data_offset && index_offset <= points.file_offset + section_length)
? index_offset
: points.file_offset + section_length;
PointCloud cloud;
std::size_t decoded = 0;
std::uint64_t packet_pos = data_offset;
while (decoded < points.record_count) {
if (packet_pos + 6 > data_end) {
throw std::runtime_error("E57 standard: truncated data packet header");
}
std::vector<char> header(6);
read_at(packet_pos, header.data(), header.size());
if (static_cast<std::uint8_t>(header[0]) != 1) {
throw std::runtime_error("E57 standard: expected data packet");
}
const std::uint16_t packet_length_minus1 = le_u16(header.data() + 2);
const std::uint16_t stream_count = le_u16(header.data() + 4);
const std::size_t packet_length = static_cast<std::size_t>(packet_length_minus1) + 1;
if (packet_length < 6u + 2u * stream_count || packet_pos + packet_length > data_end) {
throw std::runtime_error("E57 standard: invalid data packet length");
}
if (stream_count != points.fields.size()) {
throw std::runtime_error("E57 standard: bytestream count does not match prototype");
}
std::vector<char> rest(packet_length - 6);
read_at(packet_pos + 6, rest.data(), rest.size());
std::vector<char> packet(packet_length);
std::memcpy(packet.data(), header.data(), 6);
std::memcpy(packet.data() + 6, rest.data(), rest.size());
std::vector<std::uint16_t> stream_lengths(stream_count);
std::size_t stream_base = 6u + 2u * stream_count;
std::size_t stream_total = 0;
for (std::size_t i = 0; i < stream_count; ++i) {
stream_lengths[i] = le_u16(packet.data() + 6 + 2 * i);
stream_total += stream_lengths[i];
}
if (stream_base + stream_total > packet_length) {
throw std::runtime_error("E57 standard: bytestream lengths exceed packet");
}
std::size_t records_in_packet = points.record_count - decoded;
for (std::size_t i = 0; i < points.fields.size(); ++i) {
const unsigned bits = points.fields[i].bits_per_record;
if (bits == 0) continue;
const std::size_t possible = (static_cast<std::size_t>(stream_lengths[i]) * 8u) / bits;
records_in_packet = std::min(records_in_packet, possible);
}
if (records_in_packet == 0) {
throw std::runtime_error("E57 standard: data packet has no decodable records");
}
// Decode records field-by-field, then append to cloud.
std::vector<std::vector<double>> values(points.fields.size(),
std::vector<double>(records_in_packet, 0.0));
std::size_t stream_offset = stream_base;
for (std::size_t f = 0; f < points.fields.size(); ++f) {
const auto& field = points.fields[f];
const auto* data = reinterpret_cast<const std::uint8_t*>(packet.data() + stream_offset);
const std::size_t length = stream_lengths[f];
std::size_t bit_position = 0;
for (std::size_t i = 0; i < records_in_packet; ++i) {
double value = 0.0;
if (field.bits_per_record == 0) {
value = static_cast<double>(field.min_val);
} else if (field.kind == E57FieldKind::Float) {
const std::uint64_t raw = read_lsb_bits(data, length, bit_position,
field.bits_per_record);
bit_position += field.bits_per_record;
if (field.byte_size == 8) {
double d = 0.0;
std::memcpy(&d, &raw, sizeof(d));
value = d;
} else {
const std::uint32_t raw32 = static_cast<std::uint32_t>(raw);
float fv = 0.0f;
std::memcpy(&fv, &raw32, sizeof(fv));
value = static_cast<double>(fv);
}
} else {
const std::uint64_t raw = read_lsb_bits(data, length, bit_position,
field.bits_per_record);
bit_position += field.bits_per_record;
value = static_cast<double>(raw) + static_cast<double>(field.min_val);
if (field.kind == E57FieldKind::ScaledInt) {
value = value * field.scale + field.offset;
}
}
values[f][i] = value;
}
stream_offset += length;
}
for (std::size_t i = 0; i < records_in_packet; ++i) {
E57Record rec;
for (std::size_t f = 0; f < points.fields.size(); ++f) {
map_e57_field(rec, points.fields[f], values[f][i]);
}
cloud.vertices.push_back(Point3D(rec.x, rec.y, rec.z));
if (rec.has_normals) cloud.normals.push_back(Vector3D(rec.nx, rec.ny, rec.nz));
if (rec.has_color) cloud.colors.push_back({{rec.r, rec.g, rec.b}});
if (rec.has_intensity) cloud.intensities.push_back(rec.intensity);
}
decoded += records_in_packet;
packet_pos += packet_length;
}
if (decoded != points.record_count) {
throw std::runtime_error("E57 standard: record count mismatch");
}
if (!cloud.normals.empty() && cloud.normals.size() < cloud.vertices.size()) {
cloud.normals.resize(cloud.vertices.size(), Vector3D(0, 0, 1));
}
if (!cloud.colors.empty() && cloud.colors.size() < cloud.vertices.size()) {
cloud.colors.resize(cloud.vertices.size(), {{128, 128, 128}});
}
if (!cloud.intensities.empty() && cloud.intensities.size() < cloud.vertices.size()) {
cloud.intensities.resize(cloud.vertices.size(), 0.0);
}
return cloud;
}
} // anonymous namespace
PointCloud PointCloud::load_e57(const std::string& path) {
return load_e57(path, E57ReadOptions{});
}
PointCloud PointCloud::load_e57(const std::string& path, const E57ReadOptions& options) {
// E57 format per ASTM E2807:
// Header (48 bytes): magic(8) major(4) minor(4) phys_offset(8) phys_length(8) xml_offset(8) xml_length(8)
// XML section: metadata describing data3D structures with prototype field layouts
// Binary section: packed point records following each data3D's prototype
std::ifstream in(path, std::ios::binary);
if (!in) throw std::runtime_error("Cannot open E57 file: " + path);
// ── Read 48-byte header ──
in.seekg(0, std::ios::end);
const std::uint64_t file_size = static_cast<std::uint64_t>(in.tellg());
in.seekg(0);
char header[48];
in.read(header, 48);
if (!in || std::string(header, 8) != "ASTM-E57") {
throw std::runtime_error("Not a valid E57 file (bad magic): " + path);
}
// Standard E57 header: filePhysicalLength@16, xmlPhysicalOffset@24,
// xmlLogicalLength@32, pageSize@40. Legacy VDE minimal header reused
// bytes 16-31/32-47 differently; detect by file length + XML probe.
const std::uint64_t standard_file_length = le_u64(header + 16);
const std::uint64_t standard_xml_offset = le_u64(header + 24);
const std::uint64_t standard_xml_length = le_u64(header + 32);
const std::uint64_t page_size_field = le_u64(header + 40);
const auto looks_like_xml = [&](std::uint64_t offset, std::uint64_t length) {
if (length == 0 || offset < 48 || offset + length > file_size) return false;
in.seekg(static_cast<std::streamoff>(offset));
char probe[16] = {};
in.read(probe, 16);
std::size_t i = 0;
while (i < 16 && (probe[i] == ' ' || probe[i] == '\n' || probe[i] == '\r' ||
probe[i] == '\t')) ++i;
return i < 16 && probe[i] == '<';
};
// Standard-shaped header (pageSize 0 or 1024, XML at 48) that does not
// match the physical file length is a truncated standard E57, not legacy.
if ((page_size_field == 0 || page_size_field == kE57PhysicalPageSize) &&
standard_xml_offset == 48 && standard_xml_length > 0 &&
standard_file_length != file_size) {
throw std::runtime_error("E57 standard: truncated physical file: " + path);
}
const bool standard = standard_file_length == file_size &&
looks_like_xml(standard_xml_offset, standard_xml_length);
const bool page_layer = standard && page_size_field == kE57PhysicalPageSize &&
file_size >= kE57PhysicalPageSize &&
(file_size % kE57PhysicalPageSize) == 0;
uint64_t xml_offset = 0;
uint64_t xml_length = 0;
if (standard) {
xml_offset = standard_xml_offset;
xml_length = standard_xml_length;
} else {
xml_offset = le_u64(header + 32);
xml_length = le_u64(header + 40);
if (xml_offset < 48 || xml_offset + xml_length > file_size) {
throw std::runtime_error("Not a valid E57 file (bad XML offsets): " + path);
}
}
// ── Read XML ──
std::string xml_data;
std::vector<char> logical;
if (page_layer) {
// Depage: 1024B physical = 1020B logical data + 4B CRC-32C.
logical.reserve(static_cast<std::size_t>((file_size / kE57PhysicalPageSize) *
kE57LogicalPageSize));
in.clear();
in.seekg(0);
const std::uint64_t page_count = file_size / kE57PhysicalPageSize;
for (std::uint64_t page = 0; page < page_count; ++page) {
char page_data[kE57PhysicalPageSize] = {};
in.read(page_data, static_cast<std::streamsize>(kE57PhysicalPageSize));
if (!in) throw std::runtime_error("Cannot read E57 physical page: " + path);
const std::uint32_t stored_crc =
(static_cast<std::uint32_t>(static_cast<std::uint8_t>(
page_data[kE57LogicalPageSize + 0])) << 24) |
(static_cast<std::uint32_t>(static_cast<std::uint8_t>(
page_data[kE57LogicalPageSize + 1])) << 16) |
(static_cast<std::uint32_t>(static_cast<std::uint8_t>(
page_data[kE57LogicalPageSize + 2])) << 8) |
static_cast<std::uint32_t>(static_cast<std::uint8_t>(
page_data[kE57LogicalPageSize + 3]));
if (options.verify_page_crc) {
const std::uint32_t computed = crc32c(
reinterpret_cast<const std::uint8_t*>(page_data), kE57LogicalPageSize);
if (computed != stored_crc) {
throw std::runtime_error("E57 page CRC mismatch at page " +
std::to_string(page) + ": " + path);
}
}
logical.insert(logical.end(), page_data, page_data + kE57LogicalPageSize);
}
const std::uint64_t xml_logical =
physical_to_logical(standard_xml_offset);
if (xml_logical + standard_xml_length > logical.size()) {
throw std::runtime_error("E57 page-layer XML out of range: " + path);
}
xml_data.assign(logical.data() + xml_logical,
logical.data() + xml_logical + standard_xml_length);
const E57ReadAt read_logical = [&logical](std::uint64_t offset, char* data,
std::size_t size) {
if (offset + size > logical.size()) {
throw std::runtime_error("E57 page-layer read out of range");
}
std::memcpy(data, logical.data() + offset, size);
};
return load_standard_e57(read_logical, xml_data, logical.size(), true);
}
in.seekg(static_cast<std::streamoff>(xml_offset));
xml_data.assign(static_cast<size_t>(xml_length), '\0');
in.read(xml_data.data(), static_cast<std::streamsize>(xml_length));
if (!in) throw std::runtime_error("Cannot read E57 XML: " + path);
if (standard) {
const E57ReadAt read_direct = [&in, file_size](std::uint64_t offset, char* data,
std::size_t size) {
if (offset + size > file_size) {
throw std::runtime_error("E57 standard: read out of range");
}
in.seekg(static_cast<std::streamoff>(offset));
in.read(data, static_cast<std::streamsize>(size));
if (!in) throw std::runtime_error("E57 standard: truncated read");
};
return load_standard_e57(read_direct, xml_data, file_size, false);
}
// ── Find all data3D sections ──
// Each data3D has a <points type="Structure" ...> with a prototype reference
struct Data3DInfo {
uint64_t offset = 0; // binary section offset
size_t count = 0; // pointCount
};
std::vector<Data3DInfo> scans;
std::string proto_type; // the prototype type name used for points
// Search for all <data3D ...> elements
{
size_t search_pos = 0;
while (true) {
auto ds = xml_data.find("<data3D", search_pos);
if (ds == std::string::npos) break;
auto de = xml_data.find("</data3D>", ds);
if (de == std::string::npos) {
// Self-closing short form, take ~4KB
de = std::min(ds + 4096, xml_data.size());
} else {
de += std::string("</data3D>").size();
}
std::string section = xml_data.substr(ds, de - ds);
Data3DInfo info;
// Extract pointCount
auto pc = section.find("<pointCount");
if (pc != std::string::npos) {
auto v1 = section.find('>', pc);
auto v2 = section.find('<', v1);
if (v1 != std::string::npos && v2 != std::string::npos)
info.count = std::stoull(section.substr(v1 + 1, v2 - v1 - 1));
}
// Extract points proto type (look for <points type="..." prototype="...")
auto pts_pos = section.find("<points ");
if (pts_pos != std::string::npos) {
proto_type = xml_attr(section.substr(pts_pos, 500), "prototype");
}
// Extract binary offset: look for <fileOffset>
auto fo = section.find("<fileOffset");
if (fo != std::string::npos) {
auto v1 = section.find('>', fo);
auto v2 = section.find('<', v1);
if (v1 != std::string::npos && v2 != std::string::npos)
info.offset = std::stoull(section.substr(v1 + 1, v2 - v1 - 1));
}
if (info.count > 0 && info.offset > 0) {
scans.push_back(info);
}
search_pos = de;
}
}
// If no scans found via structured parsing, fall back to simple estimate
if (scans.empty()) {
Data3DInfo fallback;
auto pc = xml_data.find("pointCount");
if (pc != std::string::npos) {
auto v1 = xml_data.find('>', pc);
auto v2 = xml_data.find('<', v1);
if (v1 != std::string::npos && v2 != std::string::npos)
fallback.count = std::stoull(xml_data.substr(v1 + 1, v2 - v1 - 1));
}
fallback.offset = xml_offset + xml_length;
if (fallback.count == 0) {
// Estimate from file size
in.seekg(0, std::ios::end);
auto file_size = static_cast<uint64_t>(in.tellg());
fallback.count = (file_size - fallback.offset) / (3 * 8); // assume 3 doubles
}
scans.push_back(fallback);
}
// ── Parse the prototype to determine field layout ──
std::vector<E57Field> fields;
if (!proto_type.empty()) {
fields = find_prototype(xml_data, proto_type);
}
if (fields.empty()) {
// Fallback: try common prototype names
for (auto& name : {"points", "PointRecord", "data3DPoint"}) {
fields = find_prototype(xml_data, name);
if (!fields.empty()) break;
}
// Search recursively for any prototype containing "cartesianX" or "cartesianY"
if (fields.empty()) {
// Just use a default layout: 3 doubles for x,y,z
}
}
int rec_size = fields.empty() ? 24 : compute_record_size(fields);
// ── Read all scan stations into a single PointCloud ──
PointCloud cloud;
size_t total_points = 0;
for (const auto& s : scans) total_points += s.count;
cloud.vertices.reserve(total_points);
for (const auto& scan : scans) {
in.seekg(static_cast<std::streamoff>(scan.offset));
for (size_t i = 0; i < scan.count; ++i) {
if (fields.empty()) {
// Default: 3 doubles
double xyz[3];
if (!in.read(reinterpret_cast<char*>(xyz), 24)) break;
cloud.vertices.emplace_back(xyz[0], xyz[1], xyz[2]);
} else {
std::vector<char> buf(static_cast<size_t>(rec_size));
if (!in.read(buf.data(), rec_size)) break;
auto rec = read_e57_record(buf.data(), fields);
// Skip invalid points (E57 uses cartesianInvalidState)
cloud.vertices.emplace_back(rec.x, rec.y, rec.z);
if (rec.has_normals) {
cloud.normals.emplace_back(rec.nx, rec.ny, rec.nz);
}
if (rec.has_color) {
cloud.colors.push_back({{rec.r, rec.g, rec.b}});
}
if (rec.has_intensity) {
cloud.intensities.push_back(rec.intensity);
}
}
}
}
// Pad missing attributes for consistency
if (!cloud.normals.empty() && cloud.normals.size() < cloud.vertices.size()) {
cloud.normals.resize(cloud.vertices.size(), Vector3D(0, 0, 1));
}
if (!cloud.colors.empty() && cloud.colors.size() < cloud.vertices.size()) {
cloud.colors.resize(cloud.vertices.size(), {{128, 128, 128}});
}
if (!cloud.intensities.empty() && cloud.intensities.size() < cloud.vertices.size()) {
cloud.intensities.resize(cloud.vertices.size(), 0.0);
}
return cloud;
}
// ───────────────────────────────────────────────────────────
// LAS 1.2 / 1.3 / 1.4 (ASPRS) — 二进制点云解析器
// ───────────────────────────────────────────────────────────
namespace {
// ── LAS Public Header Block ──
struct LasHeader {
char file_signature[4]; // "LASF"
uint16_t file_source_id;
uint16_t global_encoding;
uint32_t guid_data1;
uint16_t guid_data2;
uint16_t guid_data3;
uint8_t guid_data4[8];
uint8_t version_major;
uint8_t version_minor;
char system_identifier[32];
char generating_software[32];
uint16_t creation_day;
uint16_t creation_year;
uint16_t header_size;
uint32_t offset_to_point_data;
uint32_t number_of_vlrs;
uint8_t point_data_format;
uint16_t point_data_record_length;
uint32_t number_of_point_records; // legacy
uint32_t number_of_points_by_return[5]; // legacy
double x_scale_factor;
double y_scale_factor;
double z_scale_factor;
double x_offset;
double y_offset;
double z_offset;
double max_x;
double min_x;
double max_y;
double min_y;
double max_z;
double min_z;
// 1.3+ fields
uint64_t start_of_waveform_data_packet_record = 0;
// 1.4+ fields
uint64_t start_of_first_evlr = 0;
uint32_t number_of_evlrs = 0;
uint64_t number_of_point_records_64 = 0;
uint64_t number_of_points_by_return_64[15] = {};
};
/// Read a 1-byte uint8, advance offset
uint8_t r_u8(const char* buf, int& off) {
uint8_t v = static_cast<uint8_t>(buf[off]);
off += 1;
return v;
}
/// Read a 2-byte little-endian uint16
uint16_t r_u16(const char* buf, int& off) {
uint16_t v;
std::memcpy(&v, buf + off, 2);
off += 2;
return v;
}
/// Read a 4-byte little-endian uint32
uint32_t r_u32(const char* buf, int& off) {
uint32_t v;
std::memcpy(&v, buf + off, 4);
off += 4;
return v;
}
/// Read an 8-byte little-endian uint64
uint64_t r_u64(const char* buf, int& off) {
uint64_t v;
std::memcpy(&v, buf + off, 8);
off += 8;
return v;
}
/// Read an 8-byte little-endian double
double r_f64(const char* buf, int& off) {
double v;
std::memcpy(&v, buf + off, 8);
off += 8;
return v;
}
/// Decompress LAS scaled integer coordinates → double
double las_decompress(int32_t raw, double scale, double offset) {
return static_cast<double>(raw) * scale + offset;
}
} // anonymous namespace
PointCloud PointCloud::load_las(const std::string& path) {
// LAS format per ASPRS LAS 1.2/1.3/1.4 specification:
// Public Header Block (227 bytes in 1.2, 235 in 1.3, 375 in 1.4)
// Variable Length Records (VLRs)
// Point Data Records (each point_data_record_length bytes)
// Extended VLRs (1.4+)
//
// Supported point formats: 0–10
// Format 0: X,Y,Z,Intensity,Return#,NumReturns,ScanDir,Edge,Class,ScanAngle,UserData,PointSourceID (20B)
// Format 1: +GPS Time (28B)
// Format 2: +R,G,B (26B)
// Format 3: +GPS Time,R,G,B (34B)
// Format 4: +GPS Time,Wave Packet (57B)
// Format 5: +GPS Time,R,G,B,Wave Packet (63B)
// Format 6: +GPS Time (extended: int32→int64 for x,y,z) (30B)
// Format 7: +GPS Time,R,G,B (extended) (36B)
// Format 8: +GPS Time,R,G,B,NIR (extended) (38B)
// Format 9: +GPS Time,Wave Packet (extended) (59B)
// Format 10: +GPS Time,R,G,B,NIR,Wave Packet (extended) (67B)
std::ifstream in(path, std::ios::binary);
if (!in) throw std::runtime_error("Cannot open LAS file: " + path);
// ── Read Public Header Block ──
// LAS 1.2 → 227 bytes; LAS 1.3 → 235 bytes; LAS 1.4 → 375 bytes
// We'll first read 227 bytes, then extend based on version
char raw_header[375];
std::memset(raw_header, 0, sizeof(raw_header));
if (!in.read(raw_header, 227)) {
throw std::runtime_error("Failed to read LAS header: " + path);
}
int off = 0;
LasHeader hdr;
std::memcpy(hdr.file_signature, raw_header + off, 4); off += 4;
if (std::string(hdr.file_signature, 4) != "LASF") {
throw std::runtime_error("Not a valid LAS file (bad signature): " + path);
}
hdr.file_source_id = r_u16(raw_header, off);
hdr.global_encoding = r_u16(raw_header, off);
hdr.guid_data1 = r_u32(raw_header, off);
hdr.guid_data2 = r_u16(raw_header, off);
hdr.guid_data3 = r_u16(raw_header, off);
for (int i = 0; i < 8; ++i) hdr.guid_data4[i] = r_u8(raw_header, off);
hdr.version_major = r_u8(raw_header, off);
hdr.version_minor = r_u8(raw_header, off);
std::memcpy(hdr.system_identifier, raw_header + off, 32); off += 32;
std::memcpy(hdr.generating_software, raw_header + off, 32); off += 32;
hdr.creation_day = r_u16(raw_header, off);
hdr.creation_year = r_u16(raw_header, off);
hdr.header_size = r_u16(raw_header, off);
hdr.offset_to_point_data = r_u32(raw_header, off);
hdr.number_of_vlrs = r_u32(raw_header, off);
hdr.point_data_format = r_u8(raw_header, off);
hdr.point_data_record_length = r_u16(raw_header, off);
// off is now 107 — legacy point count
hdr.number_of_point_records = r_u32(raw_header, off);
for (int i = 0; i < 5; ++i) hdr.number_of_points_by_return[i] = r_u32(raw_header, off);
hdr.x_scale_factor = r_f64(raw_header, off);
hdr.y_scale_factor = r_f64(raw_header, off);
hdr.z_scale_factor = r_f64(raw_header, off);
hdr.x_offset = r_f64(raw_header, off);
hdr.y_offset = r_f64(raw_header, off);
hdr.z_offset = r_f64(raw_header, off);
hdr.max_x = r_f64(raw_header, off);
hdr.min_x = r_f64(raw_header, off);
hdr.max_y = r_f64(raw_header, off);
hdr.min_y = r_f64(raw_header, off);
hdr.max_z = r_f64(raw_header, off);
hdr.min_z = r_f64(raw_header, off);
// off = 227 at this point
// ── Read extended header fields (1.3+: 235 bytes, 1.4+: 375 bytes) ──
if (hdr.version_minor >= 3 && hdr.header_size >= 235) {
// We already read 227; read the remaining bytes
int remaining_header = hdr.header_size - 227;
std::vector<char> extra(std::max(remaining_header, 0));
if (remaining_header > 0) {
in.read(extra.data(), remaining_header);
// Append to raw_header so our offset-based reading works
std::memcpy(raw_header + 227, extra.data(), remaining_header);
}
if (remaining_header >= 8) {
off = 227;
hdr.start_of_waveform_data_packet_record = r_u64(raw_header, off);
}
// 1.4+: 375-byte header
if (hdr.version_minor >= 4 && hdr.header_size >= 375) {
off = 235;
hdr.start_of_first_evlr = r_u64(raw_header, off);
hdr.number_of_evlrs = r_u32(raw_header, off);
hdr.number_of_point_records_64 = r_u64(raw_header, off);
for (int i = 0; i < 15; ++i)
hdr.number_of_points_by_return_64[i] = r_u64(raw_header, off);
}
}
// Determine real point count (1.4+ uses 64-bit counter)
uint64_t num_points = hdr.number_of_point_records;
if (hdr.version_minor >= 4 && hdr.number_of_point_records == 0) {
num_points = hdr.number_of_point_records_64;
}
if (num_points == 0) {
throw std::runtime_error("LAS file has 0 points: " + path);
}
// ── VLR 扫描:识别 LASzip 压缩点数据(VLR 22204 "laszip encoded")──
bool laz_compressed = (hdr.point_data_format & 0x80) != 0;
uint16_t laz_compressor = 0;
uint32_t laz_chunk_size = 0;
uint16_t laz_num_items = 0;
uint16_t laz_item_type[8] = {};
uint16_t laz_item_version[8] = {};
if (hdr.number_of_vlrs > 0 &&
hdr.offset_to_point_data >= static_cast<uint32_t>(hdr.header_size) + 54u) {
in.seekg(hdr.header_size, std::ios::beg);
for (uint32_t vi = 0; vi < hdr.number_of_vlrs; ++vi) {
char vh[54];
if (!in.read(vh, 54)) break;
int vo = 0;
(void)r_u16(vh, vo); // reserved
char uid_raw[17] = {};
std::memcpy(uid_raw, vh + vo, 16);
vo += 16;
const std::string uid(uid_raw);
const uint16_t record_id = r_u16(vh, vo);
const uint16_t rec_len_after = r_u16(vh, vo);
vo += 32; // description
std::vector<char> payload(rec_len_after);
if (rec_len_after > 0 && !in.read(payload.data(), rec_len_after)) break;
if ((uid == "laszip encoded" || uid == "LAZ encoded") && record_id == 22204) {
laz_compressed = true;
if (payload.size() >= 34) {
int po = 0;
laz_compressor = r_u16(payload.data(), po); // compressor
(void)r_u16(payload.data(), po); // coder
(void)r_u8(payload.data(), po); // version major
(void)r_u8(payload.data(), po); // version minor
(void)r_u16(payload.data(), po); // version revision
(void)r_u32(payload.data(), po); // options
laz_chunk_size = r_u32(payload.data(), po);
(void)r_u64(payload.data(), po); // special EVLR count
(void)r_u64(payload.data(), po); // special EVLR offset
laz_num_items = r_u16(payload.data(), po);
for (uint16_t ii = 0; ii < laz_num_items && ii < 8; ++ii) {
laz_item_type[ii] = r_u16(payload.data(), po);
(void)r_u16(payload.data(), po); // size
laz_item_version[ii] = r_u16(payload.data(), po);
}
}
}
}
}
// Determine point format byte sizes
// Format → record size (standard), plus fields available
uint8_t fmt = static_cast<uint8_t>(hdr.point_data_format & 0x3F);
uint16_t rec_len = hdr.point_data_record_length;
bool has_rgb = false;
switch (fmt) {
case 0: break; // 20B
case 1: break; // 28B
case 2: has_rgb = true; break; // 26B
case 3: has_rgb = true; break; // 34B
case 4: break; // 57B
case 5: has_rgb = true; break; // 63B
case 6: break; // 30B
case 7: has_rgb = true; break; // 36B
case 8: has_rgb = true; break; // 38B
case 9: break; // 59B
case 10: has_rgb = true; break; // 67B
default:
break;
}
// ── 读取原始点记录:未压缩 LAS,或 LAZ(LASzip pointwise chunked, compressor 1/2)──
std::vector<uint8_t> point_bytes;
if (laz_compressed) {
if (laz_compressor != 1 && laz_compressor != 2) {
throw std::runtime_error(
"LAZ file uses unsupported LASzip compressor " +
std::to_string(static_cast<int>(laz_compressor)) +
" (only pointwise/pointwise-chunked are decoded): " + path);
}
if (fmt != 0 && fmt != 2) {
throw std::runtime_error(
"LAZ file uses unsupported point format " + std::to_string(static_cast<int>(fmt)) +
" (only LAS formats 0/2 are decoded): " + path);
}
if (laz_num_items < 1 || laz_item_type[0] != 6 || laz_item_version[0] != 2) {
throw std::runtime_error(
"LAZ file: missing/incompatible POINT10 v2 item in LASzip VLR: " + path);
}
if (has_rgb) {
const uint16_t rgb_item = (laz_num_items >= 2) ? laz_item_type[1] : 0;
const uint16_t rgb_ver = (laz_num_items >= 2) ? laz_item_version[1] : 0;
if (rgb_item != 8 || rgb_ver != 2) {
throw std::runtime_error(
"LAZ file: missing/incompatible RGB12 v2 item in LASzip VLR: " + path);
}
}
// 读取整个压缩数据块(chunk table offset + chunks + chunk table)
in.seekg(hdr.offset_to_point_data, std::ios::beg);
std::vector<uint8_t> file_bytes;
{
std::vector<char> rest((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
file_bytes.assign(rest.begin(), rest.end());
}
size_t pos = 0;
uint64_t got = 0;
std::vector<uint32_t> chunk_sizes;
if (laz_compressor == 2) {
if (file_bytes.size() < 8) {
throw std::runtime_error("LAZ file: truncated chunk table offset: " + path);
}
int64_t cto_abs = 0;
std::memcpy(&cto_abs, file_bytes.data(), 8);
pos = 8;
const uint64_t pd_start = hdr.offset_to_point_data;
const uint64_t cto = static_cast<uint64_t>(cto_abs) - pd_start;
if (static_cast<uint64_t>(cto_abs) < pd_start + 8 ||
cto + 8 > file_bytes.size()) {
throw std::runtime_error("LAZ file: invalid chunk table offset: " + path);
}
uint32_t table_version = 0, table_chunks = 0;
std::memcpy(&table_version, file_bytes.data() + cto, 4);
std::memcpy(&table_chunks, file_bytes.data() + cto + 4, 4);
if (table_version != 0) {
throw std::runtime_error("LAZ file: unsupported chunk table version: " + path);
}
if (table_chunks == 0) {
throw std::runtime_error("LAZ file: empty chunk table: " + path);
}
laz::Decoder table_dec;
table_dec.init(file_bytes.data() + cto + 8,
file_bytes.size() - static_cast<size_t>(cto + 8));
laz::IntegerCompressor table_ic;
table_ic.setup(32, 2);
table_ic.init(nullptr, &table_dec);
uint32_t prev_size = 0;
uint64_t sizes_sum = 0;
for (uint32_t ci = 0; ci < table_chunks; ++ci) {
const uint32_t sz = static_cast<uint32_t>(
table_ic.decompress(static_cast<int32_t>(prev_size), 1));
chunk_sizes.push_back(sz);
prev_size = sz;
sizes_sum += sz;
}
if (static_cast<uint64_t>(cto) + 8u + table_dec.pos > file_bytes.size()) {
throw std::runtime_error("LAZ file: truncated chunk table: " + path);
}
if (pos + sizes_sum != static_cast<uint64_t>(cto)) {
throw std::runtime_error(
"LAZ file: chunk sizes inconsistent with chunk table offset: " + path);
}
} else {
chunk_sizes.push_back(static_cast<uint32_t>(file_bytes.size()));
}
const uint32_t chunk_pts = laz_chunk_size > 0 ? laz_chunk_size : 0xFFFFFFFFu;
for (uint32_t sz : chunk_sizes) {
if (got >= num_points) break;
if (static_cast<uint64_t>(sz) < rec_len) {
throw std::runtime_error("LAZ file: chunk smaller than a point record: " + path);
}
const uint32_t count = static_cast<uint32_t>(
std::min<uint64_t>(num_points - got, static_cast<uint64_t>(chunk_pts)));
laz::decode_chunk(file_bytes.data() + pos, sz, count, rec_len, has_rgb, point_bytes);
pos += sz;
got += count;
}
if (got != num_points) {
throw std::runtime_error("LAZ file: decoded point count mismatch: " + path);
}
} else {
in.seekg(hdr.offset_to_point_data, std::ios::beg);
point_bytes.resize(static_cast<size_t>(num_points) * rec_len);
if (!in.read(reinterpret_cast<char*>(point_bytes.data()),
static_cast<std::streamsize>(point_bytes.size()))) {
throw std::runtime_error("LAS file: truncated point data: " + path);
}
}
PointCloud cloud;
cloud.vertices.reserve(static_cast<size_t>(num_points));
cloud.colors.reserve(has_rgb ? static_cast<size_t>(num_points) : 0);
cloud.intensities.reserve(static_cast<size_t>(num_points));
for (uint64_t i = 0; i < num_points; ++i) {
const char* rec = reinterpret_cast<const char*>(
point_bytes.data() + static_cast<size_t>(i) * rec_len);
// ── Read X, Y, Z (int32 LE at offset 0, 4, 8) ──
int32_t raw_x, raw_y, raw_z;
std::memcpy(&raw_x, rec, 4);
std::memcpy(&raw_y, rec + 4, 4);
std::memcpy(&raw_z, rec + 8, 4);
double x = las_decompress(raw_x, hdr.x_scale_factor, hdr.x_offset);
double y = las_decompress(raw_y, hdr.y_scale_factor, hdr.y_offset);
double z = las_decompress(raw_z, hdr.z_scale_factor, hdr.z_offset);
cloud.vertices.emplace_back(x, y, z);
// ── Intensity (uint16 LE at offset 12) ──
uint16_t intens;
std::memcpy(&intens, rec + 12, 2);
cloud.intensities.push_back(static_cast<double>(intens));
// ── Classification (uint8 at offset 15 in base) ──
uint8_t classification = static_cast<uint8_t>(rec[15]);
// ── RGB (formats 2,3,5,7,8,10) ──
if (has_rgb) {
// RGB in LAS: uint16 LE at specific offsets
// Format 2: red=20, green=22, blue=24
// Format 3,5: red=28, green=30, blue=32
// Format 7,8,10: red=30, green=32, blue=34
uint16_t r=0, g=0, b=0;
if (fmt == 2) {
std::memcpy(&r, rec + 20, 2);
std::memcpy(&g, rec + 22, 2);
std::memcpy(&b, rec + 24, 2);
} else if (fmt == 3) {
std::memcpy(&r, rec + 28, 2);
std::memcpy(&g, rec + 30, 2);
std::memcpy(&b, rec + 32, 2);
} else if (fmt == 5) {
std::memcpy(&r, rec + 28, 2);
std::memcpy(&g, rec + 30, 2);
std::memcpy(&b, rec + 32, 2);
} else if (fmt == 7 || fmt == 8 || fmt == 10) {
std::memcpy(&r, rec + 30, 2);
std::memcpy(&g, rec + 32, 2);
std::memcpy(&b, rec + 34, 2);
}
// LAS stores RGB as 16-bit; scale to 8-bit
cloud.colors.push_back({{
static_cast<uint8_t>(r >> 8),
static_cast<uint8_t>(g >> 8),
static_cast<uint8_t>(b >> 8)
}});
}
// Skip GPS, Wave, NIR for now (not needed in basic PointCloud)
(void)classification;
}
return cloud;
}
// ───────────────────────────────────────────────────────────
// PTX (Leica scanner format)
// ───────────────────────────────────────────────────────────
PointCloud PointCloud::load_ptx(const std::string& path) {
// PTX format: text format, each scan section has:
// Line 1: num_columns num_rows
// Line 2-4: scanner transformation matrix (3 lines of 4x3)
// Lines 5+: point data: X Y Z intensity R G B (7 columns, space-separated)
// Invalid points: X=Y=Z=0 (or intensity=0)
std::ifstream in(path);
if (!in) throw std::runtime_error("Cannot open PTX file: " + path);
PointCloud cloud;
std::string line;
while (std::getline(in, line)) {
if (line.empty()) continue;
std::istringstream iss(line);
int cols = 0, rows = 0;
iss >> cols >> rows;
if (cols <= 0 || rows <= 0) continue;
size_t num_pts = static_cast<size_t>(cols) * rows;
// Skip 3 transformation matrix lines
for (int i = 0; i < 3; ++i) std::getline(in, line);
// Read points
for (size_t i = 0; i < num_pts; ++i) {
if (!std::getline(in, line)) break;
std::istringstream pis(line);
double x, y, z, intensity;
int r = 0, g = 0, b = 0;
pis >> x >> y >> z >> intensity >> r >> g >> b;
// Skip invalid points (all zeros)
if (x == 0.0 && y == 0.0 && z == 0.0) continue;
cloud.vertices.emplace_back(x, y, z);
if (cloud.colors.empty()) cloud.colors.resize(cloud.vertices.size() - 1);
cloud.colors.push_back({static_cast<uint8_t>(r), static_cast<uint8_t>(g), static_cast<uint8_t>(b)});
}
}
return cloud;
}
// ───────────────────────────────────────────────────────────
// k-nearest neighbors (brute-force for small/medium clouds)
// ───────────────────────────────────────────────────────────
std::vector<std::vector<size_t>> PointCloud::k_nearest_neighbors(size_t k) const {
size_t n = vertices.size();
if (k >= n) k = n - 1;
if (k < 1) k = 1;
std::vector<std::vector<size_t>> result(n);
// Use a simple spatial hash grid for moderate-sized clouds
// Grid size based on average point spacing
AABB3D bb = bounds();
Vector3D ext = bb.extent();
double avg_spacing = std::cbrt((ext.x() * ext.y() * ext.z()) / n);
double cell_size = avg_spacing * 3.0;
// Build spatial grid
using CellKey = std::tuple<int, int, int>;
std::map<CellKey, std::vector<size_t>> grid;
auto to_cell = [&](const Point3D& p) -> CellKey {
return CellKey{
static_cast<int>(std::floor((p.x() - bb.min().x()) / cell_size)),
static_cast<int>(std::floor((p.y() - bb.min().y()) / cell_size)),
static_cast<int>(std::floor((p.z() - bb.min().z()) / cell_size))
};
};
for (size_t i = 0; i < n; ++i) {
grid[to_cell(vertices[i])].push_back(i);
}
for (size_t i = 0; i < n; ++i) {
const auto& pi = vertices[i];
auto [cx, cy, cz] = to_cell(pi);
// Collect candidates from 27 neighboring cells
std::vector<std::pair<double, size_t>> dists;
for (int dx = -1; dx <= 1; ++dx) {
for (int dy = -1; dy <= 1; ++dy) {
for (int dz = -1; dz <= 1; ++dz) {
auto it = grid.find({cx + dx, cy + dy, cz + dz});
if (it != grid.end()) {
for (size_t j : it->second) {
if (j == i) continue;
double d2 = (vertices[j] - pi).squaredNorm();
dists.emplace_back(d2, j);
}
}
}
}
}
// Sort and take top k
std::sort(dists.begin(), dists.end());
result[i].reserve(k);
for (size_t j = 0; j < k && j < dists.size(); ++j) {
result[i].push_back(dists[j].second);
}
}
return result;
}
// ───────────────────────────────────────────────────────────
// PCA normal
// ───────────────────────────────────────────────────────────
Vector3D PointCloud::pca_normal(const std::vector<Point3D>& local_pts) {
if (local_pts.size() < 3) return Vector3D(0, 0, 1);
// Compute centroid
Point3D centroid(0, 0, 0);
for (const auto& p : local_pts) centroid = Point3D(
centroid.x() + p.x(), centroid.y() + p.y(), centroid.z() + p.z());
centroid = Point3D(
centroid.x() / local_pts.size(),
centroid.y() / local_pts.size(),
centroid.z() / local_pts.size());
// Build covariance matrix
double c00 = 0, c01 = 0, c02 = 0, c11 = 0, c12 = 0, c22 = 0;
for (const auto& p : local_pts) {
double dx = p.x() - centroid.x();
double dy = p.y() - centroid.y();
double dz = p.z() - centroid.z();
c00 += dx * dx; c01 += dx * dy; c02 += dx * dz;
c11 += dy * dy; c12 += dy * dz;
c22 += dz * dz;
}
// Jacobi eigenvalue for 3x3 symmetric matrix
// Eigenvectors of C: use power iteration for smallest eigenvalue
// Start with random vector and shift
double eps = 1e-12;
// Find the eigenvalue range
double trace = c00 + c11 + c22;
double shift = trace / 3.0;
// Shifted matrix: C - shift*I — solve eigenvalue closest to 0
// Power iteration on inverse-shifted matrix times vector
// For 3x3, just compute eigenvalues directly via closed form
double m00 = c00 - shift, m11 = c11 - shift, m22 = c22 - shift;
double m01 = c01, m02 = c02, m12 = c12;
// Characteristic polynomial: λ³ + p*λ² + q*λ + r = 0
// For shifted matrix (trace=0), p = 0
double q = -(m00*m00 + m11*m11 + m22*m22 + 2*(m01*m01 + m02*m02 + m12*m12)) / 2.0;
double r = -(m00*m11*m22 + 2*m01*m02*m12 - m00*m12*m12 - m11*m02*m02 - m22*m01*m01);
// Solve depressed cubic: t³ + q*t + r = 0
double disc = (r*r/4.0) + (q*q*q/27.0);
// Compute eigenvalues: λ = 2*sqrt(-q/3)*cos((acos(...)+2πk)/3)
double lambda_min;
if (std::abs(disc) < eps) {
// Multiple root
double root = std::cbrt(-r / 2.0);
lambda_min = 2 * root;
} else if (disc < 0) {
// Three real roots
double phi = std::acos(r / (2.0 * std::sqrt(-q*q*q / 27.0)));
double m = 2.0 * std::sqrt(-q / 3.0);
double r0 = m * std::cos(phi / 3.0);
double r1 = m * std::cos((phi + 2 * M_PI) / 3.0);
double r2 = m * std::cos((phi + 4 * M_PI) / 3.0);
lambda_min = std::min({r0, r1, r2});
} else {
// One real root
double sqrt_disc = std::sqrt(disc);
double u = std::cbrt(-r/2.0 + sqrt_disc);
double v = std::cbrt(-r/2.0 - sqrt_disc);
lambda_min = u + v;
}
// Now find eigenvector for lambda_min
// Solve (C - lambda*I)v = 0 using nullspace
double lam = lambda_min;
double a00 = c00 - lam, a01 = c01, a02 = c02;
double a11 = c11 - lam, a12 = c12;
double a22 = c22 - lam;
Vector3D normal(0, 0, 1);
// Use cross product of two rows for the eigenvector
Vector3D r0(a00, a01, a02);
Vector3D r1(a01, a11, a12); // r1 is col1 (symmetric)
Vector3D r2(a02, a12, a22);
Vector3D n0 = r0.cross(r1);
Vector3D n1 = r1.cross(r2);
Vector3D n2 = r0.cross(r2);
double n_norm0 = n0.squaredNorm();
double n_norm1 = n1.squaredNorm();
double n_norm2 = n2.squaredNorm();
if (n_norm0 >= n_norm1 && n_norm0 >= n_norm2 && n_norm0 > eps)
normal = n0.normalized();
else if (n_norm1 >= n_norm2 && n_norm1 > eps)
normal = n1.normalized();
else if (n_norm2 > eps)
normal = n2.normalized();
return normal;
}
// ───────────────────────────────────────────────────────────
// normal_estimation
// ───────────────────────────────────────────────────────────
PointCloud PointCloud::normal_estimation(int k) const {
#if defined(VDE_HAVE_COMPUTE)
// 大点云优先尝试 GPU 批核(与 CPU 同口径的 27 邻域 kNN + PCA);
// 后端不支持/失败时回退下方 CPU 实现,std::vector 结果完全一致。
if (vertices.size() >= point_cloud_gpu_min_points()) {
PointCloud gpu_result = *this;
gpu_result.normals.resize(vertices.size());
std::vector<double> unused_distances;
if (gpu_cloud_stats(vertices, k, &gpu_result.normals, &unused_distances))
return gpu_result;
}
#endif
auto knn = k_nearest_neighbors(static_cast<size_t>(k));
PointCloud result = *this;
result.normals.resize(vertices.size());
for (size_t i = 0; i < vertices.size(); ++i) {
std::vector<Point3D> local_pts;
local_pts.reserve(knn[i].size() + 1);
local_pts.push_back(vertices[i]);
for (size_t j : knn[i]) local_pts.push_back(vertices[j]);
Vector3D n = pca_normal(local_pts);
// Flip normal toward viewpoint (origin = (0,0,0))
Vector3D view_dir = Vector3D(0, 0, 0) - Vector3D(vertices[i].x(), vertices[i].y(), vertices[i].z());
if (view_dir.dot(n) < 0) n = -n;
result.normals[i] = n;
}
return result;
}
// ───────────────────────────────────────────────────────────
// voxel_downsample
// ───────────────────────────────────────────────────────────
PointCloud PointCloud::voxel_downsample(double voxel_size) const {
if (voxel_size <= 0 || vertices.empty()) return *this;
using CellKey = std::tuple<int, int, int>;
std::map<CellKey, std::vector<size_t>> grid;
AABB3D bb = bounds();
for (size_t i = 0; i < vertices.size(); ++i) {
CellKey key{
static_cast<int>(std::floor((vertices[i].x() - bb.min().x()) / voxel_size)),
static_cast<int>(std::floor((vertices[i].y() - bb.min().y()) / voxel_size)),
static_cast<int>(std::floor((vertices[i].z() - bb.min().z()) / voxel_size))
};
grid[key].push_back(i);
}
PointCloud result;
for (const auto& [key, indices] : grid) {
double cx = 0, cy = 0, cz = 0;
for (size_t idx : indices) {
cx += vertices[idx].x();
cy += vertices[idx].y();
cz += vertices[idx].z();
}
double inv = 1.0 / indices.size();
result.vertices.emplace_back(cx * inv, cy * inv, cz * inv);
if (has_normals()) {
double nx = 0, ny = 0, nz = 0;
for (size_t idx : indices) {
nx += normals[idx].x();
ny += normals[idx].y();
nz += normals[idx].z();
}
Vector3D avg_n(nx * inv, ny * inv, nz * inv);
result.normals.push_back(avg_n.normalized());
}
if (has_colors()) {
int cr = 0, cg = 0, cb = 0;
for (size_t idx : indices) {
cr += colors[idx][0];
cg += colors[idx][1];
cb += colors[idx][2];
}
result.colors.push_back({
static_cast<uint8_t>(cr / indices.size()),
static_cast<uint8_t>(cg / indices.size()),
static_cast<uint8_t>(cb / indices.size())
});
}
}
return result;
}
// ───────────────────────────────────────────────────────────
// statistical_outlier_removal
// ───────────────────────────────────────────────────────────
PointCloud PointCloud::statistical_outlier_removal(int k, double std_ratio) const {
if (vertices.size() < static_cast<size_t>(k) + 1) return *this;
std::vector<double> mean_dists(vertices.size());
bool distances_ready = false;
#if defined(VDE_HAVE_COMPUTE)
// 大点云优先尝试 GPU 批核:点数不足/不支持/失败时回退下方 CPU kNN 统计。
if (vertices.size() >= point_cloud_gpu_min_points()) {
std::vector<Vector3D> unused_normals;
distances_ready = gpu_cloud_stats(vertices, k, &unused_normals, &mean_dists);
}
#endif
if (!distances_ready) {
auto knn = k_nearest_neighbors(static_cast<size_t>(k));
for (size_t i = 0; i < vertices.size(); ++i) {
double sum = 0;
for (size_t j : knn[i]) {
sum += std::sqrt((vertices[j] - vertices[i]).squaredNorm());
}
mean_dists[i] = sum / knn[i].size();
}
}
double global_mean = std::accumulate(mean_dists.begin(), mean_dists.end(), 0.0) / mean_dists.size();
double sum_sq = 0;
for (double d : mean_dists) sum_sq += (d - global_mean) * (d - global_mean);
double global_std = std::sqrt(sum_sq / mean_dists.size());
double threshold = global_mean + std_ratio * global_std;
PointCloud result;
for (size_t i = 0; i < vertices.size(); ++i) {
if (mean_dists[i] <= threshold) {
result.vertices.push_back(vertices[i]);
if (has_normals()) result.normals.push_back(normals[i]);
if (has_colors()) result.colors.push_back(colors[i]);
}
}
return result;
}
// ───────────────────────────────────────────────────────────
// curvature_aware_sampling
// ───────────────────────────────────────────────────────────
std::vector<size_t> PointCloud::curvature_aware_sampling(size_t target_count) const {
size_t n = vertices.size();
if (target_count >= n) {
std::vector<size_t> result(n);
std::iota(result.begin(), result.end(), 0);
return result;
}
// Compute approximate curvature per point via eigenvalue ratio
auto knn = k_nearest_neighbors(10);
std::vector<double> curvature(n, 0.0);
for (size_t i = 0; i < n; ++i) {
std::vector<Point3D> local_pts;
local_pts.push_back(vertices[i]);
for (size_t j : knn[i]) local_pts.push_back(vertices[j]);
// Compute centroid
Point3D centroid(0, 0, 0);
for (const auto& p : local_pts)
centroid = Point3D(
centroid.x() + p.x(), centroid.y() + p.y(), centroid.z() + p.z());
double inv_m = 1.0 / local_pts.size();
centroid = Point3D(centroid.x() * inv_m, centroid.y() * inv_m, centroid.z() * inv_m);
// Covariance
double c00 = 0, c01 = 0, c02 = 0, c11 = 0, c12 = 0, c22 = 0;
for (const auto& p : local_pts) {
double dx = p.x() - centroid.x();
double dy = p.y() - centroid.y();
double dz = p.z() - centroid.z();
c00 += dx*dx; c01 += dx*dy; c02 += dx*dz;
c11 += dy*dy; c12 += dy*dz; c22 += dz*dz;
}
// Approximate: smallest_eigenvalue / sum_of_eigenvalues
double trace = c00 + c11 + c22;
double frob2 = c00*c00 + c11*c11 + c22*c22 + 2*(c01*c01 + c02*c02 + c12*c12);
// For 3x3: λ1+λ2+λ3 = trace, λ1²+λ2²+λ3² = frob2
// Use simple residual: smallest eigenvalue ≈ trace - sqrt(2*(frob2 - trace²/3))
double trace2_over3 = trace * trace / 3.0;
double var = frob2 - trace2_over3;
if (var < 0) var = 0;
double lambda_min = (trace - std::sqrt(2.0 * var)) / 3.0;
if (lambda_min < 0) lambda_min = 0;
curvature[i] = lambda_min / (trace + 1e-12);
}
// Normalize curvature to [0, 1]
double max_c = *std::max_element(curvature.begin(), curvature.end());
if (max_c > 1e-12)
for (auto& c : curvature) c /= max_c;
// Weighted reservoir sampling: curvature-weighted selection
std::vector<size_t> result;
result.reserve(target_count);
std::vector<size_t> indices(n);
std::iota(indices.begin(), indices.end(), 0);
// Sort by curvature descending, pick top portion with higher probability
std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
return curvature[a] > curvature[b];
});
// Take points: top ~70% from high curvature, rest uniform
size_t high_count = target_count * 70 / 100;
std::unordered_set<size_t> selected;
for (size_t i = 0; i < std::min(high_count, n); ++i) {
selected.insert(indices[i]);
}
// Fill remaining with uniform sampling
std::vector<size_t> remaining;
for (size_t i = 0; i < n; ++i)
if (!selected.count(i)) remaining.push_back(i);
if (remaining.size() > 0) {
size_t step = std::max(size_t(1), remaining.size() / (target_count - selected.size()));
for (size_t i = 0; i < remaining.size() && selected.size() < target_count; i += step) {
selected.insert(remaining[i]);
}
}
result.assign(selected.begin(), selected.end());
return result;
}
// ───────────────────────────────────────────────────────────
// smoothing_filter (bilateral for point cloud)
// ───────────────────────────────────────────────────────────
PointCloud PointCloud::smoothing_filter(double sigma_c, double sigma_n, int iterations) const {
PointCloud result = *this;
if (vertices.empty()) return result;
auto knn = k_nearest_neighbors(20);
// Auto sigma_c based on average spacing
if (sigma_c <= 0) {
double avg_dist = 0;
size_t count = 0;
for (size_t i = 0; i < std::min(vertices.size(), size_t(1000)); ++i) {
if (!knn[i].empty()) {
avg_dist += std::sqrt((vertices[knn[i][0]] - vertices[i]).squaredNorm());
++count;
}
}
sigma_c = count > 0 ? avg_dist / count : 0.01;
}
for (int iter = 0; iter < iterations; ++iter) {
std::vector<Point3D> new_verts = result.vertices;
for (size_t i = 0; i < result.vertices.size(); ++i) {
const auto& pi = result.vertices[i];
Vector3D ni = result.has_normals() ? result.normals[i] : Vector3D(0, 0, 1);
double weight_sum = 0;
Vector3D displacement(0, 0, 0);
for (size_t j : knn[i]) {
if (j == i) continue;
const auto& pj = result.vertices[j];
Vector3D nj = result.has_normals() ? result.normals[j] : ni;
double d2 = (pj - pi).squaredNorm();
double w_c = std::exp(-d2 / (2.0 * sigma_c * sigma_c));
double dot_n = std::abs(ni.dot(nj));
double theta = std::acos(std::min(1.0, std::max(-1.0, dot_n)));
double w_n = std::exp(-theta * theta / (2.0 * sigma_n * sigma_n));
double w = w_c * w_n;
displacement = Vector3D(
displacement.x() + w * (pj.x() - pi.x()),
displacement.y() + w * (pj.y() - pi.y()),
displacement.z() + w * (pj.z() - pi.z()));
weight_sum += w;
}
if (weight_sum > 1e-12) {
double inv_w = 1.0 / weight_sum;
new_verts[i] = Point3D(
pi.x() + displacement.x() * inv_w * 0.5,
pi.y() + displacement.y() * inv_w * 0.5,
pi.z() + displacement.z() * inv_w * 0.5);
}
}
result.vertices = std::move(new_verts);
// Recompute normals after smoothing
result = result.normal_estimation(10);
}
return result;
}
// ───────────────────────────────────────────────────────────
// normal_aware_smoothing (VDE-330)
// ───────────────────────────────────────────────────────────
PointCloud PointCloud::normal_aware_smoothing(
int k_normal, double sigma_c, double sigma_n, int iterations) const
{
PointCloud result = *this;
if (vertices.empty()) return result;
// 若无法线则先计算
if (!result.has_normals()) {
result = result.normal_estimation(k_normal);
}
auto knn = k_nearest_neighbors(20);
// Auto sigma_c based on average spacing
if (sigma_c <= 0) {
double avg_dist = 0;
size_t count = 0;
for (size_t i = 0; i < std::min(vertices.size(), size_t(1000)); ++i) {
if (!knn[i].empty()) {
avg_dist += std::sqrt((vertices[knn[i][0]] - vertices[i]).squaredNorm());
++count;
}
}
sigma_c = count > 0 ? avg_dist / count : 0.01;
}
for (int iter = 0; iter < iterations; ++iter) {
// Step a: 重新估计法线(每轮迭代前)
if (result.has_normals()) {
result = result.normal_estimation(k_normal);
}
// Step b: 双边位置修正
std::vector<Point3D> new_verts = result.vertices;
for (size_t i = 0; i < result.vertices.size(); ++i) {
const auto& pi = result.vertices[i];
Vector3D ni = result.has_normals() ? result.normals[i] : Vector3D(0, 0, 1);
double weight_sum = 0;
Vector3D displacement(0, 0, 0);
for (size_t j : knn[i]) {
if (j == i) continue;
const auto& pj = result.vertices[j];
Vector3D nj = result.has_normals() ? result.normals[j] : ni;
double d2 = (pj - pi).squaredNorm();
double w_c = std::exp(-d2 / (2.0 * sigma_c * sigma_c));
double dot_n = std::abs(ni.dot(nj));
double theta = std::acos(std::min(1.0, std::max(-1.0, dot_n)));
double w_n = std::exp(-theta * theta / (2.0 * sigma_n * sigma_n));
double w = w_c * w_n;
displacement = Vector3D(
displacement.x() + w * (pj.x() - pi.x()),
displacement.y() + w * (pj.y() - pi.y()),
displacement.z() + w * (pj.z() - pi.z()));
weight_sum += w;
}
if (weight_sum > 1e-12) {
double inv_w = 1.0 / weight_sum;
new_verts[i] = Point3D(
pi.x() + displacement.x() * inv_w * 0.5,
pi.y() + displacement.y() * inv_w * 0.5,
pi.z() + displacement.z() * inv_w * 0.5);
}
}
result.vertices = std::move(new_verts);
}
return result;
}
bool point_cloud_gpu_available() {
#if defined(VDE_HAVE_COMPUTE)
return gpu_cloud_probe();
#else
return false;
#endif
}
std::size_t point_cloud_gpu_min_points() {
#if defined(VDE_HAVE_COMPUTE)
const char* text = std::getenv("VDE_GPU_CLOUD_MIN_POINTS");
if (text && *text) {
char* end = nullptr;
const unsigned long long parsed = std::strtoull(text, &end, 10);
if (end && *end == '\0') return static_cast<std::size_t>(parsed);
}
return kGpuCloudDefaultMinPoints;
#else
return 0; // 未编译 GPU 后端:阈值无意义,始终走 CPU
#endif
}
} // namespace vde::mesh