Utilities#

class MaterialDefs#
#include <material_defs.h>

Class representing material definitions that translates between material names, colors, and ids.

Public Functions

glm::vec4 color(const std::string &name) const#

Returns the color of the material given the name, as RGBA in the range [0, 255].

Parameters:

name – The name of the material

Throws:

MaterialExceptions::MaterialNotFound – if the name is not in the configuration

Returns:

The RGBA color

glm::vec4 color(uint8_t material) const#

Returns the color of the material given the id, as RGBA in the range [0, 255].

Parameters:

material – The id of the material

Throws:

MaterialExceptions::MaterialNotFound – if the id is not in the configuration

Returns:

The RGBA color

bool contains(const std::string &name) const#

Returns true if the material exists.

Parameters:

name – The name of the material

Returns:

True if a material with that name is configured

std::optional<double> density(const std::string &name) const#

Returns the density of a material in g/cm^3, when the configuration gives one.

Parameters:

name – The name of the material

Throws:

MaterialExceptions::MaterialNotFound – if the name is not in the configuration

Returns:

The density, or std::nullopt when the configuration gives none for this material

std::optional<double> density(uint8_t material) const#

Returns the density of a material in g/cm^3, when the configuration gives one.

A material entry may carry an optional “density” key, in g/cm^3 (the unit data sheets use). The void material (id 0) is empty space and always has density 0. Mass analyses (mass_properties()) read these values to turn volume fractions into a density.

Parameters:

material – The id of the material

Throws:

MaterialExceptions::MaterialNotFound – if the id is not in the configuration

Returns:

The density, or std::nullopt when the configuration gives none for this material

nlohmann::json get_raw_settings(const std::string &name) const#

Returns the full configuration entry of a material, including any extra keys.

Parameters:

name – The name of the material

Throws:

MaterialExceptions::MaterialNotFound – if the name is not in the configuration

Returns:

A copy of the JSON entry

uint8_t id(const std::string &name) const#

Returns the id of the material given the name.

Parameters:

name – The name of the material

Throws:

MaterialExceptions::MaterialNotFound – if the name is not in the configuration

Returns:

The id

uint8_t id(glm::vec4 color) const#

Returns the id of the material given the color.

Parameters:

color – The color of the material, RGBA in [0, 255]; must match exactly

Throws:

MaterialExceptions::MaterialNotFound – if no material has the color

Returns:

The lowest id with that color

MaterialDefs()#

Default constructor. Initializes empty definition with only void space.

MaterialDefs(const std::string &path)#

Constructor that takes a string.

Parameters:

path – The path to the material configuration file

std::string name(uint8_t material) const#

Returns the name of the material given the id.

Parameters:

material – The id of the material

Throws:

MaterialExceptions::MaterialNotFound – if the id is not in the configuration

Returns:

The name; “void” for id 0

size_t num_materials() const#

Returns the number of materials.

Returns:

The number of materials

std::vector<glm::vec4> palette() const#

Returns the material colors, indexed by material id.

Returns:

A list of 4-component colors (RGBA) in the range [0, 255]

std::vector<glm::vec4> prescaled_color_list() const#

Returns the material colors divided by 255, indexed by material id.

Returns:

A list of 4-component colors (RGBA) in the floating point range [0, 1]

void set_density(const std::string &name, double density)#

Sets or replaces the density of a material, in g/cm^3.

Parameters:
  • name – The name of the material

  • density – A finite, non-negative density in g/cm^3

void set_density(uint8_t material, double density)#

Sets or replaces the density of a material, in g/cm^3.

Parameters:
  • material – The id of the material (not 0: void is always empty)

  • density – A finite, non-negative density in g/cm^3

Throws:
void update_color(uint8_t id, glm::vec4 color)#

Updates the color of the material given the id.

Parameters:
  • id – The id of the material

  • color – The new color of the material (RGBA, each component in the range [0, 255])

Private Functions

const nlohmann::json *entry_for(uint8_t material) const#

Returns the configuration entry that carries an id, or nullptr.

Private Members

std::vector<glm::vec4> m_id_to_color_lookup#
nlohmann::json m_materials#
namespace MaterialExceptions#
struct MaterialNotFound : public std::exception#
#include <material_defs.h>

Thrown when a material id, name or color is not in the configuration.

Public Functions

inline MaterialNotFound(const std::string &message)#

Constructor.

Parameters:

message – The error message.

inline const char *what() const noexcept override#

Returns the error message.

Returns:

The message.

Public Members

std::string m_message#

The error message.

class ColorMap#
#include <color_map.h>

A piecewise-linear color map over [0, 1].

Colors are RGB in [0, 1], placed at stop values. get_color() clamps its input to [0, 1] and interpolates linearly between the two nearest stops.

Public Functions

void add_color(double value, const glm::vec3 &color)#

Add a color stop, replacing any stop already at value.

Parameters:
  • value – Stop position. get_color() only reads values in [0, 1].

  • color – RGB color with channels in [0, 1].

ColorMap() = default#

Create an empty map. get_color() returns white until a stop is added.

glm::vec3 get_color(double value) const#

Look up the color at a value.

The value is clamped to [0, 1]. Below the first stop or above the last, the end color is returned; between stops the color is interpolated linearly.

Parameters:

value – Value to look up.

Returns:

RGB color with channels in [0, 1], or white when the map has no stops.

Public Static Functions

static ColorMap create_grayscale()#

Black at 0 to white at 1.

Returns:

The map.

static ColorMap create_inferno()#

A five-stop approximation of matplotlib’s inferno.

Returns:

The map.

static ColorMap create_plasma()#

A five-stop approximation of matplotlib’s plasma.

Returns:

The map.

static ColorMap create_viridis()#

A five-stop approximation of matplotlib’s viridis.

Returns:

The map.

Private Members

std::map<double, glm::vec3> m_color_points#
class TreeSampler#
#include <tree_sampler.h>

Samples a node tree onto a regular voxel grid or at arbitrary points.

The grid covers the root’s bounding box grown by two voxels on every side. Voxel (x, y, z) sits at bbox_min + (x, y, z) * voxel_size, and every flat grid array uses index x + y * nx + z * nx * ny (x fastest), with (nx, ny, nz) from sample_dimensions(). Grid samples are computed in parallel on per-thread clones of the root and cached, so repeated calls are cheap. The root, voxel size and material definitions are fixed at construction; to change any of them, build a new TreeSampler.

Public Types

typedef std::function<void(int)> ProgressCallback#

Progress callback receiving integer percentages from 0 to 100.

Public Functions

std::vector<float> as_float_array(const std::string &attribute, ProgressCallback progress = nullptr)#

Sample a scalar attribute at every voxel.

Uses the cached voxel grid, sampling it on the first call. Voxels outside the object, missing the attribute, or holding a non-scalar value are 0.

Parameters:
  • attribute – Attribute name to sample.

  • progress – Optional progress callback receiving integer values from 0 to 100.

Returns:

A flat array of nx * ny * nz values.

std::vector<float> as_material_fraction_array(const std::string &attribute, ProgressCallback progress = nullptr)#

Sample a volume-fraction attribute into a per-material fraction grid.

Produces one fraction per material per voxel, laid out as a flat array of size (m_size_x * m_size_y * m_size_z) * num_materials in voxel-major order: voxel i occupies indices [i * num_materials, (i + 1) * num_materials). Voxels that are outside the object, missing the attribute, or whose attribute is not a volume-fraction map contribute zeros. Requires material definitions; throws if none were supplied. Backs the whole-object statistics view for VFM attributes.

Parameters:
  • attribute – Volume-fraction attribute name to sample.

  • progress – Optional progress callback receiving integer values from 0 to 100.

Returns:

A flat vector of per-material fractions; reshape to (num_voxels, num_materials).

std::vector<float> as_narrow_band_signed_distance_array(const ProgressCallback &progress = nullptr, float band_voxels = 3.0f, int coarse_factor = 4)#

The signed distance field on the same grid as as_signed_distance_array(), evaluated exactly only near the surface.

The grid is split into coarse cells of coarse_factor^3 voxels. Each cell is probed at its corners and center. A cell is filled instead of evaluated only when the root’s distance bound (Node::distance_accuracy() and lipschitz_bound(), read through DistanceCertifier) proves that every voxel in it lies on the probes’ side of the surface with a value beyond band_voxels voxels: with L the Lipschitz bound and T the root’s sample bandwidth, every probe’s value clamped to T (T for no value) must exceed the band by L times the distance from the cell’s voxels to the nearest probe. A filled cell holds the smallest probed distance (at most T) with the probes’ sign, or the “no value” marker when no probe had a value. Every other cell is evaluated voxel by voxel, exactly as as_signed_distance_array() does.

When the root is approximate, its bound is not finite, culling is switched off (OPENVCAD_DISABLE_CULLING=1) or the bandwidth is too small to prove any cell, the full field is sampled instead (and cached as as_signed_distance_array()). Finally, any filled cell that the contour or its normals would read (both ends of every sign-changing edge and their six neighbours) is evaluated, repeatedly; this only happens for bands narrower than 2 L voxels.

Voxels within the band therefore hold exactly the full field’s values, every voxel has the full field’s sign, and contouring the result at 0 gives the same surface and gradient normals, in a fraction of the time for designs with empty space. Use the full field for anything that reads values deep inside or far outside (volume rendering, offsets).

The result is cached; when the full field has already been sampled it is returned instead. culling_stats() describes the pass (sampled = voxels evaluated).

Parameters:
  • progress – Optional progress callback receiving integer values from 0 to 100.

  • band_voxels – Half-width, in voxels, of the band kept exact. Defaults to 3.

  • coarse_factor – Coarse cell size in voxels (>= 2). Defaults to 4.

Returns:

A flat array in the layout of as_signed_distance_array().

openvdb::GridBase::Ptr as_openvdb_attribute_grid(const std::string &attribute, const ProgressCallback &progress = nullptr)#

Sample one attribute into a typed OpenVDB grid.

The attribute type is inferred from actual inside/on-surface samples. Scalar attributes become FloatGrid, vec3 attributes become Vec3SGrid, and vec4 attributes become Vec4sGrid. Missing attribute samples remain inactive. Volume fraction map samples are ignored and return nullptr if they are the only samples found. Samples come from as_sample_array() (every voxel, not culled).

Parameters:
  • attribute – Attribute name to export.

  • progress – Optional progress callback receiving integer values from 0 to 100.

Returns:

A typed OpenVDB grid, or nullptr when the attribute only produced volume fractions.

openvdb::BoolGrid::Ptr as_openvdb_occupancy_grid(const ProgressCallback &progress = nullptr)#

Sample the tree into a boolean OpenVDB occupancy grid.

Occupancy is true where Node::evaluate() returns a value less than or equal to zero. Undefined samples are treated as unoccupied. The grid is named “occupancy” and its transform maps index (0,0,0) to this sampler’s expanded minimum bounding-box corner. Voxels the root’s distance bound proves empty are not evaluated (see culling_stats()); the grid is the same as evaluating every voxel.

Parameters:

progress – Optional progress callback receiving integer values from 0 to 100.

Returns:

A BoolGrid containing occupied voxels as active true values.

openvdb::FloatGrid::Ptr as_openvdb_sdf_grid(const ProgressCallback &progress = nullptr)#

Sample the tree into an OpenVDB signed-distance level set.

The grid is named “surface”, marked as GRID_LEVEL_SET, and uses this sampler’s existing OpenVDB transform. Values are active only within a narrow band around the zero isosurface, with signed inactive values flood-filled by OpenVDB.

Parameters:

progress – Optional progress callback receiving integer values from 0 to 100.

Returns:

A FloatGrid containing the signed-distance field.

openvdb::FloatGrid::Ptr as_openvdb_sdf_grid_block_culled(const ProgressCallback &progress = nullptr)#

Sample a narrow-band OpenVDB SDF with per-block exterior culling.

Same transform / half-width conventions as as_openvdb_sdf_grid(), but partitions the domain into blocks of 8^3 voxels and skips a block, or an octant of it down to 4^3 voxels, when a probe at its centre proves through the root’s distance bound (DistanceCertifier) that every voxel in it has a value beyond the half-width. The grid is therefore the same as as_openvdb_sdf_grid(), which it falls back to when the root is approximate, its bound is not finite, culling is switched off (OPENVCAD_DISABLE_CULLING=1) or the bandwidth is too small to prove anything. Prefer as_openvdb_sdf_grid_narrow_band() for meshing; this method is useful when a coarse-to-fine pass is unnecessary. culling_stats() describes the pass.

Parameters:

progress – Optional progress callback receiving integer values from 0 to 100.

Returns:

A FloatGrid containing the signed-distance field.

openvdb::FloatGrid::Ptr as_openvdb_sdf_grid_narrow_band(const ProgressCallback &progress = nullptr, int coarse_factor = 4)#

Sample a narrow-band OpenVDB SDF via coarse-to-fine culling.

Samples a lattice of coarse-cell corners (shared by neighbouring cells) plus each cell center, and skips every cell whose probes prove through the root’s distance bound that no voxel in it has a value within the half-width, with the same rule as as_narrow_band_signed_distance_array(). The remaining cells are evaluated; in cells wider than 4 voxels, octants down to 4^3 voxels are again skipped when a probe proves them. The grid is the same as as_openvdb_sdf_grid(), which it falls back to under the same conditions as as_openvdb_sdf_grid_block_culled(). Preferred entry point for surface meshing. culling_stats() describes the pass.

Parameters:
  • progress – Optional progress callback receiving integer values from 0 to 100.

  • coarse_factor – Integer coarsening factor (>= 2). Defaults to 4.

Returns:

A FloatGrid containing the signed-distance field.

std::vector<uint8_t> as_rgba_array(const std::string &attribute, const std::shared_ptr<ColorMap> &color_map, bool blend = true, ProgressCallback progress = nullptr)#

Color every voxel inside the object by an attribute.

Uses the cached voxel grid, sampling it on the first call. Voxels outside the object stay (0, 0, 0, 0). Scalar attributes (and “Signed Distance”) are normalized to the sampled min/max, or to the override range, and mapped through color_map. Volume-fraction samples are colored from the material definitions: blended by fraction when blend is true, or one material picked at random by weight otherwise. vec3/vec4 samples are read as RGB/RGBA in [0, 1]. The attribute name “none” paints every inside voxel opaque gray. Inside voxels missing the attribute get the stripe pattern (see set_undefined_attribute_pattern_enabled()) or stay transparent.

Parameters:
  • attribute – Attribute name to color by.

  • color_map – Color map for scalar attributes.

  • blend – Blend volume fractions instead of picking one material per voxel.

  • progress – Optional progress callback receiving integer values from 0 to 100.

Returns:

A flat array of nx * ny * nz * 4 RGBA bytes.

const std::vector<std::pair<std::optional<double>, std::optional<AttributeSamples>>> &as_sample_array(const ProgressCallback &progress = nullptr)#

Samples every voxel once and caches the result; later calls return the cache.

Returned by reference: the array holds one entry per voxel and can be very large. Every voxel is sampled, outside ones included.

Parameters:

progress – Optional progress callback receiving integer values from 0 to 100.

Returns:

One (signed distance, attribute samples) pair per voxel, in grid order.

std::vector<float> as_signed_distance_array(const ProgressCallback &progress = nullptr)#

The signed distance at every voxel of the grid.

Every voxel is evaluated, outside ones included. Voxels where the tree has no value hold the largest float (FLT_MAX). The result is cached after the first call.

Parameters:

progress – Optional progress callback receiving integer values from 0 to 100.

Returns:

A flat array of nx * ny * nz values; reshape with sample_dimensions().

std::vector<glm::vec3> as_vec3_array(const std::string &attribute, ProgressCallback progress = nullptr)#

Sample a vec3 attribute at every voxel.

Same rules as as_float_array(); unset voxels are (0, 0, 0).

Parameters:
  • attribute – Attribute name to sample.

  • progress – Optional progress callback receiving integer values from 0 to 100.

Returns:

A flat array of nx * ny * nz vectors.

std::vector<glm::vec4> as_vec4_array(const std::string &attribute, ProgressCallback progress = nullptr)#

Sample a vec4 attribute at every voxel.

Same rules as as_float_array(); unset voxels are (0, 0, 0, 0).

Parameters:
  • attribute – Attribute name to sample.

  • progress – Optional progress callback receiving integer values from 0 to 100.

Returns:

A flat array of nx * ny * nz vectors.

void cancel()#

Asks in-flight and later sampling passes to stop early.

Safe to call from a progress callback or another thread. The sampler stays cancelled, and any array it returns afterwards is incomplete, so callers should discard both the sampler and its results.

void clear_double_attribute_range_override()#

Go back to normalizing scalar coloring by the sampled range.

CullingStats culling_stats() const#

Counts from the last sampling pass that can skip voxels.

Set by the voxel-grid pass behind as_rgba_array(), as_float_array(), as_vec3_array(), as_vec4_array() and as_material_fraction_array(), and by as_openvdb_occupancy_grid(): these skip voxels the root’s distance bound proves hold no material (sampled = sample() or evaluate() calls). Also set by as_narrow_band_signed_distance_array(), as_openvdb_sdf_grid_narrow_band() and as_openvdb_sdf_grid_block_culled(), which skip voxels proven to lie beyond the narrow band (sampled = voxels evaluated exactly, probes = evaluate() calls spent on proofs). Results served from a cache leave it unchanged; before any such pass it is empty. When culling did not run, active is false and fallback_reason says why.

Returns:

The counts of that pass.

std::vector<std::optional<double>> evaluate_points(const std::vector<glm::vec3> &points, ProgressCallback progress = nullptr)#

Evaluate the signed-distance field at arbitrary world-space points.

Evaluates the prepared tree in parallel while preserving the input point order. Each result has the same semantics as Node::evaluate(): a signed distance when defined, or an empty optional outside the prepared domain.

Parameters:
  • points – World-space points to evaluate.

  • progress – Optional progress callback receiving integer values from 0 to 100.

Returns:

One optional signed-distance value per input point, in matching order.

std::pair<double, double> get_double_attribute_min_max() const#

The scalar range used to normalize the last scalar coloring.

Returns:

(min, max): the override range when one is set, otherwise the range found by the last as_rgba_array() or sample_points_to_colors() call.

size_t observed_thread_count() const#

The number of distinct threads that ran sampling work since the last reset.

Returns:

The thread count.

void reset_thread_usage()#

Forget the worker threads recorded so far.

std::tuple<size_t, size_t, size_t> sample_dimensions()#

The grid size in voxels.

Returns:

(nx, ny, nz).

std::vector<Node::TreeSample> sample_line(const glm::vec3 &start, const glm::vec3 &end, size_t count, ProgressCallback progress = nullptr)#

Sample the tree at evenly spaced points along a straight line.

Generates count points from start to end (inclusive of both ends) and samples the implicit tree at each one, returning the full signed distance and attribute samples per point. Sampling is parallelized across the points exactly like sample_points(). This is the fast path behind the Plot Over Line inspection tool, which needs signed distance (to break the plot outside the object) together with every attribute value in a single call.

Parameters:
  • start – World-space start point of the line.

  • end – World-space end point of the line.

  • count – Number of samples along the line; clamped to a minimum of 2.

  • progress – Optional progress callback receiving integer values from 0 to 100.

Returns:

A vector of TreeSample (signed distance + attribute samples) of length count.

std::vector<Node::TreeSample> sample_points(const std::vector<glm::vec3> &points, ProgressCallback progress = nullptr)#

Sample signed distance and attributes at arbitrary world-space points.

Samples the prepared tree in parallel while preserving the input point order. Each result has the same semantics as Node::sample().

Parameters:
  • points – World-space points to sample.

  • progress – Optional progress callback receiving integer values from 0 to 100.

Returns:

One TreeSample per input point, in matching order.

std::vector<glm::vec3> sample_points_to_colors(std::vector<glm::vec3> &points, const std::string &attribute, const std::shared_ptr<ColorMap> &color_map, bool blend = true, ProgressCallback progress = nullptr)#

Color arbitrary points by an attribute.

Uses the same coloring rules as as_rgba_array(), with the scalar range taken from these points (or the override). A point missing the attribute takes it from the first of its 26 voxel neighbours that has it; if none does, it gets the stripe pattern or gray (128, 128, 128). “Signed Distance” colors by evaluate().

Parameters:
  • points – World-space points to color.

  • attribute – Attribute name to color by.

  • color_map – Color map for scalar attributes.

  • blend – Blend volume fractions instead of picking one material per point.

  • progress – Optional progress callback receiving integer values from 0 to 100.

Returns:

One RGB color, with channels in 0-255, per input point.

std::vector<float> sample_points_to_float_array(std::vector<glm::vec3> &points, const std::string &attribute, ProgressCallback progress = nullptr)#

Sample a scalar attribute at arbitrary points.

Like sample_points_to_colors(), a point missing the attribute takes it from a voxel neighbour when one has it, and “Signed Distance” reads evaluate(). Points still missing the attribute, or holding a non-scalar value, give 0.

Parameters:
  • points – World-space points to sample.

  • attribute – Attribute name to sample.

  • progress – Optional progress callback receiving integer values from 0 to 100.

Returns:

One value per input point, in matching order.

std::vector<float> sample_points_to_material_fraction_array(std::vector<glm::vec3> &points, const std::string &attribute, ProgressCallback progress = nullptr)#

Sample a volume-fraction attribute at arbitrary points into a per-material fraction array.

Mirrors as_material_fraction_array but at explicit world-space points (e.g. iso-surface vertices) rather than the voxel grid. Produces one fraction per material per point, laid out as a flat array of size points.size() * num_materials in point-major order: point i occupies indices [i * num_materials, (i + 1) * num_materials). Points that are outside the object, missing the attribute, or whose attribute is not a volume-fraction map contribute zeros. Requires material definitions; throws if none were supplied.

Parameters:
  • points – World-space points to sample.

  • attribute – Volume-fraction attribute name to sample.

  • progress – Optional progress callback receiving integer values from 0 to 100.

Returns:

A flat vector of per-material fractions; reshape to (points.size(), num_materials).

std::vector<glm::vec3> sample_points_to_vec3_array(std::vector<glm::vec3> &points, const std::string &attribute, ProgressCallback progress = nullptr)#

Sample a vec3 attribute at arbitrary points.

Points missing the attribute (after the neighbour lookup of sample_points_to_float_array()), or holding another type, give (0, 0, 0).

Parameters:
  • points – World-space points to sample.

  • attribute – Attribute name to sample.

  • progress – Optional progress callback receiving integer values from 0 to 100.

Returns:

One vector per input point, in matching order.

std::vector<glm::vec4> sample_points_to_vec4_array(std::vector<glm::vec3> &points, const std::string &attribute, ProgressCallback progress = nullptr)#

Sample a vec4 attribute at arbitrary points.

Points missing the attribute (after the neighbour lookup of sample_points_to_float_array()), or holding another type, give (0, 0, 0, 0).

Parameters:
  • points – World-space points to sample.

  • attribute – Attribute name to sample.

  • progress – Optional progress callback receiving integer values from 0 to 100.

Returns:

One vector per input point, in matching order.

glm::vec3 sample_space_size() const#

The world-space extent of the sampled region.

Returns:

The size of the root’s bounding box grown by two voxels on every side.

void save_openvdb_occupancy_grid(const std::string &file_path, const ProgressCallback &progress = nullptr)#

Save the sampled boolean occupancy grid to a VDB file.

The output file contains exactly one BoolGrid named “occupancy”.

Parameters:
  • file_path – The VDB file path to write.

  • progress – Optional progress callback receiving integer values from 0 to 100.

void set_double_attribute_range_override(double min_value, double max_value)#

Normalize scalar coloring to a fixed range instead of the sampled one.

Parameters:
  • min_value – Value mapped to the start of the color map.

  • max_value – Value mapped to the end of the color map.

Throws:

std::runtime_error – if max_value < min_value.

void set_undefined_attribute_pattern_enabled(bool enabled)#

Enable or disable the undefined-attribute stripe pattern.

When enabled (the default), voxels/points inside geometry that are missing the selected attribute are rendered with a subtle world-space stripe pattern instead of plain gray.

Parameters:

enabled – True to draw the pattern.

const ThreadUsageTracker &thread_usage_tracker() const#

The tracker that records which threads ran sampling work.

Returns:

The tracker.

TreeSampler(const std::shared_ptr<Node> &root, const glm::vec3 &voxel_size, const std::shared_ptr<MaterialDefs> &material_defs = nullptr, bool root_already_prepared = false)#

Create a sampler for a tree and prepare it.

Unless root_already_prepared is true, calls root->prepare(voxel_size, 6 * max(voxel_size)). Then computes the grid from the root’s bounding box.

Parameters:
  • root – Root node of the tree to sample.

  • voxel_size – Voxel size along x, y and z, in world units.

  • material_defs – Material definitions. Required by as_material_fraction_array() and sample_points_to_material_fraction_array(), and by the color methods when the attribute holds volume fractions. May be nullptr otherwise.

  • root_already_prepared – Skip the prepare() call when the caller already prepared the tree.

Private Functions

glm::vec4 color_for_sample(Attribute::Value sample, const std::shared_ptr<ColorMap> &color_map) const#
void compute_sample_dimensions()#
void compute_voxel_min_max(const std::string &attribute)#
openvdb::FloatGrid::Ptr create_empty_sdf_grid(float half_width) const#

Shared setup for OpenVDB SDF grids (transform, metadata, background).

openvdb::math::Transform::Ptr create_openvdb_transform() const#
double culling_margin() const#

Slack for culling geometry: float rounding of voxel coordinates and of stored probe values.

template<typename WorkerFactory>
void for_each_voxel_that_may_hold_material(const ProgressCallback &progress, const WorkerFactory &make_worker)#

Calls a worker for every voxel of the grid that may hold material, in parallel.

Each layer is culled with LayerCuller from the root’s distance bound: voxels proven to hold no material (sample() would report outside or no value) are skipped, every other voxel is visited exactly as a full pass would. make_worker() is called once per block of rows, and its result as worker(root, x, y, z, point) with the thread’s clone of the root. Sets m_culling_stats.

void sample_signed_distance_field(const ProgressCallback &progress = nullptr)#
void sample_voxel_grid(const ProgressCallback &progress = nullptr)#

Private Members

std::vector<SampleResult> m_attribute_samples#
glm::vec3 m_bbox_max#
glm::vec3 m_bbox_min#
tbb::task_group_context m_context#
CullingStats m_culling_stats#
double m_dbl_attribute_max = std::numeric_limits<double>::lowest()#
double m_dbl_attribute_min = std::numeric_limits<double>::max()#
double m_dbl_attribute_override_max = 1.0#
double m_dbl_attribute_override_min = 0.0#
bool m_has_dbl_attribute_range_override = false#
std::shared_ptr<MaterialDefs> m_material_defs#
std::pair<float, int> m_narrow_band_parameters = {0.0f, 0}#
std::vector<float> m_narrow_band_signed_distance_field#
std::shared_ptr<SampleResult> m_points_samples#
std::shared_ptr<Node> m_root#
std::vector<std::pair<std::optional<double>, std::optional<AttributeSamples>>> m_sample_array#
bool m_show_undefined_attribute_pattern = true#
std::vector<float> m_signed_distance_field#
size_t m_size_x#
size_t m_size_y#
size_t m_size_z#
tbb::enumerable_thread_specific<std::shared_ptr<Node>> m_thread_local_roots#
ThreadUsageTracker m_thread_usage_tracker#
bool m_use_blending = true#
glm::vec3 m_voxel_size#

Private Static Functions

static glm::vec4 BlendDistribution(const Attribute::VolumeFractionMapPtr &distribution, const std::shared_ptr<MaterialDefs> &material_defs)#
static std::optional<Attribute::Value> FuzzySampleAttribute(const std::shared_ptr<Node> &root, const glm::vec3 &p, const glm::vec3 &voxel_size, const std::string &attribute)#
static glm::vec4 UndefinedStripeColor(const glm::vec3 &world_pos, float stripe_period, float alpha)#
static void UpdateProgress(size_t &local_count, std::atomic<size_t> &global_count, const size_t &total_voxels, const ProgressCallback &progress, std::mutex &progress_mutex)#
static void write_narrow_band_value(openvdb::FloatGrid::Accessor &accessor, const std::shared_ptr<Node> &root, int x, int y, int z, const glm::vec3 &bbox_min, const glm::vec3 &voxel_size, float half_width)#

Evaluate and write a fine voxel into a local SDF accessor when in-band.

struct SampleResult#

Public Members

bool inside = false#
std::optional<AttributeSamples> samples#

Only stored for inside voxels.

std::optional<double> sdf#

Only stored for inside voxels; no reader uses the others.

struct CullingStats#
#include <voxel_culling.h>

Counts from a culled sampling pass.

Public Functions

inline double skipped_fraction() const#

Fraction of voxels skipped, 0 when nothing was counted.

Returns:

skipped_voxels / total_voxels.

Public Members

DistanceAccuracy accuracy = DistanceAccuracy::approximate#

The root’s distance_accuracy().

bool active = false#

True if culling ran; false if every voxel was sampled.

double bandwidth = 0.0#

The bandwidth the root was prepared with.

std::string fallback_reason#

Why culling did not run (empty when active).

double lipschitz = 0.0#

The root’s lipschitz_bound().

size_t probes = 0#

evaluate() calls spent on proofs.

size_t sampled_voxels = 0#

Voxels left for sample() (one call each).

size_t skipped_voxels = 0#

Voxels proven outside without a sample() call.

size_t total_voxels = 0#

Voxels in all layers built so far.

class DistanceCertifier#
#include <voxel_culling.h>

Turns one evaluate() probe of a prepared tree into a ball proven free of material.

Relies on the contract behind Node::distance_accuracy(): for a root that is exact or bound with Lipschitz bound L and bandwidth T, the value v at c clamped to [-T, T] (T where there is no value) is L-Lipschitz, so no inside point lies within clamp(v) / L of c when that is positive; and the inside set lies in the root’s bounding box, so none lies closer than the box either. Values beyond the bandwidth are never trusted. NaN and infinity prove nothing. When the root is approximate, its bound is not finite, or culling is switched off, every radius is zero.

Public Functions

inline DistanceAccuracy accuracy() const#

The root’s distance_accuracy().

Returns:

The accuracy.

inline double band_radius() const#

The largest radius any probe can prove empty inside the root’s box: T / L.

Returns:

T / L, or 0 when disabled.

inline double bandwidth() const#

The bandwidth T the root was prepared with.

Returns:

The bandwidth.

double box_distance(const glm::dvec3 &p) const#

Euclidean distance from p to the root’s bounding box (0 inside it).

Parameters:

p – The point.

Returns:

The distance.

DistanceCertifier(const std::shared_ptr<Node> &root, bool enabled = true)#

Reads the root’s accuracy, bound, bandwidth and box.

Parameters:
  • root – The root of the tree. It must already be prepared.

  • enabled – False to switch culling off (the reason is then “disabled”).

double empty_radius(const glm::dvec3 &p, const std::optional<double> &value) const#

Radius of a ball around p that provably holds no inside point.

Parameters:
  • p – The probe point.

  • value – evaluate() at p.

Returns:

The radius, or 0 when nothing is proven.

double empty_radius(const std::optional<double> &value) const#

The part of empty_radius() that comes from the value alone: min(v, T) / L, T / L for no value.

Without the bounding box, this radius also bounds the values around the probe: at distance d < radius every value clamped to the bandwidth is at least L * (radius - d). Use it to prove regions free of values near zero (a narrow band), not only free of material.

Parameters:

value – evaluate() at the probe.

Returns:

The radius, or 0 when nothing is proven.

inline bool enabled() const#

True if probes can prove anything.

Returns:

Whether culling is enabled.

inline const std::string &fallback_reason() const#

Why the certifier is disabled; empty when enabled.

Returns:

The reason.

double full_radius(const std::optional<double> &value) const#

Radius of a ball around p that provably holds no outside point.

Parameters:

value – evaluate() at p.

Returns:

The radius, or 0 when nothing is proven.

inline double lipschitz() const#

The root’s lipschitz_bound(), L.

Returns:

The bound.

Public Static Functions

static bool disabled_by_environment()#

True if the environment variable OPENVCAD_DISABLE_CULLING is set to anything but “0”.

Returns:

Whether culling is switched off by the environment.

static double rounding_margin(double finest_spacing, double largest_coordinate, double bandwidth)#

Slack to keep between a certified radius and the voxels it proves empty.

Nodes may evaluate in float (Rotate, Torus, sampled grids), so a probe’s value can be off by several float ulps of the coordinates; node tolerances, such as the 1e-6 similarity test of Transform, add a small part of the bandwidth. A ten-thousandth of the finest voxel spacing covers the rest.

Parameters:
  • finest_spacing – The finest voxel spacing of the grid.

  • largest_coordinate – The largest coordinate magnitude of the grid and the root’s box.

  • bandwidth – The root’s bandwidth.

Returns:

The margin, in world units.

Private Members

DistanceAccuracy m_accuracy = DistanceAccuracy::approximate#
double m_bandwidth = 0.0#
glm::dvec3 m_box_max = glm::dvec3(0.0)#
glm::dvec3 m_box_min = glm::dvec3(0.0)#
bool m_enabled = false#
std::string m_fallback_reason#
double m_lipschitz = 0.0#
class LayerCuller#
#include <voxel_culling.h>

Marks, layer by layer, the voxels of a grid that may hold material.

Each layer is covered by square tiles that are split as a quadtree down to a leaf size. A tile is skipped when a certified empty ball (its own probe’s or an ancestor’s) contains every voxel of it; it is sampled whole, without more probes, when a certified full ball contains it; leaves that prove nothing are sampled. A tile is only probed when a probe could prove it empty at all, so the large tiles inside the root’s box cost no evaluations. Tile boxes come from the exact coordinates the caller samples, so a skipped voxel is one whose sample() would report no material.

The caller keeps its own loops and skips voxels whose mask entry is 0, which keeps the order of the remaining sample() calls exactly as before. Choose the mask layout that matches the caller’s innermost loop so the mask is read contiguously. Probes use the caller’s thread-local root, so build_layer() is safe to call from many threads at once.

Public Functions

inline bool active() const#

True if culling runs; false if every voxel will be sampled.

Returns:

Whether culling is active.

const std::vector<uint8_t> &build_layer(Node &root, long z)#

Builds the mask of one layer in a buffer owned by the calling thread.

Parameters:
  • root – The calling thread’s clone of the root, used for probes.

  • z – The layer index.

Returns:

The mask, indexed x + y * xs.size() (or y + x * ys.size() with Options::y_fastest): 1 = sample, 0 = provably no material. Valid until the same thread calls build_layer() again.

LayerCuller(const std::shared_ptr<Node> &root, std::vector<double> xs, std::vector<double> ys, std::vector<double> zs)#

Same, with default options.

Parameters:
  • root – The prepared root.

  • xs – The x coordinate of each voxel column.

  • ys – The y coordinate of each voxel row.

  • zs – The z coordinate of each layer.

LayerCuller(const std::shared_ptr<Node> &root, std::vector<double> xs, std::vector<double> ys, std::vector<double> zs, const Options &options)#

Sets up culling for a grid of voxels.

Parameters:
  • root – The prepared root (accuracy, bound, bandwidth and box are read from it).

  • xs – The x coordinate of each voxel column, exactly as the caller samples it (increasing).

  • ys – The y coordinate of each voxel row, exactly as the caller samples it (increasing).

  • zs – The z coordinate of each layer, exactly as the caller samples it.

  • options – Tile sizes and the off switch. The environment variable OPENVCAD_DISABLE_CULLING also switches culling off.

CullingStats stats() const#

Totals over every layer built so far.

total_voxels counts only the layers built so far, not the whole grid.

Returns:

The counts, with the certifier’s accuracy, bound, bandwidth and fallback reason.

Public Static Functions

template<typename PositionFunction>
static inline std::vector<double> coordinates(long count, PositionFunction position)#

Builds a coordinate list from a function of the voxel index.

Parameters:
  • count – Number of coordinates; 0 or less gives an empty list.

  • position – Called with each index from 0 to count - 1; its result is cast to double.

Returns:

The coordinates.

Private Functions

bool ball_contains(const Ball &ball, const glm::dvec3 &low, const glm::dvec3 &high) const#
void mark(Counters &counters, long x0, long y0, long x1, long y1)#
void visit_tile(Node &root, Counters &counters, long z, long x0, long y0, long x1, long y1)#

Private Members

DistanceCertifier m_certifier#
tbb::enumerable_thread_specific<Counters> m_counters#
double m_margin = 0.0#
Options m_options#
std::vector<double> m_xs#
std::vector<double> m_ys#
std::vector<double> m_zs#
struct Ball#

Public Members

glm::dvec3 centre#
bool empty#

true: no inside point; false: no outside point.

double radius#
struct Counters#

Public Members

std::vector<Ball> balls#
std::vector<uint8_t> mask#
size_t probes = 0#
size_t sampled = 0#
size_t skipped = 0#
size_t total = 0#
struct Options#
#include <voxel_culling.h>

Tile sizes, mask layout and the off switch.

Public Members

bool enabled = true#

False samples every voxel (the mask is all ones).

long leaf_tile = 4#

Tiles this small are sampled when nothing is proven.

long root_tile = 64#

Tile size (in voxels) at the top of the quadtree.

bool y_fastest = false#

Mask index y + x * ys.size() (for loops with y innermost) instead of x + y * xs.size().

class AttributeVoxelGrid#
#include <attribute_voxel_grid.h>

Shared dense voxel grid of precomputed child-node attributes.

A typed, mask-aware 3D grid used by the Blend and Convolve nodes to cache the result of a child’s attribute evaluation across space. The grid stores samples at grid “corners” (the world position of voxel (i,j,k) is origin + (i,j,k) * voxel_size), which means any query point that aligns with a corner resolves without interpolation, preserving exact numerical parity with direct child sampling in the aligned case.

The utility handles:

  • Parallel filling via a per-thread cloned child prototype and TBB.

  • Lazy per-attribute type discovery during the fill (scalar, vec3, vec4, or volume fraction map), with per-attribute mutexes to allow safe concurrent allocation of typed buffers.

  • Trilinear interpolation at sample time, mask-weighted so cells with no source data do not drag neighbors toward zero.

  • A separable 1D masked box blur (prefix-sum based) that Blend uses to produce a Gaussian-like ramp across attribute boundaries while keeping per-sample cost O(1).

Public Types

enum class ValueKind#

Discovered value type for an attribute in the grid.

Values:

enumerator unknown#

No sample seen yet.

enumerator dbl#

Scalar values, stored in values_dbl.

enumerator vec3#

Vec3 values, stored in values_vec3.

enumerator vec4#

Vec4 values, stored in values_vec4.

enumerator vfm#

Volume fractions, one plane per material in vfm_planes.

Public Functions

AttributeVoxelGrid() = default#
inline glm::ivec3 dims() const#

Grid dimensions in voxels.

Returns:

(nx, ny, nz).

const Entry *entry(const std::string &name) const#

Read-only accessor for a named attribute entry.

Parameters:

name – Attribute name.

Returns:

The entry, or nullptr if not present.

Entry *entry_mut(const std::string &name)#

Mutable accessor for a named attribute entry.

Used by Blend to apply an in-place blur to the raw grid.

Parameters:

name – Attribute name.

Returns:

The entry, or nullptr if not present.

std::vector<std::string> entry_names() const#

Names of all entries stored in the grid.

Returns:

The names, in no particular order.

inline glm::vec3 origin() const#

World-space position of voxel (0, 0, 0).

Returns:

The origin.

std::optional<TrilinearResult> trilinear(double x, double y, double z, const std::string &name) const#

Sample the grid at an arbitrary world-space position for one attribute using mask-weighted trilinear interpolation.

Positions outside the grid use the nearest edge voxels.

Parameters:
  • x – World x coordinate.

  • y – World y coordinate.

  • z – World z coordinate.

  • name – Attribute name.

Returns:

nullopt if the attribute is not present or the effective mask is ~0.

inline glm::vec3 voxel_size() const#

World-space spacing between adjacent voxels along each axis.

Returns:

The voxel size.

Public Static Functions

static void blur_axis_masked(std::vector<float> &values, std::vector<float> &mask, const glm::ivec3 &dims, int axis, int radius)#

Masked 1D box blur along a single axis of a dense 3D buffer.

Uses prefix sums so per-voxel cost is O(1) regardless of radius.

Parameters:
  • values – Values buffer, blurred in-place. Must be pre-multiplied by mask before calling so the prefix-sum aggregates values*mask.

  • mask – Mask buffer, blurred in-place alongside values.

  • dims – Grid dimensions (nx, ny, nz); buffer layout is x-fastest.

  • axis – 0 for X, 1 for Y, 2 for Z.

  • radius – Half-width of the blur kernel in voxels.

static void blur_scalar_plane(std::vector<float> &values, std::vector<float> &mask, const glm::ivec3 &dims, const glm::ivec3 &grid_radius, int num_passes)#

Run num_passes full X,Y,Z separable box blurs on a single scalar plane, renormalizing between passes so the repeated-box operator converges to a Gaussian-like kernel.

Leaves values = 0 and mask = 0 where the mask was empty, and values = average and mask = 1 elsewhere.

Parameters:
  • values – Values buffer, blurred in-place; pre-multiplied by mask as for blur_axis_masked().

  • mask – Mask buffer, blurred in-place alongside values.

  • dims – Grid dimensions (nx, ny, nz); buffer layout is x-fastest.

  • grid_radius – Blur half-width in voxels along each axis.

  • num_passes – Number of X,Y,Z passes; 0 or less does nothing.

static std::shared_ptr<AttributeVoxelGrid> build(Node &child_proto, const glm::vec3 &origin, const glm::ivec3 &dims, const glm::vec3 &voxel_size, const std::vector<std::string> &targeted_attrs)#

Parallel-fills a grid by cloning child_proto per thread and sampling its attributes at every grid corner.

Parameters:
  • child_proto – Prototype node; the utility clones it once per TBB worker via Node::clone() (must have already had prepare() called on it).

  • origin – World-space coordinate of voxel (0, 0, 0).

  • dims – Grid dimensions in voxels along each axis. Each axis must be >= 1.

  • voxel_size – World-space distance between adjacent grid corners along each axis.

  • targeted_attrs – Names of the attributes to record. If empty, every attribute observed on the child during the fill is recorded.

Returns:

Shared pointer to the populated grid.

Private Members

glm::ivec3 m_dims = glm::ivec3(0)#
std::unordered_map<std::string, Entry> m_entries#
glm::vec3 m_origin = glm::vec3(0.0f)#
glm::vec3 m_voxel_size = glm::vec3(1.0f)#
struct Entry#
#include <attribute_voxel_grid.h>

Per-attribute typed storage.

Only the fields matching kind are populated.

Public Members

ValueKind kind = ValueKind::unknown#

Value type of the attribute.

std::vector<float> mask#

Per-voxel effective-mask weight.

For raw (unblurred) grids this is 0 where the child had no value and 1 where it did. For Blend’s blurred grids this becomes a fractional neighborhood weight that is used at interpolation time to discount empty cells.

std::vector<float> values_dbl#

Scalar value per voxel (kind dbl).

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

Vec3 value per voxel (kind vec3).

std::vector<glm::vec4> values_vec4#

Vec4 value per voxel (kind vec4).

std::unordered_map<uint8_t, std::vector<float>> vfm_planes#

Material ID to fraction per voxel (kind vfm).

struct TrilinearResult#
#include <attribute_voxel_grid.h>

Output of trilinear().

value is the interpolated Attribute::Value, and mask is the effective-mask weight after interpolation, in [0, 1+] range.

Public Members

double mask = 0.0#

The interpolated mask weight.

Attribute::Value value#

The interpolated value.

class MeshSampler#
#include <mesh_sampler.h>

Fast signed-distance sampler for SurfaceMesh.

MeshSampler builds a CGAL acceleration structure once during construction and reuses it for repeated distance queries.

Public Types

typedef CGAL::AABB_face_graph_triangle_primitive<CGALMesh> AABBPrimitive#

One mesh triangle in the tree.

typedef CGAL::Surface_mesh<SC_Point> CGALMesh#

CGAL copy of the mesh.

typedef CGAL::AABB_traits_3<SC_Kernel, AABBPrimitive> MeshAABBTraits#

Traits of the triangle tree.

typedef CGAL::AABB_tree<MeshAABBTraits> MeshAABBTree#

Tree for closest-point queries.

typedef CGAL::Side_of_triangle_mesh<CGALMesh, SC_Kernel> PointInside#

Inside/outside test.

Public Functions

explicit MeshSampler(const std::shared_ptr<SurfaceMesh> &mesh)#

Constructor.

Parameters:

mesh – Shared pointer to the mesh to sample.

explicit MeshSampler(const SurfaceMesh &mesh)#

Constructor.

Parameters:

mesh – The mesh to sample.

double signed_distance(double x, double y, double z) const#

Calculates signed distance from a point to the mesh surface.

Parameters:
  • x – Query point X.

  • y – Query point Y.

  • z – Query point Z.

Returns:

Negative values are inside, positive are outside.

Private Functions

void initialize(const SurfaceMesh &mesh)#

Private Members

std::shared_ptr<CGALMesh> m_cgal_mesh#
std::shared_ptr<PointInside> m_inside_tester#
std::shared_ptr<MeshAABBTree> m_tree#
namespace SurfaceProbe#

Surface interrogation helpers for prepared OpenVCAD trees.

These helpers answer the two questions a designer needs when placing one node against the surface of another: “where exactly is the surface here?” and “which way is it facing?”. The returned position/normal pair can be fed straight into alignment_angles() to build the Rotate node that aligns a child’s local +Z with the surface normal.

Warning

Every function that takes a Node requires that prepare() has already been called on the root of that tree. The queries below use evaluate() and gradient(), which are undefined before prepare().

Functions

glm::vec3 alignment_angles(const glm::vec3 &forward, const glm::vec3 &up = glm::vec3(0.0f, 0.0f, 1.0f))#

Computes the Rotate angles that aim a child node’s local axes along a chosen frame.

The returned angles are in the Rotate node’s own convention, so they can be handed straight to Rotate(pitch, yaw, roll, child). The child’s local +Z is aimed along forward and its local +Y along up. up is orthogonalized against forward, so it only has to be roughly right; when the two are parallel a fallback world axis is substituted.

The Text node extrudes along +Z, so aiming +Z along a surface normal stands text up off that surface. Note that Text builds its glyphs on a flipped X axis, which puts their visual up along its own -Y: pass the negated world up to get text that reads upright.

Parameters:
  • forward – The world direction that the child’s local +Z should point along.

  • up – The world direction that the child’s local +Y should point along, before orthogonalization.

Throws:

std::runtime_error – if forward is zero length or non-finite.

Returns:

Euler angles in degrees, packed as (pitch, yaw, roll) for the Rotate node.

Probe probe_point(Node &node, const glm::vec3 &point, double tolerance = 1e-4, int max_iterations = 16)#

Projects a point onto the nearest surface of a tree and reports the normal there.

Runs a damped Newton iteration along the signed distance gradient, which lands on the surface in a handful of steps for well-behaved fields. The best iterate is kept, so a field that fails to converge still returns its closest approach (with hit set to false).

Parameters:
  • node – The prepared node to interrogate.

  • point – The starting point. May be inside, outside, or already on the surface.

  • tolerance – The absolute signed distance, in model units, that counts as “on the surface”.

  • max_iterations – The maximum number of Newton steps to take.

Throws:

std::runtime_error – if tolerance is not positive or max_iterations is not positive.

Returns:

A Probe describing the surface point. hit is false when the field is undefined at the starting point, when the gradient is unusable, or when the iteration did not converge.

Probe probe_ray(Node &node, const glm::vec3 &origin, const glm::vec3 &direction, double step_size = 0.0, double tolerance = 1e-4)#

Casts a ray at a tree and reports the first surface it enters.

The ray is clipped to the node’s bounding box, marched until the signed distance turns negative, bisected onto the crossing, and finally refined with probe_point(). This is the query a viewport pick maps onto: the camera position is the origin and the unprojected click direction is the direction.

Parameters:
  • node – The prepared node to interrogate.

  • origin – The ray origin in world coordinates.

  • direction – The ray direction. Need not be normalized, but must not be zero length.

  • step_size – The march step in model units. Pass 0 (the default) to derive one from the bounding box diagonal.

  • tolerance – The absolute signed distance, in model units, that counts as “on the surface”.

Throws:

std::runtime_error – if direction is zero length, or if step_size or tolerance is negative.

Returns:

A Probe describing the entry point. hit is false when the ray misses the node.

glm::vec3 surface_normal(Node &node, const glm::vec3 &point)#

Returns the outward unit surface normal of a tree at a point.

This is the normalized signed distance gradient. The point does not have to lie exactly on the surface; away from it the result is the direction of steepest increase of the field.

Parameters:
  • node – The prepared node to interrogate.

  • point – The point to evaluate, in world coordinates.

Returns:

The unit normal, or a zero vector when the gradient is degenerate or non-finite.

struct Probe#
#include <surface_probe.h>

The result of a single surface interrogation.

position and normal are always populated with the best answer the probe could find, even when hit is false, so callers can debug a failed probe. Only trust them when hit is true.

Public Members

bool hit = false#

True when the probe converged onto the surface within the requested tolerance.

glm::vec3 normal = glm::vec3(0.0f, 0.0f, 1.0f)#

The outward unit surface normal at position. Points away from the solid.

glm::vec3 position = glm::vec3(0.0f)#

The point on (or nearest to) the surface, in world coordinates.

double signed_distance = 0.0#

The residual signed distance at position. Near zero for a converged probe.

Enums

enum class DICOMSliceOrder#

Strategy used to decide the order in which the files of a DICOM series are stacked.

Real-world exporters name slice files in wildly different ways (“1.dcm”, “001.dcm”, “IMG0001.dcm”, “slice_0098.dcm”, “IMG_0009_0071.dcm”, or bare SOP Instance UIDs), so filenames alone are not a dependable ordering key. The default AUTO strategy therefore prefers the Instance Number (0020,0013) tag stored in each file and only falls back to filenames when that tag is missing or ambiguous.

Values:

enumerator AUTO#

Sort by Instance Number when every file carries a unique one, otherwise sort by filename.

enumerator INSTANCE_NUMBER#

Always sort by Instance Number (0020,0013); throws when the tag is missing or duplicated.

enumerator SLICE_POSITION#

Sort by the geometric slice position; throws when the position cannot be determined.

Uses Image Position Patient (0020,0032) projected onto the slice normal derived from Image Orientation Patient (0020,0037), falling back to Slice Location (0020,1041). Not used by AUTO because many non-clinical exports write a constant (or absent) patient position for every slice.

enumerator FILENAME#

Sort by filename only, using a natural (digit-aware) comparison. Reads no metadata.

namespace DICOMSeries#

Helpers for discovering and ordering the slice files that make up a DICOM series.

Functions

std::vector<std::string> CollectFiles(const std::string &directory)#

Collect the candidate DICOM slice files stored in a directory.

Hidden entries (anything whose name starts with ‘.’, which covers “.DS_Store” and the “._name” resource forks that macOS archives leave behind) and the “DICOMDIR” index file are skipped, since they are not slices. The returned paths are not ordered.

Parameters:

directory – The directory containing the DICOM stack.

Throws:

std::runtime_error – If the directory does not exist or holds no candidate files.

Returns:

The absolute or relative paths of every candidate slice file.

bool NaturalFilenameLess(const std::string &a, const std::string &b, const std::string &ignore_prefix = "")#

Compare two paths by filename using a natural, digit-aware ordering.

Runs of digits compare by numeric value rather than character by character, so “slice_2” sorts before “slice_10” and zero padding of any width (“1”, “01”, “0001”) compares equal in value. Equal filenames fall back to comparing the full paths so the comparison stays a strict weak ordering.

Parameters:
  • a – The first path.

  • b – The second path.

  • ignore_prefix – A literal filename prefix stripped from both names before comparing.

Returns:

True when a orders before b.

std::vector<std::string> SortSlices(std::vector<std::string> files, DICOMSliceOrder order = DICOMSliceOrder::AUTO, const std::string &ignore_prefix = "")#

Order the files of a DICOM series so that index 0 is the first slice of the stack.

Parameters:
  • files – The slice files to order, as returned by CollectFiles.

  • order – The ordering strategy to apply.

  • ignore_prefix – A literal filename prefix stripped before any filename comparison. Use it when the fixed part of a filename contains digits that must not take part in the ordering (for example “scan2024_” in “scan2024_001.dcm”). Ignored when the ordering is resolved from metadata.

Throws:

std::runtime_error – If the requested metadata ordering cannot be resolved.

Returns:

The ordered file paths.

class ExpressionEvaluator#
#include <expression_evaluator.h>

A class to evaluate mathematical expressions.

This class uses the exprtk library to evaluate mathematical expressions. The class can compile a function and evaluate it with a set of variables. The variables are passed in as a map of variable names to pointers to double values.

Note

This class is thread NOT safe.

Public Functions

bool compile(const std::string &function, const std::unordered_map<std::string, double*> &variables)#

compiles a function with a set of variables

Parameters:
  • function – The function to compile

  • variables – A map of variable names to pointers to double values

Returns:

True if the function compiled successfully, false otherwise

std::string error()#

Returns the parser’s first error message from the last compile.

Returns:

The error text, or “No Error” after a successful compile

double evaluate()#

Evaluates the compiled function.

Returns:

The result of the function

ExpressionEvaluator()#

Default constructor.

double *getVariable(const std::string &name)#

Returns the pointer registered for a variable.

Parameters:

name – The variable name

Returns:

The pointer passed to compile(), or nullptr if the name was not registered

void setVariable(const std::string &name, double value)#

Writes a value through the pointer registered for a variable.

Parameters:
  • name – The variable name; it must have been registered with compile(), otherwise std::runtime_error is thrown

  • value – The new value

Private Members

bool m_compiled = false#
exprtk::expression<double> m_expression#
std::string m_function#
exprtk::parser<double> m_parser#
exprtk::symbol_table<double> m_symbol_table#
std::unordered_map<std::string, double*> m_variables#
namespace ExpressionCoordinateUtils#

Helpers that give expression nodes their extra coordinate variables.

Functions

inline void populate_radial_coordinates(double x, double y, double z, double &rho, double &phic, double &r, double &theta, double &phis)#

Computes the cylindrical and spherical coordinates of a point.

Angles are in radians. phis is 0 at the origin, where it is undefined.

Parameters:
  • x – Cartesian x.

  • y – Cartesian y.

  • z – Cartesian z.

  • rho – Receives the cylindrical radius sqrt(x^2 + y^2).

  • phic – Receives the cylindrical azimuth atan2(y, x), in [-pi, pi].

  • r – Receives the spherical radius sqrt(x^2 + y^2 + z^2).

  • theta – Receives the spherical azimuth atan2(y, x), equal to phic.

  • phis – Receives the spherical polar angle from +z, acos(z / r), in [0, pi].

namespace MathUtils#

A namespace for mathematical utility functions.

Functions

std::pair<glm::vec3, glm::vec3> CombinedBBox(std::vector<std::pair<glm::vec3, glm::vec3>> bboxes)#

Computes the bounding box of a list of bounding boxes.

Note

If any of the bounding boxes are infinite, they are ignored

Note

If no bounding boxes are finite, the function returns an infinite bounding box

Note

If the vector is empty, the function returns [0,0,0] to [0,0,0]

Parameters:

bboxes – The list of bounding boxes

Returns:

The combined bounding box TODO: this function is used in the composition nodes. However it might be smarter to use a tighter bounding box depending on the operation (e.g. intersection, union, etc.)

int compute_new_material(const std::unordered_map<uint8_t, float> &probabilities, bool prob_mode)#

Computes the new material based on the probabilities.

Parameters:
  • probabilities – A map of material IDs to probabilities

  • prob_mode – Whether to use probability mode or threshold mode

Returns:

The new material ID

void FilterNearlyCollinearPoints(std::vector<Point_2> &points, double epsilon)#

Removes interior points that are nearly collinear with their neighbours, in place.

Walks the list once; a point is removed when it and its current neighbours form a triangle with area below epsilon. The first and last points are always kept.

Parameters:
  • points – The points to filter

  • epsilon – The area threshold

std::pair<glm::vec3, glm::vec3> IntersectedBBox(std::vector<std::pair<glm::vec3, glm::vec3>> bboxes)#

Computes the intersected bounding box of a list of bounding boxes.

Note

Boxes without a definition (+inf corners) are ignored; if none is left, the result is that box.

Note

A side that no box bounds (a -inf or +inf corner) stays infinite.

Note

An empty intersection, or an empty list, gives [0,0,0] to [0,0,0].

Parameters:

bboxes – The list of bounding boxes

Returns:

The intersected bounding box

bool IsNearlyCollinear(const glm::vec2 &point1, const glm::vec2 &point2, const glm::vec2 &point3, double epsilon)#

Checks if three 2D points are nearly collinear.

Uses the area of the triangle formed by the points to determine collinearity

Parameters:
  • point1 – The first point

  • point2 – The second point

  • point3 – The third point

  • epsilon – The epsilon value

Returns:

True if the points are nearly collinear, false otherwise

bool IsNearlyCollinear(const Point_2 &point1, const Point_2 &point2, const Point_2 &point3, double epsilon)#

Checks if three CGAL 2D points are nearly collinear.

Same test as the glm overload: the triangle’s area is below epsilon

Parameters:
  • point1 – The first point

  • point2 – The second point

  • point3 – The third point

  • epsilon – The area threshold

Returns:

True if the points are nearly collinear, false otherwise

double smooth_min(double first, double second, double blend_radius)#

Compute the quadratic smooth minimum used by smooth Boolean unions.

The result matches an ordinary minimum when the input fields differ by at least four times the blend radius. Kept for existing callers; it is SmoothBlend::smooth_min with BlendProfile::quadratic.

Parameters:
  • first – First signed-distance-like field value.

  • second – Second signed-distance-like field value.

  • blend_radius – Non-negative blend radius in world units.

Returns:

The smoothly combined field value.

template<typename T>
T tet_interpolate(const glm::vec4 &bary_coords, const T &a, const T &b, const T &c, const T &d)#

Interpolates a value using barycentric coordinates.

Parameters:
  • bary_coords – The barycentric coordinates

  • a – The value at the first vertex

  • b – The value at the second vertex

  • c – The value at the third vertex

  • d – The value at the fourth vertex

Returns:

The interpolated value

float tet_volume(const glm::vec3 &a, const glm::vec3 &b, const glm::vec3 &c, const glm::vec3 &d)#

Computes the volume of a tetrahedron.

Parameters:
  • a – The first vertex of the tetrahedron

  • b – The second vertex of the tetrahedron

  • c – The third vertex of the tetrahedron

  • d – The fourth vertex of the tetrahedron

Returns:

The volume of the tetrahedron

class Random#
#include <random.h>

Process-wide random numbers backed by the C library’s rand().

A singleton: getInstance() seeds rand() from the current time on first use, and reseed() makes later draws repeatable. Every method draws from the shared rand() state.

Public Functions

double random_double(double min, double max)#

A random real number in [min, max].

Parameters:
  • min – Smallest value.

  • max – Largest value.

Returns:

The number.

int random_int(int min, int max)#

A random integer in [min, max], both ends included.

Parameters:
  • min – Smallest value.

  • max – Largest value; must be at least min.

Returns:

The integer.

void reseed(int seed)#

Reseed rand() so later draws repeat.

Parameters:

seed – The seed passed to srand().

Public Static Functions

static Random *getInstance()#

The shared instance, created and time-seeded on first call.

Returns:

The instance.

static uint8_t Weighted3ComponentSample(double a, double b, double c)#

Pick 0, 1 or 2 with probabilities a, b and the remainder.

Parameters:
  • a – Probability of 0.

  • b – Probability of 1.

  • c – Probability of 2. Unused: 2 is returned whenever 0 and 1 are not, so a + b + c should be 1.

Returns:

The chosen index.

static uint8_t Weighted5ComponentSample(double a, double b, double c, double d, double e)#

Pick 0 to 4 with probabilities a to d and the remainder.

Parameters:
  • a – Probability of 0.

  • b – Probability of 1.

  • c – Probability of 2.

  • d – Probability of 3.

  • e – Probability of 4. Unused: 4 is returned whenever 0 to 3 are not, so the five should sum to 1.

Returns:

The chosen index.

static size_t WeightedMaterialSample(const std::unordered_map<uint8_t, double> &materials_with_weights)#

Pick a material ID with probability proportional to its weight.

Parameters:

materials_with_weights – Material ID to non-negative weight; weights need not sum to 1.

Returns:

The chosen material ID, or 0 if none was chosen.

static size_t WeightedMaterialSample(const std::unordered_map<uint8_t, float> &materials_with_weights)#

Pick a material ID with probability proportional to its weight.

Parameters:

materials_with_weights – Material ID to non-negative weight; weights need not sum to 1.

Returns:

The chosen material ID, or 0 if none was chosen.

static size_t WeightedSample(const std::vector<double> &weights)#

Pick an index with probability proportional to its weight.

Parameters:

weights – Non-negative weights; they need not sum to 1.

Returns:

The chosen index, or 0 if none was chosen.

Private Functions

Random()#

Private Static Attributes

static Random *m_instance#

Functions

inline std::string report_version()#

Enums

enum class NoiseType#

The base noise functions.

  • simplex: 3D gradient noise on a simplex grid, smooth (C2), in [-1, 1] with mean 0.

  • cellular_f1: distance to the nearest of a set of random feature points (one per unit cell), in cell units. Round cells, 0 at each feature point.

  • cellular_f2: distance to the second-nearest feature point.

  • cellular_f2_minus_f1: F2 - F1, 0 on the boundaries between cells (a Voronoi web).

Values:

enumerator simplex#
enumerator cellular_f1#
enumerator cellular_f2#
enumerator cellular_f2_minus_f1#

Functions

std::pair<double, double> cellular_noise(const glm::dvec3 &point, uint32_t seed)#

The distances (F1, F2) from a point in noise space to its nearest and second-nearest feature points, in cell units.

The search is exact: it grows ring by ring until no closer point can exist.

uint32_t noise_hash(int32_t i, int32_t j, int32_t k, uint32_t seed)#

Hashes an integer cell and a seed.

uint32_t noise_hash(uint32_t value)#

Mixes 32 bits so every input bit affects every output bit (an integer hash we own, so results do not depend on the platform’s std::hash or random number generator).

double noise_lipschitz_bound(const NoiseSettings &settings)#

Returns an upper bound on the slope of a noise field, per mm, derived analytically.

NoiseType noise_type_from_name(const std::string &name)#

Returns a noise type by name (“simplex”, “cellular_f1”, “cellular_f2”, “cellular_f2_minus_f1”).

Throws:

std::runtime_error – listing the valid names when the name is unknown.

std::string noise_type_name(NoiseType type)#

Returns the name of a noise type.

std::pair<double, double> noise_value_bounds(NoiseType type)#

Returns the range every field of a type stays in: [-1, 1] for simplex, [0, sqrt(3)] for F1 and [0, 2 sqrt(3)] for F2 and F2 - F1 (typical values stay below about 1.2).

double sample_noise(const NoiseSettings &settings, const glm::dvec3 &point, uint32_t channel = 0)#

Samples a noise field at a point in mm.

Parameters:
  • settings – The noise settings (assumed valid).

  • point – The point in mm.

  • channel – Selects an unrelated field with the same settings (used for vector noise).

double simplex_noise(const glm::dvec3 &point, uint32_t seed)#

Simplex noise at a point given in noise space (one unit is one feature), in [-1, 1].

struct NoiseSettings#
#include <noise.h>

Everything that defines a noise field.

The same settings give the same values on every platform.

Octaves are summed as fractal Brownian motion: octave i is sampled at frequency * lacunarity^i with weight gain^i and its own seed, and the sum is divided by the sum of the weights, so the range does not grow with the number of octaves.

Public Functions

void validate() const#

Checks the settings.

Throws:

std::runtime_error – for a non-positive or non-finite frequency, lacunarity or gain, or octaves outside 1 to 16.

Public Members

double frequency = 0.1#

Features per mm of the first octave (0.1 gives features about 10 mm across).

double gain = 0.5#

Weight multiplier between octaves, positive.

double lacunarity = 2.0#

Frequency multiplier between octaves, positive.

int octaves = 1#

Number of octaves, 1 to 16.

uint32_t seed = 0#

Any value; different seeds give unrelated fields.

NoiseType type = NoiseType::simplex#

Which noise to sample.

Enums

enum class Easing#

Shaping curves that map [0, 1] onto [0, 1], used to ease ramps and other normalized fields.

Every curve starts at 0 and ends at 1 and never decreases, so an eased field keeps the range of its input. Inputs outside [0, 1] are clamped first.

  • linear: t.

  • smoothstep: 3t² − 2t³ (zero slope at both ends).

  • smootherstep: 6t⁵ − 15t⁴ + 10t³ (zero slope and curvature at both ends).

  • power: t^p with shape p > 0 (p > 1 starts slowly, p < 1 starts quickly).

  • sine: (1 − cos πt) / 2 (zero slope at both ends).

  • exponential: (e^{kt} − 1) / (e^k − 1) with shape k ≠ 0 (k > 0 starts slowly, k < 0 starts quickly).

Values:

enumerator linear#
enumerator smoothstep#
enumerator smootherstep#
enumerator power#
enumerator sine#
enumerator exponential#

Functions

double default_easing_shape(Easing easing)#

Returns the shape used when none is given: 2 for power, 4 for exponential, else 0.

double ease(Easing easing, double t, double shape = 0.0)#

Evaluates an easing curve.

Parameters:
  • easing – The curve.

  • t – The input; clamped to [0, 1].

  • shape – The exponent of power or the rate of exponential; ignored by the other curves.

Returns:

The eased value in [0, 1].

std::optional<double> ease_max_slope(Easing easing, double shape = 0.0)#

Returns the largest slope of an easing curve on [0, 1], or std::nullopt when it is unbounded (power with p < 1 is vertical at 0).

Easing easing_from_name(const std::string &name)#

Returns a curve by name (“linear”, “smoothstep”, “smootherstep”, “power”, “sine”, “exponential”).

Throws:

std::runtime_error – listing the valid names when the name is unknown.

std::string easing_name(Easing easing)#

Returns the name of a curve.

void validate_easing(Easing easing, double shape)#

Checks the shape of a curve.

Throws:

std::runtime_error – if power has a non-positive or non-finite exponent, or exponential a zero or non-finite rate.

Functions

PiecewiseSegment locate_segment(const std::vector<double> &knots, double value)#

Locates a value in ascending knots by binary search, clamping to the ends.

This is the one knot search for every piecewise table in OpenVCAD (transfer curves and LookupTableConverter’s LINEAR mode). Repeated knots are allowed: a value equal to a repeated knot lands on the last copy, so a zero-length segment is never returned.

Parameters:
  • knots – Knot positions in ascending order; must not be empty.

  • value – The value to locate.

Returns:

{0, 0} at or before the first knot, {last, 0} at or after the last one, otherwise the segment that holds the value (with knots[index] <= value < knots[index + 1]).

class PiecewiseCurve#
#include <piecewise_curve.h>

A scalar transfer curve through control points, interpolated linearly or smoothly.

Smooth interpolation is a monotone cubic Hermite spline (PCHIP, Fritsch–Butland tangents): C1, and between two control points it stays between their values, so it never overshoots. Before the first and after the last control point the curve holds the end values. Immutable and thread-safe.

Public Types

enum class Interpolation#

How the curve passes between control points.

Values:

enumerator linear#

Straight lines between control points.

enumerator smooth#

Monotone cubic Hermite spline (PCHIP).

Public Functions

double evaluate(double x) const#

Evaluates the curve.

Parameters:

x – The input value.

Returns:

The curve’s value at x; the end values outside the control points.

inline Interpolation interpolation() const#

Returns the interpolation.

Returns:

The interpolation mode.

inline const std::vector<double> &knots() const#

Returns the control x values in ascending order.

Returns:

The knots.

inline double max_slope() const#

Returns the largest |dy/dx| anywhere on the curve.

Returns:

The maximum absolute slope.

PiecewiseCurve(std::vector<std::pair<double, double>> points, Interpolation interpolation)#

Constructor.

Parameters:
  • points – Control points (x, y), in any order; at least two, with distinct finite x and finite y.

  • interpolation – Linear or smooth (monotone cubic).

Throws:

std::runtime_error – for fewer than two points, repeated x or non-finite values.

std::pair<double, double> value_range() const#

Returns the smallest and largest control value, which bound the whole curve.

Returns:

(min, max) of the control values.

inline const std::vector<double> &values() const#

Returns the control y values, in the order of knots().

Returns:

The values.

Private Functions

void compute_max_slope()#
void compute_tangents()#

Private Members

Interpolation m_interpolation#
double m_max_slope = 0.0#
std::vector<double> m_tangents#
std::vector<double> m_x#
std::vector<double> m_y#
struct PiecewiseSegment#
#include <piecewise_curve.h>

Where a value falls in a sorted list of knots: the segment [knots[index], knots[index + 1]) and the fraction t of the way along it.

t is 0 when the value sits exactly on knots[index], and always for values clamped to the first or last knot (index 0 or the last index).

Public Members

size_t index = 0#

Index of the knot that starts the segment.

double t = 0.0#

Fraction of the way along the segment, in [0, 1).

class ThreadUsageTracker#
#include <thread_usage_tracker.h>

Tracks distinct threads that participate in a parallel export stage.

Public Functions

size_t count() const#

The number of distinct threads recorded.

Returns:

The thread count.

void merge(const ThreadUsageTracker &other)#

Add every thread recorded by another tracker.

Parameters:

other – The tracker to merge in; merging a tracker into itself does nothing.

void record_current_thread()#

Record the calling thread. Safe to call from many threads at once.

void reset()#

Forget every recorded thread.

Private Members

mutable std::mutex m_mutex#
std::unordered_set<std::thread::id> m_thread_ids#