Files
OrcaSlicer/src/libslic3r/GCode/AdaptivePAProcessor.cpp
T
Ian Bassi e821665e4b Add orca-translations Claude skill and PO tool (#16436)
* Add orca-translations Claude skill and PO tool

Add a .claude skill that guides translation passes over the localization/i18n gettext catalogs. It covers the workflow: run gettext, settle new glossary terms, translate in batches, verify, and report.

Includes translation-rules.md, which condenses the placeholder, line-break and glossary rules plus the guidance on review notes.

Also adds scripts/po_tool.py (standard library only). It lists pending entries with glossary hints, validates and applies translations, adding '# AI Translated' and '# Needs human review' comments, and rewrites only the entries it changes. It can also check catalogs, look up existing translations, suggest glossary candidates and update the wiki glossary TSV.

* Let po_tool apply translations by entry id

pending now gives each entry a short id, so a translation file can name
entries by id instead of repeating the English msgid. apply accepts either.

A "review": "" item clears an earlier review note when overwriting an
entry, and check gives each msgfmt run its own temporary output file so
parallel checks do not collide.

* Fill all empty translations

Regenerate the template with run_gettext --full and translate every empty
entry in the 22 catalogs (7,089 entries) with the orca-translations skill,
following the localization glossary, including the new belt printer,
IDEX/IQEX and plugin terms. Every new entry is marked "# AI Translated";
122 also carry "# Needs human review" with what to check.

* Show entry ids in po_tool lookup and search translations

lookup now prints each entry's id, so an entry found there can be
rewritten with apply --overwrite without repeating the English, and
--msgstr searches the translations instead of the msgids, which finds
every entry that still uses a term being changed.

SKILL.md describes how to change an established term: check the
catalog's usage first, update the glossary cell, then rewrite only the
entries where the term has that meaning.

* Fix mistranslated terms and align catalogs with the glossary

Correct labels that the glossary had copied, and the entries that used
them:
- ca: Raft was rendered as the Brim term; it is now "Rai". Exhaust fan,
  Monotonic line, Unretract, Slice, Lateral Honeycomb and PA Tower
  labels fixed.
- cs: Lightning infill is "Blesk", not "Osvětlení" (illumination).
- sv: Retraction is "Retraktion", not "Reduktion"; Unretract,
  Lagerhöjd, Delkylningsfläkt, Utsugsfläkt, Aligned Rectilinear and the
  Preset label fixed.
- de: Brim is "Rand" and Skirt is "Umrandung", as most entries already
  had them.
- lt: brim entries used the Skirt word "apvadas"; they now use "kraštas".
- es: Sparse infill is "relleno de baja densidad", the catalog majority.
- eu: nozzle wipe is "garbiketa", not purge.
- th: the project plate is "เพลต", distinct from the bed.
- uk: Quarter Cubic, Latin "PA" in PA Tower, and Belt purge tower.
- pl: Cross Hatch, Tri-hexagon, Volumetric speed and Raft labels.
- zh_TW: Brim stays "Brim", as the existing labels have it.
- tr: "Prime Tower" read "Prime Minister Tower".
- ko: the plugin "Capabilities" label read "performance".
- Build Volume labels fixed in tr, de, cs and eu.

All 242 rewritten entries are marked "# AI Translated".

* Make more UI text translatable and fix pluralization and context

Audit the sources for text that translators could not translate
correctly and fix it.

Mark text that reached users in English only: IDEX/IQEX role names,
plugin permission prompts and errors, 3MF/preset loading errors, G-code
placeholder parser errors, calibration and device messages, notification
texts, file dialog filters, and the config validation messages.

Replace sentences built from translated fragments, such as the prime
tower warnings, "left"/"right" nozzle names, and "Filament " + number,
with single msgids that have placeholders, so translators can reorder
and inflect them.

Use plural forms for texts with a count ("%1% mixed filaments",
"%d objects", "%1% triangles") instead of "(s)" and mismatched verbs.
Fix the swapped singular/plural pair in "The following presets inherit
this preset".

Add translation contexts where one English word has several meanings
(Subscribed/Local, Standard, Pause, View, Step, Model, Camera, Flow,
Filter, Others, Prepare, the Design tools). Show "Size" instead of
"Build Volume" in the Cut tool, which displays the object size.

Fix code that compared translated text with English (the Edit G-code
dialog group, the plugin registration failure check), and add the
bundled web pages' missing string-table entries. Use the single
character for degrees Celsius, say "G-code", and describe the head
filament map without internal jargon.

Install the libslic3r translate callback before the presets load, so
their load errors are translated, and list the 28 source files that had
marked strings but were never extracted into localization/i18n/list.txt.

* Suggest earlier translations and list fuzzy entries in po_tool pending

pending now attaches the closest earlier translation of a similar
English text (from obsolete or translated entries), so a reworded or
split string keeps its wording, and it lists fuzzy entries by default,
since users never see them. A fuzzy entry also carries its stale
translation as previous_translation.

* Fix wording of the non-boolean operands error

The logical operation error said "operators" where it means the
operands the operation was applied to.

* Translate the newly translatable strings in all languages

Regenerate the template after the translatability changes and fill every
new or changed entry in the 22 catalogs (about 12,800 entries): the
strings that became translatable, the plural forms, the entries split by
context, and the previously fuzzy singular entries that became plurals.

Every new entry is marked "# AI Translated", and about 360 also carry a
"# Needs human review" note saying what to check. Terms follow the
localization glossary. Earlier translations of reworded strings were
reused where the meaning was unchanged. Existing entries were not
changed, and obsolete entries are kept.

* Document the source translatability audit in the orca-translations skill

Add a reference describing how strings reach translators, what to look
for (untranslated text, spliced sentences, missing plurals, ambiguous
words), what not to translate, where a context cannot be carried, and
what to do after the edits, plus a scanner that lists untranslated
user-facing string literals.

* Document how to write translatable strings in AGENTS.md

Tell developers to keep each message complete in one msgid: use
placeholders instead of concatenating translated fragments, plural forms
for counts, and contexts for ambiguous words, and to list new source
files in localization/i18n/list.txt. Add a matching code review item.

* Translate the strings added since the rebase

Regenerate the template against the current main and translate the 26
new entries per language: the Fix Model commands and messages, and the
texture displacement image adjustment panel. Each new entry is marked
"# AI Translated"; existing entries are unchanged.

* tidy
2026-10-13 10:53:57 -03:00

379 lines
20 KiB
C++

// AdaptivePAProcessor.cpp
// OrcaSlicer
//
// Implementation of the AdaptivePAProcessor class, responsible for processing G-code layers with adaptive pressure advance.
#include "../GCode.hpp"
#include "libslic3r/GCode/AdaptivePAInterpolator.hpp"
#include "libslic3r/libslic3r.h"
#include "AdaptivePAProcessor.hpp"
#include <memory>
#include <cstddef>
#include <regex>
#include <iosfwd>
#include <algorithm>
#include <exception>
#include <sstream>
#include <iostream>
#include <cmath>
#include <cctype>
#include <string>
#include <utility>
#include "libslic3r/Config.hpp"
#include "libslic3r/GCodeWriter.hpp"
#include "libslic3r/PrintConfig.hpp"
#include "libslic3r/I18N.hpp"
#include "libslic3r/format.hpp"
namespace Slic3r {
/**
* @brief Constructor for AdaptivePAProcessor.
*
* This constructor initializes the AdaptivePAProcessor with a reference to a GCode object.
* It also initializes the configuration reference, pressure advance interpolation object,
* and regular expression patterns used for processing the G-code.
*
* @param gcodegen A reference to the GCode object that generates the G-code.
*/
AdaptivePAProcessor::AdaptivePAProcessor(GCode &gcodegen)
: m_gcodegen(gcodegen),
m_config(gcodegen.config()),
m_last_predicted_pa(0.0),
m_max_next_feedrate(0.0),
m_next_feedrate(0.0),
m_current_feedrate(0.0),
m_last_config_index(-1),
m_pa_change_pattern(R"(; PA_CHANGE:T(\d+) MM3MM:([0-9]*\.[0-9]+) ACCEL:(\d+) BR:(\d+) RC:(\d+) OV:(\d+))"),
m_g1_f_pattern(R"(G1 F([0-9]+))")
{
const size_t indices = std::max(m_config.adaptive_pressure_advance.size(), m_config.enable_pressure_advance.size());
for (size_t i = 0; i < indices && !m_enabled; ++i)
m_enabled = m_config.adaptive_pressure_advance.get_at(i) && m_config.enable_pressure_advance.get_at(i);
}
// Method to get the interpolator for a specific filament config index.
// The model is built the first time an index is requested, as the indices in use depend on
// the extruder variant each filament prints with.
AdaptivePAInterpolator* AdaptivePAProcessor::getInterpolator(unsigned int config_index) {
auto [it, inserted] = m_AdaptivePAInterpolators.try_emplace(config_index);
// Only enable model for the index if both PA and adaptive PA options are enabled
if (inserted && m_config.adaptive_pressure_advance.get_at(config_index) && m_config.enable_pressure_advance.get_at(config_index)) {
it->second = std::make_unique<AdaptivePAInterpolator>();
it->second->parseAndSetData(m_config.adaptive_pressure_advance_model.get_at(config_index));
}
return it->second.get();
}
/**
* @brief Processes a layer of G-code and applies adaptive pressure advance.
*
* This method processes the G-code for a single layer, identifying the appropriate
* pressure advance settings and applying them based on the current state and configurations.
*
* @param gcode A string containing the G-code for the layer.
* @return A string containing the processed G-code with adaptive pressure advance applied.
*/
std::string AdaptivePAProcessor::process_layer(std::string &&gcode) {
// Without PA_CHANGE tags the loop below would only terminate the layer's last line.
if (!m_enabled && gcode.find("; PA_CHANGE") == std::string::npos) {
if (!gcode.empty() && gcode.back() != '\n')
gcode += '\n';
return std::move(gcode);
}
std::istringstream stream(gcode);
std::string line;
std::ostringstream output;
double mm3mm_value = 0.0;
unsigned int accel_value = 0;
std::string pa_change_line;
bool wipe_command = false;
// Iterate through each line of the layer G-code
while (std::getline(stream, line)) {
// If a wipe start command is found, ignore all speed changes till the wipe end part is found
if (line.find("WIPE_START") != std::string::npos) {
wipe_command = true;
}
// Update current feed rate (this is preceding an extrude or wipe command only). Ignore any speed changes that are emitted during a wipe move.
// Travel feedrate is output as part of a G1 X Y (Z) F command
if ( (line.find("G1 F") == 0) && (!wipe_command) ) { // prune lines quickly before running pattern matching
std::size_t pos = line.find('F');
if (pos != std::string::npos){
m_current_feedrate = std::stod(line.substr(pos + 1)) / 60.0; // Convert from mm/min to mm/s
}
}
// Wipe end found, continue searching for current feed rate.
if (line.find("WIPE_END") != std::string::npos) {
wipe_command = false;
}
// Reset next feedrate to zero enable searching for the first encountered
// feedrate change command after the PA change tag.
m_next_feedrate = 0;
// Check for PA_CHANGE pattern in the line
// We will only find this pattern for extruders where adaptive PA is enabled.
// If there is mixed extruders in the layer (i.e. with adaptive PA on and off
// this will only update the extruders where the adaptive PA is enabled
// as these are the only ones where the PA pattern is output
// For a mixed extruder layer with both adaptive PA enabled and disabled when the new tool is selected
// the PA for that material is set. As no tag below will be found for this extruder, the original PA is retained.
if (line.find("; PA_CHANGE") == 0) { // prune lines quickly before running regex check as regex is more expensive to run
if (std::regex_search(line, m_match, m_pa_change_pattern)) {
// The tag carries the filament config index, which selects the PA settings of the filament's extruder variant
int config_index = std::stoi(m_match[1].str());
mm3mm_value = std::stod(m_match[2].str());
accel_value = std::stod(m_match[3].str());
int isBridge = std::stoi(m_match[4].str());
int roleChange = std::stoi(m_match[5].str());
int isOverhang = std::stoi(m_match[6].str());
// Check if the filament config index has changed
bool config_index_changed = (config_index != m_last_config_index);
m_last_config_index = config_index;
// Save the PA_CHANGE line to output later after finding feedrate
pa_change_line = line;
// Look ahead for feedrate before any line containing both G and E commands
std::streampos current_pos = stream.tellg();
std::string next_line;
double temp_feed_rate = 0;
bool extrude_move_found = false;
int line_counter = 0;
// Carry on searching on the layer gcode lines to find the print speed
// If a G1 Fxxxx pattern is found, the new speed is identified
// Carry on searching for feedrates to find the maximum print speed
// until a feature change pattern or a wipe command is detected
while (std::getline(stream, next_line)) {
line_counter++;
// Found an extrude move, set extrude move found flag and move to the next line
if ((!extrude_move_found) && next_line.find("G1 ") == 0 &&
next_line.find('X') != std::string::npos &&
next_line.find('Y') != std::string::npos &&
next_line.find('E') != std::string::npos) {
// Pattern matched, break the loop
extrude_move_found = true;
continue;
}
// Found a travel move after we've found at least one extrude move
// We now need to stop searching for speeds as we're done printing this island
if (next_line.find("G1 ") == 0 &&
next_line.find('X') != std::string::npos && // X is present
next_line.find('Y') != std::string::npos && // Y is present
next_line.find('E') == std::string::npos && // no "E" present
extrude_move_found) { // An extrude move has happened already
// First travel move after extrude move found. Stop searching
break;
}
// Found a WIPE command
// If we have a wipe command, usually the wipe speed is different (larger) than the max print speed
// for that feature. So stop searching if a wipe command is found because we do not want to overwrite the
// speed used for PA calculation by the Wipe speed.
if (next_line.find("WIPE") != std::string::npos) {
break; // Stop searching if wipe command is found
}
// Found another PA_CHANGE pattern
// If RC = 1, it means we have a role change, so stop trying to find the max speed for the feature.
// This is possibly redundant as a new feature would always have a travel move preceding it
// but check anyway. However check last so to not invoke it without reason...
if (next_line.find("; PA_CHANGE") == 0) { // prune lines quickly before running pattern matching
std::size_t rc_pos = next_line.rfind("RC:");
if (rc_pos != std::string::npos) {
int rc_value = std::stoi(next_line.substr(rc_pos + 3));
if (rc_value == 1) {
break; // Role change found, stop searching
}
}
}
// Found a Feedrate change command
// If the new feedrate is greater than any feedrate encountered so far after the PA change command, use that to calculate the PA value
// Also if this is the first feedrate we encounter, store it as the next feedrate.
if (next_line.find("G1 F") == 0) { // prune lines quickly before running pattern matching
std::size_t pos = next_line.find('F');
if (pos != std::string::npos) {
double feedrate = std::stod(next_line.substr(pos + 1)) / 60.0; // Convert from mm/min to mm/s
if(line_counter==1){ // this is the first command after the PA change pattern, and hence before any extrusion has happened. Reset
// the current speed to this one
m_current_feedrate = feedrate;
}
if (temp_feed_rate < feedrate) {
temp_feed_rate = feedrate;
}
if(m_next_feedrate < EPSILON){ // This the first feedrate found after the PA Change command
m_next_feedrate = feedrate;
}
}
continue;
}
}
// If we found a new maximum feedrate after the PA change command, use it
if (temp_feed_rate > 0) {
m_max_next_feedrate = temp_feed_rate;
} else // If we didnt find a new feedrate at all after the PA change command, use the current feedrate.
m_max_next_feedrate = m_current_feedrate;
// Restore stream position
stream.clear();
stream.seekg(current_pos);
// Calculate the predicted PA using the upcomming feature maximum feedrate
// Get the interpolator for the active tool
AdaptivePAInterpolator* interpolator = getInterpolator(m_last_config_index);
double predicted_pa = 0;
double adaptive_PA_speed = 0;
if(!interpolator){ // Tool not found in the interpolator map
// Tool not found in the PA interpolator to tool map
predicted_pa = m_config.enable_pressure_advance.get_at(m_last_config_index) ? m_config.pressure_advance.get_at(m_last_config_index) : 0;
if(m_config.gcode_comments) output << "; APA: Tool doesnt have APA enabled\n";
} else if (!interpolator->isInitialised() || (!m_config.adaptive_pressure_advance.get_at(m_last_config_index)) )
// Check if the model is not initialised by the constructor for the active extruder
// Also check that adaptive PA is enabled for that extruder. This should not be needed
// as the PA change flag should not be set upstream (in the GCode.cpp file) if adaptive PA is disabled
// however check for robustness sake.
{
// Model failed or adaptive pressure advance not enabled - use default value from m_config
predicted_pa = m_config.enable_pressure_advance.get_at(m_last_config_index) ? m_config.pressure_advance.get_at(m_last_config_index) : 0;
if(m_config.gcode_comments) output << "; APA: Interpolator setup failed, using default pressure advance\n";
} else { // Model setup succeeded
// Proceed to identify the print speed to use to calculate the adaptive PA value
if(isOverhang > 0){ // If we are in an overhang area, use the minimum between current print speed
// and any speed immediately after
// In most cases the current speed is the minimum one;
// however if slowdown for layer cooling is enabled, the overhang
// may be slowed down more than the current speed.
adaptive_PA_speed = (m_current_feedrate == 0 || m_next_feedrate == 0) ?
std::max(m_current_feedrate, m_next_feedrate) :
std::min(m_current_feedrate, m_next_feedrate);
}else{ // If this is not an overhang area, use the maximum speed from the current and
// upcomming speeds for the island.
adaptive_PA_speed = std::max(m_max_next_feedrate,m_current_feedrate);
}
// Calculate the adaptive PA value
predicted_pa = (*interpolator)(mm3mm_value * adaptive_PA_speed, accel_value);
// This is a bridge, use the dedicated PA setting.
if(isBridge && m_config.adaptive_pressure_advance_bridges.get_at(m_last_config_index) > EPSILON)
predicted_pa = m_config.adaptive_pressure_advance_bridges.get_at(m_last_config_index);
if (predicted_pa < 0) { // If extrapolation fails, fall back to the default PA for the extruder.
predicted_pa = m_config.enable_pressure_advance.get_at(m_last_config_index) ? m_config.pressure_advance.get_at(m_last_config_index) : 0;
if(m_config.gcode_comments) output << "; APA: Interpolation failed, using fallback pressure advance value\n";
}
}
if(m_config.gcode_comments) {
// Output debug GCode comments
output << pa_change_line << '\n'; // Output PA change command tag
if(isBridge && m_config.adaptive_pressure_advance_bridges.get_at(m_last_config_index) > EPSILON)
output << "; APA Model Override (bridge)\n";
output << "; APA Current Speed: " << std::to_string(m_current_feedrate) << "\n";
output << "; APA Next Speed: " << std::to_string(m_next_feedrate) << "\n";
output << "; APA Max Next Speed: " << std::to_string(m_max_next_feedrate) << "\n";
output << "; APA Speed Used: " << std::to_string(adaptive_PA_speed) << "\n";
output << "; APA Flow rate: " << std::to_string(mm3mm_value * m_max_next_feedrate) << "\n";
output << "; APA Prev PA: " << std::to_string(m_last_predicted_pa) << " New PA: " << std::to_string(predicted_pa) << "\n";
}
if (config_index_changed || std::fabs(predicted_pa - m_last_predicted_pa) > EPSILON) {
output << m_gcodegen.writer().set_pressure_advance(predicted_pa); // Use m_writer to set pressure advance
m_last_predicted_pa = predicted_pa; // Update the last predicted PA value
}
}
}else {
// Output the current line as this isn't a PA change tag
output << line << '\n';
}
}
return output.str();
}
std::string AdaptivePAProcessor::validate_adaptive_pa_model(const std::string& model_str)
{
if (model_str.empty())
return {}; // Empty model is valid
std::istringstream model_stream(model_str);
std::string line;
int line_number = 0;
while (std::getline(model_stream, line)) {
++line_number;
// Trim whitespace
const auto first = line.find_first_not_of(" \t\r\n");
if (first == std::string::npos)
continue; // Skip empty lines
const auto last = line.find_last_not_of(" \t\r\n");
line = line.substr(first, last - first + 1);
// Only numbers, commas and dots are allowed (no letters or other characters)
for (char c : line) {
if (!std::isdigit(static_cast<unsigned char>(c)) && c != ',' && c != '.') {
return Slic3r::format(_u8L("Line %1%: only numbers, commas and dots are allowed"), line_number);
}
}
// Count commas to validate format (should be exactly 2 for 3 values)
int comma_count = 0;
for (char c : line) {
if (c == ',') comma_count++;
}
if (comma_count != 2) {
return Slic3r::format(_u8L("Line %1%: must contain exactly 3 comma-separated values (PA, flow, acceleration)"), line_number);
}
// Parse and validate the values
try {
std::istringstream line_stream(line);
std::string value;
// Parse PA
if (!std::getline(line_stream, value, ','))
return Slic3r::format(_u8L("Line %1%: missing PA value"), line_number);
double pa = std::stod(value);
// Parse flow
if (!std::getline(line_stream, value, ','))
return Slic3r::format(_u8L("Line %1%: missing flow value"), line_number);
double flow = std::stod(value);
// Parse acceleration
if (!std::getline(line_stream, value, ','))
return Slic3r::format(_u8L("Line %1%: missing acceleration value"), line_number);
double accel = std::stod(value);
// Validate constraints
if (pa >= 2.0) {
return Slic3r::format(_u8L("Line %1%: PA value must be less than 2"), line_number);
}
if (flow <= pa) {
return Slic3r::format(_u8L("Line %1%: flow value must be greater than PA value"), line_number);
}
if (accel <= flow) {
return Slic3r::format(_u8L("Line %1%: acceleration value must be greater than flow value"), line_number);
}
} catch (const std::exception&) {
return Slic3r::format(_u8L("Line %1%: invalid numeric value"), line_number);
}
}
return {}; // All validations passed
}
} // namespace Slic3r