// WP-P4-35/P4-57 官方 CAM G-code 后处理插件(ABI 1.2 VdeCamStrategyPlugin;纯 C ABI,不链接内核)。 // // 输入:VDE 序列化 B-Rep 模型 model_data + args_json。 // 通过 host->body_from_serialized / body_bbox 取毛坯包围盒,生成 Fanuc/Grbl // raster 或 contour 粗加工刀路(简化实现,不做残料/碰撞/进退刀策略)。 // // args JSON(UTF-8,可为空 = 默认): // { // "strategy": "raster", // raster | contour // "direction": "x", // raster 行方向:x | y // "passes": 1, // Z 多程 1..20;1 程切 zmax,多程均分到 zmin // "tool_radius": 0.0, // >=0 刀具半径(几何偏置) // "finish_allowance": 0.0, // >=0 精加工余量(与 tool_radius 一起偏置) // "stepover": 5.0, // >0 行距 // "feed": 300.0, // >0 切削进给 // "rapid": 1000.0, // >0 快速移动(校验/注释;G0 由控制器决定速度) // "clearance": 5.0, // >=0 安全平面相对毛坯顶面的高度 // "postprocessor": "fanuc", // fanuc | grbl // "line_numbers": false, // 是否输出 N 行号(默认 false) // "safe_z": 7.0 // 可选,绝对安全 Z;必须 >= bbox.zmax // } // // 输出 G-code 文本(host->alloc;宿主 free_buffer):G21/G90/G17、G0 安全 Z、 // 每程 G1 Z、raster/contour 刀路、G0 退刀、M30;Fanuc 头尾含 %/O 程序号, // Grbl 使用 ; 注释与 M5 尾。 #include #include #include #include #include #include #include #include #include #include #include "vde/plugin/vde_plugin_api.h" namespace { constexpr const char* kPluginId = "com.vde.official.cam.gcode"; constexpr const char* kStrategyId = "cam.post.gcode"; constexpr const char* kManifestVersion = "1.0.0"; constexpr std::uint32_t kPluginAbiMinor = 2; int cam_fail(const VdePluginHost* host, int code, const std::string& message) { if (host != nullptr && host->set_error != nullptr) host->set_error(message.c_str()); return code; } struct ArgValue { enum class Kind { Number, String, Bool, Null }; Kind kind = Kind::Null; double number = 0.0; std::string text; bool boolean = false; }; class FlatJsonParser { public: explicit FlatJsonParser(const std::string& input) : input_(input) {} bool parse(std::map& out, std::string& error) { skip_ws(); if (pos_ >= input_.size() || input_[pos_] != '{') { error = "args must be a JSON object"; return false; } ++pos_; skip_ws(); if (pos_ < input_.size() && input_[pos_] == '}') { ++pos_; return finish(error); } while (true) { skip_ws(); std::string key; if (!parse_string(key, error)) return false; skip_ws(); if (pos_ >= input_.size() || input_[pos_] != ':') { error = "expected ':' after args key"; return false; } ++pos_; skip_ws(); ArgValue value; if (!parse_value(value, error)) return false; if (out.find(key) != out.end()) { error = "duplicate args key: " + key; return false; } out.emplace(std::move(key), std::move(value)); skip_ws(); if (pos_ >= input_.size()) { error = "unterminated args object"; return false; } if (input_[pos_] == ',') { ++pos_; continue; } if (input_[pos_] == '}') { ++pos_; return finish(error); } error = "expected ',' or '}' in args"; return false; } } private: bool finish(std::string& error) { skip_ws(); if (pos_ != input_.size()) { error = "trailing characters after args JSON"; return false; } return true; } bool parse_value(ArgValue& value, std::string& error) { skip_ws(); if (pos_ >= input_.size()) { error = "unexpected end of args"; return false; } const char c = input_[pos_]; if (c == '"') { value.kind = ArgValue::Kind::String; return parse_string(value.text, error); } if (c == 't' || c == 'f') { const bool flag = c == 't'; const char* literal = flag ? "true" : "false"; const std::size_t length = std::strlen(literal); if (input_.compare(pos_, length, literal) != 0) { error = "invalid boolean in args"; return false; } pos_ += length; value.kind = ArgValue::Kind::Bool; value.boolean = flag; return true; } if (c == 'n') { if (input_.compare(pos_, 4, "null") != 0) { error = "invalid literal in args"; return false; } pos_ += 4; value.kind = ArgValue::Kind::Null; return true; } if (c == '-' || (c >= '0' && c <= '9')) { const std::size_t begin = pos_; if (input_[pos_] == '-') ++pos_; if (pos_ >= input_.size() || input_[pos_] < '0' || input_[pos_] > '9') { error = "invalid number in args"; return false; } while (pos_ < input_.size() && input_[pos_] >= '0' && input_[pos_] <= '9') ++pos_; if (pos_ < input_.size() && input_[pos_] == '.') { ++pos_; if (pos_ >= input_.size() || input_[pos_] < '0' || input_[pos_] > '9') { error = "invalid fraction in args"; return false; } while (pos_ < input_.size() && input_[pos_] >= '0' && input_[pos_] <= '9') ++pos_; } if (pos_ < input_.size() && (input_[pos_] == 'e' || input_[pos_] == 'E')) { ++pos_; if (pos_ < input_.size() && (input_[pos_] == '+' || input_[pos_] == '-')) ++pos_; if (pos_ >= input_.size() || input_[pos_] < '0' || input_[pos_] > '9') { error = "invalid exponent in args"; return false; } while (pos_ < input_.size() && input_[pos_] >= '0' && input_[pos_] <= '9') ++pos_; } const std::string token = input_.substr(begin, pos_ - begin); char* end = nullptr; const double value_number = std::strtod(token.c_str(), &end); if (end == nullptr || *end != '\0' || !std::isfinite(value_number)) { error = "args number must be finite"; return false; } value.kind = ArgValue::Kind::Number; value.number = value_number; return true; } error = "unsupported value in args (object/array not allowed)"; return false; } bool parse_string(std::string& out, std::string& error) { skip_ws(); if (pos_ >= input_.size() || input_[pos_] != '"') { error = "expected string in args"; return false; } ++pos_; out.clear(); while (pos_ < input_.size()) { const unsigned char c = static_cast(input_[pos_++]); if (c == '"') return true; if (c < 0x20) { error = "control character in args string"; return false; } if (c != '\\') { out.push_back(static_cast(c)); continue; } if (pos_ >= input_.size()) { error = "unterminated escape in args string"; return false; } const char escape = input_[pos_++]; switch (escape) { case '"': out.push_back('"'); break; case '\\': out.push_back('\\'); break; case '/': out.push_back('/'); break; case 'b': out.push_back('\b'); break; case 'f': out.push_back('\f'); break; case 'n': out.push_back('\n'); break; case 'r': out.push_back('\r'); break; case 't': out.push_back('\t'); break; default: error = "unsupported escape in args string"; return false; } } error = "unterminated args string"; return false; } void skip_ws() { while (pos_ < input_.size()) { const char c = input_[pos_]; if (c == ' ' || c == '\t' || c == '\n' || c == '\r') ++pos_; else break; } } const std::string& input_; std::size_t pos_ = 0; }; bool get_number(const std::map& args, const char* key, double& out, std::string& error) { const auto it = args.find(key); if (it == args.end()) return true; if (it->second.kind != ArgValue::Kind::Number) { error = std::string("args.") + key + " must be a number"; return false; } out = it->second.number; return true; } bool get_bool(const std::map& args, const char* key, bool& out, std::string& error) { const auto it = args.find(key); if (it == args.end()) return true; if (it->second.kind != ArgValue::Kind::Bool) { error = std::string("args.") + key + " must be boolean"; return false; } out = it->second.boolean; return true; } bool get_string(const std::map& args, const char* key, std::string& out, std::string& error) { const auto it = args.find(key); if (it == args.end()) return true; if (it->second.kind != ArgValue::Kind::String) { error = std::string("args.") + key + " must be a string"; return false; } out = it->second.text; return true; } bool get_integer(const std::map& args, const char* key, int minimum, int maximum, int& out, std::string& error) { const auto it = args.find(key); if (it == args.end()) return true; if (it->second.kind != ArgValue::Kind::Number || !std::isfinite(it->second.number)) { error = std::string("args.") + key + " must be an integer"; return false; } const double rounded = std::round(it->second.number); if (std::fabs(it->second.number - rounded) > 1e-9 || rounded < minimum || rounded > maximum) { error = std::string("args.") + key + " must be an integer in [" + std::to_string(minimum) + "," + std::to_string(maximum) + "]"; return false; } out = static_cast(rounded); return true; } std::string lower_ascii(std::string text) { for (char& c : text) { if (c >= 'A' && c <= 'Z') c = static_cast(c - 'A' + 'a'); } return text; } std::string format_number(double value) { char buffer[64]; std::snprintf(buffer, sizeof(buffer), "%.6f", value); return buffer; } struct PostConfig { std::string strategy = "raster"; // raster | contour std::string direction = "x"; // raster: x | y int passes = 1; // 1..20 Z 多程 double tool_radius = 0.0; // 刀具半径(几何偏置;>=0) double finish_allowance = 0.0; // 精加工余量(与 tool_radius 一起偏置;>=0) double stepover = 5.0; double feed = 300.0; double rapid = 1000.0; double clearance = 5.0; bool safe_z_given = false; double safe_z = 0.0; bool line_numbers = false; std::string postprocessor = "fanuc"; }; bool parse_args(const char* args_json, PostConfig& config, std::string& error) { if (args_json == nullptr || *args_json == '\0') return true; const std::string args_text(args_json); std::map args; FlatJsonParser parser(args_text); if (!parser.parse(args, error)) return false; if (!get_string(args, "strategy", config.strategy, error)) return false; if (!get_string(args, "direction", config.direction, error)) return false; if (!get_integer(args, "passes", 1, 20, config.passes, error)) return false; if (!get_number(args, "tool_radius", config.tool_radius, error)) return false; if (!get_number(args, "finish_allowance", config.finish_allowance, error)) return false; if (!get_number(args, "stepover", config.stepover, error)) return false; if (!get_number(args, "feed", config.feed, error)) return false; if (!get_number(args, "rapid", config.rapid, error)) return false; if (!get_number(args, "clearance", config.clearance, error)) return false; if (!get_bool(args, "line_numbers", config.line_numbers, error)) return false; if (!get_string(args, "postprocessor", config.postprocessor, error)) return false; const auto safe_it = args.find("safe_z"); if (safe_it != args.end()) { if (safe_it->second.kind != ArgValue::Kind::Number) { error = "args.safe_z must be a number"; return false; } config.safe_z = safe_it->second.number; config.safe_z_given = true; } config.postprocessor = lower_ascii(config.postprocessor); config.strategy = lower_ascii(config.strategy); config.direction = lower_ascii(config.direction); if (config.postprocessor != "fanuc" && config.postprocessor != "grbl") { error = "args.postprocessor must be fanuc or grbl"; return false; } if (config.strategy != "raster" && config.strategy != "contour") { error = "args.strategy must be raster or contour"; return false; } if (config.direction != "x" && config.direction != "y") { error = "args.direction must be x or y"; return false; } if (!std::isfinite(config.tool_radius) || config.tool_radius < 0.0) { error = "args.tool_radius must be finite and >= 0"; return false; } if (!std::isfinite(config.finish_allowance) || config.finish_allowance < 0.0) { error = "args.finish_allowance must be finite and >= 0"; return false; } if (!std::isfinite(config.stepover) || config.stepover <= 0.0) { error = "args.stepover must be > 0"; return false; } if (!std::isfinite(config.feed) || config.feed <= 0.0) { error = "args.feed must be > 0"; return false; } if (!std::isfinite(config.rapid) || config.rapid <= 0.0) { error = "args.rapid must be > 0"; return false; } if (!std::isfinite(config.clearance) || config.clearance < 0.0) { error = "args.clearance must be >= 0"; return false; } if (config.safe_z_given && !std::isfinite(config.safe_z)) { error = "args.safe_z must be finite"; return false; } return true; } int cam_invoke(const VdePluginHost* host, const void* model_data, std::size_t model_size, const char* args_json, VdeBuffer* out) { if (out != nullptr) { out->data = nullptr; out->size = 0; } else { return cam_fail(host, VDE_PLUGIN_ERR_INVALID_ARG, "cam.gcode: output buffer is null"); } if (host == nullptr || host->alloc == nullptr || host->set_error == nullptr || host->body_from_serialized == nullptr || host->body_bbox == nullptr || host->body_destroy == nullptr || host->abi_major != VDE_PLUGIN_ABI_MAJOR) { return cam_fail(host, VDE_PLUGIN_ERR_UNSUPPORTED, "cam.gcode: host services incomplete or ABI incompatible"); } if (model_data == nullptr || model_size == 0) { return cam_fail(host, VDE_PLUGIN_ERR_INVALID_ARG, "cam.gcode: model_data is empty"); } PostConfig config; std::string error; if (!parse_args(args_json, config, error)) { return cam_fail(host, VDE_PLUGIN_ERR_INVALID_ARG, "cam.gcode: " + error); } VdeBody body = host->body_from_serialized(model_data, model_size); if (body == nullptr) { return cam_fail(host, VDE_PLUGIN_ERR_PARSE, "cam.gcode: body_from_serialized failed"); } double bbox_min[3] = {0.0, 0.0, 0.0}; double bbox_max[3] = {0.0, 0.0, 0.0}; const int bbox_rc = host->body_bbox(body, bbox_min, bbox_max); host->body_destroy(body); if (bbox_rc != VDE_PLUGIN_OK) { return cam_fail(host, VDE_PLUGIN_ERR_INTERNAL, "cam.gcode: body_bbox failed"); } for (int axis = 0; axis < 3; ++axis) { if (!std::isfinite(bbox_min[axis]) || !std::isfinite(bbox_max[axis]) || bbox_min[axis] > bbox_max[axis]) { return cam_fail(host, VDE_PLUGIN_ERR_INTERNAL, "cam.gcode: invalid bbox"); } } if (config.safe_z_given && config.safe_z < bbox_max[2]) { return cam_fail(host, VDE_PLUGIN_ERR_INVALID_ARG, "cam.gcode: args.safe_z must be >= bbox.zmax"); } if (!config.safe_z_given) config.safe_z = bbox_max[2] + config.clearance; if (!std::isfinite(config.safe_z)) { return cam_fail(host, VDE_PLUGIN_ERR_INTERNAL, "cam.gcode: safe_z is not finite"); } const double stock_x0 = bbox_min[0]; const double stock_x1 = bbox_max[0]; const double stock_y0 = bbox_min[1]; const double stock_y1 = bbox_max[1]; const double stock_z0 = bbox_min[2]; const double stock_z1 = bbox_max[2]; const bool fanuc = config.postprocessor == "fanuc"; const bool raster = config.strategy == "raster"; const double compensation = config.tool_radius + config.finish_allowance; if (!std::isfinite(compensation)) { return cam_fail(host, VDE_PLUGIN_ERR_INVALID_ARG, "cam.gcode: tool_radius + finish_allowance must be finite"); } double path_x0 = stock_x0; double path_x1 = stock_x1; double path_y0 = stock_y0; double path_y1 = stock_y1; if (raster) { const double min_extent = std::min(stock_x1 - stock_x0, stock_y1 - stock_y0); if (compensation > 0.0 && (min_extent <= 0.0 || compensation * 2.0 >= min_extent)) { return cam_fail(host, VDE_PLUGIN_ERR_INVALID_ARG, "cam.gcode: tool_radius + finish_allowance too large for raster stock"); } path_x0 = stock_x0 + compensation; path_x1 = stock_x1 - compensation; path_y0 = stock_y0 + compensation; path_y1 = stock_y1 - compensation; } else { // 轮廓策略:刀心沿 bbox 外侧偏移 tool_radius + finish_allowance,闭合矩形。 path_x0 = stock_x0 - compensation; path_x1 = stock_x1 + compensation; path_y0 = stock_y0 - compensation; path_y1 = stock_y1 + compensation; } if (path_x0 > path_x1 || path_y0 > path_y1) { return cam_fail(host, VDE_PLUGIN_ERR_INVALID_ARG, "cam.gcode: compensated path bounds are invalid"); } std::string code; int block = 10; const auto comment = [&](const std::string& text) { code += "; " + text + "\n"; }; const auto command = [&](const std::string& text) { if (config.line_numbers) code += "N" + std::to_string(block) + " "; code += text + "\n"; block += 10; }; comment("VDE official CAM G-code post (strategy=" + config.strategy + ", direction=" + config.direction + ", passes=" + std::to_string(config.passes) + ")"); comment("postprocessor: " + config.postprocessor); comment("stock bbox X[" + format_number(stock_x0) + "," + format_number(stock_x1) + "] Y[" + format_number(stock_y0) + "," + format_number(stock_y1) + "] Z[" + format_number(stock_z0) + "," + format_number(stock_z1) + "]"); comment("stepover=" + format_number(config.stepover) + " feed=" + format_number(config.feed) + " rapid=" + format_number(config.rapid) + " clearance=" + format_number(config.clearance) + " safe_z=" + format_number(config.safe_z)); comment("tool_radius=" + format_number(config.tool_radius) + " finish_allowance=" + format_number(config.finish_allowance) + " compensation=" + format_number(compensation)); if (fanuc) { code += "%\n"; code += "O0001 (VDE CAM)\n"; } else { code += "; GRBL post\n"; } command("G21"); command("G90"); command("G17"); command("G40 G49 G80"); const auto pass_z = [&](int pass) { if (config.passes <= 1 || stock_z1 <= stock_z0) return stock_z1; return stock_z1 - (stock_z1 - stock_z0) * static_cast(pass) / static_cast(config.passes - 1); }; const double start_x = path_x0; const double start_y = path_y0; std::size_t row_count = 0; for (int pass = 0; pass < config.passes; ++pass) { command("G0 Z" + format_number(config.safe_z)); command("G0 X" + format_number(start_x) + " Y" + format_number(start_y)); command("G1 Z" + format_number(pass_z(pass)) + " F" + format_number(config.feed)); if (raster) { if (config.direction == "x") { double y = path_y0; bool forward = true; while (true) { const double target_x = forward ? path_x1 : path_x0; command("G1 X" + format_number(target_x) + " Y" + format_number(y) + " F" + format_number(config.feed)); ++row_count; if (y >= path_y1 - 1e-9) break; y = std::min(y + config.stepover, path_y1); command("G1 Y" + format_number(y) + " F" + format_number(config.feed)); forward = !forward; } } else { double x = path_x0; bool forward = true; while (true) { const double target_y = forward ? path_y1 : path_y0; command("G1 Y" + format_number(target_y) + " X" + format_number(x) + " F" + format_number(config.feed)); ++row_count; if (x >= path_x1 - 1e-9) break; x = std::min(x + config.stepover, path_x1); command("G1 X" + format_number(x) + " F" + format_number(config.feed)); forward = !forward; } } } else { command("G1 X" + format_number(path_x1) + " Y" + format_number(path_y0) + " F" + format_number(config.feed)); command("G1 Y" + format_number(path_y1) + " F" + format_number(config.feed)); command("G1 X" + format_number(path_x0) + " F" + format_number(config.feed)); command("G1 Y" + format_number(path_y0) + " F" + format_number(config.feed)); ++row_count; } } command("G0 Z" + format_number(config.safe_z)); if (fanuc) { command("M30"); code += "%\n"; } else { command("M5"); command("M30"); } comment("passes: " + std::to_string(config.passes)); comment("path_rows: " + std::to_string(row_count)); void* buffer = host->alloc(code.size() + 1); if (buffer == nullptr) { return cam_fail(host, VDE_PLUGIN_ERR_BUFFER, "cam.gcode: cannot allocate output"); } std::memcpy(buffer, code.data(), code.size() + 1); out->data = buffer; out->size = code.size(); return VDE_PLUGIN_OK; } const char* describe() { return "VDE official CAM G-code post (raster/contour, Fanuc/Grbl, ABI 1.2)"; } const VdeCamStrategyPlugin kStrategy = [] { VdeCamStrategyPlugin strategy{}; strategy.struct_size = static_cast(sizeof(VdeCamStrategyPlugin)); strategy.strategy_id = kStrategyId; strategy.postprocessor_id = "fanuc"; strategy.machine_id = "generic-3axis"; strategy.invoke = &cam_invoke; strategy.describe = &describe; return strategy; }(); } // namespace extern "C" { VDE_PLUGIN_EXPORT int vde_plugin_query(std::uint32_t host_abi_major, VdePluginInfo* info) { if (info == nullptr || info->struct_size < sizeof(VdePluginInfo)) { return VDE_PLUGIN_ERR_INVALID_ARG; } if (host_abi_major != VDE_PLUGIN_ABI_MAJOR) return VDE_PLUGIN_ERR_ABI; info->id = kPluginId; info->name = "VDE Official CAM G-code Post (raster/contour, Fanuc/Grbl, ABI 1.2)"; info->version = kManifestVersion; info->kind = VDE_PLUGIN_KIND_CAM_STRATEGY; info->abi_major = VDE_PLUGIN_ABI_MAJOR; info->abi_minor = kPluginAbiMinor; info->capabilities = "cam_strategy:post.gcode"; info->license = "Apache-2.0"; return VDE_PLUGIN_OK; } VDE_PLUGIN_EXPORT int vde_plugin_init(const VdePluginHost* host, VdePluginRegistration* reg) { if (host == nullptr || reg == nullptr) return VDE_PLUGIN_ERR_INVALID_ARG; const std::size_t cam_field_end = offsetof(VdePluginRegistration, cam_strategy) + sizeof(reg->cam_strategy); if (reg->struct_size < cam_field_end) return VDE_PLUGIN_ERR_ABI; if (host->alloc == nullptr || host->set_error == nullptr || host->body_from_serialized == nullptr || host->body_bbox == nullptr || host->body_destroy == nullptr) { if (host->set_error) host->set_error("cam.gcode: host services incomplete"); return VDE_PLUGIN_ERR_UNSUPPORTED; } reg->kind = VDE_PLUGIN_KIND_CAM_STRATEGY; reg->format = nullptr; reg->generic = nullptr; reg->cae_solver = nullptr; reg->cam_strategy = &kStrategy; return VDE_PLUGIN_OK; } VDE_PLUGIN_EXPORT void vde_plugin_shutdown() {} } // extern "C"