Skip to content

Commit

Permalink
chore(lib): return NumPy array as attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
jeertmans committed Jan 8, 2024
1 parent 812748a commit ebedb68
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
3 changes: 2 additions & 1 deletion python/differt/geometry/triangle_mesh.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,8 @@ def load_obj(cls, file: Path) -> "TriangleMesh":
"""
mesh = _core.geometry.triangle_mesh.TriangleMesh.load_obj(str(file))
return cls(
vertices=mesh.vertices, triangles=mesh.triangles
vertices=mesh.vertices,
triangles=mesh.triangles,
)

def plot(self, **kwargs: Any) -> Any:
Expand Down
31 changes: 30 additions & 1 deletion src/geometry/triangle_mesh.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,51 @@
use std::fs::File;
use std::io::BufReader;

use numpy::{Element, PyArray2};
use obj::raw::object::{parse_obj, RawObj};
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::types::PyType;

#[pyclass]
#[pyo3(get_all)]
struct TriangleMesh {
/// Array of size [num_vertices 3].
vertices: Vec<(f32, f32, f32)>,
/// Array of size [num_triangles 3].
triangles: Vec<(usize, usize, usize)>,
}

#[inline]
fn pyarray2_from_vec_tuple<'py, T: Copy + Element>(
py: Python<'py>,
v: &[(T, T, T)],
) -> &'py PyArray2<T> {
let n = v.len();
unsafe {
let arr = PyArray2::<T>::new(py, [n, 3], false);

for i in 0..n {
let tup = v.get_unchecked(i);
arr.uget_raw([i, 0]).write(tup.0);
arr.uget_raw([i, 1]).write(tup.1);
arr.uget_raw([i, 2]).write(tup.2);
}
arr
}
}

#[pymethods]
impl TriangleMesh {
#[getter]
fn vertices<'py>(&self, py: Python<'py>) -> &'py PyArray2<f32> {
pyarray2_from_vec_tuple(py, &self.vertices)
}

#[getter]
fn triangles<'py>(&self, py: Python<'py>) -> &'py PyArray2<usize> {
pyarray2_from_vec_tuple(py, &self.triangles)
}

#[classmethod]
fn load_obj(_: &PyType, filename: &str) -> PyResult<Self> {
let input = BufReader::new(File::open(filename)?);
Expand Down

0 comments on commit ebedb68

Please sign in to comment.