cam.basrelief

Contents

cam.basrelief#

BlenderCAM ‘basrelief.py’

Module to allow the creation of reliefs from Images or View Layers. (https://en.wikipedia.org/wiki/Relief#Bas-relief_or_low_relief)

Attributes#

Exceptions#

ReliefError

Common base class for all non-exit exceptions.

Classes#

BasReliefsettings

BASRELIEF_Panel

Bas Relief Panel

DoBasRelief

Calculate Bas Relief

ProblemAreas

Find Bas Relief Problem Areas

Functions#

copy_compbuf_data(inbuf, outbuf)

restrictbuf(inbuf, outbuf)

Restrict the resolution of an input buffer to match an output buffer.

prolongate(inbuf, outbuf)

Prolongate an input buffer to a larger output buffer.

idx(r, c, cols)

smooth(U, F, linbcgiterations, planar)

Smooth a matrix U using a filter F at a specified level.

calculate_defect(D, U, F)

Calculate the defect of a grid based on the input fields.

add_correction(U, C)

solve_pde_multigrid(F, U, vcycleiterations, ...)

Solve a partial differential equation using a multigrid method.

asolve(b, x)

atimes(x, res)

Apply a discrete Laplacian operator to a 2D array.

snrm(n, sx, itol)

Calculate the square root of the sum of squares or the maximum absolute

linbcg(n, b, x, itol, tol, itmax, iter, err, rows, ...)

Solve a linear system using the Biconjugate Gradient Method.

numpysave(a, iname)

Save a NumPy array as an image file in OpenEXR format.

numpytoimage(a, iname)

Convert a NumPy array to a Blender image.

imagetonumpy(i)

Convert an image to a NumPy array.

tonemap(i, exponent)

Apply tone mapping to an image array.

vert(column, row, z, XYscaling, Zscaling)

Create a single vertex in 3D space.

buildMesh(mesh_z, br)

Build a 3D mesh from a height map and apply transformations.

renderScene(width, height, bit_diameter, ...)

Render a scene using Blender's Cycles engine.

problemAreas(br)

Process image data to identify problem areas based on silhouette

relief(br)

Process an image to enhance relief features.

get_panels()

Retrieve a tuple of panel settings and related components.

register()

Register the necessary classes and properties for the add-on.

unregister()

Unregister all panels and remove basreliefsettings from the Scene type.

Module Contents#

EPS = 1e-32[source]#
PRECISION = 5[source]#
NUMPYALG = False[source]#
copy_compbuf_data(inbuf, outbuf)[source]#
restrictbuf(inbuf, outbuf)[source]#

Restrict the resolution of an input buffer to match an output buffer.

This function scales down the input buffer inbuf to fit the dimensions of the output buffer outbuf. It computes the average of the neighboring pixels in the input buffer to create a downsampled version in the output buffer. The method used for downsampling can vary based on the dimensions of the input and output buffers, utilizing either a simple averaging method or a more complex numpy-based approach.

Parameters:
  • inbuf (numpy.ndarray) – The input buffer to be downsampled, expected to be a 2D array.

  • outbuf (numpy.ndarray) – The output buffer where the downsampled result will be stored, also expected to be a 2D array.

Returns:

The function modifies outbuf in place.

Return type:

None

prolongate(inbuf, outbuf)[source]#

Prolongate an input buffer to a larger output buffer.

This function takes an input buffer and enlarges it to fit the dimensions of the output buffer. It uses different methods to achieve this based on the scaling factors derived from the input and output dimensions. The function can handle specific cases where the scaling factors are exactly 0.5, as well as a general case that applies a bilinear interpolation technique for resizing.

Parameters:
  • inbuf (numpy.ndarray) – The input buffer to be enlarged, expected to be a 2D array.

  • outbuf (numpy.ndarray) – The output buffer where the enlarged data will be stored, expected to be a 2D array of larger dimensions than inbuf.

idx(r, c, cols)[source]#
smooth(U, F, linbcgiterations, planar)[source]#

Smooth a matrix U using a filter F at a specified level.

This function applies a smoothing operation on the input matrix U using the filter F. It utilizes the linear Biconjugate Gradient method for the smoothing process. The number of iterations for the linear BCG method is specified by linbcgiterations, and the planar parameter indicates whether the operation is to be performed in a planar manner.

Parameters:
  • U (numpy.ndarray) – The input matrix to be smoothed.

  • F (numpy.ndarray) – The filter used for smoothing.

  • linbcgiterations (int) – The number of iterations for the linear BCG method.

  • planar (bool) – A flag indicating whether to perform the operation in a planar manner.

Returns:

This function modifies the input matrix U in place.

Return type:

None

calculate_defect(D, U, F)[source]#

Calculate the defect of a grid based on the input fields.

This function computes the defect values for a grid by comparing the input field F with the values in the grid U. The defect is calculated using finite difference approximations, taking into account the neighboring values in the grid. The results are stored in the output array D, which is modified in place.

Parameters:
  • D (ndarray) – A 2D array where the defect values will be stored.

  • U (ndarray) – A 2D array representing the current state of the grid.

  • F (ndarray) – A 2D array representing the target field to compare against.

Returns:

The function modifies the array D in place and does not return a

value.

Return type:

None

add_correction(U, C)[source]#
solve_pde_multigrid(F, U, vcycleiterations, linbcgiterations, smoothiterations, mins, levels, useplanar, planar)[source]#

Solve a partial differential equation using a multigrid method.

This function implements a multigrid algorithm to solve a given partial differential equation (PDE). It operates on a grid of varying resolutions, applying smoothing and correction steps iteratively to converge towards the solution. The algorithm consists of several key phases: restriction of the right-hand side to coarser grids, solving on the coarsest grid, and then interpolating corrections back to finer grids. The process is repeated for a specified number of V-cycle iterations.

Parameters:
  • F (numpy.ndarray) – The right-hand side of the PDE represented as a 2D array.

  • U (numpy.ndarray) – The initial guess for the solution, which will be updated in place.

  • vcycleiterations (int) – The number of V-cycle iterations to perform.

  • linbcgiterations (int) – The number of iterations for the linear solver used in smoothing.

  • smoothiterations (int) – The number of smoothing iterations to apply at each level.

  • mins (int) – Minimum grid size (not used in the current implementation).

  • levels (int) – The number of levels in the multigrid hierarchy.

  • useplanar (bool) – A flag indicating whether to use planar information during the solution process.

  • planar (numpy.ndarray) – A 2D array indicating planar information for the grid.

Returns:

The function modifies the input array U in place to contain the final

solution.

Return type:

None

Note

The function assumes that the input arrays F and U have compatible shapes and that the planar array is appropriately defined for the problem context.

asolve(b, x)[source]#
atimes(x, res)[source]#

Apply a discrete Laplacian operator to a 2D array.

This function computes the discrete Laplacian of a given 2D array x and stores the result in the res array. The Laplacian is calculated using finite difference methods, which involve summing the values of neighboring elements and applying specific boundary conditions for the edges and corners of the array.

Parameters:
  • x (numpy.ndarray) – A 2D array representing the input values.

  • res (numpy.ndarray) – A 2D array where the result will be stored. It must have the same shape as x.

Returns:

The result is stored directly in the res array.

Return type:

None

snrm(n, sx, itol)[source]#

Calculate the square root of the sum of squares or the maximum absolute value.

This function computes a value based on the input parameters. If the tolerance level (itol) is less than or equal to 3, it calculates the square root of the sum of squares of the input array (sx). If the tolerance level is greater than 3, it returns the maximum absolute value from the input array.

Parameters:
  • n (int) – An integer parameter, though it is not used in the current implementation.

  • sx (numpy.ndarray) – A numpy array of numeric values.

  • itol (int) – An integer that determines which calculation to perform.

Returns:

The square root of the sum of squares if itol <= 3, otherwise the

maximum absolute value.

Return type:

float

linbcg(n, b, x, itol, tol, itmax, iter, err, rows, cols, planar)[source]#

Solve a linear system using the Biconjugate Gradient Method.

This function implements the Biconjugate Gradient Method as described in Numerical Recipes in C. It iteratively refines the solution to a linear system of equations defined by the matrix-vector product. The method is particularly useful for large, sparse systems where direct methods are inefficient. The function takes various parameters to control the iteration process and convergence criteria.

Parameters:
  • n (int) – The size of the linear system.

  • b (numpy.ndarray) – The right-hand side vector of the linear system.

  • x (numpy.ndarray) – The initial guess for the solution vector.

  • itol (int) – The type of norm to use for convergence checks.

  • tol (float) – The tolerance for convergence.

  • itmax (int) – The maximum number of iterations allowed.

  • iter (int) – The current iteration count (should be initialized to 0).

  • err (float) – The error estimate (should be initialized).

  • rows (int) – The number of rows in the matrix.

  • cols (int) – The number of columns in the matrix.

  • planar (bool) – A flag indicating if the problem is planar.

Returns:

The solution is stored in the input array x.

Return type:

None

numpysave(a, iname)[source]#

Save a NumPy array as an image file in OpenEXR format.

This function takes a NumPy array and saves it as an image file using Blender’s rendering capabilities. It configures the image settings to use the OpenEXR format with black and white color mode and a color depth of 32 bits. The rendered image is saved to the specified filename.

Parameters:
  • a (numpy.ndarray) – The NumPy array to be saved as an image.

  • iname (str) – The filename (including path) where the image will be saved.

numpytoimage(a, iname)[source]#

Convert a NumPy array to a Blender image.

This function takes a NumPy array and converts it into a Blender image. It first checks if an image with the specified name and dimensions already exists in Blender. If it does, that image is used; otherwise, a new image is created with the specified name and dimensions. The function then reshapes the NumPy array to match the image format and assigns the pixel data to the image.

Parameters:
  • a (numpy.ndarray) – A 2D NumPy array representing the pixel data of the image.

  • iname (str) – The name to assign to the Blender image.

Returns:

The Blender image created or modified with the pixel data from the NumPy

array.

Return type:

bpy.types.Image

imagetonumpy(i)[source]#

Convert an image to a NumPy array.

This function takes an image object and converts its pixel data into a NumPy array. It first retrieves the pixel data from the image, then reshapes and rearranges it to match the image’s dimensions. The resulting array is structured such that the height and width of the image are preserved, and the color channels are appropriately ordered.

Parameters:

i (Image) – An image object that contains pixel data.

Returns:

A 2D NumPy array representing the pixel data of the image.

Return type:

numpy.ndarray

Note

The function optimizes performance by directly accessing pixel data instead of using slower methods.

tonemap(i, exponent)[source]#

Apply tone mapping to an image array.

This function performs tone mapping on the input image array by first filtering out values that are excessively high, which may indicate that the depth buffer was not written correctly. It then normalizes the values between the minimum and maximum heights, and finally applies an exponentiation to adjust the brightness of the image.

Parameters:
  • i (numpy.ndarray) – A numpy array representing the image data.

  • exponent (float) – The exponent used for adjusting the brightness of the normalized image.

Returns:

The function modifies the input array in place.

Return type:

None

vert(column, row, z, XYscaling, Zscaling)[source]#

Create a single vertex in 3D space.

This function calculates the 3D coordinates of a vertex based on the provided column and row values, as well as scaling factors for the X-Y and Z dimensions. The resulting coordinates are scaled accordingly to fit within a specified 3D space.

Parameters:
  • column (float) – The column value representing the X coordinate.

  • row (float) – The row value representing the Y coordinate.

  • z (float) – The Z coordinate value.

  • XYscaling (float) – The scaling factor for the X and Y coordinates.

  • Zscaling (float) – The scaling factor for the Z coordinate.

Returns:

A tuple containing the scaled X, Y, and Z coordinates.

Return type:

tuple

buildMesh(mesh_z, br)[source]#

Build a 3D mesh from a height map and apply transformations.

This function constructs a 3D mesh based on the provided height map (mesh_z) and applies various transformations such as scaling and positioning based on the parameters defined in the br object. It first removes any existing BasReliefMesh objects from the scene, then creates a new mesh from the height data, and finally applies decimation if the specified ratio is within acceptable limits.

Parameters:
  • mesh_z (numpy.ndarray) – A 2D array representing the height values for the mesh vertices.

  • br (object) – An object containing properties for width, height, thickness, justification, and decimation ratio.

renderScene(width, height, bit_diameter, passes_per_radius, make_nodes, view_layer)[source]#

Render a scene using Blender’s Cycles engine.

This function switches the rendering engine to Cycles, sets up the necessary nodes for depth rendering if specified, and configures the render resolution based on the provided parameters. It ensures that the scene is in object mode before rendering and restores the original rendering engine after the process is complete.

Parameters:
  • width (int) – The width of the render in pixels.

  • height (int) – The height of the render in pixels.

  • bit_diameter (float) – The diameter used to calculate the number of passes.

  • passes_per_radius (int) – The number of passes per radius for rendering.

  • make_nodes (bool) – A flag indicating whether to create render nodes.

  • view_layer (str) – The name of the view layer to be rendered.

Returns:

This function does not return any value.

Return type:

None

problemAreas(br)[source]#

Process image data to identify problem areas based on silhouette thresholds.

This function analyzes an image and computes gradients to detect and recover silhouettes based on specified parameters. It utilizes various settings from the provided br object to adjust the processing, including silhouette thresholds, scaling factors, and iterations for smoothing and recovery. The function also handles image scaling and applies a gradient mask if specified. The resulting data is then converted back into an image format for further use.

Parameters:

br (object) – An object containing various parameters for processing, including: - use_image_source (bool): Flag to determine if a specific image source should be used. - source_image_name (str): Name of the source image if use_image_source is True. - silhouette_threshold (float): Threshold for silhouette detection. - recover_silhouettes (bool): Flag to indicate if silhouettes should be recovered. - silhouette_scale (float): Scaling factor for silhouette recovery. - min_gridsize (int): Minimum grid size for processing. - smooth_iterations (int): Number of iterations for smoothing. - vcycle_iterations (int): Number of iterations for V-cycle processing. - linbcg_iterations (int): Number of iterations for linear BCG processing. - use_planar (bool): Flag to indicate if planar processing should be used. - gradient_scaling_mask_use (bool): Flag to indicate if a gradient scaling mask should be used. - gradient_scaling_mask_name (str): Name of the gradient scaling mask image. - depth_exponent (float): Exponent for depth adjustment. - silhouette_exponent (int): Exponent for silhouette recovery. - attenuation (float): Attenuation factor for processing.

Returns:

The function does not return a value but processes the image data and

saves the result.

Return type:

None

relief(br)[source]#

Process an image to enhance relief features.

This function takes an input image and applies various processing techniques to enhance the relief features based on the provided parameters. It utilizes gradient calculations, silhouette recovery, and optional detail enhancement through Fourier transforms. The processed image is then used to build a mesh representation.

Parameters:

br (object) – An object containing various parameters for the relief processing, including: - use_image_source (bool): Whether to use a specified image source. - source_image_name (str): The name of the source image. - silhouette_threshold (float): Threshold for silhouette detection. - recover_silhouettes (bool): Flag to indicate if silhouettes should be recovered. - silhouette_scale (float): Scale factor for silhouette recovery. - min_gridsize (int): Minimum grid size for processing. - smooth_iterations (int): Number of iterations for smoothing. - vcycle_iterations (int): Number of iterations for V-cycle processing. - linbcg_iterations (int): Number of iterations for linear BCG processing. - use_planar (bool): Flag to indicate if planar processing should be used. - gradient_scaling_mask_use (bool): Flag to indicate if a gradient scaling mask should be used. - gradient_scaling_mask_name (str): Name of the gradient scaling mask image. - depth_exponent (float): Exponent for depth adjustment. - attenuation (float): Attenuation factor for the processing. - detail_enhancement_use (bool): Flag to indicate if detail enhancement should be applied. - detail_enhancement_freq (float): Frequency for detail enhancement. - detail_enhancement_amount (float): Amount of detail enhancement to apply.

Returns:

The function processes the image and builds a mesh but does not return a

value.

Return type:

None

Raises:

ReliefError – If the input image is blank or invalid.

class BasReliefsettings[source]#

Bases: bpy.types.PropertyGroup

use_image_source: BoolProperty(name='Use Image Source', description='', default=False)[source]#
source_image_name: StringProperty(name='Image Source', description='image source')[source]#
view_layer_name: StringProperty(name='View Layer Source', description='Make a bas-relief from whatever is on this view layer')[source]#
bit_diameter: FloatProperty(name='Diameter of Ball End in mm', description='Diameter of bit which will be used for carving', min=0.01, max=50.0, default=3.175, precision=PRECISION)[source]#
pass_per_radius: IntProperty(name='Passes per Radius', description='Amount of passes per radius\n(more passes, more mesh precision)', default=2, min=1, max=10)[source]#
widthmm: IntProperty(name='Desired Width in mm', default=200, min=5, max=4000)[source]#
heightmm: IntProperty(name='Desired Height in mm', default=150, min=5, max=4000)[source]#
thicknessmm: IntProperty(name='Thickness in mm', default=15, min=5, max=100)[source]#
justifyx: EnumProperty(name='X', items=['1', 'Left', '', 0, '-0.5', 'Centered', '', 1, '-1', 'Right', '', 2], default='-1')[source]#
justifyy: EnumProperty(name='Y', items=['1', 'Bottom', '', 0, '-0.5', 'Centered', '', 2, '-1', 'Top', '', 1], default='-1')[source]#
justifyz: EnumProperty(name='Z', items=['-1', 'Below 0', '', 0, '-0.5', 'Centered', '', 2, '1', 'Above 0', '', 1], default='-1')[source]#
depth_exponent: FloatProperty(name='Depth Exponent', description='Initial depth map is taken to this power. Higher = sharper relief', min=0.5, max=10.0, default=1.0, precision=PRECISION)[source]#
silhouette_threshold: FloatProperty(name='Silhouette Threshold', description='Silhouette threshold', min=1e-06, max=1.0, default=0.003, precision=PRECISION)[source]#
recover_silhouettes: BoolProperty(name='Recover Silhouettes', description='', default=True)[source]#
silhouette_scale: FloatProperty(name='Silhouette Scale', description='Silhouette scale', min=1e-06, max=5.0, default=0.3, precision=PRECISION)[source]#
silhouette_exponent: IntProperty(name='Silhouette Square Exponent', description='If lower, true depth distances between objects will be more visibe in the relief', default=3, min=0, max=5)[source]#
attenuation: FloatProperty(name='Gradient Attenuation', description='Gradient attenuation', min=1e-06, max=100.0, default=1.0, precision=PRECISION)[source]#
min_gridsize: IntProperty(name='Minimum Grid Size', default=16, min=2, max=512)[source]#
smooth_iterations: IntProperty(name='Smooth Iterations', default=1, min=1, max=64)[source]#
vcycle_iterations: IntProperty(name='V-Cycle Iterations', description='Set higher for planar constraint', default=2, min=1, max=128)[source]#
linbcg_iterations: IntProperty(name='LINBCG Iterations', description='Set lower for flatter relief, and when using planar constraint', default=5, min=1, max=64)[source]#
use_planar: BoolProperty(name='Use Planar Constraint', description='', default=False)[source]#
gradient_scaling_mask_use: BoolProperty(name='Scale Gradients with Mask', description='', default=False)[source]#
decimate_ratio: FloatProperty(name='Decimate Ratio', description='Simplify the mesh using the Decimate modifier. The lower the value the more simplyfied', min=0.01, max=1.0, default=0.1, precision=PRECISION)[source]#
gradient_scaling_mask_name: StringProperty(name='Scaling Mask Name', description='Mask name')[source]#
scale_down_before_use: BoolProperty(name='Scale Down Image Before Processing', description='', default=False)[source]#
scale_down_before: FloatProperty(name='Image Scale', description='Image scale', min=0.025, max=1.0, default=0.5, precision=PRECISION)[source]#
detail_enhancement_use: BoolProperty(name='Enhance Details', description='Enhance details by frequency analysis', default=False)[source]#
detail_enhancement_amount: FloatProperty(name='Amount', description='Image scale', min=0.025, max=1.0, default=0.5, precision=PRECISION)[source]#
advanced: BoolProperty(name='Advanced Options', description='Show advanced options', default=True)[source]#
class BASRELIEF_Panel[source]#

Bases: bpy.types.Panel

Bas Relief Panel

bl_label = 'Bas Relief'[source]#
bl_idname = 'WORLD_PT_BASRELIEF'[source]#
bl_space_type = 'PROPERTIES'[source]#
bl_region_type = 'WINDOW'[source]#
bl_context = 'render'[source]#
COMPAT_ENGINES[source]#
classmethod poll(context)[source]#

Check if the current render engine is compatible.

This class method checks whether the render engine specified in the provided context is included in the list of compatible engines. It accesses the render settings from the context and verifies if the engine is part of the predefined compatible engines.

Parameters:

context (Context) – The context containing the scene and render settings.

Returns:

True if the render engine is compatible, False otherwise.

Return type:

bool

draw(context)[source]#

Draw the user interface for the bas relief settings.

This method constructs the layout for the bas relief settings in the Blender user interface. It includes various properties and options that allow users to configure the bas relief calculations, such as selecting images, adjusting parameters, and setting justification options. The layout is dynamically updated based on user selections, providing a comprehensive interface for manipulating bas relief settings.

Parameters:

context (bpy.context) – The context in which the UI is being drawn.

Returns:

This method does not return any value; it modifies the layout directly.

Return type:

None

exception ReliefError[source]#

Bases: Exception

Common base class for all non-exit exceptions.

class DoBasRelief[source]#

Bases: bpy.types.Operator

Calculate Bas Relief

bl_idname = 'scene.calculate_bas_relief'[source]#
bl_label = 'Calculate Bas Relief'[source]#
bl_options[source]#
processes = [][source]#
execute(context)[source]#

Execute the relief rendering process based on the provided context.

This function retrieves the scene and its associated bas relief settings. It checks if an image source is being used and sets the view layer name accordingly. The function then attempts to render the scene and generate the relief. If any errors occur during these processes, they are reported, and the operation is canceled.

Parameters:

context – The context in which the function is executed.

Returns:

A dictionary indicating the result of the operation, either

Return type:

dict

class ProblemAreas[source]#

Bases: bpy.types.Operator

Find Bas Relief Problem Areas

bl_idname = 'scene.problemareas_bas_relief'[source]#
bl_label = 'Problem Areas Bas Relief'[source]#
bl_options[source]#
processes = [][source]#
execute(context)[source]#

Execute the operation related to the bas relief settings in the current scene.

This method retrieves the current scene from the Blender context and accesses the bas relief settings. It then calls the problemAreas function to perform operations related to those settings. The method concludes by returning a status indicating that the operation has finished successfully.

Parameters:

context (bpy.context) – The current Blender context, which provides access

Returns:

A dictionary with a status key indicating the operation result, specifically {‘FINISHED’}.

Return type:

dict

get_panels()[source]#

Retrieve a tuple of panel settings and related components.

This function returns a tuple containing various components related to Bas Relief settings. The components include BasReliefsettings, BASRELIEF_Panel, DoBasRelief, and ProblemAreas, which are likely used in the context of a graphical user interface or a specific application domain.

Returns:

A tuple containing the BasReliefsettings, BASRELIEF_Panel, DoBasRelief, and ProblemAreas components.

Return type:

tuple

register()[source]#

Register the necessary classes and properties for the add-on.

This function registers all the panels defined in the add-on by iterating through the list of panels returned by the get_panels() function. It also adds a new property, basreliefsettings, to the Scene type, which is a pointer property that references the BasReliefsettings class. This setup is essential for the proper functioning of the add-on, allowing users to access and modify the settings related to bas relief.

unregister()[source]#

Unregister all panels and remove basreliefsettings from the Scene type.

This function iterates through all registered panels and unregisters each one using Blender’s utility functions. Additionally, it removes the basreliefsettings attribute from the Scene type, ensuring that any settings related to bas relief are no longer accessible in the current Blender session.