libvcad_compilers — utilities#

Shared helpers for attribute resolution, color mixing, voxel processing, and I/O.

namespace AttributeResolver#

Functions

void validate(const std::shared_ptr<Node> &root, const std::vector<std::string> &required_attributes)#

Validates that the root node has all required attributes.

Throws std::runtime_error with a descriptive message listing missing attributes.

namespace CompilerResources#

Functions

std::string config_path(const std::string &filename)#

Returns the absolute path to a bundled config file.

Parameters:

filename – The config file name, such as “j750.json”.

Returns:

The absolute path to the config file.

std::string profile_path(const std::string &relative_path)#

Returns the absolute path to a bundled profile file.

Parameters:

relative_path – Path below the bundled profiles directory.

Returns:

The absolute path to the profile file.

std::string resource_path(const std::string &relative_path)#

Returns the absolute path to a bundled resource file.

Parameters:

relative_path – Path relative to the compiler resource root.

Returns:

The absolute path to the resource file.

class ColorPipeline#
#include <color_pipeline.h>

Converts sRGBA colors into inkjet ink choices (cyan, magenta, yellow, black, white, clear).

Colors pass through the steps enabled in ColorPipelineOptions, are split into CMYKW fractions, and are then either sampled to one ink (process()) or returned as probabilities (ink_probabilities()). Each instance owns lcms2 state; use clone() to give each thread its own copy.

Public Functions

glm::vec4 apply_icc_profile(glm::vec3 rgb) const#

Transforms an RGB color (0 to 1) to CMYK using the ICC profile.

Throws std::runtime_error when the pipeline was built with the ICC step off.

Parameters:

rgb – RGB color in [0, 1], quantized to 8 bits.

Returns:

CMYK in [0, 1].

std::shared_ptr<ColorPipeline> clone() const#

Creates a new instance with its own lcms2 state for thread safety.

Returns:

A pipeline with the same ICC profile and options.

ColorPipeline(const std::string &icc_profile = "default", const ColorPipelineOptions &options = ColorPipelineOptions())#

Creates a pipeline.

When the ICC step is enabled, loads <icc_resource_path>/<icc_profile>.icc and throws std::runtime_error if the file is missing or lcms2 cannot use it.

Parameters:
  • icc_profile – ICC profile name (file stem) in the ICC resource directory.

  • options – The correction steps to apply.

std::array<float, 6> ink_probabilities(const glm::vec4 &rgba_color) const#

Converts an sRGBA color into CMYKW+Clear ink probabilities.

Applies the same correction and CMYKW logic used by process(), but returns continuous probabilities instead of stochastically selecting one ink channel. Components are ordered Cyan, Magenta, Yellow, Black, White, Clear.

Parameters:

rgba_color – sRGBA color with components in [0, 1].

Returns:

CMYKW fractions scaled by alpha, followed by clear = 1 - alpha.

ColorSampleResult process(const glm::vec4 &rgba_color) const#

Converts sRGBA to CMYKW and stochastically picks one ink.

Applies the configured ColorPipelineOptions before CMYKW conversion. When alpha is below 1, the color is replaced by the clear ink with probability 1 - alpha; palette_index still reports the CMYKW pick.

Parameters:

rgba_color – sRGBA color with components in [0, 1].

Returns:

The picked ink.

~ColorPipeline()#

Public Static Functions

static glm::vec3 cmyk_to_rgb(const glm::vec4 &cmyk)#

Converts CMYK to RGB with the naive (1 - c)(1 - k) formula.

Parameters:

cmyk – CMYK in [0, 1].

Returns:

RGB in [0, 1].

static glm::vec3 gamma_correct(glm::vec3 rgb, float gamma = 2.2f)#

Applies a gamma curve to each channel.

Parameters:
  • rgb – RGB color in [0, 1].

  • gamma – The gamma; each channel becomes channel^(1 / gamma).

Returns:

The corrected color.

static std::vector<std::string> get_icc_profiles()#

Lists the profiles in the ICC resource directory.

Returns:

File stems of every .icc or .ICC file there.

static glm::vec4 rgb_to_cmyk(const glm::vec3 &rgb)#

Converts RGB to CMYK with the naive formula (k = 1 - max(r, g, b)).

Parameters:

rgb – RGB in [0, 1].

Returns:

CMYK in [0, 1]; pure black maps to (0, 0, 0, 1).

static std::tuple<double, double, double, double, double> rgb_to_cmykw(glm::vec4 rgba)#

Splits an RGB color into normalized cyan, magenta, yellow, black and white fractions.

White fills whatever CMYK leaves below 1. Alpha is ignored.

Parameters:

rgba – RGBA color in [0, 1].

Returns:

(C, M, Y, K, W), summing to 1; white input gives (0, 0, 0, 0, 1).

static void set_icc_resource_path(const std::string &path)#

Sets the directory holding the .icc profiles (shared by all instances).

Parameters:

path – The ICC profile directory.

Private Functions

glm::vec3 color_managed_rgb(const glm::vec3 &rgb) const#
float compute_cmyk_primary_affinity(const glm::vec4 &cmyk) const#

Private Members

cmsHTRANSFORM m_color_transform#
cmsHPROFILE m_icc_profile#
std::string m_icc_profile_name#
ColorPipelineOptions m_options#
std::vector<glm::vec4> m_palette#
cmsHPROFILE m_srgb_profile#

Private Static Attributes

static std::string s_icc_resource_path#
struct ColorSampleResult#
#include <color_pipeline.h>

Result of process().

Public Members

glm::vec4 color#

RGBA of the ink written to the slice, in 0-255; the clear ink when the alpha draw picks it.

bool is_active#

Always true for process() results.

size_t palette_index#

Picked ink: 0 cyan, 1 magenta, 2 yellow, 3 black, 4 white.

struct ColorPipelineOptions#
#include <color_pipeline.h>

Enables or disables individual color pipeline correction steps.

Defaults match the full legacy color correction pipeline.

Public Functions

bool any_enabled() const#

Returns true when any step is enabled.

Returns:

True if at least one of the four flags is set.

Public Members

bool affinity_blend_enabled = true#

Blend back toward the first-gamma color near cyan, magenta or black.

bool first_gamma_enabled = true#

Apply gamma_correct() before the ICC step.

bool icc_profile_enabled = true#

Round-trip the color through the ICC profile’s CMYK space.

bool second_gamma_enabled = true#

Apply gamma_correct() after the ICC step.

class FullSpectrumColorMatcher#
#include <full_spectrum_color.h>

Builds Orca FullSpectrum-compatible filament mix recipes.

Public Functions

FullSpectrumRecipe best_mixed_recipe(FullSpectrumRgb8 target) const#

Returns the closest mixed-filament recipe by DeltaE00.

Parameters:

target – The color to match.

Returns:

A mixed recipe; invalid when there are fewer than two filaments.

FullSpectrumRecipe best_physical_recipe(FullSpectrumRgb8 target) const#

Returns the closest physical filament by DeltaE00.

Parameters:

target – The color to match.

Returns:

A physical recipe; invalid when there are no filaments.

FullSpectrumColorMatcher(const std::vector<std::string> &physical_colors, int min_component_percent, size_t max_recipe_components)#

Creates a matcher for a set of physical filaments.

Parameters:
  • physical_colors – Filament colors as “#RRGGBB”, in slot order (slot 1 first).

  • min_component_percent – Smallest allowed share of any mix component, clamped to [0, 50].

  • max_recipe_components – Largest number of filaments in a mix, clamped to [2, 5].

Public Static Functions

static FullSpectrumRgb8 blend_pair(FullSpectrumRgb8 left, FullSpectrumRgb8 right, double t)#

Blends two 8-bit sRGB colors through FilamentMixer.

Parameters:
  • left – The first color.

  • right – The second color.

  • t – Share of right, clamped to [0, 1].

Returns:

The pigment-style blend.

static double delta_e00(FullSpectrumLab lhs, FullSpectrumLab rhs)#

Returns the CIEDE2000 color difference of two Lab colors.

Parameters:
  • lhs – The first color.

  • rhs – The second color.

Returns:

DeltaE00.

static double delta_e00(FullSpectrumRgb8 lhs, FullSpectrumRgb8 rhs)#

Returns the CIEDE2000 color difference of two sRGB colors.

Parameters:
  • lhs – The first color.

  • rhs – The second color.

Returns:

DeltaE00.

static FullSpectrumRgb8 parse_hex_color(const std::string &value)#

Parses a “#RRGGBB” or “RRGGBB” color.

Throws std::runtime_error on any other format.

Parameters:

value – The hex string.

Returns:

The parsed color.

static std::string rgb_to_hex(FullSpectrumRgb8 color)#

Formats a color as upper-case “#RRGGBB”.

Parameters:

color – The color.

Returns:

The hex string.

static FullSpectrumLab rgb_to_lab(FullSpectrumRgb8 color)#

Converts sRGB to CIE Lab (D65 white point).

Parameters:

color – The sRGB color.

Returns:

The Lab color.

Private Functions

FullSpectrumRecipe build_multi_candidate(const std::vector<unsigned int> &ids, const std::vector<int> &weights, FullSpectrumRgb8 target) const#
FullSpectrumRecipe build_pair_candidate(unsigned int component_a, unsigned int component_b, int mix_b_percent, FullSpectrumRgb8 target) const#

Private Members

size_t m_max_recipe_components = 5#
int m_min_component_percent = 15#
std::vector<FullSpectrumRgb8> m_physical_colors#
struct FullSpectrumLab#
#include <full_spectrum_color.h>

CIE Lab color used for DeltaE00 matching.

Public Members

double a = 0.0#

Green-red axis a*.

double b = 0.0#

Blue-yellow axis b*.

double l = 0.0#

Lightness L*.

struct FullSpectrumRecipe#
#include <full_spectrum_color.h>

A physical or virtual FullSpectrum filament assignment.

Public Functions

int distribution_mode() const#

Returns the Orca distribution mode of the mix.

Returns:

2 for a pair, 0 for a 3+ component gradient mix.

std::string recipe_key() const#

Returns a key that identifies equal recipes.

Returns:

“p:\<id\>” for physical recipes, a key of the mix fields otherwise, or “” when invalid.

std::string serialize_mixed_row() const#

Serializes a mixed recipe as one Orca FullSpectrum mixed-filament row.

Returns:

The comma-separated row, or “” for physical recipes.

Public Members

unsigned int component_a = 1#

1-based slot of the first mix component (the heaviest in a 3+ component mix).

unsigned int component_b = 2#

1-based slot of the second mix component.

double delta_e = 0.0#

DeltaE00 between preview_color and the target.

std::string gradient_component_ids#

Slot digits of a 3+ component mix (e.g.

“132”); empty for pairs.

std::string gradient_component_weights#

Slash-separated percents matching gradient_component_ids (e.g.

“50/30/20”).

int mix_b_percent = 50#

Share of component_b in the a/b pair, 0-100.

bool physical = false#

True for a single physical filament, false for a mix.

unsigned int physical_id = 0#

1-based physical filament slot when physical is true.

FullSpectrumRgb8 preview_color#

Predicted printed color of the recipe.

uint64_t stable_id = 0#

Hash of recipe_key(), used as the Orca row ID.

bool valid = false#

False when no recipe was found.

struct FullSpectrumRgb8#
#include <full_spectrum_color.h>

8-bit sRGB color used by the FullSpectrum color matcher.

Public Members

uint8_t b = 0#

Blue, 0-255.

uint8_t g = 0#

Green, 0-255.

uint8_t r = 0#

Red, 0-255.

Typedefs

using PrintableColorMixBuilder = PrusaColorMixBuilder#
using PrintableColorMixColorModel = PrusaColorMixColorModel#
using PrintableColorMixComponent = PrusaColorMixComponent#
using PrintableColorMixMaterialMapping = PrusaColorMixMaterialMapping#
using PrintableColorMixMeshRegion = PrusaColorMixMeshRegion#
using PrintableColorMixPaletteEntry = PrusaColorMixPaletteEntry#
using PrintableColorMixPhysicalFilament = PrusaColorMixPhysicalFilament#
using PrintableColorMixRecipe = PrusaColorMixRecipe#
using PrintableColorMixRecipePreset = PrusaColorMixRecipePreset#
using PrintableColorMixSettings = PrusaColorMixSettings#
using PrintableVolumeFractionPaletteMode = PrusaVolumeFractionPaletteMode#

Enums

enum class PrusaColorMixColorModel#

Color prediction model used while selecting printable recipes.

Values:

enumerator Prusa#

Predict mixes with the PrusaSlicer ColorMix model.

enumerator FullSpectrum#

Predict mixes with the Orca FullSpectrum (FilamentMixer) model.

enum class PrusaColorMixRecipePreset#

Built-in Prusa ColorMix printable recipe vocabularies.

Values:

enumerator Conservative#

Single filaments and two-filament mixes at 25/50/75%.

enumerator Expanded#

Conservative plus three-filament mixes when max_recipe_components >= 3.

enum class PrusaVolumeFractionPaletteMode#

Strategy used to pick VOLUME_FRACTIONS palette recipes.

Uniform chops the fraction range into max_palette_size equal bins and places one recipe at each bin center, so every region spans the same fraction width regardless of how the samples are distributed. Adaptive runs a median cut over the sampled fraction histogram, which spends recipes where the samples actually are but only subdivides in halves, so bin widths are uneven unless max_palette_size is a power of two. Uniform binning is only defined for a single degree of freedom, so a two-material export honours it and any export with three or more materials falls back to Adaptive.

Values:

enumerator Uniform#

Equal-width bins; two-material exports only.

enumerator Adaptive#

Median cut of the sampled fraction histogram.

class PrusaColorMixBuilder#
#include <prusa_color_mix.h>

Builds PrusaSlicer ColorMix palettes and mesh regions from sampled attributes.

Public Types

using CancelCallback = std::function<void()>#

Called periodically; throws to cancel.

using ProgressCallback = std::function<void(double)>#

Receives progress in [0, 1].

using TreeSampleArray = std::vector<Node::TreeSample>#

Sampled grid, x fastest, then y, then z.

Public Functions

std::vector<PrusaColorMixPaletteEntry> build_color_palette() const#

Builds a palette from sampled COLOR_RGB attributes.

Returns:

Device-aware ColorMix palette entries selected from printable recipes.

std::string build_color_report_json(const std::vector<PrusaColorMixPaletteEntry> &palette) const#

Builds an embedded JSON quality report for a COLOR_RGB ColorMix palette.

Parameters:

palette – Selected printable recipe palette from build_color_palette().

Returns:

JSON report string containing recipe and DeltaE summary data.

std::vector<PrusaColorMixMeshRegion> build_regions(const std::vector<PrusaColorMixPaletteEntry> &palette, const std::string &name_prefix, const CancelCallback &cancel = nullptr, const ProgressCallback &progress = nullptr) const#

Generates overlapping mesh regions for the supplied ColorMix palette.

Parameters:
  • palette – Palette entries to convert into extruder-assigned settings regions.

  • name_prefix – Prefix used for generated region names.

  • cancel – Optional cancellation check invoked during mesh extraction.

  • progress – Optional progress callback receiving values in [0, 1].

Returns:

Mesh regions with PrusaSlicer extruder ids attached.

std::vector<PrusaColorMixPaletteEntry> build_volume_fraction_palette() const#

Builds a palette from sampled VOLUME_FRACTIONS attributes.

Returns:

Palette entries whose recipes follow mapped material fractions.

vtkSmartPointer<vtkImageData> compute_region_sdf_image(const std::vector<PrusaColorMixPaletteEntry> &palette, size_t region_index) const#

Computes an image-space signed distance field for one palette region.

Note

Recomputes the shared nearest-palette cache on every call. Prefer build_regions() when extracting more than one region, since it computes that cache once for the whole palette.

Parameters:
  • palette – Palette entries used for region classification.

  • region_index – Palette entry index to extract.

Returns:

VTK image containing the extracted region SDF.

PrusaColorMixBuilder(const TreeSampleArray &sample_array, size_t size_x, size_t size_y, size_t size_z, glm::vec3 min_coord, glm::vec3 voxel_size, const PrusaColorMixSettings &settings)#

Creates a builder over a sampled voxel grid.

Keeps a reference to sample_array, which must outlive the builder.

Parameters:
  • sample_array – Samples of the prepared tree, size_x * size_y * size_z entries.

  • size_x – Samples along x.

  • size_y – Samples along y.

  • size_z – Samples along z.

  • min_coord – World position of sample (0, 0, 0).

  • voxel_size – Sample spacing.

  • settings – Palette and recipe options.

void validate_settings() const#

Validates physical filament, palette, and recipe settings.

Public Static Functions

static std::vector<PrusaColorMixPhysicalFilament> default_cmykw_filaments()#

Returns the default CMYKW physical filament set for a five-tool Prusa profile.

Returns:

Physical filament slots 1-5 with cyan, magenta, yellow, black, and white colors.

Private Functions

NearestPaletteCache compute_nearest_palette_cache(const std::vector<PrusaColorMixPaletteEntry> &palette) const#

Finds each voxel’s nearest and second-nearest palette entry.

Parameters:

palette – Palette entries used for region classification.

Returns:

Per-voxel cache consumed by compute_region_sdf_image().

vtkSmartPointer<vtkImageData> compute_region_sdf_image(const std::vector<PrusaColorMixPaletteEntry> &palette, size_t region_index, const NearestPaletteCache &nearest_cache) const#

Computes an image-space signed distance field for one palette region using a precomputed nearest-palette cache.

Private Members

glm::vec3 m_min_coord = {0.0f}#
const TreeSampleArray &m_sample_array#
PrusaColorMixSettings m_settings#
size_t m_size_x = 0#
size_t m_size_y = 0#
size_t m_size_z = 0#
glm::vec3 m_voxel_size = {1.0f}#
struct NearestPaletteCache#

Per-voxel nearest and second-nearest palette distances.

Shared across every region in a palette so build_regions() finds each voxel’s nearest/second-nearest palette entry once (O(N * palette)) instead of once per region (O(N * palette^2)).

Public Members

std::vector<double> nearest_distance#
std::vector<size_t> nearest_index#
std::vector<double> second_distance#
struct PrusaColorMixComponent#
#include <prusa_color_mix.h>

One physical component in a PrusaSlicer ColorMix recipe.

Public Members

unsigned int extruder = 0#

1-based physical extruder slot.

double ratio = 0.0#

Share of this extruder in the mix, 0-1.

struct PrusaColorMixMaterialMapping#
#include <prusa_color_mix.h>

Maps a VCAD volume-fraction material to a physical filament slot.

Public Members

uint8_t material_id = 0#

Material ID, resolved from material_name by the compiler.

std::string material_name#

MaterialDefs name of the design material.

unsigned int slot = 0#

1-based physical extruder slot that prints the material.

struct PrusaColorMixMeshRegion#
#include <prusa_color_mix.h>

One generated ColorMix mesh region.

Public Members

int extruder_id = 0#

Extruder ID from the palette entry.

std::shared_ptr<SurfaceMesh> mesh#

Region surface mesh.

std::string name#

Region name, name_prefix + “_” + palette index.

struct PrusaColorMixPaletteEntry#
#include <prusa_color_mix.h>

One quantized target color or material recipe and its slicer extruder id.

Public Members

int extruder_id = 0#

Physical slot, or a virtual ID above total_physical_extruders for mixes.

std::vector<double> fraction_weights#

Per-material weights in volume_fraction_materials order; empty for COLOR_RGB.

FullSpectrumRgb8 preview_color#

Predicted printed color of the recipe.

PrusaColorMixRecipe recipe#

The printable recipe.

size_t sample_count = 0#

Number of samples assigned to the entry.

FullSpectrumRgb8 target_color#

Mean sampled color of the entry (the recipe preview for volume fractions).

struct PrusaColorMixPhysicalFilament#
#include <prusa_color_mix.h>

Physical filament slot description for PrusaSlicer ColorMix export.

Public Members

std::string color_hex#

Filament color as “#RRGGBB”.

double nozzle_diameter_mm = 0.4#

Nozzle diameter in mm; carried through but not read by PrusaColorMixBuilder.

unsigned int slot = 0#

1-based physical extruder slot.

struct PrusaColorMixRecipe#
#include <prusa_color_mix.h>

Physical or virtual PrusaSlicer ColorMix assignment.

Public Functions

std::string recipe_key() const#

Returns a stable key for deduplicating physical and virtual recipes.

Returns:

Physical extruder id or sorted component ratios encoded as text.

Public Members

std::vector<PrusaColorMixComponent> components#

Mix components; ratios sum to 1.

double delta_e = 0.0#

DeltaE00 between preview_color and the target.

bool physical = false#

True for a single physical filament, false for a mix.

unsigned int physical_id = 0#

1-based physical slot when physical is true.

FullSpectrumRgb8 preview_color#

Predicted printed color of the recipe.

bool valid = false#

False when no recipe was found.

struct PrusaColorMixSettings#
#include <prusa_color_mix.h>

Options for COLOR_RGB or VOLUME_FRACTIONS to PrusaSlicer ColorMix export.

Public Members

PrusaColorMixColorModel color_model = PrusaColorMixColorModel::Prusa#

Mix prediction model used to score recipes.

double direct_physical_delta_e = 1.0#

Legacy setting kept for compatibility; PrusaColorMixBuilder does not read it.

size_t max_palette_size = 32#

Largest number of palette entries.

size_t max_recipe_components = 3#

Largest number of physical filaments in one recipe.

int min_component_percent = 15#

Smallest allowed share of any mix component, in percent.

std::vector<PrusaColorMixPhysicalFilament> physical_filaments#

Physical filaments; slots must lie in [1, total_physical_extruders].

PrusaColorMixRecipePreset recipe_preset = PrusaColorMixRecipePreset::Expanded#

Recipe vocabulary for COLOR_RGB palettes.

double region_overlap_mm = 0.2#

Distance in mm by which neighbouring regions overlap; must be non-negative.

size_t total_physical_extruders = 5#

Physical extruder count, 1-9. Virtual (mixed) extruder IDs start after it.

std::vector<PrusaColorMixMaterialMapping> volume_fraction_materials#

Design material to slot mapping; required for VOLUME_FRACTIONS palettes.

PrusaVolumeFractionPaletteMode volume_fraction_palette_mode = PrusaVolumeFractionPaletteMode::Uniform#

How VOLUME_FRACTIONS palette recipes are chosen.

namespace ErrorDiffusion3D#

Utilities for quantizing arbitrary multi-channel voxel fields.

Functions

void dither(std::vector<float> &probabilities, const std::vector<uint8_t> &occupied, const std::vector<uint8_t> &eligibility, std::vector<uint8_t> &assignments, size_t x_dim, size_t y_dim, size_t z_dim, size_t channel_count, const std::function<void()> &cancellation_check = nullptr, const std::function<void(double)> &progress_callback = nullptr)#

Quantizes a dense multi-channel voxel field with 3D error diffusion.

Voxels are traversed in ascending Z with a serpentine X scan. Quantization error is distributed to unprocessed occupied voxels in the current and next Z planes. When eligibility is supplied, each channel is diffused only to voxels that allow that channel.

Parameters:
  • probabilities – Flat voxel-major probability tensor. Modified in place.

  • occupied – Flat voxel occupancy mask.

  • eligibility – Optional flat voxel-major channel mask. An empty vector means every channel is eligible at every occupied voxel.

  • assignments – Receives one selected channel per voxel.

  • x_dim – Number of voxels along X.

  • y_dim – Number of voxels along Y.

  • z_dim – Number of voxels along Z.

  • channel_count – Number of channels per voxel. Must be in [1, 256].

  • cancellation_check – Optional callback invoked before each Z plane.

  • progress_callback – Optional callback receiving progress in [0, 1].

namespace ImageOutput#

Functions

std::string setup_output_directory(const std::string &output_directory, const std::string &file_prefix)#

Creates the output directory if it doesn’t exist and returns the full filename root path (directory + file_prefix).

size_t trim_empty_layers(const std::vector<size_t> &active_voxel_counts, const std::string &filename_root, const std::string &extension = ".png")#

Removes empty layers from the beginning and end of a numbered PNG stack.

Renumbers remaining files to start at 0.

Returns:

the number of remaining layers.

bool write_binary_bmp_1bit(const std::string &path, long width, long height, const std::vector<unsigned char> &binary_data, std::int32_t x_pixels_per_meter = 11811, std::int32_t y_pixels_per_meter = 11811)#

Writes a 1-bit monochrome BMP file with a two-entry black/white palette.

Non-zero values in binary_data are written as black pixels (material present). Zero values are written as white pixels. The file uses a BITMAPINFOHEADER and a bottom-up pixel layout.

Returns:

true on success, false on failure.

bool write_grayscale_bmp(const std::string &path, long width, long height, const std::vector<unsigned char> &grayscale_data)#

Writes an 8-bit grayscale BMP file with an identity grayscale palette.

Returns:

true on success, false on failure.

bool write_grayscale_png(const std::string &path, long width, long height, const std::vector<unsigned char> &grayscale_data)#

Writes an 8-bit grayscale PNG file.

Returns:

true on success, false on failure.

bool write_rgba_png(const std::string &path, long width, long height, const std::vector<unsigned char> &rgba_data)#

Writes an RGBA image as a PNG file.

Returns:

true on success, false on failure.

class ParallelVoxelLoop#
#include <parallel_voxel_loop.h>

Runs a per-layer callback over z layers in parallel with TBB.

Each worker thread gets its own clone of the root, made the first time that thread runs a layer, so callbacks can sample the tree without sharing node state. The root must be prepared before run() is called.

Public Types

using LayerCallback = std::function<void(const std::shared_ptr<Node> &thread_local_root, long z_index)>#

Callback run once per z layer with the calling thread’s clone of the root.

Public Functions

ParallelVoxelLoop(const std::shared_ptr<Node> &root)#

Creates a loop over a root node.

Parameters:

root – The tree to clone for each worker thread.

void run(long z_dim, const LayerCallback &layer_fn, const std::atomic<bool> &cancelled, const std::function<void(double)> &progress_callback = nullptr, ThreadUsageTracker *thread_usage_tracker = nullptr)#

Runs parallel_for over [0, z_dim).

For each z, calls layer_fn with a thread-local clone of root. Checks cancellation between layers and reports progress after each layer completes.

Progress is the number of finished layers divided by z_dim, so the last report of an uncancelled run is exactly 1.0. Reports are serialized but may arrive from any worker thread. Once cancelled is set, layers not yet started are skipped; run() returns without throwing.

Parameters:
  • z_dim – Number of layers.

  • layer_fn – Called once per layer with the thread’s root clone and the layer index.

  • cancelled – Flag checked before each layer.

  • progress_callback – Optional; receives progress in (0, 1] after each layer.

  • thread_usage_tracker – Optional; records each worker thread that runs a layer.

Private Members

tbb::task_group_context m_context#
std::shared_ptr<Node> m_root#
tbb::enumerable_thread_specific<std::shared_ptr<Node>> m_thread_roots#
namespace RequiredAttributeCheck#

Utilities for enforcing required attribute presence at sampled points during compilation.

All checks throw std::runtime_error with the first failing world-space coordinate when the attribute is absent.

Functions

void require(const std::string &compiler_name, const std::string &attribute_name, const glm::vec3 &world_pos, const std::optional<AttributeSamples> &samples)#

Verifies that a required attribute is present in the given samples.

Fast path: returns immediately when the attribute key exists. Throws std::runtime_error with compiler name, attribute name, and world-space XYZ when the attribute is missing.

Parameters:
  • compiler_name – Human-readable compiler name for the error message.

  • attribute_name – The attribute key that must be present.

  • world_pos – The world-space position of the sample point.

  • samples – The attribute samples at that point (may be nullopt).

void require_fuzzy(const std::shared_ptr<Node> &root, const glm::vec3 &voxel_size, const std::string &compiler_name, const std::string &attribute_name, const glm::vec3 &world_pos, const std::optional<AttributeSamples> &samples)#

Same as require() but attempts a fuzzy 3x3x3 neighbor probe before throwing.

Use this for compilers whose sampling grid may land just outside the implicit surface.

Parameters:
  • root – The prepared node tree (used for neighbor sampling).

  • voxel_size – The voxel size (determines neighbor offsets).

  • compiler_name – Human-readable compiler name for the error message.

  • attribute_name – The attribute key that must be present.

  • world_pos – The world-space position of the sample point.

  • samples – The attribute samples at that point (may be nullopt).

namespace StochasticSampler#

Functions

MaterialSampleResult sample(const AttributeSamples &samples, double signed_distance, const std::shared_ptr<MaterialDefs> &material_defs, double liquid_keep_out_distance = 0.0, const std::vector<uint8_t> &keep_out_material_ids = {})#

Extracts VOLUME_FRACTIONS from samples and performs weighted stochastic material selection.

Applies liquid keep-out if configured.

Parameters:
  • samples – The attribute samples at the voxel location.

  • signed_distance – The signed distance value at the voxel location.

  • material_defs – Material definitions for color lookup.

  • liquid_keep_out_distance – Distance from surface within which the keep-out materials are removed.

  • keep_out_material_ids – The material IDs removed within the keep-out distance.

Returns:

MaterialSampleResult with the selected material.

struct MaterialSampleResult#
#include <stochastic_sampler.h>

Result of one stochastic material pick.

Public Members

glm::vec4 color#

Color of the picked material from MaterialDefs; (0, 0, 0, 0) when inactive.

bool is_active#

False when there are no volume fractions to pick from.

uint8_t material_id#

Picked material ID; 0 when inactive.

class VoxelGrid#
#include <voxel_grid.h>

Regular voxel grid over an axis-aligned bounding box.

Each dimension holds ceil(box extent / voxel size) voxels. Voxel (0, 0, 0) sits at bbox_min, and linear indices run x fastest, then y, then z.

Public Functions

glm::vec3 bbox_max() const#

Returns the maximum box corner passed to the constructor.

Returns:

The maximum corner.

glm::vec3 bbox_min() const#

Returns the minimum box corner passed to the constructor.

Returns:

The minimum corner.

std::tuple<size_t, size_t, size_t> index_to_xyz(size_t index) const#

Converts a linear index back to voxel indices.

Parameters:

index – Linear index, as returned by xyz_to_index().

Returns:

The (x, y, z) voxel indices.

glm::vec3 space_size() const#

Returns the box extent.

Returns:

The absolute size of the box along each axis.

glm::vec3 voxel_size() const#

Returns the voxel size passed to the constructor.

Returns:

Voxel edge lengths along x, y and z.

VoxelGrid(glm::vec3 bbox_min, glm::vec3 bbox_max, glm::vec3 voxel_size)#

Builds the grid for a bounding box and voxel size.

Parameters:
  • bbox_min – Minimum corner of the box.

  • bbox_max – Maximum corner of the box.

  • voxel_size – Voxel edge lengths along x, y and z.

glm::vec3 world_position(long x, long y, long z) const#

Returns the world position of a voxel.

Parameters:
  • x – Voxel index along x.

  • y – Voxel index along y.

  • z – Voxel index along z.

Returns:

bbox_min + (x, y, z) * voxel_size (the voxel’s minimum corner, not its centre).

long x_dim() const#

Returns the number of voxels along x.

Returns:

ceil(box width / voxel_size.x).

size_t xyz_to_index(size_t x, size_t y, size_t z) const#

Converts voxel indices to a linear index.

Parameters:
  • x – Voxel index along x.

  • y – Voxel index along y.

  • z – Voxel index along z.

Returns:

x + y * x_dim + z * x_dim * y_dim.

long y_dim() const#

Returns the number of voxels along y.

Returns:

ceil(box depth / voxel_size.y).

long z_dim() const#

Returns the number of voxels along z.

Returns:

ceil(box height / voxel_size.z).

Private Members

glm::vec3 m_max#
glm::vec3 m_min#
glm::vec3 m_space_size#
glm::vec3 m_voxel_size#
long m_x_dim#
long m_y_dim#
long m_z_dim#

Enums

enum class SimulationCellType#

Supported cell topologies for simulation export.

Values:

enumerator tet4#

Linear tetrahedron, 4 nodes per cell.

enumerator hex8#

Linear hexahedron, 8 nodes per cell.

struct SimulationModel#
#include <simulation_model.h>

Backend-agnostic prepared simulation model.

Writers consume this normalized structure so geometry discretization and attribute sampling remain shared across export backends.

Public Members

std::vector<glm::vec3> cell_centroids#

Element centroids, one per element, where attributes are sampled.

SimulationCellType cell_type = SimulationCellType::hex8#

Cell topology of every element.

std::vector<size_t> connectivity#

Flat element connectivity: nodes_per_cell zero-based node indices per element.

std::vector<uint8_t> material_ids#

One material ID per element, drawn from the centroid’s volume fractions with a seeded weighted pick (0 for void or unsampled).

Empty when the design has no volume fractions.

std::map<uint8_t, std::string> material_names#

Name of each material with a positive fraction somewhere, from MaterialDefs or material_\<id\>.

std::vector<glm::vec3> nodes#

Node coordinates.

size_t nodes_per_cell = 8#

Nodes per element (4 for tet4, 8 for hex8).

std::unordered_map<std::string, std::vector<double>> scalar_fields#

Per-element values of each direct scalar attribute, keyed by attribute name.

std::map<uint8_t, std::vector<double>> volume_fraction_fields#

Per-element volume fraction of each material, keyed by material ID.

struct SimulationLsDynaSettings#
#include <simulation_lsdyna_writer.h>

Options for the LS-DYNA keyword (.k) export of the SimulationCompiler.

The deck is geometry-only: nodes, solid elements, one part/section/placeholder material per material, and part sets. It has no loads, boundary conditions, contact, or control cards. Units are mm, tonne, s, N, MPa. Checked with LS-DYNA R16.1 (SMP, double precision): exported decks read and initialise without errors and run a short explicit test (see the simulation compiler guide).

Public Members

double default_density = 1.0e-9#

Placeholder density (tonne/mm^3) for materials without a “density” entry in the material table.

double default_modulus = 100.0#

Placeholder Young’s modulus (MPa) for materials without a “modulus” entry in the material table.

double default_poissons_ratio = 0.3#

Placeholder Poisson’s ratio for materials without a “poissons_ratio” entry in the material table.

uint64_t element_id_offset = 0#

Added to every element ID (element index + 1 + offset).

int hex_element_formulation = 1#

*SECTION_SOLID ELFORM used for hexahedral meshes (default 1, constant-stress solid; 2 is fully integrated).

bool include_void_elements = false#

Write elements whose sampled material is void (material ID 0).

Off by default: void has no stiffness, so those elements are dropped together with nodes that only they used.

bool long_format = false#

Force long format (*KEYWORD LONG=Y, 20-column fields).

Long format is also chosen automatically when an ID exceeds 99,999,999.

int mixed_material_tet_element_formulation = 10#

*SECTION_SOLID ELFORM used instead of 13 for tetrahedral decks whose parts have different bulk moduli and share nodes (default 10, 1-point tetrahedron).

ELFORM 13 averages nodal pressures across parts, which LS-DYNA forbids for different bulk moduli (*SECTION_SOLID remark 12, warning 30490). Set it to 13 to keep ELFORM 13 anyway.

uint64_t node_id_offset = 0#

Added to every node ID (node index + 1 + offset). Useful when the deck is included into a larger model.

uint64_t part_id_offset = 0#

Added to every part, section, material and part-set ID.

int tet_element_formulation = 13#

*SECTION_SOLID ELFORM used for tetrahedral meshes (default 13, 1-point nodal-pressure tetrahedron).

When this is 13 and parts with different bulk moduli share nodes, the deck uses mixed_material_tet_element_formulation instead (LS-DYNA does not allow ELFORM 13 there).

std::string title = "OpenVCAD simulation export"#

*TITLE text (at most 80 characters are written).

namespace SimulationLsDynaWriter#

Writes a SimulationModel as an LS-DYNA keyword deck (.k).

Functions

void write(const std::string &path, const SimulationModel &model, const SimulationLsDynaSettings &settings = SimulationLsDynaSettings(), const std::shared_ptr<MaterialDefs> &material_defs = nullptr)#

Writes the deck.

One *PART, *SECTION_SOLID, *MAT_ELASTIC and *SET_PART_LIST is written per material present in model.material_ids (or a single part when the model has no material partition), plus one part set containing every part. Node IDs are model node index + 1 and element IDs are model element index + 1 (both plus the configured offsets), so they match the GENERIC model and the Abaqus export. Only nodes referenced by written elements are written.

Parameters:
  • path – The output .k path. Parent directories are created.

  • model – The prepared simulation model (tet4 or hex8).

  • settings – LS-DYNA options.

  • material_defs – Optional material table. A material’s JSON entry may hold “density” (tonne/mm^3), “modulus” (MPa) and “poissons_ratio”; missing values use the settings’ placeholders.

Throws:

std::runtime_error – for an invalid model, invalid settings, IDs above 2,147,483,647, or a model that has no elements left after void elements are omitted.

namespace SimulationAbaqusWriter#

Functions

void write(const std::string &path, const SimulationModel &model)#
namespace FenicsxXdmfWriter#

Functions

void write(const std::string &xdmf_path, const std::string &h5_path, const SimulationModel &model)#
class BambuOrcaThreeMFWriter#
#include <three_mf_writer.h>

Writes a Bambu/Orca component-based 3MF project file.

Public Functions

explicit BambuOrcaThreeMFWriter(const std::string &output_file_path)#

Creates a writer for one output file.

Parameters:

output_file_path – Path of the .3mf file to write.

void set_components(const std::string &object_name, const std::vector<Component> &components, size_t physical_filament_count = 1)#

Sets the object and its parts (required).

Parameters:
  • object_name – Name of the single object that holds the parts.

  • components – One part per mesh region.

  • physical_filament_count – Number of physical filaments; values below 1 are raised to 1.

void set_openvcad_full_spectrum_report(const std::string &json)#

Sets the JSON stored as Metadata/OpenVCAD_full_spectrum_report.json.

Skipped when empty.

Parameters:

json – The FullSpectrum report JSON.

void set_project_config(const std::string &json)#

Sets the JSON stored as Metadata/project_settings.config (required).

Parameters:

json – The project settings JSON.

void write() const#

Writes the 3MF file.

Throws std::runtime_error if there are no components, a component mesh is empty, or the project config is missing.

Private Members

std::vector<Component> m_components#
std::string m_object_name#
std::string m_openvcad_full_spectrum_report#
std::string m_output_file_path#
size_t m_physical_filament_count = 1#
std::string m_project_config#
struct Component#
#include <three_mf_writer.h>

One mesh resource in a Bambu/Orca component project.

Public Members

int extruder_id = 0#

Extruder (filament) ID assigned to the part.

std::shared_ptr<SurfaceMesh> mesh#

Part mesh; must be non-empty.

std::string name#

Part name shown in the slicer.

class PrusaSlicerThreeMFWriter#
#include <three_mf_writer.h>

Writes a PrusaSlicer-compatible 3MF project file.

Set the mesh and model config (both required) and any optional parts, then call write().

Public Functions

explicit PrusaSlicerThreeMFWriter(const std::string &output_file_path)#

Creates a writer for one output file.

Parameters:

output_file_path – Path of the .3mf file to write.

void set_full_spectrum_config(const std::string &json)#

Sets the JSON stored as Metadata/Prusa_Slicer_full_spectrum.json.

Skipped when empty.

Parameters:

json – The ColorMix config JSON.

void set_mesh(const std::shared_ptr<SurfaceMesh> &mesh)#

Sets the mesh written as the 3MF model (required).

Parameters:

mesh – The surface mesh.

void set_model_config(const std::string &xml)#

Sets the XML stored as Metadata/Slic3r_PE_model.config (required).

Parameters:

xml – The model config XML.

void set_openvcad_colormix_report(const std::string &json)#

Sets the JSON stored as Metadata/OpenVCAD_prusa_colormix_report.json.

Skipped when empty.

Parameters:

json – The ColorMix report JSON.

void set_project_config(const std::string &config)#

Sets the text stored as Metadata/Slic3r_PE.config.

Skipped when empty.

Parameters:

config – The project config text.

void write() const#

Writes the 3MF file.

Throws std::runtime_error if the mesh or model config is missing.

Private Members

std::string m_full_spectrum_config#
std::shared_ptr<SurfaceMesh> m_mesh#
std::string m_model_config#
std::string m_openvcad_colormix_report#
std::string m_output_file_path#
std::string m_project_config#
class OrcaProfileResolver#
#include <orca_profile_resolver.h>

Resolves Orca JSON profile inheritance into a flat project config.

Orca profile presets are small JSON overlays with an optional inherits key. This utility finds profiles by file path or profile name, resolves parent profiles first, then overlays child settings so the slicer project can embed a self-contained config.

Public Functions

explicit OrcaProfileResolver(const std::vector<std::string> &search_roots)#

Constructor.

Parameters:

search_roots – Directories searched recursively for JSON profiles.

nlohmann::json resolve_profile(const std::string &path_or_name, const std::string &expected_type = std::string()) const#

Resolves a profile by explicit file path or Orca profile name.

Parameters:
  • path_or_name – Existing file path, filename stem, filename, or JSON name field.

  • expected_type – Optional type value that the leaf profile must have.

Returns:

Flattened profile JSON.

Public Static Functions

static std::string default_pla_filament_profile_path()#

Default bundled PLA filament profile path.

Returns:

Path of the bundled fdm_filament_pla filament profile.

static std::string default_prusa_xl_5t_machine_profile_path()#

Default bundled Prusa XL 5T machine profile path.

Returns:

Path of the bundled “Prusa XL 5T 0.4 nozzle” machine profile.

static std::string default_prusa_xl_5t_process_profile_path()#

Default bundled Prusa XL 5T process profile path.

Returns:

Path of the bundled “0.20mm Speed @Prusa XL 5T 0.4” process profile.

static std::vector<std::string> default_prusa_xl_5t_search_paths()#

Default bundled profile search roots for Prusa XL 5T export.

Returns:

The bundled orca/prusa_xl_5t/machine, orca/prusa_xl_5t/process and orca/filaments directories.

Private Functions

std::string find_profile_path(const std::string &path_or_name) const#
nlohmann::json resolve_profile_impl(const std::string &path_or_name, const std::string &expected_type, std::vector<std::string> &resolution_stack) const#

Private Members

std::vector<std::string> m_search_roots#

Private Static Functions

static void merge_profile(nlohmann::json &base, const nlohmann::json &overlay)#