Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,4 @@ Contributors:
* Zhiyi Wu <xiki-tempula>
* Olivier Languin-Cattoën <ollyfutur>
* Andrés Montoya <conradolandia> (logo)
* Shreejan Dolai <spyke7>
13 changes: 13 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,19 @@ The rules for this file:
* accompany each entry with github issue/PR number (Issue #xyz)

------------------------------------------------------------------------------
27/12/2025 IAlibay, spyke7, orbeckst
* 1.1.0

Changes

* Added `OpenVDB.py` inside `gridData` to simply export and write in .vdb format
* Added `test_vdb.py` inside `gridData\tests`

Fixes

* Adding openVDB formats (Issue #141)


??/??/???? IAlibay, ollyfutur, conradolandia, orbeckst
* 1.1.0

Expand Down
190 changes: 190 additions & 0 deletions gridData/OpenVDB.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
r"""
:mod:`~gridData.OpenVDB` --- routines to write OpenVDB files
=============================================================

The OpenVDB format is used by Blender and other VFX software for
volumetric data. See https://www.openvdb.org

.. Note:: This module implements a simple writer for 3D regular grids,
sufficient to export density data for visualization in Blender.

The OpenVDB format uses a sparse tree structure to efficiently store
volumetric data. It is the native format for Blender's volume system.


Writing OpenVDB files
---------------------

If you have a :class:`~gridData.core.Grid` object, you can write it to
OpenVDB format::

from gridData import Grid
g = Grid("data.dx")
g.export("data.vdb")

This will create a file that can be imported directly into Blender
(File -> Import -> OpenVDB).


Building an OpenVDB field from a numpy array
---------------------------------------------

Requires:

grid
numpy 3D array
origin
cartesian coordinates of the center of the (0,0,0) grid cell
delta
n x n array with the length of a grid cell along each axis

Example::

import OpenVDB
vdb_field = OpenVDB.field('density')
vdb_field.populate(grid, origin, delta)
vdb_field.write('output.vdb')


Classes and functions
---------------------

"""

import numpy
import warnings

try:
import pyopenvdb as vdb
except ImportError:
vdb = None


class field(object):
"""OpenVDB field object for writing volumetric data.

This class provides a simple interface to write 3D grid data to
OpenVDB format, which can be imported into Blender and other
VFX software.

The field object holds grid data and metadata, and can write it
to a .vdb file.

Example
-------
Create a field and write it::

vdb_field = OpenVDB.field('density')
vdb_field.populate(grid, origin, delta)
vdb_field.write('output.vdb')

Or use directly from Grid::

g = Grid(...)
g.export('output.vdb', format='vdb')

"""

def __init__(self, name='density'):
"""Initialize an OpenVDB field.

Parameters
----------
name : str
Name of the grid (will be visible in Blender)

"""
if vdb is None:
raise ImportError(
"pyopenvdb is required to write VDB files. "
)
self.name = name
self.grid = None
self.origin = None
self.delta = None

def populate(self, grid, origin, delta):
"""Populate the field with grid data.

Parameters
----------
grid : numpy.ndarray
3D numpy array with the data
origin : numpy.ndarray
Coordinates of the center of grid cell [0,0,0]
delta : numpy.ndarray
Grid spacing (can be 1D array or diagonal matrix)

Raises
------
ValueError
If grid is not 3D

"""
grid = numpy.asarray(grid)
if grid.ndim != 3:
raise ValueError(
"OpenVDB only supports 3D grids, got {}D".format(grid.ndim))

self.grid = grid.astype(numpy.float32) # OpenVDB uses float32
self.origin = numpy.asarray(origin)

# Handle delta: could be 1D array or diagonal matrix
delta = numpy.asarray(delta)
if delta.ndim == 2:
# Extract diagonal if it's a matrix
self.delta = numpy.array([delta[i, i] for i in range(3)])
else:
self.delta = delta

def write(self, filename):
"""Write the field to an OpenVDB file.

Parameters
----------
filename : str
Output filename (should end in .vdb)

"""
if self.grid is None:
raise ValueError("No data to write. Use populate() first.")

# Create OpenVDB grid
vdb_grid = vdb.FloatGrid()
vdb_grid.name = self.name

# Set up transform (voxel size and position)
# Check for uniform spacing
if not numpy.allclose(self.delta, self.delta[0]):
warnings.warn(
"Non-uniform grid spacing {}. Using average spacing.".format(
self.delta))
voxel_size = float(numpy.mean(self.delta))
else:
voxel_size = float(self.delta[0])

# Create linear transform with uniform voxel size
transform = vdb.createLinearTransform(voxelSize=voxel_size)

# OpenVDB transform is at corner of voxel [0,0,0],
# but GridDataFormats origin is at center of voxel [0,0,0]
corner_origin = self.origin - 0.5 * self.delta
transform.translate(corner_origin)
vdb_grid.transform = transform

# Set background value for sparse storage
vdb_grid.background = 0.0

# Populate the grid

accessor = vdb_grid.getAccessor()
threshold = 1e-10

for i in range(self.grid.shape[0]):
for j in range(self.grid.shape[1]):
for k in range(self.grid.shape[2]):
value = float(self.grid[i, j, k])
if abs(value) > threshold:
accessor.setValueOn((i, j, k), value)

vdb.write(filename, grids=[vdb_grid])
3 changes: 2 additions & 1 deletion gridData/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,9 @@
from . import OpenDX
from . import gOpenMol
from . import mrc
from . import OpenVDB

__all__ = ['Grid', 'OpenDX', 'gOpenMol', 'mrc']
__all__ = ['Grid', 'OpenDX', 'gOpenMol', 'mrc', 'OpenVDB']

from importlib.metadata import version
__version__ = version("GridDataFormats")
Expand Down
21 changes: 21 additions & 0 deletions gridData/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
from . import OpenDX
from . import gOpenMol
from . import mrc
from . import OpenVDB


def _grid(x):
Expand Down Expand Up @@ -203,6 +204,7 @@ def __init__(self, grid=None, edges=None, origin=None, delta=None,
'PKL': self._export_python,
'PICKLE': self._export_python, # compatibility
'PYTHON': self._export_python, # compatibility
'VDB': self._export_vdb,
}
self._loaders = {
'CCP4': self._load_mrc,
Expand Down Expand Up @@ -676,7 +678,26 @@ def _export_dx(self, filename, type=None, typequote='"', **kwargs):
if ext == '.gz':
filename = root + ext
dx.write(filename)

def _export_vdb(self, filename, **kwargs):
"""Export the density grid to an OpenVDB file.

The file format is compatible with Blender's volume system.
Only 3D grids are supported.

For the file format see https://www.openvdb.org
"""
if self.grid.ndim != 3:
raise ValueError(
"OpenVDB export requires a 3D grid, got {}D".format(self.grid.ndim))

# Get grid name from metadata if available
grid_name = self.metadata.get('name', 'density')

# Create and populate VDB field
vdb_field = OpenVDB.field(grid_name)
vdb_field.populate(self.grid, self.origin, self.delta)
vdb_field.write(filename)
def save(self, filename):
"""Save a grid object to `filename` and add ".pickle" extension.

Expand Down
Loading