Files

543 lines
21 KiB
C++
Raw Permalink 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.
// 官方 ASCII OFF 格式插件(VDE 微内核 P4-21;纯 C ABI,不链接内核)。
//
// 读:OFF / COFF(Object File Format)。
// - 首 token OFF 或 COFF(大小写不敏感),counts 行可与首 token 同行;
// - counts = 顶点数 面数 [边数],边数读取后忽略;
// - '#' 注释与空行可出现在任意位置;
// - 顶点行读取 x y z,行尾附加字段(如 COFF 颜色)忽略;
// - 面行格式为 k i0 i1 ... i(k-1),k >= 3,索引 0-based、
// 必须小于顶点数;按扇形 (i0, i(j-1), ij) 三角化;
// - 显式错误:空文件/坏头/counts 非法/截断/索引越界/超出上限/多余数据。
// 写:所有实体经宿主 body_tessellate 摊平成三角面后合并为一个 ASCII OFF
// (顶点数为各实体三角化结果之和,面数为三角面数,边数固定 0)。
// 所有几何能力经宿主服务表获得,插件不链接内核。
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <new>
#include <string>
#include <vector>
#include "../common/format_plugin_common.h"
namespace {
using vde_plugin_common::MeshAccumulator;
using vde_plugin_common::fail;
using vde_plugin_common::is_space_char;
using vde_plugin_common::lower_copy;
using vde_plugin_common::read_file_bytes;
using vde_plugin_common::validate_common_host;
using vde_plugin_common::validate_read_host;
using vde_plugin_common::validate_write_host;
using vde_plugin_common::write_file_bytes;
constexpr std::uint64_t kMaxVertices = 20000000ull;
constexpr std::uint64_t kMaxFaces = 20000000ull;
constexpr std::uint64_t kMaxFaceVertices = 1000000ull;
constexpr std::size_t kMaxTriangles = 50000000u;
std::vector<std::string> split_ws(const std::string& line) {
std::vector<std::string> tokens;
std::size_t i = 0;
while (i < line.size()) {
while (i < line.size() && is_space_char(line[i])) ++i;
if (i >= line.size()) break;
const std::size_t begin = i;
while (i < line.size() && !is_space_char(line[i])) ++i;
tokens.push_back(line.substr(begin, i - begin));
}
return tokens;
}
bool parse_uint_token(const std::string& token, std::uint64_t* out) {
if (token.empty() || !out) return false;
std::uint64_t value = 0;
for (char c : token) {
if (c < '0' || c > '9') return false;
const std::uint64_t digit = static_cast<std::uint64_t>(c - '0');
if (value > (UINT64_MAX - digit) / 10ull) return false;
value = value * 10ull + digit;
}
*out = value;
return true;
}
bool parse_real_token(const std::string& token, double* out) {
if (token.empty() || !out) return false;
char* parse_end = nullptr;
const double value = std::strtod(token.c_str(), &parse_end);
if (parse_end != token.c_str() + token.size()) return false;
if (!std::isfinite(value)) return false;
*out = value;
return true;
}
/// 逐行读取内容行:跳过空行、跳过 '#' 起始或行内注释、去掉行尾 CR。
struct LineReader {
const char* cursor = nullptr;
const char* end = nullptr;
bool next_content_line(std::string* line) {
if (!cursor || !end || !line) return false;
while (cursor < end) {
const char* line_end = cursor;
while (line_end < end && *line_end != '\n') ++line_end;
line->assign(cursor, static_cast<std::size_t>(line_end - cursor));
cursor = (line_end < end) ? line_end + 1 : end;
if (!line->empty() && line->back() == '\r') line->pop_back();
const std::size_t comment = line->find('#');
if (comment != std::string::npos) line->resize(comment);
std::size_t begin = 0;
while (begin < line->size() && is_space_char((*line)[begin])) ++begin;
std::size_t finish = line->size();
while (finish > begin && is_space_char((*line)[finish - 1])) --finish;
if (finish > begin) {
*line = line->substr(begin, finish - begin);
return true;
}
}
return false;
}
};
bool parse_off(const char* data, std::size_t size, MeshAccumulator* mesh,
std::string* error) {
if (!data || size == 0) {
if (error) *error = "off: 空文件";
return false;
}
// 容忍 UTF-8 BOM(部分文本编辑器会写入)。
if (size >= 3 && static_cast<unsigned char>(data[0]) == 0xEF &&
static_cast<unsigned char>(data[1]) == 0xBB &&
static_cast<unsigned char>(data[2]) == 0xBF) {
data += 3;
size -= 3;
}
LineReader reader{data, data + size};
std::string line;
if (!reader.next_content_line(&line)) {
if (error) *error = "off: 空文件";
return false;
}
std::vector<std::string> tokens = split_ws(line);
if (tokens.empty()) {
if (error) *error = "off: 空文件";
return false;
}
const std::string magic = lower_copy(tokens[0]);
if (magic != "off" && magic != "coff") {
if (error) *error = "off: 文件头不是 OFF/COFF";
return false;
}
std::vector<std::string> count_tokens(tokens.begin() + 1, tokens.end());
if (count_tokens.empty()) {
if (!reader.next_content_line(&line)) {
if (error) *error = "off: 缺少 counts 行";
return false;
}
count_tokens = split_ws(line);
}
if (count_tokens.size() < 2 || count_tokens.size() > 3) {
if (error) *error = "off: counts 行必须包含 2 或 3 个非负整数";
return false;
}
std::uint64_t vertex_count = 0;
std::uint64_t face_count = 0;
if (!parse_uint_token(count_tokens[0], &vertex_count) ||
!parse_uint_token(count_tokens[1], &face_count)) {
if (error) *error = "off: counts 行包含非法整数";
return false;
}
if (count_tokens.size() == 3) {
std::uint64_t edge_count = 0;
if (!parse_uint_token(count_tokens[2], &edge_count)) {
if (error) *error = "off: counts 行包含非法整数";
return false;
}
(void)edge_count; // OFF 的边数不参与网格构建
}
if (vertex_count > kMaxVertices) {
if (error) *error = "off: 顶点数量超过上限";
return false;
}
if (face_count > kMaxFaces) {
if (error) *error = "off: 面数量超过上限";
return false;
}
for (std::uint64_t i = 0; i < vertex_count; ++i) {
if (!reader.next_content_line(&line)) {
if (error) *error = "off: 顶点数据被截断";
return false;
}
const std::vector<std::string> fields = split_ws(line);
if (fields.size() < 3) {
if (error) *error = "off: 顶点行数据不足(需要 x y z)";
return false;
}
double xyz[3] = {0.0, 0.0, 0.0};
for (int axis = 0; axis < 3; ++axis) {
if (!parse_real_token(fields[static_cast<std::size_t>(axis)], &xyz[axis])) {
if (error) *error = "off: 顶点坐标非法";
return false;
}
}
mesh->add_vertex(xyz[0], xyz[1], xyz[2]);
}
std::vector<std::uint32_t> face_indices;
for (std::uint64_t f = 0; f < face_count; ++f) {
if (!reader.next_content_line(&line)) {
if (error) *error = "off: 面数据被截断";
return false;
}
const std::vector<std::string> fields = split_ws(line);
if (fields.empty()) {
if (error) *error = "off: 面行为空";
return false;
}
std::uint64_t k = 0;
if (!parse_uint_token(fields[0], &k)) {
if (error) *error = "off: 面顶点数非法";
return false;
}
if (k < 3) {
if (error) *error = "off: 面顶点数小于 3";
return false;
}
if (k > kMaxFaceVertices) {
if (error) *error = "off: 单面顶点数超过上限";
return false;
}
if (k > static_cast<std::uint64_t>(fields.size() - 1)) {
if (error) *error = "off: 面索引被截断";
return false;
}
if (k > vertex_count) {
if (error) *error = "off: 面顶点数超过顶点总数";
return false;
}
face_indices.clear();
face_indices.reserve(static_cast<std::size_t>(k));
for (std::uint64_t j = 0; j < k; ++j) {
std::uint64_t index = 0;
if (!parse_uint_token(fields[static_cast<std::size_t>(1 + j)], &index)) {
if (error) *error = "off: 面索引非法";
return false;
}
if (index >= vertex_count) {
if (error) *error = "off: 面索引越界";
return false;
}
face_indices.push_back(static_cast<std::uint32_t>(index));
}
for (std::size_t i = 2; i < face_indices.size(); ++i) {
// 重复索引形成的退化三角面直接跳过(与内核网格导入口径一致)。
mesh->add_triangle(face_indices[0], face_indices[i - 1], face_indices[i]);
if (mesh->triangle_count() > kMaxTriangles) {
if (error) *error = "off: 三角面数量超过上限";
return false;
}
}
}
if (reader.next_content_line(&line)) {
if (error) *error = "off: 面数据后存在多余内容";
return false;
}
return true;
}
// ─────────────────────────────────────────────────────────
// 写出
// ─────────────────────────────────────────────────────────
bool collect_write_mesh(const VdePluginHost* host, const VdeBody* bodies,
std::size_t count, MeshAccumulator* out, std::string* error) {
if (!host || !out) return false;
if (!bodies || count == 0) {
if (error) *error = "off: 没有实体可写出";
return false;
}
for (std::size_t body_index = 0; body_index < count; ++body_index) {
if (!bodies[body_index]) {
if (error) *error = "off: 实体句柄为空";
return false;
}
VdeMeshData mesh{};
mesh.struct_size = static_cast<std::uint32_t>(sizeof(VdeMeshData));
const int rc = host->body_tessellate(bodies[body_index], 0.01, &mesh);
const auto release = [&]() {
if (!host->free_buffer) return;
host->free_buffer(mesh.positions);
host->free_buffer(mesh.indices);
host->free_buffer(mesh.normals);
mesh.positions = nullptr;
mesh.indices = nullptr;
mesh.normals = nullptr;
};
if (rc != VDE_PLUGIN_OK) {
release();
if (error) *error = "off: 实体三角化失败";
return false;
}
if (!mesh.positions || !mesh.indices || mesh.num_triangles == 0) {
release();
continue; // 空实体不贡献顶点/面
}
if (mesh.num_vertices == 0) {
release();
if (error) *error = "off: 三角化结果顶点为空";
return false;
}
const std::uint64_t vertex_total =
static_cast<std::uint64_t>(out->vertex_count()) + mesh.num_vertices;
if (vertex_total > 0xFFFFFFFFull) {
release();
if (error) *error = "off: 合并后顶点数量超过 uint32 范围";
return false;
}
const std::uint32_t offset = static_cast<std::uint32_t>(out->vertex_count());
out->positions.reserve(out->positions.size() + mesh.num_vertices * 3u);
for (std::size_t i = 0; i < mesh.num_vertices * 3u; ++i)
out->positions.push_back(mesh.positions[i]);
for (std::size_t t = 0; t < mesh.num_triangles; ++t) {
const std::uint32_t a = mesh.indices[3u * t + 0u];
const std::uint32_t b = mesh.indices[3u * t + 1u];
const std::uint32_t c = mesh.indices[3u * t + 2u];
if (static_cast<std::size_t>(a) >= mesh.num_vertices ||
static_cast<std::size_t>(b) >= mesh.num_vertices ||
static_cast<std::size_t>(c) >= mesh.num_vertices) {
release();
if (error) *error = "off: 三角化索引越界";
return false;
}
out->add_triangle(offset + a, offset + b, offset + c);
if (out->triangle_count() > kMaxTriangles) {
release();
if (error) *error = "off: 三角面数量超过上限";
return false;
}
}
release();
}
if (out->empty()) {
if (error) *error = "off: 实体三角化后没有三角面";
return false;
}
return true;
}
void append_number(std::string* out, double value) {
char buffer[64];
const int written = std::snprintf(buffer, sizeof(buffer), "%.17g", value);
if (written > 0) out->append(buffer, static_cast<std::size_t>(written));
}
std::string serialize_off(const MeshAccumulator& mesh) {
std::string out;
out.reserve(mesh.vertex_count() * 56u + mesh.triangle_count() * 28u + 64u);
out += "OFF\n";
out += std::to_string(mesh.vertex_count());
out += ' ';
out += std::to_string(mesh.triangle_count());
out += " 0\n";
for (std::size_t i = 0; i < mesh.vertex_count(); ++i) {
append_number(&out, mesh.positions[3u * i + 0u]);
out += ' ';
append_number(&out, mesh.positions[3u * i + 1u]);
out += ' ';
append_number(&out, mesh.positions[3u * i + 2u]);
out += '\n';
}
for (std::size_t t = 0; t < mesh.triangle_count(); ++t) {
out += "3 ";
out += std::to_string(mesh.indices[3u * t + 0u]);
out += ' ';
out += std::to_string(mesh.indices[3u * t + 1u]);
out += ' ';
out += std::to_string(mesh.indices[3u * t + 2u]);
out += '\n';
}
return out;
}
// ─────────────────────────────────────────────────────────
// 入口
// ─────────────────────────────────────────────────────────
int off_read_memory_impl(const VdePluginHost* host, const void* data, std::size_t size,
VdeBody** bodies, std::size_t* count) {
if (bodies) *bodies = nullptr;
if (count) *count = 0;
if (!bodies || !count) return fail(host, VDE_PLUGIN_ERR_INVALID_ARG, "off: 输出指针为空");
const int host_rc = validate_read_host(host);
if (host_rc != VDE_PLUGIN_OK) return host_rc;
if (!data || size == 0) return fail(host, VDE_PLUGIN_ERR_INVALID_ARG, "off: 内存数据为空");
try {
MeshAccumulator mesh;
std::string error;
if (!parse_off(static_cast<const char*>(data), size, &mesh, &error))
return fail(host, VDE_PLUGIN_ERR_PARSE, error.c_str());
return vde_plugin_common::publish_single_body(host, mesh, bodies, count, "off");
} catch (const std::bad_alloc&) {
return fail(host, VDE_PLUGIN_ERR_INTERNAL, "off: 解析内存不足");
} catch (...) {
return fail(host, VDE_PLUGIN_ERR_INTERNAL, "off: 解析发生未知异常");
}
}
int off_read_file(const VdePluginHost* host, const char* path, VdeBody** bodies,
std::size_t* count) {
if (bodies) *bodies = nullptr;
if (count) *count = 0;
if (!bodies || !count) return fail(host, VDE_PLUGIN_ERR_INVALID_ARG, "off: 输出指针为空");
const int host_rc = validate_read_host(host);
if (host_rc != VDE_PLUGIN_OK) return host_rc;
if (!path || !*path) return fail(host, VDE_PLUGIN_ERR_INVALID_ARG, "off: 输入路径为空");
std::string bytes;
if (!read_file_bytes(path, &bytes))
return fail(host, VDE_PLUGIN_ERR_IO, "off: 无法读取输入文件");
return off_read_memory_impl(host, bytes.data(), bytes.size(), bodies, count);
}
int off_read_memory(const VdePluginHost* host, const void* data, std::size_t size,
VdeBody** bodies, std::size_t* count) {
return off_read_memory_impl(host, data, size, bodies, count);
}
int off_write_file(const VdePluginHost* host, const char* path, const VdeBody* bodies,
std::size_t count) {
if (!path || !*path) return fail(host, VDE_PLUGIN_ERR_INVALID_ARG, "off: 输出路径为空");
const int host_rc = validate_write_host(host);
if (host_rc != VDE_PLUGIN_OK) return host_rc;
try {
MeshAccumulator mesh;
std::string error;
if (!collect_write_mesh(host, bodies, count, &mesh, &error))
return fail(host, VDE_PLUGIN_ERR_INTERNAL, error.c_str());
const std::string bytes = serialize_off(mesh);
if (!write_file_bytes(path, bytes.data(), bytes.size()))
return fail(host, VDE_PLUGIN_ERR_IO, "off: 写出文件失败");
return VDE_PLUGIN_OK;
} catch (const std::bad_alloc&) {
return fail(host, VDE_PLUGIN_ERR_INTERNAL, "off: 写出内存不足");
} catch (...) {
return fail(host, VDE_PLUGIN_ERR_INTERNAL, "off: 写出发生未知异常");
}
}
int off_write_memory(const VdePluginHost* host, const VdeBody* bodies, std::size_t count,
VdeBuffer* out) {
if (out) {
out->data = nullptr;
out->size = 0;
}
if (!out) return fail(host, VDE_PLUGIN_ERR_INVALID_ARG, "off: out 为空");
const int host_rc = validate_write_host(host);
if (host_rc != VDE_PLUGIN_OK) return host_rc;
try {
MeshAccumulator mesh;
std::string error;
if (!collect_write_mesh(host, bodies, count, &mesh, &error))
return fail(host, VDE_PLUGIN_ERR_INTERNAL, error.c_str());
const std::string bytes = serialize_off(mesh);
void* buffer = host->alloc(bytes.size());
if (!buffer) return fail(host, VDE_PLUGIN_ERR_BUFFER, "off: 输出缓冲分配失败");
std::memcpy(buffer, bytes.data(), bytes.size());
out->data = buffer;
out->size = bytes.size();
return VDE_PLUGIN_OK;
} catch (const std::bad_alloc&) {
return fail(host, VDE_PLUGIN_ERR_INTERNAL, "off: 写出内存不足");
} catch (...) {
return fail(host, VDE_PLUGIN_ERR_INTERNAL, "off: 写出发生未知异常");
}
}
int off_probe(const void* head, std::size_t head_size) {
if (!head || head_size == 0) return 0;
const char* p = static_cast<const char*>(head);
const char* end = p + head_size;
if (head_size >= 3 && static_cast<unsigned char>(p[0]) == 0xEF &&
static_cast<unsigned char>(p[1]) == 0xBB &&
static_cast<unsigned char>(p[2]) == 0xBF) {
p += 3;
}
while (p < end) {
const char* line_end = p;
while (line_end < end && *line_end != '\n') ++line_end;
const char* q = p;
while (q < line_end && is_space_char(*q)) ++q;
if (q < line_end && *q != '#') {
const char* token_end = q;
while (token_end < line_end && !is_space_char(*token_end)) ++token_end;
const std::string token = lower_copy(std::string(q, token_end));
return (token == "off" || token == "coff") ? 100 : 0;
}
p = (line_end < end) ? line_end + 1 : end;
}
return 0;
}
const char* off_describe() {
return "VDE official ASCII OFF format (OFF/COFF read; ASCII OFF write)";
}
const VdeFormatPlugin kFormat = [] {
VdeFormatPlugin format{};
format.struct_size = static_cast<std::uint32_t>(sizeof(VdeFormatPlugin));
format.format_id = "off";
format.extensions = ".off";
format.probe = &off_probe;
format.read_file = &off_read_file;
format.read_memory = &off_read_memory;
format.write_file = &off_write_file;
format.write_memory = &off_write_memory;
format.describe = &off_describe;
return format;
}();
} // namespace
extern "C" {
VDE_PLUGIN_EXPORT int vde_plugin_query(std::uint32_t host_abi_major, VdePluginInfo* info) {
if (!info || info->struct_size < sizeof(VdePluginInfo)) return VDE_PLUGIN_ERR_ABI;
if (host_abi_major != VDE_PLUGIN_ABI_MAJOR) return VDE_PLUGIN_ERR_ABI;
info->id = "com.vde.official.off";
info->name = "VDE Official ASCII OFF Format";
info->version = "1.0.0";
info->kind = VDE_PLUGIN_KIND_FORMAT;
info->abi_major = VDE_PLUGIN_ABI_MAJOR;
info->abi_minor = VDE_PLUGIN_ABI_MINOR;
info->capabilities = "format:off.read;format:off.write";
info->license = "Apache-2.0";
return VDE_PLUGIN_OK;
}
VDE_PLUGIN_EXPORT int vde_plugin_init(const VdePluginHost* host,
VdePluginRegistration* reg) {
if (!reg || reg->struct_size < sizeof(VdePluginRegistration))
return VDE_PLUGIN_ERR_ABI;
const int host_rc = validate_common_host(host);
if (host_rc != VDE_PLUGIN_OK) return host_rc;
reg->kind = VDE_PLUGIN_KIND_FORMAT;
reg->format = &kFormat;
reg->generic = nullptr;
reg->cae_solver = nullptr;
reg->cam_strategy = nullptr;
reg->gcs_solver = nullptr;
reg->mesher = nullptr;
reg->optimizer = nullptr;
reg->io_batch = nullptr;
return VDE_PLUGIN_OK;
}
VDE_PLUGIN_EXPORT void vde_plugin_shutdown() {}
} // extern "C"