How to use generic - 10 common examples

To help you get started, we’ve selected a few generic examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mikedh / trimesh / tests / test_dxf.py View on Github external
# get a path we can write
        temp_name = g.tempfile.NamedTemporaryFile(
            suffix='.dxf', delete=False).name

        # split drawings into single body parts
        splits = []
        for d in g.get_2D():
            s = d.split()
            # check area of split result vs source
            assert g.np.isclose(sum(i.area for i in s),
                                d.area)
            splits.append(s)

            d.export(file_obj=temp_name)
            r = g.trimesh.load(temp_name)
            assert g.np.isclose(r.area, d.area)

        single = g.np.hstack(splits)

        for p in single:
            p.vertices /= p.scale

            # make sure exporting by name works
            # use tempfile to avoid dumping file in
            # our working directory
            p.export(temp_name)
            r = g.trimesh.load(temp_name)

            ratio = abs(p.length - r.length) / p.length
            if ratio > .01:
                g.log.error('perimeter ratio on export %s wrong! %f %f %f',
                            p.metadata['file_name'],
github mikedh / trimesh / tests / test_loaded.py View on Github external
# we're going to load faces in a basic text way
        # and compare the order from this method to the
        # trimesh loader, to see if we get the same thing
        faces = []
        verts = []
        with open(file_name, 'r') as f:
            for line in f:
                line = line.strip()
                if line[0] == 'f':
                    faces.append(line[1:].strip().split())
                if line[0] == 'v':
                    verts.append(line[1:].strip().split())

        # get faces as basic numpy array
        faces = g.np.array(faces, dtype=g.np.int64) - 1
        verts = g.np.array(verts, dtype=g.np.float64)

        # trimesh loader should return the same face order
        assert g.np.allclose(faces, m.faces)
        assert g.np.allclose(verts, m.vertices)
github mikedh / trimesh / tests / test_obj.py View on Github external
# we're going to load faces in a basic text way
        # and compare the order from this method to the
        # trimesh loader, to see if we get the same thing
        faces = []
        verts = []
        with open(file_name, 'r') as f:
            for line in f:
                line = line.strip()
                if line[0] == 'f':
                    faces.append(line[1:].strip().split())
                if line[0] == 'v':
                    verts.append(line[1:].strip().split())

        # get faces as basic numpy array
        faces = g.np.array(faces, dtype=g.np.int64) - 1
        verts = g.np.array(verts, dtype=g.np.float64)

        # trimesh loader should return the same face order
        assert g.np.allclose(faces, m.faces)
        assert g.np.allclose(verts, m.vertices)
github mikedh / trimesh / tests / test_paths.py View on Github external
assert s.shape[1] == 2

    def test_color(self):
        p = g.get_mesh('2D/wrench.dxf')
        # make sure we have entities
        assert len(p.entities) > 0
        # make sure shape of colors is correct
        assert p.colors.shape == (len(p.entities), 4)
        color = [255, 0, 0, 255]
        # assign a color to the entity
        p.entities[0].color = color
        # make sure this is reflected in the path color
        assert g.np.allclose(p.colors[0], color)


class SplitTest(g.unittest.TestCase):

    def test_split(self):

        for fn in ['2D/ChuteHolderPrint.DXF',
                   '2D/tray-easy1.dxf',
                   '2D/sliding-base.dxf',
                   '2D/wrench.dxf',
                   '2D/spline_1.dxf']:
            p = g.get_mesh(fn)

            # make sure something was loaded
            assert len(p.root) > 0

            # split by connected
            split = p.split()
github mikedh / trimesh / tests / test_cache.py View on Github external
try:
    from . import generic as g
except BaseException:
    import generic as g

TEST_DIM = (10000, 3)


class CacheTest(g.unittest.TestCase):

    def test_hash(self):
        setup = 'import numpy, trimesh;'
        setup += 'd = numpy.random.random((10000,3));'
        setup += 't = trimesh.caching.tracked_array(d)'

        count = 10000

        mt = g.timeit.timeit(setup=setup,
                             stmt='t._modified_m=True;t.md5()',
                             number=count)
        ct = g.timeit.timeit(setup=setup,
                             stmt='t._modified_c=True;t.crc()',
                             number=count)
        xt = g.timeit.timeit(setup=setup,
                             stmt='t._modified_x=True;t.fast_hash()',
github mikedh / trimesh / tests / test_proximity.py View on Github external
n = 20
        n += n % 2
        pts = g.np.transpose([g.np.zeros(n),
                              g.np.ones(n),
                              g.np.linspace(-1, 1, n)])

        # the faces facing the points should differ for first and second half of the set
        # check their indices for inequality
        faceIdxsA, faceIdxsB = g.np.split(mesh.nearest.on_surface(pts)[-1], 2)
        assert (g.np.all(faceIdxsA == faceIdxsA[0]) and
                g.np.all(faceIdxsB == faceIdxsB[0]) and
                faceIdxsA[0] != faceIdxsB[0])


if __name__ == '__main__':
    g.trimesh.util.attach_to_log()
    g.unittest.main()
github mikedh / trimesh / tests / test_packing.py View on Github external
def test_paths(self):
        from trimesh.path import packing
        paths = [g.trimesh.load_path(i) for i in self.nestable]

        r, inserted = packing.pack_paths(paths)

        # number of paths inserted
        count = len(g.np.unique(inserted))
        # should have inserted all our paths
        assert count == len(paths)
        # splitting should result in the right number of paths
        assert count == len(r.split())


if __name__ == '__main__':
    g.trimesh.util.attach_to_log()
    g.unittest.main()
github mikedh / trimesh / tests / test_paths.py View on Github external
g.log.error('discrete %s not ccw!',
                                d.metadata['file_name'])

            for i in range(len(d.paths)):
                assert d.polygons_closed[i].is_valid
                assert d.polygons_closed[i].area > g.tol_path.zero
            export_dict = d.export(file_type='dict')
            to_dict = d.to_dict()
            assert isinstance(to_dict, dict)
            assert isinstance(export_dict, dict)
            assert len(to_dict) == len(export_dict)

            export_svg = d.export(file_type='svg')  # NOQA
            simple = d.simplify()  # NOQA
            split = d.split()
            g.log.info('Split %s into %d bodies, checking identifiers',
                       d.metadata['file_name'],
                       len(split))
            for body in split:
                body.identifier

            if len(d.root) == 1:
                d.apply_obb()

            # store the X values of bounds
            ori = d.bounds.copy()
            # apply a translation
            d.apply_translation([10, 0])
            # X should have translated by 10.0
            assert g.np.allclose(d.bounds[:, 0] - 10, ori[:, 0])
            # Y should not have moved
            assert g.np.allclose(d.bounds[:, 1], ori[:, 1])
github mikedh / trimesh / tests / test_graph.py View on Github external
def test_engine_time(self):
        for mesh in g.get_meshes():
            tic = [g.time.time()]
            for engine in self.engines:
                mesh.split(engine=engine, only_watertight=False)
                g.trimesh.graph.facets(mesh=mesh, engine=engine)
                tic.append(g.time.time())

            tic_diff = g.np.diff(tic)
            tic_min = tic_diff.min()
            tic_diff /= tic_min
            g.log.info('graph engine on %s (scale %f sec):\n%s',
                       mesh.metadata['file_name'],
                       tic_min,
                       str(g.np.column_stack((self.engines,
                                              tic_diff))))
github mikedh / trimesh / tests / test_boolean.py View on Github external
def test_multiple(self):
        """
        Make sure boolean operations work on multiple meshes.
        """
        engines = [
            ('blender', g.trimesh.interfaces.blender.exists),
            ('scad', g.trimesh.interfaces.scad.exists)]
        for engine, exists in engines:
            if not exists:
                continue
            a = g.trimesh.primitives.Sphere(center=[0, 0, 0])
            b = g.trimesh.primitives.Sphere(center=[0, 0, .75])
            c = g.trimesh.primitives.Sphere(center=[0, 0, 1.5])

            r = g.trimesh.boolean.union([a, b, c])

            assert r.is_volume
            assert r.body_count == 1
            assert g.np.isclose(r.volume,
                                8.617306056726884)