Export a mesh to a dict

    Parameters
    ------------
    mesh : Trimesh object
             Mesh to be exported
    encoding : str, or None
                 'base64'

    Returns
    -------------
16895
def export_dict(mesh, encoding=None):
    

    def encode(item, dtype=None):
        if encoding is None:
            return item.tolist()
        else:
            if dtype is None:
                dtype = item.dtype
            return util.array_to_encoded(item, dtype=dtype, encoding=encoding)

    # metadata keys we explicitly want to preserve
    # sometimes there are giant datastructures we don't
    # care about in metadata which causes exports to be
    # extremely slow, so skip all but known good keys
    meta_keys = ['units', 'file_name', 'file_path']
    metadata = {k: v for k, v in mesh.metadata.items() if k in meta_keys}

    export = {
        'metadata': metadata,
        'faces': encode(mesh.faces),
        'face_normals': encode(mesh.face_normals),
        'vertices': encode(mesh.vertices)
    }
    if mesh.visual.kind == 'face':
        export['face_colors'] = encode(mesh.visual.face_colors)
    elif mesh.visual.kind == 'vertex':
        export['vertex_colors'] = encode(mesh.visual.vertex_colors)

    return export
213362
def export_to_json(self):
        

        return {
            hostname: sorted(self._encode_key(key) for key in pins)
            for hostname, pins in self._storage.items()
        }
179430
def decode_coords(ds, gridfile=None):
        
        extra_coords = set(ds.coords)
        for var in six.itervalues(ds.variables):
            if 'mesh' in var.attrs:
                mesh = var.attrs['mesh']
                if mesh not in extra_coords:
                    extra_coords.add(mesh)
                    try:
                        mesh_var = ds.variables[mesh]
                    except KeyError:
                        warn('Could not find mesh variable %s' % mesh)
                        continue
                    if 'node_coordinates' in mesh_var.attrs:
                        extra_coords.update(
                            mesh_var.attrs['node_coordinates'].split())
                    if 'face_node_connectivity' in mesh_var.attrs:
                        extra_coords.add(
                            mesh_var.attrs['face_node_connectivity'])
        if gridfile is not None and not isinstance(gridfile, xr.Dataset):
            gridfile = open_dataset(gridfile)
            ds.update({k: v for k, v in six.iteritems(gridfile.variables)
                       if k in extra_coords})
        if xr_version < (0, 11):
            ds.set_coords(extra_coords.intersection(ds.variables),
                          inplace=True)
        else:
            ds._coord_names.update(extra_coords.intersection(ds.variables))
        return ds
751962
def write(filename, mesh, file_format=None, **kwargs):
    
    if not file_format:
        # deduce file format from extension
        file_format = _filetype_from_filename(filename)

    # check cells for sanity
    for key, value in mesh.cells.items():
        if key[:7] == "polygon":
            assert value.shape[1] == int(key[7:])
        else:
            assert value.shape[1] == num_nodes_per_cell[key]

    try:
        interface, args, default_kwargs = _writer_map[file_format]
    except KeyError:
        raise KeyError(
            "Unknown format '{}'. Pick one of {}".format(
                file_format, sorted(list(_writer_map.keys()))
            )
        )

    # Build kwargs
    _kwargs = default_kwargs.copy()
    _kwargs.update(kwargs)

    # Write
    return interface.write(filename, mesh, *args, **_kwargs)
254570
def export(self):
        
        data = {}
        for key, value in self.items():
            data[key] = value

        return data
1098088
def from_proto(cls, proto_mesh, scale):
        

        mesh = cls(**proto_mesh.items())
        mesh._copy_roche_values()
        mesh._scale_mesh(scale=scale)

        return mesh
910485
def export_collada(mesh, **kwargs):
    
    meshes = mesh
    if not isinstance(mesh, (list, tuple, set, np.ndarray)):
        meshes = [mesh]

    c = collada.Collada()
    nodes = []
    for i, m in enumerate(meshes):

        # Load uv, colors, materials
        uv = None
        colors = None
        mat = _unparse_material(None)
        if m.visual.defined:
            if m.visual.kind == 'texture':
                mat = _unparse_material(m.visual.material)
                uv = m.visual.uv
            elif m.visual.kind == 'vertex':
                colors = (m.visual.vertex_colors / 255.0)[:, :3]
        c.effects.append(mat.effect)
        c.materials.append(mat)

        # Create geometry object
        vertices = collada.source.FloatSource(
            'verts-array', m.vertices.flatten(), ('X', 'Y', 'Z'))
        normals = collada.source.FloatSource(
            'normals-array', m.vertex_normals.flatten(), ('X', 'Y', 'Z'))
        input_list = collada.source.InputList()
        input_list.addInput(0, 'VERTEX', '#verts-array')
        input_list.addInput(1, 'NORMAL', '#normals-array')
        arrays = [vertices, normals]
        if uv is not None:
            texcoords = collada.source.FloatSource(
                'texcoords-array', uv.flatten(), ('U', 'V'))
            input_list.addInput(2, 'TEXCOORD', '#texcoords-array')
            arrays.append(texcoords)
        if colors is not None:
            idx = 2
            if uv:
                idx = 3
            colors = collada.source.FloatSource('colors-array',
                                                colors.flatten(), ('R', 'G', 'B'))
            input_list.addInput(idx, 'COLOR', '#colors-array')
            arrays.append(colors)
        geom = collada.geometry.Geometry(
            c, uuid.uuid4().hex, uuid.uuid4().hex, arrays
        )
        indices = np.repeat(m.faces.flatten(), len(arrays))

        matref = 'material{}'.format(i)
        triset = geom.createTriangleSet(indices, input_list, matref)
        geom.primitives.append(triset)
        c.geometries.append(geom)

        matnode = collada.scene.MaterialNode(matref, mat, inputs=[])
        geomnode = collada.scene.GeometryNode(geom, [matnode])
        node = collada.scene.Node('node{}'.format(i), children=[geomnode])
        nodes.append(node)
    scene = collada.scene.Scene('scene', nodes)
    c.scenes.append(scene)
    c.scene = scene

    b = io.BytesIO()
    c.write(b)
    b.seek(0)
    return b.read()
686898
def export_to_tf_tensor(self, x):
    
    mesh_impl = self.mesh_impl(x)
    return mesh_impl.export_to_tf_tensor(
        x, self.tensors[x].to_laid_out_tensor())
361427
def import_surf_mesh(file_name):
    
    raw_content = read_file(file_name)
    raw_content = raw_content.split("\n")
    content = []
    for rc in raw_content:
        temp = rc.strip().split()
        content.append(temp)

    # 1st line defines the dimension and it must be 3
    if int(content[0][0]) != 3:
        raise TypeError("Input mesh '" + str(file_name) + "' must be 3-dimensional")

    # Create a NURBS surface instance and fill with the data read from mesh file
    surf = shortcuts.generate_surface(rational=True)

    # 2nd line is the degrees
    surf.degree_u = int(content[1][0])
    surf.degree_v = int(content[1][1])

    # 3rd line is the number of weighted control points in u and v directions
    dim_u = int(content[2][0])
    dim_v = int(content[2][1])

    # Starting from 6th line, we have the weighted control points
    ctrlpts_end = 5 + (dim_u * dim_v)
    ctrlpts_mesh = content[5:ctrlpts_end]

    # mesh files have the control points in u-row order format
    ctrlpts = compatibility.flip_ctrlpts_u(ctrlpts_mesh, dim_u, dim_v)

    # mesh files store control points in format (x, y, z, w)
    ctrlptsw = compatibility.generate_ctrlptsw(ctrlpts)

    # Set control points
    surf.set_ctrlpts(ctrlptsw, dim_u, dim_v)

    # 4th and 5th lines are knot vectors
    surf.knotvector_u = [float(u) for u in content[3]]
    surf.knotvector_v = [float(v) for v in content[4]]

    # Return the surface instance
    return surf
21619
def write(self, filename="mesh.vtk", binary=True):
        
        import vtkplotter.vtkio as vtkio

        return vtkio.write(self, filename, binary)
856751
def out_shape_from_meshgrid(mesh):
    """"""
    if len(mesh) == 1:
        return (len(mesh[0]),)
    else:
        return np.broadcast(*mesh).shape
396549
def normalize_mesh(mesh):
  ''''''
  mesh = dict(mesh)
  pos = mesh['position'][:,:3].copy()
  pos -= (pos.max(0)+pos.min(0)) / 2.0
  pos /= np.abs(pos).max()
  mesh['position'] = pos
  return mesh
1192829
def export(self, mesh, rlzs_by_gsim, num_ses):
        
        rupture = self.rupture
        events = self.get_events(rlzs_by_gsim)
        events_by_ses = self.get_events_by_ses(events, num_ses)
        new = ExportedRupture(self.serial, events_by_ses)
        new.mesh = mesh[()]
        if isinstance(rupture.surface, geo.ComplexFaultSurface):
            new.typology = 'complexFaultsurface'
        elif isinstance(rupture.surface, geo.SimpleFaultSurface):
            new.typology = 'simpleFaultsurface'
        elif isinstance(rupture.surface, geo.GriddedSurface):
            new.typology = 'griddedRupture'
        elif isinstance(rupture.surface, geo.MultiSurface):
            new.typology = 'multiPlanesRupture'
        else:
            new.typology = 'singlePlaneRupture'
        new.is_from_fault_source = iffs = isinstance(
            rupture.surface, (geo.ComplexFaultSurface,
                              geo.SimpleFaultSurface))
        new.is_gridded_surface = igs = isinstance(
            rupture.surface, geo.GriddedSurface)
        new.is_multi_surface = ims = isinstance(
            rupture.surface, geo.MultiSurface)
        new.lons, new.lats, new.depths = get_geom(
            rupture.surface, iffs, ims, igs)
        new.surface = rupture.surface
        new.strike = rupture.surface.get_strike()
        new.dip = rupture.surface.get_dip()
        new.rake = rupture.rake
        new.hypocenter = rupture.hypocenter
        new.tectonic_region_type = rupture.tectonic_region_type
        new.magnitude = new.mag = rupture.mag
        new.top_left_corner = None if iffs or ims or igs else (
            new.lons[0], new.lats[0], new.depths[0])
        new.top_right_corner = None if iffs or ims or igs else (
            new.lons[1], new.lats[1], new.depths[1])
        new.bottom_left_corner = None if iffs or ims or igs else (
            new.lons[2], new.lats[2], new.depths[2])
        new.bottom_right_corner = None if iffs or ims or igs else (
            new.lons[3], new.lats[3], new.depths[3])
        return new
693268
def vecs_to_datmesh(x, y):
    
    x, y = meshgrid(x, y)
    out = zeros(x.shape + (2,), dtype=float)
    out[:, :, 0] = x
    out[:, :, 1] = y
    return out
451663
function processMesh(mesh) {
      var geometry = mesh.geometry;

      var mode;

      // Use the correct mode
      if (mesh.isLineSegments) {
        mode = WEBGL_CONSTANTS.LINES;
      } else if (mesh.isLineLoop) {
        mode = WEBGL_CONSTANTS.LINE_LOOP;
      } else if (mesh.isLine) {
        mode = WEBGL_CONSTANTS.LINE_STRIP;
      } else if (mesh.isPoints) {
        mode = WEBGL_CONSTANTS.POINTS;
      } else {
        if (!geometry.isBufferGeometry) {
          var geometryTemp = new THREE.BufferGeometry();
          geometryTemp.fromGeometry(geometry);
          geometry = geometryTemp;
        }

        if (mesh.drawMode === THREE.TriangleFanDrawMode) {
          console.warn(
            'GLTFExporter: TriangleFanDrawMode and wireframe incompatible.'
          );
          mode = WEBGL_CONSTANTS.TRIANGLE_FAN;
        } else if (mesh.drawMode === THREE.TriangleStripDrawMode) {
          mode = mesh.material.wireframe
            ? WEBGL_CONSTANTS.LINE_STRIP
            : WEBGL_CONSTANTS.TRIANGLE_STRIP;
        } else {
          mode = mesh.material.wireframe
            ? WEBGL_CONSTANTS.LINES
            : WEBGL_CONSTANTS.TRIANGLES;
        }
      }

      var gltfMesh = {};

      var attributes = {};
      var primitives = [];
      var targets = [];

      // Conversion between attributes names in threejs and gltf spec
      var nameConversion = {
        uv: 'TEXCOORD_0',
        uv2: 'TEXCOORD_1',
        color: 'COLOR_0',
        skinWeight: 'WEIGHTS_0',
        skinIndex: 'JOINTS_0'
      };

      var originalNormal = geometry.getAttribute('normal');

      if (
        originalNormal !== undefined &&
        !isNormalizedNormalAttribute(originalNormal)
      ) {
        console.warn(
          'THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one.'
        );

        geometry.addAttribute(
          'normal',
          createNormalizedNormalAttribute(originalNormal)
        );
      }

      // @QUESTION Detect if .vertexColors = THREE.VertexColors?
      // For every attribute create an accessor
      for (var attributeName in geometry.attributes) {
        var attribute = geometry.attributes[attributeName];
        attributeName =
          nameConversion[attributeName] || attributeName.toUpperCase();

        // JOINTS_0 must be UNSIGNED_BYTE or UNSIGNED_SHORT.
        var array = attribute.array;
        if (
          attributeName === 'JOINTS_0' &&
          !(array instanceof Uint16Array) &&
          !(array instanceof Uint8Array)
        ) {
          console.warn(
            'GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.'
          );
          attribute = new THREE.BufferAttribute(
            new Uint16Array(array),
            attribute.itemSize,
            attribute.normalized
          );
        }

        if (attributeName.substr(0, 5) !== 'MORPH') {
          var accessor = processAccessor(attribute, geometry);
          if (accessor !== null) {
            attributes[attributeName] = accessor;
          }
        }
      }

      if (originalNormal !== undefined)
        geometry.addAttribute('normal', originalNormal);

      // Skip if no exportable attributes found
      if (Object.keys(attributes).length === 0) {
        return null;
      }

      // Morph targets
      if (
        mesh.morphTargetInfluences !== undefined &&
        mesh.morphTargetInfluences.length > 0
      ) {
        var weights = [];
        var targetNames = [];
        var reverseDictionary = {};

        if (mesh.morphTargetDictionary !== undefined) {
          for (var key in mesh.morphTargetDictionary) {
            reverseDictionary[mesh.morphTargetDictionary[key]] = key;
          }
        }

        for (var i = 0; i < mesh.morphTargetInfluences.length; ++i) {
          var target = {};

          var warned = false;

          for (var attributeName in geometry.morphAttributes) {
            // glTF 2.0 morph supports only POSITION/NORMAL/TANGENT.
            // Three.js doesn't support TANGENT yet.

            if (attributeName !== 'position' && attributeName !== 'normal') {
              if (!warned) {
                console.warn(
                  'GLTFExporter: Only POSITION and NORMAL morph are supported.'
                );
                warned = true;
              }

              continue;
            }

            var attribute = geometry.morphAttributes[attributeName][i];

            // Three.js morph attribute has absolute values while the one of glTF has relative values.
            //
            // glTF 2.0 Specification:
            // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#morph-targets

            var baseAttribute = geometry.attributes[attributeName];
            // Clones attribute not to override
            var relativeAttribute = attribute.clone();

            for (var j = 0, jl = attribute.count; j < jl; j++) {
              relativeAttribute.setXYZ(
                j,
                attribute.getX(j) - baseAttribute.getX(j),
                attribute.getY(j) - baseAttribute.getY(j),
                attribute.getZ(j) - baseAttribute.getZ(j)
              );
            }

            target[attributeName.toUpperCase()] = processAccessor(
              relativeAttribute,
              geometry
            );
          }

          targets.push(target);

          weights.push(mesh.morphTargetInfluences[i]);
          if (mesh.morphTargetDictionary !== undefined)
            targetNames.push(reverseDictionary[i]);
        }

        gltfMesh.weights = weights;

        if (targetNames.length > 0) {
          gltfMesh.extras = {};
          gltfMesh.extras.targetNames = targetNames;
        }
      }

      var extras =
        Object.keys(geometry.userData).length > 0
          ? serializeUserData(geometry)
          : undefined;

      var forceIndices = options.forceIndices;
      var isMultiMaterial = Array.isArray(mesh.material);

      if (isMultiMaterial && geometry.groups.length === 0) return null;

      if (!forceIndices && geometry.index === null && isMultiMaterial) {
        // temporal workaround.
        console.warn(
          'THREE.GLTFExporter: Creating index for non-indexed multi-material mesh.'
        );
        forceIndices = true;
      }

      var didForceIndices = false;

      if (geometry.index === null && forceIndices) {
        var indices = [];

        for (var i = 0, il = geometry.attributes.position.count; i < il; i++) {
          indices[i] = i;
        }

        geometry.setIndex(indices);

        didForceIndices = true;
      }

      var materials = isMultiMaterial ? mesh.material : [mesh.material];
      var groups = isMultiMaterial
        ? geometry.groups
        : [{ materialIndex: 0, start: undefined, count: undefined }];

      for (var i = 0, il = groups.length; i < il; i++) {
        var primitive = {
          mode: mode,
          attributes: attributes
        };

        if (extras) primitive.extras = extras;

        if (targets.length > 0) primitive.targets = targets;

        if (geometry.index !== null) {
          primitive.indices = processAccessor(
            geometry.index,
            geometry,
            groups[i].start,
            groups[i].count
          );
        }

        var material = processMaterial(materials[groups[i].materialIndex]);

        if (material !== null) {
          primitive.material = material;
        }

        primitives.push(primitive);
      }

      if (didForceIndices) {
        geometry.setIndex(null);
      }

      gltfMesh.primitives = primitives;

      if (!outputJSON.meshes) {
        outputJSON.meshes = [];
      }

      outputJSON.meshes.push(gltfMesh);

      return outputJSON.meshes.length - 1;
    }
1251796
def get_header(mesh):
    
    nr_all_nodes = len(mesh['nodes'])
    nr_types = 1  # triangles

    # compute bandwidth
    bandwidth = -1
    for triangle in mesh['elements']['2']:
        diff1 = abs(triangle[0] - triangle[1])
        diff2 = abs(triangle[0] - triangle[2])
        diff3 = abs(triangle[1] - triangle[2])
        diffm = max(diff1, diff2, diff3)
        if(diffm > bandwidth):
            bandwidth = diffm

    el_infos = []
    # triangles
    for element in ('2',):
        el = mesh['elements'][element]
        if(element == '2'):
            el_type = 3
        elif(element == '1'):
            el_type = 12  # Neumann
        nr = len(el)
        nr_nodes = len(el[0])
        el_infos.append((el_type, nr, nr_nodes))

    # boundary elements
    for btype in ('12', '11'):
        if(btype in mesh['boundaries']):
            el_type = int(btype)
            nr = len(mesh['boundaries'][btype])
            nr_nodes = 2
            if(nr > 0):
                nr_types += 1
                el_infos.append((el_type, nr, nr_nodes))

    # now convert to string
    str_header = ''
    for a, b, c in [(nr_all_nodes, nr_types, bandwidth), ] + el_infos:
        str_header = str_header + '{0}  {1} {2}\n'.format(a, b, c)
    return str_header
1251590
public static void dumpTexCoords(AiMesh mesh, int coords) {
        if (!mesh.hasTexCoords(coords)) {
            System.out.println("mesh has no texture coordinate set " + coords);
            return;
        }
        
        for (int i = 0; i < mesh.getNumVertices(); i++) {
            int numComponents = mesh.getNumUVComponents(coords);
            System.out.print("[" + mesh.getTexCoordU(i, coords));
            
            if (numComponents > 1) {
                System.out.print(", " + mesh.getTexCoordV(i, coords));
            }
            
            if (numComponents > 2) {
                System.out.print(", " + mesh.getTexCoordW(i, coords));
            }
            
            System.out.println("]");
        }
    }