_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q23200 | Arcball.next | train | def next(self, acceleration=0.0):
"""Continue rotation in direction of last drag."""
q | python | {
"resource": ""
} |
q23201 | validate_polygon | train | def validate_polygon(obj):
"""
Make sure an input can be returned as a valid polygon.
Parameters
-------------
obj : shapely.geometry.Polygon, str (wkb), or (n, 2) float
Object which might be a polygon
Returns
------------
polygon : shapely.geometry.Polygon
Valid polygon object
Raises
| python | {
"resource": ""
} |
q23202 | extrude_polygon | train | def extrude_polygon(polygon,
height,
**kwargs):
"""
Extrude a 2D shapely polygon into a 3D mesh
Parameters
----------
polygon : shapely.geometry.Polygon
2D geometry to extrude
height : float
Distance to extrude polygon along Z
**kwargs:
passed to Trimesh
Returns
----------
mesh : | python | {
"resource": ""
} |
q23203 | extrude_triangulation | train | def extrude_triangulation(vertices,
faces,
height,
**kwargs):
"""
Turn a 2D triangulation into a watertight Trimesh.
Parameters
----------
vertices : (n, 2) float
2D vertices
faces : (m, 3) int
Triangle indexes of vertices
height : float
Distance to extrude triangulation
**kwargs:
passed to Trimesh
Returns
---------
mesh : trimesh.Trimesh
Mesh created from extrusion
"""
vertices = np.asanyarray(vertices, dtype=np.float64)
height = float(height)
faces = np.asanyarray(faces, dtype=np.int64)
if not util.is_shape(vertices, (-1, 2)):
raise ValueError('Vertices must be (n,2)')
if not util.is_shape(faces, (-1, 3)):
raise ValueError('Faces must be (n,3)')
if np.abs(height) < tol.merge:
raise ValueError('Height must be nonzero!')
# make sure triangulation winding is pointing up
normal_test = normals(
[util.stack_3D(vertices[faces[0]])])[0]
normal_dot = np.dot(normal_test,
[0.0, 0.0, np.sign(height)])[0]
# make sure the triangulation is aligned with the sign of
# the height we've been passed
if normal_dot < 0.0:
faces = np.fliplr(faces)
# stack the (n,3) faces into (3*n, 2) edges
edges = faces_to_edges(faces)
edges_sorted = np.sort(edges, axis=1)
# edges which only occur once are on the boundary of the polygon
# since the triangulation may have subdivided the boundary of the
# shapely polygon, we need to find it again
edges_unique = grouping.group_rows(edges_sorted, require_count=1)
# (n, 2, 2) set of line segments (positions, not references)
boundary = vertices[edges[edges_unique]]
# we are creating | python | {
"resource": ""
} |
q23204 | _polygon_to_kwargs | train | def _polygon_to_kwargs(polygon):
"""
Given a shapely polygon generate the data to pass to
the triangle mesh generator
Parameters
---------
polygon : Shapely.geometry.Polygon
Input geometry
Returns
--------
result : dict
Has keys: vertices, segments, holes
"""
if not polygon.is_valid:
raise ValueError('invalid shapely polygon passed!')
def round_trip(start, length):
"""
Given a start index and length, create a series of (n, 2) edges which
create a closed traversal.
Examples
---------
start, length = 0, 3
returns: [(0,1), (1,2), (2,0)]
"""
tiled = np.tile(np.arange(start, start + length).reshape((-1, 1)), 2)
tiled = tiled.reshape(-1)[1:-1].reshape((-1, 2))
tiled = np.vstack((tiled, [tiled[-1][-1], tiled[0][0]]))
return tiled
def add_boundary(boundary, start):
# coords is an (n, 2) ordered list of points on the polygon boundary
# the first and last points are the same, and there are no
# guarantees on points not being duplicated (which will
# later cause meshpy/triangle to shit a brick)
coords = np.array(boundary.coords)
# find indices points which occur only once, and sort them
# to maintain order
unique = np.sort(grouping.unique_rows(coords)[0])
cleaned = coords[unique]
vertices.append(cleaned)
facets.append(round_trip(start, len(cleaned)))
# holes require points inside the region of the hole, which we find
# by creating a polygon from the cleaned boundary region, and then
# using a representative point. You could do things like take the mean of
# the points, but this is more robust (to things like concavity), if | python | {
"resource": ""
} |
q23205 | icosahedron | train | def icosahedron():
"""
Create an icosahedron, a 20 faced polyhedron.
Returns
-------------
ico : trimesh.Trimesh
Icosahederon centered at the origin.
"""
t = (1.0 + 5.0**.5) / 2.0
vertices = [-1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, 0, -1, t, 0, 1, t,
0, -1, -t, 0, 1, -t, t, 0, -1, t, 0, 1, -t, 0, -1, -t, 0, 1]
faces = [0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
3, 9, 4, 3, 4, 2, 3, | python | {
"resource": ""
} |
q23206 | icosphere | train | def icosphere(subdivisions=3, radius=1.0, color=None):
"""
Create an isophere centered at the origin.
Parameters
----------
subdivisions : int
How many times to subdivide the mesh.
Note that the number of faces will grow as function of
4 ** subdivisions, so you probably want to keep this under ~5
radius : float
Desired radius of sphere
color: (3,) float or uint8
Desired color of sphere
Returns
---------
ico : trimesh.Trimesh
Meshed sphere
"""
def refine_spherical():
vectors = ico.vertices
scalar = (vectors ** 2).sum(axis=1)**.5 | python | {
"resource": ""
} |
q23207 | capsule | train | def capsule(height=1.0,
radius=1.0,
count=[32, 32]):
"""
Create a mesh of a capsule, or a cylinder with hemispheric ends.
Parameters
----------
height : float
Center to center distance of two spheres
radius : float
Radius of the cylinder and hemispheres
count : (2,) int
Number of sections on latitude and longitude
Returns
----------
capsule : trimesh.Trimesh
Capsule geometry with:
- cylinder axis is along Z
- one hemisphere is centered at the origin
- other hemisphere is centered along the Z axis at height
"""
height = float(height)
radius = float(radius)
count = np.array(count, dtype=np.int)
count += np.mod(count, 2)
# create a theta where there is a double band around the equator
# so that we can offset the top | python | {
"resource": ""
} |
q23208 | cylinder | train | def cylinder(radius=1.0,
height=1.0,
sections=32,
segment=None,
transform=None,
**kwargs):
"""
Create a mesh of a cylinder along Z centered at the origin.
Parameters
----------
radius : float
The radius of the cylinder
height : float
The height of the cylinder
sections : int
How many pie wedges should the cylinder have
segment : (2, 3) float
Endpoints of axis, overrides transform and height
transform : (4, 4) float
Transform to apply
**kwargs:
passed to Trimesh to create cylinder
Returns
----------
cylinder: trimesh.Trimesh
Resulting mesh of a cylinder
"""
if segment is not None:
segment = np.asanyarray(segment, dtype=np.float64)
if segment.shape != (2, 3):
raise ValueError('segment must be 2 3D points!')
vector = segment[1] - segment[0]
# override height with segment length
height = np.linalg.norm(vector)
# point in middle of line
midpoint = segment[0] + (vector * 0.5)
# align Z with our desired direction
rotation = align_vectors([0, 0, 1], vector)
# translate to midpoint of segment
translation = transformations.translation_matrix(midpoint)
# compound the rotation and translation
transform = np.dot(translation, rotation)
# create a 2D pie out of wedges
theta = np.linspace(0, np.pi * 2, sections)
vertices = np.column_stack((np.sin(theta),
| python | {
"resource": ""
} |
q23209 | annulus | train | def annulus(r_min=1.0,
r_max=2.0,
height=1.0,
sections=32,
transform=None,
**kwargs):
"""
Create a mesh of an annular cylinder along Z,
centered at the origin.
Parameters
----------
r_min : float
The inner radius of the annular cylinder
r_max : float
The outer radius of the annular cylinder
height : float
The height of the annular cylinder
sections : int
How many pie wedges should the annular cylinder have
**kwargs:
passed to Trimesh to create annulus
Returns
----------
annulus : trimesh.Trimesh
Mesh of annular cylinder
"""
r_min = abs(float(r_min))
r_max = abs(float(r_max))
height = float(height)
sections = int(sections)
# if center radius is zero this is a cylinder
if r_min < tol.merge:
return cylinder(radius=r_max,
height=height,
| python | {
"resource": ""
} |
q23210 | random_soup | train | def random_soup(face_count=100):
"""
Return random triangles as a Trimesh
Parameters
-----------
face_count : int
Number of faces desired in mesh
Returns
| python | {
"resource": ""
} |
q23211 | axis | train | def axis(origin_size=0.04,
transform=None,
origin_color=None,
axis_radius=None,
axis_length=None):
"""
Return an XYZ axis marker as a Trimesh, which represents position
and orientation. If you set the origin size the other parameters
will be set relative to it.
Parameters
----------
transform : (4, 4) float
Transformation matrix
origin_size : float
Radius of sphere that represents the origin
origin_color : (3,) float or int, uint8 or float
Color of the origin
axis_radius : float
Radius of cylinder that represents x, y, z axis
axis_length: float
Length of cylinder that represents x, y, z axis
Returns
-------
marker : trimesh.Trimesh
Mesh geometry of axis indicators
"""
# the size of the ball representing the origin
origin_size = float(origin_size)
# set the transform and use origin-relative
# sized for other parameters if not specified
if transform is None:
transform = np.eye(4)
if origin_color is None:
origin_color = [255, 255, 255, 255]
if axis_radius is None:
axis_radius = origin_size / 5.0
if axis_length is None:
axis_length = | python | {
"resource": ""
} |
q23212 | camera_marker | train | def camera_marker(camera,
marker_height=0.4,
origin_size=None):
"""
Create a visual marker for a camera object, including an axis and FOV.
Parameters
---------------
camera : trimesh.scene.Camera
Camera object with FOV and transform defined
marker_height : float
How far along the camera Z should FOV indicators be
origin_size : float
Sphere radius of the origin (default: marker_height / 10.0)
Returns
------------
meshes : list
Contains Trimesh and Path3D objects which can be visualized
"""
camera_transform = camera.transform
if camera_transform is None:
camera_transform = np.eye(4)
# append the visualizations to an array
meshes = [axis(origin_size=marker_height / 10.0)]
meshes[0].apply_transform(camera_transform)
try:
# path is a soft dependency
from .path.exchange.load import load_path
except ImportError:
# they probably don't have shapely installed
log.warning('unable to create FOV visualization!',
exc_info=True)
return meshes
# create sane origin size from marker height
if origin_size is None:
origin_size = marker_height / 10.0
# calculate vertices from camera FOV angles
x = marker_height * np.tan(np.deg2rad(camera.fov[0]) / 2.0)
y = marker_height * np.tan(np.deg2rad(camera.fov[1]) / 2.0)
z = marker_height
# | python | {
"resource": ""
} |
q23213 | convex_hull | train | def convex_hull(obj, qhull_options='QbB Pp QJn'):
"""
Get a new Trimesh object representing the convex hull of the
current mesh, with proper normals and watertight.
Requires scipy >.12.
Arguments
--------
obj : Trimesh, or (n,3) float
Mesh or cartesian points
Returns
--------
convex : Trimesh
Mesh of convex hull
"""
from .base import Trimesh
if isinstance(obj, Trimesh):
points = obj.vertices.view(np.ndarray)
else:
# will remove subclassing
points = np.asarray(obj, dtype=np.float64)
if not util.is_shape(points, (-1, 3)):
raise ValueError('Object must be Trimesh or (n,3) points!')
hull = spatial.ConvexHull(points,
qhull_options=qhull_options)
# hull object doesn't remove unreferenced vertices
# create a mask to re- index faces for only referenced vertices
vid = np.sort(hull.vertices)
mask = np.zeros(len(hull.points), dtype=np.int64)
mask[vid] = np.arange(len(vid))
# remove unreferenced vertices here
faces = mask[hull.simplices].copy()
# rescale vertices back to original size
vertices = hull.points[vid].copy()
# qhull returns faces with random winding
# calculate the returned normal of each face
crosses = triangles.cross(vertices[faces])
# qhull returns zero magnitude faces like an asshole
normals, valid = util.unitize(crosses, check_valid=True)
# remove zero magnitude faces
faces = faces[valid]
crosses = crosses[valid]
# each triangle area and mean center
triangles_area = triangles.area(crosses=crosses, sum=False)
triangles_center = vertices[faces].mean(axis=1)
# since the convex hull is (hopefully) convex, the vector from
# the centroid to the center of each face
# should have a positive dot product with the normal of that face
# if it doesn't it is probably backwards
# note that this sometimes gets screwed up by precision issues
centroid = np.average(triangles_center,
weights=triangles_area,
axis=0)
# a vector from the centroid to a point on each face
test_vector = triangles_center - centroid
# check the projection against face normals
backwards = util.diagonal_dot(normals,
test_vector) < 0.0
# flip the winding outward facing
faces[backwards] = np.fliplr(faces[backwards])
# flip the normal
normals[backwards] *= -1.0
| python | {
"resource": ""
} |
q23214 | adjacency_projections | train | def adjacency_projections(mesh):
"""
Test if a mesh is convex by projecting the vertices of
a triangle onto the normal of its adjacent face.
Parameters
----------
mesh : Trimesh
Input geometry
Returns
----------
projection : (len(mesh.face_adjacency),) float
Distance of projection of adjacent vertex onto plane
"""
# normals and origins from the first column of face adjacency
normals = mesh.face_normals[mesh.face_adjacency[:, 0]]
# one | python | {
"resource": ""
} |
q23215 | is_convex | train | def is_convex(mesh):
"""
Check if a mesh is convex.
Parameters
-----------
mesh : Trimesh
Input geometry
Returns
-----------
convex : bool
Was passed mesh convex or not
"""
# don't consider zero- area faces
nonzero = mesh.area_faces > tol.merge
# adjacencies with two nonzero faces
adj_ok = nonzero[mesh.face_adjacency].all(axis=1)
# make threshold of convexity scale- relative
threshold = tol.planar * mesh.scale | python | {
"resource": ""
} |
q23216 | hull_points | train | def hull_points(obj, qhull_options='QbB Pp'):
"""
Try to extract a convex set of points from multiple input formats.
Parameters
---------
obj: Trimesh object
(n,d) points
(m,) Trimesh objects
Returns
--------
points: (o,d) convex set of points
"""
if hasattr(obj, 'convex_hull'):
return obj.convex_hull.vertices
initial = np.asanyarray(obj, | python | {
"resource": ""
} |
q23217 | Entity.closed | train | def closed(self):
"""
If the first point is the same as the end point
the entity is closed
"""
| python | {
"resource": ""
} |
q23218 | Entity.length | train | def length(self, vertices):
"""
Return the total length of the entity.
Returns
---------
length: float, total length of entity
""" | python | {
"resource": ""
} |
q23219 | Text.plot | train | def plot(self, vertices, show=False):
"""
Plot the text using matplotlib.
Parameters
--------------
vertices : (n, 2) float
Vertices in space
show : bool
If True, call plt.show()
"""
if vertices.shape[1] != 2:
| python | {
"resource": ""
} |
q23220 | Text.angle | train | def angle(self, vertices):
"""
If Text is 2D, get the rotation angle in radians.
Parameters
-----------
vertices : (n, 2) float
Vertices in space referenced by self.points
Returns
---------
angle : float
Rotation angle in radians
"""
if vertices.shape[1] != 2:
raise ValueError('angle only valid for 2D points!')
| python | {
"resource": ""
} |
q23221 | Line.discrete | train | def discrete(self, vertices, scale=1.0):
"""
Discretize into a world- space path.
Parameters
------------
vertices: (n, dimension) float
Points in space
scale : float
Size of overall scene for numerical comparisons
| python | {
"resource": ""
} |
q23222 | Line.is_valid | train | def is_valid(self):
"""
Is the current entity valid.
Returns
-----------
valid : bool
Is the current entity well formed
""" | python | {
"resource": ""
} |
q23223 | Line.explode | train | def explode(self):
"""
If the current Line entity consists of multiple line
break it up into n Line entities.
Returns
----------
exploded: (n,) Line entities
"""
points = np.column_stack((
| python | {
"resource": ""
} |
q23224 | Arc.discrete | train | def discrete(self, vertices, scale=1.0):
"""
Discretize the arc entity into line sections.
Parameters
------------
vertices : (n, dimension) float
Points in space
scale : float
| python | {
"resource": ""
} |
q23225 | Arc.bounds | train | def bounds(self, vertices):
"""
Return the AABB of the arc entity.
Parameters
-----------
vertices: (n,dimension) float, vertices in space
Returns
-----------
bounds: (2, dimension) float, (min, max) coordinate of AABB
"""
if util.is_shape(vertices, (-1, 2)) and self.closed:
# if we have a closed arc (a circle), we can return the actual bounds
# this only works in two dimensions, otherwise this would | python | {
"resource": ""
} |
q23226 | Bezier.discrete | train | def discrete(self, vertices, scale=1.0, count=None):
"""
Discretize the Bezier curve.
Parameters
-------------
vertices : (n, 2) or (n, 3) float
Points in space
scale : float
Scale of overall drawings (for precision)
count : int
Number of segments to return
Returns
-------------
discrete : (m, 2) or (m, 3) float
| python | {
"resource": ""
} |
q23227 | BSpline.discrete | train | def discrete(self, vertices, count=None, scale=1.0):
"""
Discretize the B-Spline curve.
Parameters
-------------
vertices : (n, 2) or (n, 3) float
Points in space
scale : float
Scale of overall drawings (for precision)
count : int
Number of segments to return
Returns
-------------
discrete : (m, 2) or (m, 3) float
| python | {
"resource": ""
} |
q23228 | BSpline.to_dict | train | def to_dict(self):
"""
Returns a dictionary with all of the information
about the entity.
"""
return {'type': self.__class__.__name__,
| python | {
"resource": ""
} |
q23229 | print_element | train | def print_element(element):
"""
Pretty- print an lxml.etree element.
Parameters
------------
element : etree element
"""
pretty | python | {
"resource": ""
} |
q23230 | merge_vertices | train | def merge_vertices(mesh,
digits=None,
textured=True,
uv_digits=4):
"""
Removes duplicate vertices based on integer hashes of
each row.
Parameters
-------------
mesh : Trimesh object
Mesh to merge vertices on
digits : int
How many digits to consider for vertices
If not specified uses tol.merge
textured : bool
If True, for textured meshes only merge vertices
with identical positions AND UV coordinates.
No effect on untextured meshes
uv_digits : int
Number of digits to consider for UV coordinates.
"""
if not isinstance(digits, int):
digits = util.decimal_to_digits(tol.merge)
# UV texture visuals require us to update the
# vertices and normals differently
if (textured and
mesh.visual.defined and
mesh.visual.kind == 'texture' and
mesh.visual.uv is not None):
# get an array with vertices and UV coordinates
# converted to integers at requested precision
stacked = np.column_stack((
mesh.vertices * (10 ** digits),
mesh.visual.uv * (10 ** uv_digits))).round().astype(np.int64)
| python | {
"resource": ""
} |
q23231 | group | train | def group(values, min_len=0, max_len=np.inf):
"""
Return the indices of values that are identical
Parameters
----------
values: 1D array
min_len: int, the shortest group allowed
All groups will have len >= min_length
max_len: int, the longest group allowed
All groups will have len <= max_length
Returns
----------
groups: sequence of indices to form groups
IE [0,1,0,1] returns [[0,2], [1,3]]
"""
original = np.asanyarray(values)
# save the sorted order and then apply it
order = original.argsort()
values = original[order]
# find | python | {
"resource": ""
} |
q23232 | hashable_rows | train | def hashable_rows(data, digits=None):
"""
We turn our array into integers based on the precision
given by digits and then put them in a hashable format.
Parameters
---------
data : (n, m) array
Input data
digits : int or None
How many digits to add to hash if data is floating point
If None, tol.merge will be used
Returns
---------
hashable : (n,) array
Custom data type which can be sorted
or used as hash keys
"""
# if there is no data return immediately
if len(data) == 0:
return np.array([])
# get array as integer to precision we care about
as_int = float_to_int(data, digits=digits)
# if it is flat integers already, return
if len(as_int.shape) == 1:
return as_int
# if array is 2D and smallish, we can try bitbanging
# this is significantly faster than the custom dtype
if len(as_int.shape) == 2 and as_int.shape[1] <= 4:
# time for some righteous bitbanging
# can we pack the whole row into a single 64 bit integer
precision = int(np.floor(64 / as_int.shape[1]))
# if the max value is less than precision we can do this
if np.abs(as_int).max() < 2**(precision - 1):
# the resulting package
hashable = np.zeros(len(as_int), dtype=np.int64)
| python | {
"resource": ""
} |
q23233 | unique_ordered | train | def unique_ordered(data):
"""
Returns the same as np.unique, but ordered as per the
first occurrence of the unique value in data.
Examples
---------
In [1]: a = [0, 3, 3, 4, 1, 3, 0, 3, 2, 1]
In [2]: np.unique(a)
Out[2]: array([0, 1, 2, 3, 4])
In [3]: trimesh.grouping.unique_ordered(a)
Out[3]: | python | {
"resource": ""
} |
q23234 | unique_bincount | train | def unique_bincount(values,
minlength,
return_inverse=True):
"""
For arrays of integers find unique values using bin counting.
Roughly 10x faster for correct input than np.unique
Parameters
--------------
values : (n,) int
Values to find unique members of
minlength : int
Maximum value that will occur in values (values.max())
return_inverse : bool
If True, return an inverse such that unique[inverse] == values
Returns
------------
unique : (m,) int
Unique values in original array
inverse : (n,) int
An array such that unique[inverse] == values
| python | {
"resource": ""
} |
q23235 | merge_runs | train | def merge_runs(data, digits=None):
"""
Merge duplicate sequential values. This differs from unique_ordered
in that values can occur in multiple places in the sequence, but
only consecutive repeats are removed
Parameters
-----------
data: (n,) float or int
Returns
--------
merged: (m,) float or int
Examples
---------
In [1]: a
Out[1]:
array([-1, -1, -1, 0, 0, 1, 1, 2, 0,
3, 3, 4, 4, 5, 5, 6, 6, | python | {
"resource": ""
} |
q23236 | unique_float | train | def unique_float(data,
return_index=False,
return_inverse=False,
digits=None):
"""
Identical to the numpy.unique command, except evaluates floating point
numbers, using a specified number of digits.
If digits isn't specified, the library default TOL_MERGE will be used.
"""
data = np.asanyarray(data)
as_int = float_to_int(data, digits)
_junk, unique, inverse = np.unique(as_int,
return_index=True,
| python | {
"resource": ""
} |
q23237 | unique_value_in_row | train | def unique_value_in_row(data, unique=None):
"""
For a 2D array of integers find the position of a value in each
row which only occurs once. If there are more than one value per
row which occur once, the last one is returned.
Parameters
----------
data: (n,d) int
unique: (m) int, list of unique values contained in data.
speedup purposes only, generated from np.unique if not passed
Returns
---------
result: (n,d) bool, with one or zero True values per row.
Examples
-------------------------------------
In [0]: r = np.array([[-1, 1, 1],
[-1, 1, -1],
[-1, 1, 1],
[-1, 1, -1],
[-1, 1, -1]], dtype=np.int8)
In [1]: unique_value_in_row(r)
Out[1]:
array([[ True, False, | python | {
"resource": ""
} |
q23238 | boolean_rows | train | def boolean_rows(a, b, operation=np.intersect1d):
"""
Find the rows in two arrays which occur in both rows.
Parameters
---------
a: (n, d) int
Array with row vectors
b: (m, d) int
Array with row vectors
operation : function
Numpy boolean set operation function:
| python | {
"resource": ""
} |
q23239 | group_vectors | train | def group_vectors(vectors,
angle=1e-4,
include_negative=False):
"""
Group vectors based on an angle tolerance, with the option to
include negative vectors.
Parameters
-----------
vectors : (n,3) float
Direction vector
angle : float
Group vectors closer than this angle in radians
include_negative : bool
If True consider the same:
[0,0,1] and [0,0,-1]
Returns
------------
new_vectors : (m,3) float
Direction vector
groups : (m,) sequence of int
Indices | python | {
"resource": ""
} |
q23240 | group_distance | train | def group_distance(values, distance):
"""
Find groups of points which have neighbours closer than radius,
where no two points in a group are farther than distance apart.
Parameters
---------
points : (n, d) float
Points of dimension d
distance : float
Max distance between points in a cluster
Returns
----------
unique : (m, d) float
Median value of each group
groups : (m) sequence of int
Indexes of points that make up a group
| python | {
"resource": ""
} |
q23241 | clusters | train | def clusters(points, radius):
"""
Find clusters of points which have neighbours closer than radius
Parameters
---------
points : (n, d) float
Points of dimension d
radius : float
Max distance between points in a cluster
| python | {
"resource": ""
} |
q23242 | blocks | train | def blocks(data,
min_len=2,
max_len=np.inf,
digits=None,
only_nonzero=False):
"""
Given an array, find the indices of contiguous blocks
of equal values.
Parameters
---------
data: (n) array
min_len: int, the minimum length group to be returned
max_len: int, the maximum length group to be retuurned
digits: if dealing with floats, how many digits to use
only_nonzero: bool, only return blocks of non- zero values
Returns
---------
blocks: (m) sequence of indices referencing data
"""
data = float_to_int(data, digits=digits)
# find the inflection points, or locations where the array turns
# from True to False.
infl = np.concatenate(([0],
np.nonzero(np.diff(data))[0] + 1,
[len(data)]))
infl_len = np.diff(infl)
infl_ok = np.logical_and(infl_len >= min_len,
| python | {
"resource": ""
} |
q23243 | group_min | train | def group_min(groups, data):
"""
Given a list of groups, find the minimum element of data within each group
Parameters
-----------
groups : (n,) sequence of (q,) int
Indexes of each group corresponding to each element in data
data : (m,)
The data that groups indexes reference
| python | {
"resource": ""
} |
q23244 | minimum_nsphere | train | def minimum_nsphere(obj):
"""
Compute the minimum n- sphere for a mesh or a set of points.
Uses the fact that the minimum n- sphere will be centered at one of
the vertices of the furthest site voronoi diagram, which is n*log(n)
but should be pretty fast due to using the scipy/qhull implementations
of convex hulls and voronoi diagrams.
Parameters
----------
obj : (n, d) float or trimesh.Trimesh
Points or mesh to find minimum bounidng nsphere
Returns
----------
center : (d,) float
Center of fitted n- sphere
radius : float
Radius of fitted n-sphere
"""
# reduce the input points or mesh to the vertices of the convex hull
# since we are computing the furthest site voronoi diagram this reduces
# the input complexity substantially and returns the same value
points = convex.hull_points(obj)
# we are scaling the mesh to a unit cube
# this used to pass qhull_options 'QbB' to Voronoi however this had a bug somewhere
# to avoid this we scale to a unit cube ourselves inside this function
points_origin = points.min(axis=0)
points_scale = points.ptp(axis=0).min()
points = (points - points_origin) / points_scale
# if all of the points are on an n-sphere already the voronoi
# method will fail so we check a least squares fit before
# bothering to compute the voronoi diagram
fit_C, fit_R, fit_E = fit_nsphere(points)
# return | python | {
"resource": ""
} |
q23245 | fit_nsphere | train | def fit_nsphere(points, prior=None):
"""
Fit an n-sphere to a set of points using least squares.
Parameters
---------
points : (n, d) float
Points in space
prior : (d,) float
Best guess for center of nsphere
Returns
---------
center : (d,) float
Location of center
radius : float
Mean radius across circle
error : float
Peak to peak value of deviation from mean radius
"""
# make sure points are numpy array
points = np.asanyarray(points, dtype=np.float64)
# create ones so we can dot instead of using slower sum
ones = np.ones(points.shape[1]) | python | {
"resource": ""
} |
q23246 | is_nsphere | train | def is_nsphere(points):
"""
Check if a list of points is an nsphere.
Parameters
-----------
points : (n, dimension) float
Points in space
Returns
-----------
check : bool
True if input points | python | {
"resource": ""
} |
q23247 | contains_points | train | def contains_points(intersector,
points,
check_direction=None):
"""
Check if a mesh contains a set of points, using ray tests.
If the point is on the surface of the mesh, behavior is
undefined.
Parameters
---------
mesh: Trimesh object
points: (n,3) points in space
Returns
---------
contains : (n) bool
Whether point is inside mesh or not
"""
# convert points to float and make sure they are 3D
points = np.asanyarray(points, dtype=np.float64)
if not util.is_shape(points, (-1, 3)):
raise ValueError('points must be (n,3)')
# placeholder result with no hits we'll fill in later
contains = np.zeros(len(points), dtype=np.bool)
# cull points outside of the axis aligned bounding box
# this avoids running ray tests unless points are close
inside_aabb = bounds.contains(intersector.mesh.bounds,
points)
# if everything is outside the AABB, exit early
if not inside_aabb.any():
return contains
# default ray direction is random, but we are not generating
# uniquely each time so the behavior of this function is easier to debug
default_direction = np.array([0.4395064455,
0.617598629942,
0.652231566745])
if check_direction is None:
# if no check direction is specified use the default
# stack it only for points inside the AABB
ray_directions = np.tile(default_direction,
(inside_aabb.sum(), 1))
else:
# if a direction is passed use it
ray_directions = np.tile(
np.array(check_direction).reshape(3),
(inside_aabb.sum(), 1))
# cast a ray both forwards and backwards
location, index_ray, c = intersector.intersects_location(
np.vstack(
(points[inside_aabb],
points[inside_aabb])),
np.vstack(
(ray_directions,
-ray_directions)))
# if we hit nothing in either direction just return with no hits
if len(index_ray) == 0:
return contains
# reshape so bi_hits[0] is the result in the forward direction and
# bi_hits[1] is the result in the backwards directions
bi_hits = np.bincount(
index_ray,
minlength=len(ray_directions) * 2).reshape((2, -1))
# a point is probably inside if it hits a surface an odd number of times
bi_contains = np.mod(bi_hits, 2) == 1
# if the mod of the hit count is the same in both
# directions, we can save that result and move on
agree = np.equal(*bi_contains)
# in order to do an assignment we can only have one
# level | python | {
"resource": ""
} |
q23248 | mesh_to_BVH | train | def mesh_to_BVH(mesh):
"""
Create a BVHModel object from a Trimesh object
Parameters
-----------
mesh : Trimesh
Input geometry
Returns
------------
bvh : fcl.BVHModel
BVH of input geometry
"""
bvh = fcl.BVHModel()
bvh.beginModel(num_tris_=len(mesh.faces),
| python | {
"resource": ""
} |
q23249 | scene_to_collision | train | def scene_to_collision(scene):
"""
Create collision objects from a trimesh.Scene object.
Parameters
------------
scene : trimesh.Scene
Scene to create collision objects for
Returns
------------
manager : CollisionManager
CollisionManager for objects in scene
objects: {node name: CollisionObject}
Collision objects for nodes in scene
"""
manager = CollisionManager()
| python | {
"resource": ""
} |
q23250 | CollisionManager.add_object | train | def add_object(self,
name,
mesh,
transform=None):
"""
Add an object to the collision manager.
If an object with the given name is already in the manager,
replace it.
Parameters
----------
name : str
An identifier for the object
mesh : Trimesh object
The geometry of the collision object
transform : (4,4) float
Homogenous transform matrix for the object
"""
# if no transform passed, assume identity transform
if transform is None:
transform = np.eye(4)
transform = np.asanyarray(transform, dtype=np.float32)
if transform.shape != (4, 4):
raise ValueError('transform must be (4,4)!')
| python | {
"resource": ""
} |
q23251 | CollisionManager.remove_object | train | def remove_object(self, name):
"""
Delete an object from the collision manager.
Parameters
----------
name : str
The identifier for the object
"""
if name in self._objs:
self._manager.unregisterObject(self._objs[name]['obj'])
self._manager.update(self._objs[name]['obj'])
# remove objects from _objs | python | {
"resource": ""
} |
q23252 | CollisionManager.set_transform | train | def set_transform(self, name, transform):
"""
Set the transform for one of the manager's objects.
This replaces the prior transform.
Parameters
----------
name : str
An identifier for the object already in the manager
transform : (4,4) float
A new homogenous transform matrix for the object
"""
if name in self._objs:
o = self._objs[name]['obj']
| python | {
"resource": ""
} |
q23253 | CollisionManager.in_collision_single | train | def in_collision_single(self, mesh, transform=None,
return_names=False, return_data=False):
"""
Check a single object for collisions against all objects in the
manager.
Parameters
----------
mesh : Trimesh object
The geometry of the collision object
transform : (4,4) float
Homogenous transform matrix
return_names : bool
If true, a set is returned containing the names
of all objects in collision with the object
return_data : bool
If true, a list of ContactData is returned as well
Returns
------------
is_collision : bool
True if a collision occurs and False otherwise
names : set of str
The set of names of objects that collided with the
provided one
contacts : list of ContactData
All contacts detected
"""
if transform is None:
transform = np.eye(4)
# Create FCL data
b = self._get_BVH(mesh)
t = fcl.Transform(transform[:3, :3], transform[:3, 3])
o = fcl.CollisionObject(b, t)
# Collide with manager's objects
cdata = fcl.CollisionData()
if return_names or return_data:
cdata = fcl.CollisionData(request=fcl.CollisionRequest(
num_max_contacts=100000,
enable_contact=True))
| python | {
"resource": ""
} |
q23254 | CollisionManager.in_collision_other | train | def in_collision_other(self, other_manager,
return_names=False, return_data=False):
"""
Check if any object from this manager collides with any object
from another manager.
Parameters
-------------------
other_manager : CollisionManager
Another collision manager object
return_names : bool
If true, a set is returned containing the names
of all pairs of objects in collision.
return_data : bool
If true, a list of ContactData is returned as well
Returns
-------------
is_collision : bool
True if a collision occurred between any pair of objects
and False otherwise
names : set of 2-tup
The set of pairwise collisions. Each tuple
contains two names (first from this manager,
second from the other_manager) indicating
that the two corresponding objects are in collision.
contacts : list of ContactData
All contacts detected
"""
cdata = fcl.CollisionData()
if return_names or return_data:
cdata = fcl.CollisionData(
request=fcl.CollisionRequest(
num_max_contacts=100000,
enable_contact=True))
self._manager.collide(other_manager._manager,
cdata,
fcl.defaultCollisionCallback)
result = cdata.result.is_collision
objs_in_collision = set()
contact_data = []
if return_names or return_data:
for contact in cdata.result.contacts:
reverse = False
names = (self._extract_name(contact.o1),
| python | {
"resource": ""
} |
q23255 | CollisionManager.min_distance_single | train | def min_distance_single(self,
mesh,
transform=None,
return_name=False,
return_data=False):
"""
Get the minimum distance between a single object and any
object in the manager.
Parameters
---------------
mesh : Trimesh object
The geometry of the collision object
transform : (4,4) float
Homogenous transform matrix for the object
return_names : bool
If true, return name of the closest object
return_data : bool
If true, a DistanceData object is returned as well
Returns
-------------
distance : float
Min distance between mesh and any object in the manager
name : str
The name of the object in the manager that was closest
data : DistanceData
Extra data about the distance query
"""
if transform is None:
transform = np.eye(4)
# Create FCL data
b = self._get_BVH(mesh)
t = fcl.Transform(transform[:3, :3], transform[:3, 3])
o = fcl.CollisionObject(b, t)
# Collide with manager's objects
ddata = fcl.DistanceData()
if return_data:
| python | {
"resource": ""
} |
q23256 | CollisionManager.min_distance_internal | train | def min_distance_internal(self, return_names=False, return_data=False):
"""
Get the minimum distance between any pair of objects in the manager.
Parameters
-------------
return_names : bool
If true, a 2-tuple is returned containing the names
of the closest objects.
return_data : bool
If true, a DistanceData object is returned as well
Returns
-----------
distance : float
Min distance between any two managed objects
names : (2,) str
The names of the closest objects
data : DistanceData
Extra data about the distance query
"""
ddata = fcl.DistanceData()
if return_data:
ddata = fcl.DistanceData(
fcl.DistanceRequest(enable_nearest_points=True),
fcl.DistanceResult()
)
self._manager.distance(ddata, fcl.defaultDistanceCallback)
distance = ddata.result.min_distance
names, data = None, None
| python | {
"resource": ""
} |
q23257 | CollisionManager.min_distance_other | train | def min_distance_other(self, other_manager,
return_names=False, return_data=False):
"""
Get the minimum distance between any pair of objects,
one in each manager.
Parameters
----------
other_manager : CollisionManager
Another collision manager object
return_names : bool
If true, a 2-tuple is returned containing
the names of the closest objects.
return_data : bool
If true, a DistanceData object is returned as well
Returns
-----------
distance : float
The min distance between a pair of objects,
one from each manager.
names : 2-tup of str
A 2-tuple containing two names (first from this manager,
second from the other_manager) indicating
the two closest objects.
data : DistanceData
| python | {
"resource": ""
} |
q23258 | cylinder_inertia | train | def cylinder_inertia(mass, radius, height, transform=None):
"""
Return the inertia tensor of a cylinder.
Parameters
------------
mass : float
Mass of cylinder
radius : float
Radius of cylinder
height : float
Height of cylinder
transform : (4,4) float
Transformation of cylinder
Returns
------------
inertia : (3,3) float
Inertia tensor
"""
h2, r2 = height ** 2, radius ** 2
diagonal = np.array([((mass * h2) / 12) + ((mass * r2) / 4),
| python | {
"resource": ""
} |
q23259 | principal_axis | train | def principal_axis(inertia):
"""
Find the principal components and principal axis
of inertia from the inertia tensor.
Parameters
------------
inertia : (3,3) float
Inertia tensor
Returns
------------
components : (3,) float
Principal components of inertia
vectors : (3,3) float
Row vectors pointing along the
principal axes of inertia
| python | {
"resource": ""
} |
q23260 | transform_inertia | train | def transform_inertia(transform, inertia_tensor):
"""
Transform an inertia tensor to a new frame.
More details in OCW PDF:
MIT16_07F09_Lec26.pdf
Parameters
------------
transform : (3, 3) or (4, 4) float
Transformation matrix
inertia_tensor : (3, 3) float
Inertia tensor
Returns
------------
transformed : (3, 3) float
Inertia tensor in new frame
"""
# check inputs and extract rotation
transform = np.asanyarray(transform, dtype=np.float64)
if transform.shape == (4, 4):
rotation = transform[:3, :3]
elif transform.shape == (3, 3):
rotation = transform
else:
raise ValueError('transform must be (3,3) or (4,4)!')
| python | {
"resource": ""
} |
q23261 | autolight | train | def autolight(scene):
"""
Generate a list of lights for a scene that looks decent.
Parameters
--------------
scene : trimesh.Scene
Scene with geometry
Returns
--------------
lights : [Light]
List of light objects
transforms : (len(lights), 4, 4) float
Transformation matrices for light positions.
"""
# create two default | python | {
"resource": ""
} |
q23262 | tracked_array | train | def tracked_array(array, dtype=None):
"""
Properly subclass a numpy ndarray to track changes.
Avoids some pitfalls of subclassing by forcing contiguous
arrays, and does a view into a TrackedArray.
Parameters
------------
array : array- like object
To be turned into a TrackedArray
dtype : np.dtype
Which dtype to use for the array
Returns
------------
tracked : TrackedArray
Contains input array data
"""
# if someone passed us None, just create an empty array
if array is None:
| python | {
"resource": ""
} |
q23263 | TrackedArray.md5 | train | def md5(self):
"""
Return an MD5 hash of the current array.
Returns
-----------
md5: str, hexadecimal MD5 of the array
"""
if self._modified_m or not hasattr(self, '_hashed_md5'):
if self.flags['C_CONTIGUOUS']:
hasher = hashlib.md5(self)
self._hashed_md5 = hasher.hexdigest()
else:
# the case where we have sliced our nice
# contiguous array into a non- contiguous block
| python | {
"resource": ""
} |
q23264 | TrackedArray.crc | train | def crc(self):
"""
A zlib.crc32 or zlib.adler32 checksum
of the current data.
Returns
-----------
crc: int, checksum from zlib.crc32 or zlib.adler32
"""
if self._modified_c or not hasattr(self, '_hashed_crc'):
if self.flags['C_CONTIGUOUS']:
self._hashed_crc = crc32(self)
else:
# the case where we have sliced our nice
# contiguous array into a non- contiguous block | python | {
"resource": ""
} |
q23265 | TrackedArray._xxhash | train | def _xxhash(self):
"""
An xxhash.b64 hash of the array.
Returns
-------------
xx: int, xxhash.xxh64 hash of array.
"""
# repeat the bookkeeping to get a contiguous array inside
# the function to avoid additional function calls
# these functions are called millions of times so everything helps
if self._modified_x or not hasattr(self, '_hashed_xx'):
| python | {
"resource": ""
} |
q23266 | Cache.verify | train | def verify(self):
"""
Verify that the cached values are still for the same
value of id_function and delete all stored items if
the value of id_function has changed.
"""
# if we are in a lock don't check anything
if self._lock != 0:
return
# check the hash of our data
id_new = self._id_function()
# things changed
if id_new != self.id_current:
if len(self.cache) > 0:
log.debug('%d items cleared from cache: %s',
| python | {
"resource": ""
} |
q23267 | Cache.clear | train | def clear(self, exclude=None):
"""
Remove all elements in the cache.
"""
if exclude is None:
self.cache = {}
else:
| python | {
"resource": ""
} |
q23268 | DataStore.is_empty | train | def is_empty(self):
"""
Is the current DataStore empty or not.
Returns
----------
empty: bool, False if there are items in the DataStore
"""
if len(self.data) == 0:
return True
for v in self.data.values():
if is_sequence(v):
if len(v) == 0:
| python | {
"resource": ""
} |
q23269 | DataStore.md5 | train | def md5(self):
"""
Get an MD5 reflecting everything in the DataStore.
Returns
----------
md5: str, MD5 in hexadecimal
"""
hasher = hashlib.md5()
for key in sorted(self.data.keys()):
| python | {
"resource": ""
} |
q23270 | DataStore.crc | train | def crc(self):
"""
Get a CRC reflecting everything in the DataStore.
Returns
| python | {
"resource": ""
} |
q23271 | DataStore.fast_hash | train | def fast_hash(self):
"""
Get a CRC32 or xxhash.xxh64 reflecting the DataStore.
Returns
| python | {
"resource": ""
} |
q23272 | identifier_simple | train | def identifier_simple(mesh):
"""
Return a basic identifier for a mesh, consisting of properties
that have been hand tuned to be somewhat robust to rigid
transformations and different tesselations.
Parameters
----------
mesh : Trimesh object
Source geometry
Returns
----------
identifier : (6,) float
Identifying values of the mesh
"""
# verify the cache once
mesh._cache.verify()
# don't check hashes during identifier as we aren't
# changing any data values of the mesh inside block
# if we did change values in cache block things would break
with mesh._cache:
# pre-allocate identifier so indexes of values can't move around
# like they might if we used hstack or something else
identifier = np.zeros(6, dtype=np.float64)
# avoid thrashing the cache unnecessarily
mesh_area = mesh.area
# start with properties that are valid regardless of watertightness
# note that we're going to try to make all parameters relative
# to area so other values don't get blown up at weird scales
identifier[0] = mesh_area
# topological constant and the only thing we can really
# trust in this fallen world
identifier[1] = mesh.euler_number
# if we have a watertight mesh include volume and inertia
if mesh.is_volume:
# side length of a cube ratio
# 1.0 for cubes, different values for other things
identifier[2] = (((mesh_area / 6.0) ** (1.0 / 2.0)) /
(mesh.volume ** (1.0 / 3.0)))
# save vertices for radius calculation
vertices = mesh.vertices - mesh.center_mass
# we are going to special case radially symmetric meshes
# to replace their surface area with ratio of their
# surface area to a primitive sphere or cylinder surface area
# this is because tessellated curved surfaces are really rough
# to reliably hash as they are very sensitive to floating point
# and tessellation error. By making area proportionate to a fit
# primitive area we are able to reliably hash at more sigfigs
if mesh.symmetry == 'radial':
# cylinder height
| python | {
"resource": ""
} |
q23273 | identifier_hash | train | def identifier_hash(identifier, sigfig=None):
"""
Hash an identifier array to a specified number of
significant figures.
Parameters
----------
identifier : (n,) float
Vector of properties
sigfig : (n,) int
Number of sigfigs per property
Returns
----------
| python | {
"resource": ""
} |
q23274 | convert_to_vertexlist | train | def convert_to_vertexlist(geometry, **kwargs):
"""
Try to convert various geometry objects to the constructor
args for a pyglet indexed vertex list.
Parameters
------------
obj : Trimesh, Path2D, Path3D, (n,2) float, (n,3) float
Object to render
Returns
------------
args : tuple
Args to be passed to pyglet indexed vertex list
constructor.
"""
if util.is_instance_named(geometry, 'Trimesh'):
return mesh_to_vertexlist(geometry, **kwargs)
elif util.is_instance_named(geometry, 'Path'):
# works for Path3D and Path2D
# both of which inherit from Path
return path_to_vertexlist(geometry, **kwargs)
elif util.is_instance_named(geometry, 'PointCloud'):
# pointcloud objects contain colors
| python | {
"resource": ""
} |
q23275 | mesh_to_vertexlist | train | def mesh_to_vertexlist(mesh,
group=None,
smooth=True,
smooth_threshold=60000):
"""
Convert a Trimesh object to arguments for an
indexed vertex list constructor.
Parameters
-------------
mesh : trimesh.Trimesh
Mesh to be rendered
group : str
Rendering group for the vertex list
smooth : bool
Should we try to smooth shade the mesh
smooth_threshold : int
Maximum number of faces to smooth shade
Returns
--------------
args : (7,) tuple
Args for vertex list constructor
"""
if hasattr(mesh.visual, 'uv') and mesh.visual.uv is not None:
# if the mesh has texture defined pass it to pyglet
vertex_count = len(mesh.vertices)
normals = mesh.vertex_normals.reshape(-1).tolist()
faces = mesh.faces.reshape(-1).tolist()
vertices = mesh.vertices.reshape(-1).tolist()
# get the per- vertex UV coordinates
uv = mesh.visual.uv
# if someone passed (n, 3) UVR cut it off here
if uv.shape[1] > 2:
| python | {
"resource": ""
} |
q23276 | path_to_vertexlist | train | def path_to_vertexlist(path, group=None, colors=None, **kwargs):
"""
Convert a Path3D object to arguments for an
indexed vertex list constructor.
Parameters
-------------
path : trimesh.path.Path3D object
Mesh to be rendered
group : str
Rendering group for the vertex list
Returns
--------------
args : (7,) tuple
Args for vertex list constructor
"""
# avoid cache check inside tight loop
vertices = path.vertices
# get (n, 2, (2|3)) lines
lines = np.vstack([util.stack_lines(e.discrete(vertices))
for e in path.entities])
count = len(lines)
# stack zeros for 2D lines
if util.is_shape(vertices, (-1, 2)): | python | {
"resource": ""
} |
q23277 | points_to_vertexlist | train | def points_to_vertexlist(points,
colors=None,
group=None,
**kwargs):
"""
Convert a numpy array of 3D points to args for
a vertex list constructor.
Parameters
-------------
points : (n, 3) float
Points to be rendered
colors : (n, 3) or (n, 4) float
Colors for each point
group : str
Rendering group for the vertex list
Returns
--------------
args : (7,) tuple
Args for vertex list constructor
"""
points = np.asanyarray(points, dtype=np.float64)
if util.is_shape(points, (-1, 2)):
points = np.column_stack((points, np.zeros(len(points))))
elif not util.is_shape(points, (-1, 3)): | python | {
"resource": ""
} |
q23278 | material_to_texture | train | def material_to_texture(material):
"""
Convert a trimesh.visual.texture.Material object into
a pyglet- compatible texture object.
Parameters
--------------
material : trimesh.visual.texture.Material
Material to be converted
Returns
---------------
texture : pyglet.image.Texture
Texture loaded into pyglet form
"""
# try to extract a PIL image from material
if hasattr(material, 'image'):
img = material.image
else:
img = material.baseColorTexture
if img is None:
return None
# use a PNG export to exchange into pyglet
| python | {
"resource": ""
} |
q23279 | matrix_to_gl | train | def matrix_to_gl(matrix):
"""
Convert a numpy row- major homogenous transformation matrix
to a flat column- major GLfloat transformation.
Parameters
-------------
matrix : (4,4) float
Row- major homogenous transform
Returns
-------------
glmatrix : (16,) gl.GLfloat
Transform in pyglet format
"""
matrix = np.asanyarray(matrix, dtype=np.float64)
| python | {
"resource": ""
} |
q23280 | vector_to_gl | train | def vector_to_gl(array, *args):
"""
Convert an array and an optional set of args into a
flat vector of gl.GLfloat
| python | {
"resource": ""
} |
q23281 | light_to_gl | train | def light_to_gl(light, transform, lightN):
"""
Convert trimesh.scene.lighting.Light objects into
args for gl.glLightFv calls
Parameters
--------------
light : trimesh.scene.lighting.Light
Light object to be converted to GL
transform : (4, 4) float
Transformation matrix of light
lightN : int
Result of gl.GL_LIGHT0, gl.GL_LIGHT1, etc
Returns
--------------
multiarg : [tuple]
List of args to pass to gl.glLightFv eg:
[gl.glLightfb(*a) for a in multiarg]
"""
# convert color to opengl
gl_color = vector_to_gl(light.color.astype(np.float64) / 255.0)
assert len(gl_color) == 4
# cartesian translation from | python | {
"resource": ""
} |
q23282 | Trackball.down | train | def down(self, point):
"""Record an initial mouse press at a given point.
Parameters
----------
point : (2,) int
The x and y pixel coordinates of the mouse press.
"""
| python | {
"resource": ""
} |
q23283 | Trackball.drag | train | def drag(self, point):
"""Update the tracball during a drag.
Parameters
----------
point : (2,) int
The current x and y pixel coordinates of the mouse during a drag.
This will compute a movement for the trackball with the relative
motion between this point and the one marked by down().
"""
point = np.array(point, dtype=np.float32)
dx, dy = point - self._pdown
mindim = 0.3 * np.min(self._size)
target = self._target
x_axis = self._pose[:3, 0].flatten()
y_axis = self._pose[:3, 1].flatten()
z_axis = self._pose[:3, 2].flatten()
eye = self._pose[:3, 3].flatten()
# Interpret drag as a rotation
if self._state == Trackball.STATE_ROTATE:
x_angle = -dx / mindim
x_rot_mat = transformations.rotation_matrix(
x_angle, y_axis, target
)
y_angle = dy / mindim
y_rot_mat = transformations.rotation_matrix(
y_angle, x_axis, target
)
| python | {
"resource": ""
} |
q23284 | Trackball.scroll | train | def scroll(self, clicks):
"""Zoom using a mouse scroll wheel motion.
Parameters
----------
clicks : int
The number of clicks. Positive numbers indicate forward wheel
movement.
"""
target = self._target
ratio = 0.90
mult = 1.0
if clicks > 0:
mult = ratio**clicks
elif clicks < 0:
mult = (1.0 / ratio)**abs(clicks)
z_axis = self._n_pose[:3, 2].flatten()
eye = self._n_pose[:3, 3].flatten()
radius = np.linalg.norm(eye - target)
translation = (mult * radius - radius) * z_axis
t_tf = np.eye(4)
| python | {
"resource": ""
} |
q23285 | Trackball.rotate | train | def rotate(self, azimuth, axis=None):
"""Rotate the trackball about the "Up" axis by azimuth radians.
Parameters
----------
azimuth : float
The number of radians to rotate.
"""
target = self._target
y_axis = self._n_pose[:3, 1].flatten()
if axis is not None:
y_axis = axis
| python | {
"resource": ""
} |
q23286 | look_at | train | def look_at(points, fov, rotation=None, distance=None, center=None):
"""
Generate transform for a camera to keep a list
of points in the camera's field of view.
Parameters
-------------
points : (n, 3) float
Points in space
fov : (2,) float
Field of view, in DEGREES
rotation : None, or (4, 4) float
Rotation matrix for initial rotation
center : None, or (3,) float
Center of field of view.
Returns
--------------
transform : (4, 4) float
Transformation matrix with points in view
"""
if rotation is None:
rotation = np.eye(4)
else:
rotation = np.asanyarray(rotation, dtype=np.float64)
points = np.asanyarray(points, dtype=np.float64) | python | {
"resource": ""
} |
q23287 | camera_to_rays | train | def camera_to_rays(camera):
"""
Convert a trimesh.scene.Camera object to ray origins
and direction vectors. Will return one ray per pixel,
as set in camera.resolution.
Parameters
--------------
camera : trimesh.scene.Camera
Camera with transform defined
Returns
--------------
origins : (n, 3) float
Ray origins in space
vectors : (n, 3) float
Ray direction unit vectors
angles : (n, 2) float
Ray spherical coordinate angles in radians
"""
# radians of half the field of view
half = np.radians(camera.fov / 2.0)
# scale it down by two pixels to keep image under resolution
| python | {
"resource": ""
} |
q23288 | Camera.resolution | train | def resolution(self, values):
"""
Set the camera resolution in pixels.
Parameters
------------
resolution (2,) float
Camera resolution in pixels
"""
values = np.asanyarray(values, dtype=np.int64)
if values.shape != (2,):
| python | {
"resource": ""
} |
q23289 | Camera.scene | train | def scene(self, value):
"""
Set the reference to the scene that this camera is in.
Parameters
-------------
scene : None, or trimesh.Scene
Scene where this camera is attached
"""
# save the scene reference
self._scene = value
# check if we have local not None transform
# an if we can apply it to the scene graph
# also check here that scene is a real scene
if (hasattr(self, '_transform') and
self._transform is not None and | python | {
"resource": ""
} |
q23290 | Camera.focal | train | def focal(self):
"""
Get the focal length in pixels for the camera.
Returns
------------
focal : (2,) float
Focal length in pixels
"""
if self._focal is None:
| python | {
"resource": ""
} |
q23291 | Camera.K | train | def K(self):
"""
Get the intrinsic matrix for the Camera object.
Returns
-----------
K : (3, 3) float
Intrinsic matrix for camera
"""
K = np.eye(3, dtype=np.float64)
K[0, 0] = self.focal[0] | python | {
"resource": ""
} |
q23292 | Camera.fov | train | def fov(self):
"""
Get the field of view in degrees.
Returns
-------------
fov : (2,) float
XY field of view in degrees
"""
if self._fov is None:
fov = [2.0 * np.degrees(np.arctan((px / 2.0) / f))
| python | {
"resource": ""
} |
q23293 | Camera.fov | train | def fov(self, values):
"""
Set the field of view in degrees.
Parameters
-------------
values : (2,) float
Size of FOV to set in degrees
"""
if values is None:
| python | {
"resource": ""
} |
q23294 | sinwave | train | def sinwave(scene):
"""
A callback passed to a scene viewer which will update
transforms in the viewer periodically.
Parameters
-------------
scene : trimesh.Scene
Scene containing geometry
"""
# create an empty homogenous transformation
matrix = np.eye(4)
# set Y as cos of time
matrix[1][3] = np.cos(time.time()) * 2
# | python | {
"resource": ""
} |
q23295 | to_volume | train | def to_volume(mesh,
file_name=None,
max_element=None,
mesher_id=1):
"""
Convert a surface mesh to a 3D volume mesh generated by gmsh.
An easy way to install the gmsh sdk is through the gmsh-sdk
package on pypi, which downloads and sets up gmsh:
pip install gmsh-sdk
Algorithm details, although check gmsh docs for more information:
The "Delaunay" algorithm is split into three separate steps.
First, an initial mesh of the union of all the volumes in the model is performed,
without inserting points in the volume. The surface mesh is then recovered using H.
Si's boundary recovery algorithm Tetgen/BR. Then a three-dimensional version of the
2D Delaunay algorithm described above is applied to insert points in the volume to
respect the mesh size constraints.
The Frontal" algorithm uses J. Schoeberl's Netgen algorithm.
The "HXT" algorithm is a new efficient and parallel reimplementaton
of the Delaunay algorithm.
The "MMG3D" algorithm (experimental) allows to generate
anisotropic tetrahedralizations
Parameters
--------------
mesh : trimesh.Trimesh
Surface mesh of input geometry
file_name : str or None
Location to save output, in .msh (gmsh) or .bdf (Nastran) format
max_element : float or None
Maximum length of an element in the volume mesh
mesher_id : int
3D unstructured algorithms:
1: Delaunay, 4: Frontal, 7: MMG3D, 10: HXT
Returns
------------
data : None or bytes
MSH data, only returned if file_name is None
"""
# checks mesher selection
if mesher_id not in [1, 4, 7, 10]:
raise ValueError('unavilable mesher selected!')
else:
mesher_id = int(mesher_id)
# set max element length to a best guess if not specified
if max_element is None:
max_element = np.sqrt(np.mean(mesh.area_faces))
if file_name is not None:
# check extensions to make sure it is supported format
if not any(file_name.lower().endswith(e)
for e in ['.bdf', '.msh', '.inp', '.diff', '.mesh']):
raise ValueError(
'Only Nastran (.bdf), Gmsh (.msh), Abaqus (*.inp), ' +
'Diffpack (*.diff) and Inria Medit (*.mesh) formats ' +
'are available!')
# exports to disk for gmsh to read using a temp file
mesh_file = tempfile.NamedTemporaryFile(suffix='.stl', delete=False)
| python | {
"resource": ""
} |
q23296 | local_voxelize | train | def local_voxelize(mesh, point, pitch, radius, fill=True, **kwargs):
"""
Voxelize a mesh in the region of a cube around a point. When fill=True,
uses proximity.contains to fill the resulting voxels so may be meaningless
for non-watertight meshes. Useful to reduce memory cost for small values of
pitch as opposed to global voxelization.
Parameters
-----------
mesh : trimesh.Trimesh
Source geometry
point : (3, ) float
Point in space to voxelize around
pitch : float
Side length of a single voxel cube
radius : int
Number of voxel cubes to return in each direction.
kwargs : parameters to pass to voxelize_subdivide
Returns
-----------
voxels : (m, m, m) bool
Array of local voxels where m=2*radius+1
origin_position : (3,) float
Position of the voxel grid origin in space
"""
from scipy import ndimage
# make sure point is correct type/shape
point = np.asanyarray(point, dtype=np.float64).reshape(3)
# this is a gotcha- radius sounds a lot like it should be in
# float model space, not int voxel space so check
if not isinstance(radius, int):
raise ValueError('radius needs to be an integer number of cubes!')
# Bounds of region
bounds = np.concatenate((point - (radius + 0.5) * pitch,
point + (radius + 0.5) * pitch))
# faces that intersect axis aligned bounding box
faces = list(mesh.triangles_tree.intersection(bounds))
# didn't hit anything so exit
if len(faces) == 0:
return np.array([], dtype=np.bool), np.zeros(3)
local = mesh.submesh([[f] for f in faces], append=True)
# Translate mesh so point is at 0,0,0
local.apply_translation(-point)
sparse, origin = voxelize_subdivide(local, pitch, **kwargs)
matrix = sparse_to_matrix(sparse)
| python | {
"resource": ""
} |
q23297 | voxelize_ray | train | def voxelize_ray(mesh,
pitch,
per_cell=[2, 2],
**kwargs):
"""
Voxelize a mesh using ray queries.
Parameters
-------------
mesh : Trimesh object
Mesh to be voxelized
pitch : float
Length of voxel cube
per_cell : (2,) int
How many ray queries to make per cell
Returns
-------------
voxels : (n, 3) int
Voxel positions
origin : (3, ) int
Origin of voxels
"""
# how many rays per cell
per_cell = np.array(per_cell).astype(np.int).reshape(2)
# edge length of cube voxels
pitch = float(pitch)
| python | {
"resource": ""
} |
q23298 | fill_voxelization | train | def fill_voxelization(occupied):
"""
Given a sparse surface voxelization, fill in between columns.
Parameters
--------------
occupied: (n, 3) int, location of filled cells
Returns
--------------
filled: (m, 3) int, location of filled cells
"""
# validate inputs
occupied = np.asanyarray(occupied, dtype=np.int64)
if not util.is_shape(occupied, (-1, 3)):
raise ValueError('incorrect shape')
# create grid and mark inner voxels
max_value = occupied.max() + 3
grid = np.zeros((max_value,
max_value,
max_value),
dtype=np.int64)
voxels_sparse = np.add(occupied, 1)
grid.__setitem__(tuple(voxels_sparse.T), 1)
for i in range(max_value):
check_dir2 = False
for j in range(0, max_value - 1):
| python | {
"resource": ""
} |
q23299 | multibox | train | def multibox(centers, pitch, colors=None):
"""
Return a Trimesh object with a box at every center.
Doesn't do anything nice or fancy.
Parameters
-----------
centers: (n,3) float, center of boxes that are occupied
pitch: float, the edge length of a voxel
colors: (3,) or (4,) or (n,3) or (n, 4) float, color of boxes
Returns
---------
rough: Trimesh object representing inputs
"""
from . import primitives
from .base import Trimesh
b = primitives.Box(extents=[pitch, pitch, pitch])
v = np.tile(centers, (1, len(b.vertices))).reshape((-1, 3))
v += np.tile(b.vertices, (len(centers), 1))
f = np.tile(b.faces, (len(centers), 1))
f += np.tile(np.arange(len(centers)) * len(b.vertices),
(len(b.faces), 1)).T.reshape((-1, 1))
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.