voxcity.exporter

Submodules

Classes

EnvimetExporter

Exporter adapter to write a VoxCity model to ENVI-met INX format.

MagicaVoxelExporter

Exporter adapter to write VoxCity voxels as MagicaVoxel .vox chunks.

OBJExporter

Exporter that writes mesh collections or trimesh dicts to OBJ/MTL.

CityLesExporter

Exporter adapter to write a VoxCity model to CityLES text files.

NetCDFExporter

Exporter adapter to write a VoxCity voxel grid to NetCDF.

Exporter

Base class for protocol classes.

Functions

export_inx(city, output_directory[, file_basename, ...])

Export model data to ENVI-met INX file format.

generate_edb_file(**kwargs)

Generate ENVI-met database file for 3D plants.

generate_lad_profile(height, trunk_height_ratio[, lad])

Generate leaf area density profile for a plant.

export_magicavoxel_vox(array, output_dir[, ...])

Export a voxel model to MagicaVoxel .vox format.

export_large_voxel_model(array, color_map, output_prefix)

Export a large voxel model by splitting it into multiple .vox files.

export_obj(array, output_dir, file_name[, voxel_size, ...])

Export a voxel array to OBJ format with materials and proper face orientations.

grid_to_obj(value_array_ori, dem_array_ori, ...[, ...])

Converts a 2D array of values and a corresponding DEM array to an OBJ file

export_netcdf_to_obj(voxcity_nc, scalar_nc, ...[, ...])

Export two OBJ/MTL files using the same local meter frame:

convert_colormap_indices(original_map)

Convert a color map with arbitrary indices to sequential indices starting from 0.

mesh_faces(mask, layer_index, axis, ...)

Performs greedy meshing on a 2D mask layer and adds optimized faces to the mesh.

create_face_vertices(coords, positive_direction, axis)

Helper function to create properly oriented face vertices for OBJ export.

export_cityles(city[, output_directory, ...])

Export VoxCity data to CityLES format

voxel_to_xarray_dataset(→ xarray.Dataset)

Create an xarray Dataset from a VoxCity voxel grid.

save_voxel_netcdf(→ str)

Save a VoxCity voxel grid to a NetCDF file.

Package Contents

voxcity.exporter.export_inx(city: voxcity.models.VoxCity, output_directory: str, file_basename: str = 'voxcity', land_cover_source: str | None = None, **kwargs)[source]

Export model data to ENVI-met INX file format.

This is the main function for exporting voxel city data to ENVI-met format. It coordinates the entire export process from grid preparation to file saving.

Parameters:
  • city (VoxCity) – VoxCity instance to export

  • output_directory (str) – Directory to save output

  • file_basename (str) – Base filename (without extension)

  • land_cover_source (str | None) – Optional override for land cover source; defaults to city.extras

  • **kwargs

    Additional keyword arguments: - envimet_mapping (dict): Custom mapping from land cover class indices

    (1-based) to ENVI-met IDs. Each value is a dict with optional ‘veg’ (simple plant ID) and/or ‘mat’ (soil profile ID) keys. Tree vegetation (key 5 ‘veg’) is ignored. Example: {2: {'veg': '0200H1'}, 12: {'mat': '0200AR'}}

    • rooftop_vegetation (bool): If True, keep 1D vegetation (grass, shrubs) on building cells (e.g. green roofs). Default False (remove them).

    • Other kwargs are passed to create_xml_content().

Notes

  • Creates output directory if it doesn’t exist

  • Handles grid preparation and transformation

  • Generates complete INX file with all required data

  • Uses standardized file naming convention

voxcity.exporter.generate_edb_file(**kwargs)[source]

Generate ENVI-met database file for 3D plants.

Creates a plant database file (EDB) containing definitions for trees of different heights with customizable leaf area density profiles.

Parameters:

**kwargs

Keyword arguments: - lad (float): Leaf area density in m²/m³ (default 1.0) - trunk_height_ratio (float): Ratio of trunk height to total height

(default 11.76/19.98)

  • output_dir (str): Directory to save the EDB file (default: current directory)

Notes

  • Generates plants for heights from 1-50m

  • Uses standardized plant IDs in format ‘HxxW01’

  • Includes physical properties like wood density

  • Sets seasonal variation profiles

  • Creates complete ENVI-met plant database format

voxcity.exporter.generate_lad_profile(height, trunk_height_ratio, lad='1.00000')[source]

Generate leaf area density profile for a plant.

Creates a vertical profile of leaf area density (LAD) values for ENVI-met plant definitions, accounting for trunk space and crown distribution.

Parameters:
  • height (int) – Total height of plant in meters

  • trunk_height_ratio (float) – Ratio of trunk height to total height

  • lad (str) – Leaf area density value as string (default ‘1.00000’)

Returns:

LAD profile data formatted for ENVI-met EDB file

Return type:

str

Notes

  • LAD values start above trunk height

  • Uses 5-space indentation for ENVI-met format

  • Profile follows format: “z-level,x,y,LAD”

voxcity.exporter.export_magicavoxel_vox(array, output_dir, base_filename='chunk', voxel_color_map=None)[source]

Export a voxel model to MagicaVoxel .vox format.

This is the main entry point for voxel model export. It handles: 1. Color map management (using default if none provided) 2. Color index optimization 3. Large model splitting and export 4. Progress reporting

Parameters:
  • array (numpy.ndarray | VoxCity) – 3D array containing voxel data or a VoxCity instance. When a VoxCity is provided, its voxel classes are exported.

  • output_dir (str) – Directory to save the .vox files. Will be created if it doesn’t exist.

  • base_filename (str, optional) – Base name for the output files. Defaults to ‘chunk’. Used when model is split into multiple files.

  • voxel_color_map (dict, optional) – Dictionary mapping indices to RGB color values. If None, uses default color map from visualizer. Each value should be a list of [R,G,B] values (0-255).

Note

  • Large models are automatically split into multiple files

  • Color mapping is optimized and made sequential

  • Progress information is printed to stdout

voxcity.exporter.export_large_voxel_model(array, color_map, output_prefix, max_size=255, base_filename='chunk')[source]

Export a large voxel model by splitting it into multiple .vox files.

This function handles models of any size by: 1. Creating the output directory if needed 2. Splitting the model into manageable chunks 3. Saving each chunk as a separate .vox file 4. Maintaining consistent color mapping across all chunks

Parameters:
  • array (numpy.ndarray) – 3D array containing voxel data. Can be any size, will be split into chunks if needed.

  • color_map (dict) – Dictionary mapping indices to RGB color values. Each value should be a list of [R,G,B] values (0-255).

  • output_prefix (str) – Directory to save the .vox files. Will be created if it doesn’t exist.

  • max_size (int, optional) – Maximum size allowed for each dimension. Defaults to 255 (MagicaVoxel’s limit is 256).

  • base_filename (str, optional) – Base name for the output files. Defaults to ‘chunk’. Final filenames will be {base_filename}_{i}_{j}_{k}.vox

Returns:

(value_mapping, palette)
  • value_mapping: dict mapping original indices to MagicaVoxel indices

  • palette: numpy.ndarray of shape (256,4) containing RGBA values

Return type:

tuple

Example

>>> array = np.ones((500,500,500))
>>> color_map = {1: [255,0,0]}
>>> export_large_voxel_model(array, color_map, "output/model")
# Creates files like: output/model/chunk_0_0_0.vox, chunk_0_0_1.vox, etc.
voxcity.exporter.export_obj(array, output_dir, file_name, voxel_size=None, voxel_color_map=None)[source]

Export a voxel array to OBJ format with materials and proper face orientations.

This function converts a 3D voxel array into a complete OBJ file with materials, performing mesh optimization and ensuring proper face orientations. It generates both OBJ and MTL files with all necessary components for rendering.

Parameters:
  • array (ndarray | VoxCity) – 3D numpy array of voxel values or a VoxCity instance. Non-zero values indicate voxel presence and material type.

  • output_dir (str) – Directory to save the OBJ and MTL files. Will be created if it doesn’t exist.

  • file_name (str) – Base name for the output files. Will be used for both .obj and .mtl files.

  • voxel_size (float | None) – Size of each voxel in meters. If a VoxCity is provided, this is inferred from the object and this parameter is ignored.

  • voxel_color_map (dict, optional) – Dictionary mapping voxel values to RGB colors. If None, uses default color map. Colors should be RGB lists (0-255).

Notes

  • Generates optimized mesh using greedy meshing

  • Creates complete OBJ file with vertices, normals, and faces

  • Generates MTL file with material definitions

  • Handles proper face orientation and winding order

  • Supports color mapping for visualization

  • Uses consistent coordinate system throughout

File Format Details:

OBJ file contains: - Vertex coordinates (v) - Normal vectors (vn) - Material references (usemtl) - Face definitions (f)

MTL file contains: - Material names and colors - Ambient, diffuse, and specular properties - Transparency settings - Illumination model definitions

voxcity.exporter.grid_to_obj(value_array_ori, dem_array_ori, output_dir, file_name, cell_size, offset, colormap_name='viridis', num_colors=256, alpha=1.0, vmin=None, vmax=None)[source]

Converts a 2D array of values and a corresponding DEM array to an OBJ file with specified colormap, transparency, and value range.

This function creates a 3D visualization of 2D grid data by using elevation data and color mapping. It’s particularly useful for visualizing terrain data, analysis results, or any 2D data that should be displayed with elevation.

Parameters:
  • value_array_ori (ndarray) – 2D array of values to visualize. These values will be mapped to colors using the specified colormap.

  • dem_array_ori (ndarray) – 2D array of DEM values corresponding to value_array. Provides elevation data for the 3D visualization.

  • output_dir (str) – Directory to save the OBJ and MTL files. Will be created if it doesn’t exist.

  • file_name (str) – Base name for the output files. Used for both .obj and .mtl files.

  • cell_size (float) – Size of each cell in the grid (e.g., in meters). Used to scale the model to real-world units.

  • offset (float) – Elevation offset added after quantization. Useful for adjusting the base height of the model.

  • colormap_name (str, optional) – Name of the Matplotlib colormap to use. Defaults to ‘viridis’. Must be a valid Matplotlib colormap name.

  • num_colors (int, optional) – Number of discrete colors to use from the colormap. Defaults to 256. Higher values give smoother color transitions.

  • alpha (float, optional) – Transparency value between 0.0 (transparent) and 1.0 (opaque). Defaults to 1.0 (fully opaque).

  • vmin (float, optional) – Minimum value for colormap normalization. If None, uses data minimum. Used to control color mapping range.

  • vmax (float, optional) – Maximum value for colormap normalization. If None, uses data maximum. Used to control color mapping range.

Notes

  • Automatically handles NaN values in input arrays

  • Creates triangulated mesh for proper rendering

  • Supports transparency and color mapping

  • Generates complete OBJ and MTL files

  • Maintains consistent coordinate system

  • Optimizes mesh generation for large grids

Raises:

ValueError – If vmin equals vmax or if colormap_name is invalid

voxcity.exporter.export_netcdf_to_obj(voxcity_nc, scalar_nc, lonlat_txt, output_dir, vox_base_filename='voxcity_objects', tm_base_filename='tm_isosurfaces', scalar_var='tm', scalar_building_value=-999.99, scalar_building_tol=0.0001, stride_vox=(1, 1, 1), stride_scalar=(1, 1, 1), contour_levels=24, cmap_name='magma', vmin=None, vmax=None, iso_vmin=None, iso_vmax=None, greedy_vox=True, vox_voxel_size=None, scalar_spacing=None, opacity_points=None, max_opacity=0.1, classes_to_show=None, voxel_color_scheme='default', max_faces_warn=1000000, export_vox_base=True)[source]

Export two OBJ/MTL files using the same local meter frame: - VoxCity voxels: opaque, per-class color, fixed face winding and normals - Scalar iso-surfaces: colormap colors with variable transparency

The two outputs share the same XY origin and axes (X east, Y north, Z up), anchored at the minimum lon/lat of the VoxCity bounding rectangle.

Parameters:
  • voxcity_nc (str) – Path to VoxCity NetCDF (must include variable ‘voxels’ and coords ‘x’,’y’,’z’).

  • scalar_nc (str) – Path to scalar NetCDF containing variable specified by scalar_var.

  • lonlat_txt (str) – Text file with columns: i j lon lat (1-based indices) describing the scalar grid georef.

  • output_dir (str) – Directory to write results.

  • vox_base_filename (str) – Base filename for VoxCity OBJ/MTL.

  • tm_base_filename (str) – Base filename for scalar iso-surfaces OBJ/MTL.

  • scalar_var (str) – Name of scalar variable in scalar_nc.

  • scalar_building_value (float) – Value used in scalar field to mark buildings (to be masked).

  • scalar_building_tol (float) – Tolerance for building masking (isclose).

  • stride_vox (tuple[int,int,int]) – Downsampling strides for VoxCity (z,y,x) in voxels.

  • stride_scalar (tuple[int,int,int]) – Downsampling strides for scalar (k,j,i).

  • contour_levels (int) – Number of iso-surface levels between vmin and vmax.

  • cmap_name (str) – Matplotlib colormap name for iso-surfaces.

  • vmin (float|None) – Minimum scalar value for color mapping and iso range. If None, inferred.

  • vmax (float|None) – Maximum scalar value for color mapping and iso range. If None, inferred.

  • iso_vmin (float|None) – Minimum scalar value to generate iso-surface levels. If None, uses vmin.

  • iso_vmax (float|None) – Maximum scalar value to generate iso-surface levels. If None, uses vmax.

  • greedy_vox (bool) – If True, use greedy meshing for VoxCity faces to reduce triangles.

  • vox_voxel_size (float|tuple[float,float,float]|None) – If provided, overrides VoxCity voxel spacing for X,Y,Z respectively in meters. A single float applies to all axes.

  • scalar_spacing (tuple[float,float,float]|None) – If provided, overrides scalar grid spacing (dx,dy,dz) used for iso-surface generation. Values are in meters.

  • opacity_points (list[tuple[float,float]]|None) – Transfer function control points (value, alpha in [0..1]).

  • max_opacity (float) – Global max opacity multiplier for iso-surfaces (0..1).

  • classes_to_show (set[int]|None) – Optional subset of voxel classes to export; None -> all present (except 0).

  • voxel_color_scheme (str) – Color scheme name passed to get_voxel_color_map.

  • max_faces_warn (int) – Warn if a single class exceeds this many faces.

  • export_vox_base (bool) – If False, skip exporting VoxCity OBJ/MTL; VoxCity input is still used to define the shared coordinate system for scalar OBJ.

Returns:

Paths of written files: keys ‘vox_obj’,’vox_mtl’,’tm_obj’,’tm_mtl’ (values may be None).

Return type:

dict

voxcity.exporter.convert_colormap_indices(original_map)[source]

Convert a color map with arbitrary indices to sequential indices starting from 0.

This function takes a color map with arbitrary integer keys and creates a new map with sequential indices starting from 0, maintaining the original color values. This is useful for ensuring consistent material indexing in OBJ files.

Parameters:

original_map (dict) – Dictionary with integer keys and RGB color value lists. Each value should be a list of 3 integers (0-255) representing RGB colors.

Returns:

New color map with sequential indices starting from 0.

The values maintain their original RGB color assignments.

Return type:

dict

Example

>>> original = {5: [255, 0, 0], 10: [0, 255, 0], 15: [0, 0, 255]}
>>> new_map = convert_colormap_indices(original)
>>> _logger.info(new_map)
{0: [255, 0, 0], 1: [0, 255, 0], 2: [0, 0, 255]}
voxcity.exporter.mesh_faces(mask, layer_index, axis, positive_direction, normal_idx, voxel_size_m, vertex_dict, vertex_list, faces_per_material, voxel_value_to_material)[source]

Performs greedy meshing on a 2D mask layer and adds optimized faces to the mesh.

This function implements a greedy meshing algorithm to combine adjacent voxels into larger faces, reducing the total number of faces in the final mesh while maintaining visual accuracy. It processes each layer of voxels and generates optimized faces with proper materials and orientations.

Parameters:
  • mask (ndarray) – 2D boolean array indicating voxel presence. Non-zero values indicate voxel presence, zero indicates empty space.

  • layer_index (int) – Index of current layer being processed. Used to position faces in 3D space.

  • axis (str) – Axis perpendicular to faces being generated (‘x’, ‘y’, or ‘z’). Determines how coordinates are generated for the faces.

  • positive_direction (bool) – Whether faces point in positive axis direction. Affects face normal orientation.

  • normal_idx (int) – Index of normal vector to use for faces. References pre-defined normal vectors in the OBJ file.

  • voxel_size_m (float) – Size of each voxel in meters. Used to scale coordinates to real-world units.

  • vertex_dict (dict) – Dictionary mapping vertex coordinates to indices. Used to avoid duplicate vertices in the mesh.

  • vertex_list (list) – List of unique vertex coordinates. Stores all vertices used in the mesh.

  • faces_per_material (dict) – Dictionary collecting faces by material. Keys are material names, values are lists of face definitions.

  • voxel_value_to_material (dict) – Mapping from voxel values to material names. Used to assign materials to faces based on voxel values.

Notes

  • Uses greedy meshing to combine adjacent same-value voxels

  • Handles coordinate system conversion for proper orientation

  • Maintains consistent face winding order for rendering

  • Optimizes mesh by reusing vertices and combining faces

  • Supports different coordinate systems for each axis

voxcity.exporter.create_face_vertices(coords, positive_direction, axis)[source]

Helper function to create properly oriented face vertices for OBJ export.

This function handles the creation of face vertices with correct winding order based on the face direction and axis. It accounts for OpenGL coordinate system conventions and ensures proper face orientation for rendering.

Parameters:
  • coords (list) – List of 4 vertex coordinates defining the face corners. Each coordinate should be a tuple of (x, y, z) values.

  • positive_direction (bool) – Whether face points in positive axis direction. True = face normal points in positive direction along the axis False = face normal points in negative direction along the axis

  • axis (str) – Axis the face is perpendicular to (‘x’, ‘y’, or ‘z’). This determines how vertices are ordered for proper face orientation.

Returns:

Ordered vertex coordinates for the face, arranged to create proper

face orientation and winding order for rendering.

Return type:

list

Notes

  • Y-axis faces need special handling due to OpenGL coordinate system

  • Winding order determines which side of the face is visible

  • Consistent winding order is maintained for X and Z faces

voxcity.exporter.export_cityles(city: voxcity.models.VoxCity, output_directory: str = 'output/cityles', building_material: str = 'default', tree_type: str = 'default', trunk_height_ratio: float = _TRUNK_RATIO_SENTINEL, canopy_bottom_height_grid=None, under_tree_class_name: str = 'Bareland', under_tree_cityles_code=None, land_cover_source: str | None = None, **kwargs)[source]

Export VoxCity data to CityLES format

Parameters:

cityVoxCity

A VoxCity model instance.

output_directorystr

Output directory path.

building_materialstr

Building material type for mapping.

tree_typestr

Tree type for mapping.

trunk_height_ratiofloat, optional

Ratio of trunk height to total canopy height. When explicitly provided, the canopy bottom height grid is always recomputed as canopy_top * trunk_height_ratio, even when the VoxCity object already contains a per-cell canopy bottom grid. When omitted the existing city.tree_canopy.bottom is used if available, otherwise a default ratio of 0.3 is applied.

canopy_bottom_height_gridnumpy.ndarray, optional

Explicit canopy bottom height grid. Ignored when trunk_height_ratio is explicitly provided.

under_tree_class_namestr

Ground land-cover class to assign under tree canopy.

under_tree_cityles_codeint, optional

Override CityLES code for under-tree class.

land_cover_sourcestr, optional

Source of land cover data. Auto-detected from VoxCity extras when omitted.

**kwargsdict

Additional parameters (for compatibility).

Returns:

str : Path to output directory

voxcity.exporter.voxel_to_xarray_dataset(voxcity_grid: numpy.ndarray, voxel_size_m: float, rectangle_vertices: Sequence[Tuple[float, float]] | None = None, extra_attrs: Mapping[str, Any] | None = None) xarray.Dataset[source]

Create an xarray Dataset from a VoxCity voxel grid.

Parameters:
  • voxcity_grid – 3D numpy array with shape (rows, cols, levels) as returned by get_voxcity (first element of the returned tuple).

  • voxel_size_m – Voxel size (mesh size) in meters.

  • rectangle_vertices – Optional polygon vertices defining the area of interest in longitude/latitude pairs, typically the same list passed to get_voxcity.

  • extra_attrs – Optional mapping of additional global attributes to store in the dataset.

Returns:

Dataset containing one DataArray named “voxels” with dims (y, x, z) and coordinate variables in meters from origin.

Return type:

xr.Dataset

voxcity.exporter.save_voxel_netcdf(voxcity_grid: numpy.ndarray, output_path: str | pathlib.Path, voxel_size_m: float, rectangle_vertices: Sequence[Tuple[float, float]] | None = None, extra_attrs: Mapping[str, Any] | None = None, engine: str | None = None) str[source]

Save a VoxCity voxel grid to a NetCDF file.

Parameters:
  • voxcity_grid – 3D numpy array (rows, cols, levels) of voxel values.

  • output_path – Path to the NetCDF file to be written. Parent directories will be created as needed.

  • voxel_size_m – Voxel size in meters.

  • rectangle_vertices – Optional list of (lon, lat) pairs defining the area of interest. Stored as dataset metadata only.

  • extra_attrs – Optional additional global attributes to embed in the dataset.

  • engine – Optional xarray engine, e.g., “netcdf4” or “h5netcdf”. If not provided, xarray will choose a default; on failure we retry alternate engines.

Returns:

The string path to the written NetCDF file.

Return type:

str