Package: quantized-mesh-encoder
quantized-mesh-encoderA fast PythonQuantized Meshencoder. Encodes a mesh with
100k coordinates and 180k triangles in 20ms.Example viewer.The Grand Canyon and Walhalla Plateau. The mesh is created usingpydelatinorpymartini, encoded usingquantized-mesh-encoder, served on-demand usingdem-tiler, and
rendered withdeck.gl.OverviewQuantized Meshis a format to encode terrain meshes for
efficient client-side terrain rendering. Such files are supported inCesiumanddeck.gl.This library is designed to support performant server-side on-demand terrain
mesh generation.InstallWith pip:pip install quantized-mesh-encoderor with Conda:conda install -c conda-forge quantized-mesh-encoderUsingAPIquantized_mesh_encoder.encodeArguments:f: a writable file-like object in which to write encoded bytespositions: (array[float]): either a 1D Numpy array or a 2D Numpy array of
shape(-1, 3)containing 3D positions.indices(array[int]): either a 1D Numpy array or a 2D Numpy array of shape(-1, 3)indicating triples of coordinates frompositionsto make
triangles. For example, if the first three values ofindicesare0,1,2, then that defines a triangle formed by the first 9 values inpositions,
three for the first vertex (index0), three for the second vertex, and three
for the third vertex.Keyword arguments:bounds(List[float], optional): a list of bounds,[minx, miny, maxx, maxy]. By default, inferred as the minimum and maximum values ofpositions.sphere_method(str, optional): As part of the header information when
encoding Quantized Mesh, it's necessary to compute abounding
sphere, which contains all positions of the mesh.sphere_methoddesignates the algorithm to use for creating the bounding
sphere. Must be one of'bounding_box','naive','ritter'orNone.
Default isNone.'bounding_box': Finds the bounding box of all positions, then defines
the center of the sphere as the center of the bounding box, and defines
the radius as the distance back to the corner. This method produces the
largest bounding sphere, but is the fastest: roughly 70 µs on my computer.'naive': Finds the bounding box of all positions, then defines the
center of the sphere as the center of the bounding box. It then checks the
distance to every other point and defines the radius as the maximum of
these distances. This method will produce a slightly smaller bounding
sphere than thebounding_boxmethod when points are not in the 3D
corners. This is the next fastest at roughly 160 µs on my computer.'ritter': Implements the Ritter Method for bounding spheres. It first
finds the center of the longest span, then checks every point for
containment, enlarging the sphere if necessary. Thiscanproduce smaller
bounding spheres than the naive method, but it does not always, so often
both are run, see next option. This is the slowest method, at roughly 300
µs on my computer.None: Runs both the naive and the ritter methods, then returns the
smaller of the two. Since this runs both algorithms, it takes around 500
µs on my computerellipsoid(quantized_mesh_encoder.Ellipsoid, optional): ellipsoid defined by its semi-majoraand semi-minorbaxes.
Default: WGS84 ellipsoid.extensions: list of extensions to encode in quantized mesh object. These must beExtensioninstances. SeeQuantized Mesh Extensions.quantized_mesh_encoder.EllipsoidEllipsoid used for mesh calculations.Arguments:a(float): semi-major axisb(float): semi-minor axisquantized_mesh_encoder.WGS84DefaultWGS84 ellipsoid. Has a semi-major axisaof 6378137.0 meters and semi-minor axisbof 6356752.3142451793 meters.Quantized Mesh ExtensionsThere are a variety ofextensionsto the Quantized Mesh spec.quantized_mesh_encoder.VertexNormalsExtensionImplements theTerrain Lightingextension. Per-vertex normals will be generated from your mesh data.Keyword Arguments:indices: mesh indicespositions: mesh positionsellipsoid: instance of Ellipsoid class, default: WGS84 ellipsoidquantized_mesh_encoder.WaterMaskExtensionImplements theWater Maskextension.Keyword Arguments:data(Union[np.ndarray, np.uint8, int]): Data for water mask.quantized_mesh_encoder.MetadataExtensionImplements theMetadataextension.data(Union[Dict, bytes]): Metadata data to encode. If a dictionary,json.dumpswill be called to create bytes in UTF-8 encoding.ExamplesWrite to filefromquantized_mesh_encoderimportencodewithopen('output.terrain','wb')asf:encode(f,positions,indices)Quantized mesh files are usually saved gzipped. An easy way to create a gzipped
file is to usegzip.open:importgzipfromquantized_mesh_encoderimportencodewithgzip.open('output.terrain','wb')asf:encode(f,positions,indices)Write to bufferIt's also pretty simple to write to an in-memory buffer instead of a filefromioimportBytesIOfromquantized_mesh_encoderimportencodewithBytesIO()asbio:encode(bio,positions,indices)Or to gzip the in-memory buffer:importgzipfromioimportBytesIOwithBytesIO()asbio:withgzip.open(bio,'wb')asgzipf:encode(gzipf,positions,indices)Alternate EllipsoidBy default, theWGS84
ellipsoidis
used for all calculations. An alternate ellipsoid may be useful for non-Earth
planetary bodies.fromquantized_mesh_encoderimportencode,Ellipsoid# From https://ui.adsabs.harvard.edu/abs/2010EM%26P..106....1A/abstractmars_ellipsoid=Ellipsoid(3_395_428,3_377_678)withopen('output.terrain','wb')asf:encode(f,positions,indices,ellipsoid=mars_ellipsoid)Quantized Mesh Extensionsfromquantized_mesh_encoderimportencode,VertexNormalsExtension,MetadataExtensionvertex_normals=VertexNormalsExtension(positions=positions,indices=indices)metadata=MetadataExtension(data={'hello':'world'})withopen('output.terrain','wb')asf:encode(f,positions,indices,extensions=(vertex_normals,metadata))Generating the meshTo encode a mesh into a quantized mesh file, you first need a mesh! This project
was designed to be used withpydelatinorpymartini, fast elevation heightmap to terrain mesh generators.importquantized_mesh_encoderfromimageioimportimreadfrompymartiniimportdecode_ele,Martini,rescale_positionsimportmercantilepng=imread(png_path)terrain=decode_ele(png,'terrarium')terrain=terrain.Tmartini=Martini(png.shape[0]+1)tile=martini.create_tile(terrain)vertices,triangles=tile.get_mesh(10)# Use mercantile to find the bounds in WGS84 of this tilebounds=mercantile.bounds(mercantile.Tile(x,y,z))# Rescale positions to WGS84rescaled=rescale_positions(vertices,terrain,bounds=bounds,flip_y=True)withBytesIO()asf:quantized_mesh_encoder.encode(f,rescaled,triangles)f.seek(0)return("OK","application/vnd.quantized-mesh",f.read())You can also look at the source of_mesh()indem-tilerfor a working reference.LicenseMuch of this code is ported or derived fromquantized-mesh-tilein some way.quantized-mesh-tileis also released under the MIT license.