Files
ViewDesignEngine/plugins/official/cam_gcode/cam_gcode_plugin.cpp
T

529 lines
19 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.
// WP-P4-35 官方 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 粗加工刀路(最小实现,不做残料/碰撞/进退刀策略)。
//
// args JSON(UTF-8,可为空 = 默认):
// {
// "stepover": 5.0, // >0,Y 向行距
// "feed": 300.0, // >0,切削进给
// "rapid": 1000.0, // >0,快速移动(校验/注释;G0 由控制器决定速度)
// "clearance": 5.0, // >=0,安全平面相对毛坯顶面的高度
// "postprocessor": "fanuc", // fanuc | grbl
// "line_numbers": true, // 是否输出 N 行号(默认 false)
// "safe_z": 7.0 // 可选,绝对安全 Z;必须 >= 毛坯 bbox.zmax
// }
//
// 输出 G-code 文本(host->alloc;宿主 free_buffer):G21/G90/G17、G0 安全 Z、
// G1 光栅、G0 退刀、M30;Fanuc 头尾含 %/O 程序号,Grbl 使用 ; 注释与 M5 尾。
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <map>
#include <string>
#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<std::string, ArgValue>& 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<unsigned char>(input_[pos_++]);
if (c == '"') return true;
if (c < 0x20) {
error = "control character in args string";
return false;
}
if (c != '\\') {
out.push_back(static_cast<char>(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<std::string, ArgValue>& 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<std::string, ArgValue>& 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<std::string, ArgValue>& 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;
}
std::string lower_ascii(std::string text) {
for (char& c : text) {
if (c >= 'A' && c <= 'Z') c = static_cast<char>(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 {
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<std::string, ArgValue> args;
FlatJsonParser parser(args_text);
if (!parser.parse(args, 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);
if (config.postprocessor != "fanuc" && config.postprocessor != "grbl") {
error = "args.postprocessor must be fanuc or grbl";
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 x0 = bbox_min[0];
const double x1 = bbox_max[0];
const double y0 = bbox_min[1];
const double y1 = bbox_max[1];
const double cut_z = bbox_max[2];
const bool fanuc = config.postprocessor == "fanuc";
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 (raster roughing, minimal)");
comment("postprocessor: " + config.postprocessor);
comment("stock bbox X[" + format_number(x0) + "," + format_number(x1) + "] Y[" +
format_number(y0) + "," + format_number(y1) + "] Z[" +
format_number(bbox_min[2]) + "," + format_number(bbox_max[2]) + "]");
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));
if (fanuc) {
code += "%\n";
code += "O0001 (VDE CAM RASTER)\n";
} else {
code += "; GRBL post\n";
}
command("G21");
command("G90");
command("G17");
command("G40 G49 G80");
command("G0 Z" + format_number(config.safe_z));
command("G0 X" + format_number(x0) + " Y" + format_number(y0));
command("G1 Z" + format_number(cut_z) + " F" + format_number(config.feed));
double y = y0;
bool forward = true;
std::size_t passes = 0;
while (true) {
const double target_x = forward ? x1 : x0;
command("G1 X" + format_number(target_x) + " Y" + format_number(y) + " F" +
format_number(config.feed));
++passes;
if (y + config.stepover > y1 + 1e-9) break;
y = std::min(y + config.stepover, y1);
command("G1 Y" + format_number(y) + " F" + format_number(config.feed));
forward = !forward;
}
command("G0 Z" + format_number(config.safe_z));
if (fanuc) {
command("M30");
code += "%\n";
} else {
command("M5");
command("M30");
}
comment("passes: " + std::to_string(passes));
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 raster G-code post (Fanuc/Grbl, ABI 1.2)";
}
const VdeCamStrategyPlugin kStrategy = [] {
VdeCamStrategyPlugin strategy{};
strategy.struct_size = static_cast<std::uint32_t>(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 (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"