[WIP] adding typing and linting to visualizer code (backend python files) (#189)

* first round adding typing and linting to server files

* continued...

* added new formatting conventions

* committing current progress...

* finished with geometry

* homerun :')
This commit is contained in:
evonneng authored and GitHub committed 2022-07-22 16:38:58 -07:00
1 parent 6cfccab336
commit a78394c49d
10 files changed
+778 -278

No files matched your search

+378 -106
View File
@@ -12,56 +12,94 @@
# See the License for the specific language governing permissions and
# limitations under the License.
"""Geometry to render meshes, textures, etc.
"""
from __future__ import absolute_import, division, print_function
import sys
import base64
import sys
import uuid
from typing import Any, BinaryIO, Dict, Iterable, List, Optional, Tuple
import numpy as np
import umsgpack
if sys.version_info >= (3, 0):
unicode = str
from io import StringIO, BytesIO
UNICODE = str
from io import BytesIO, StringIO
else:
from StringIO import StringIO
BytesIO = StringIO
import umsgpack
import numpy as np
class SceneElement:
"""Base class for objects in the scene"""
class SceneElement(object):
def __init__(self):
self.uuid = unicode(uuid.uuid1())
self.uuid = UNICODE(uuid.uuid1())
def intrinsic_transform(self):
def intrinsic_transform(self): # pylint: disable=no-self-use
"""function for intrinsic transformation"""
return np.identity(4)
def lower(self, object_data: Dict[str, Any]) -> Dict[str, Any]: # pylint: disable=no-self-use
"""Formatting contents of object dictionary, returns a dictionary of formatted content
Args:
object_data: object being sent via websocket
"""
return object_data
class ReferenceSceneElement(SceneElement):
def lower_in_object(self, object_data):
"""Generic scene element class"""
field = None
def lower_in_object(self, object_data: Dict[str, Any]) -> str:
"""formatting contents of object dictionary, returns a dictionary of formatted content
Args:
object_data: object being sent via websocket
"""
object_data.setdefault(self.field, []).append(self.lower(object_data))
return self.uuid
class Geometry(ReferenceSceneElement):
"""Geometry class"""
field = "geometries"
class Material(ReferenceSceneElement):
"""Material class"""
field = "materials"
class Texture(ReferenceSceneElement):
"""Texture class"""
field = "textures"
class Image(ReferenceSceneElement):
"""Image class"""
field = "images"
class Box(Geometry):
def __init__(self, lengths):
"""Box object
Args:
lengths: length of side of box
"""
def __init__(self, lengths: List[float]):
super().__init__()
self.lengths = lengths
@@ -76,7 +114,13 @@ class Box(Geometry):
class Sphere(Geometry):
def __init__(self, radius):
"""Sphere object
Args:
radius: radius of sphere
"""
def __init__(self, radius: float):
super().__init__()
self.radius = radius
@@ -94,9 +138,12 @@ class Ellipsoid(Sphere):
"""
An Ellipsoid is treated as a Sphere of unit radius, with an affine
transformation applied to distort it into the ellipsoidal shape
Args:
radii: the radii of epllipsoid
"""
def __init__(self, radii):
def __init__(self, radii: List[float]):
super().__init__(1.0)
self.radii = radii
@@ -105,7 +152,13 @@ class Ellipsoid(Sphere):
class PlaneGeometry(Geometry):
def __init__(self, lengths):
"""Plane Class
Args:
lengths: the height and width of plane
"""
def __init__(self, lengths: List[float]):
super().__init__()
self.lengths = lengths
@@ -113,49 +166,73 @@ class PlaneGeometry(Geometry):
return {"uuid": self.uuid, "type": "PlaneGeometry", "width": self.lengths[0], "height": self.lengths[1]}
"""
A cylinder of the given height and radius. By Three.js convention, the axis of
rotational symmetry is aligned with the y-axis.
"""
class Cylinder(Geometry):
def __init__(self, height, radius=1.0, radiusTop=None, radiusBottom=None):
"""A cylinder of the given height and radius. By Three.js convention, the axis of
rotational symmetry is aligned with the y-axis.
Args:
height: height of cylinder
radius: radius for both top and bottom if top/bottom not given. Defaults to 1.0.
radius_top: radius of top. Defaults to None.
radius_bottom: radius of bottom. Defaults to None.
"""
def __init__(
self,
height: int,
radius: float = 1.0,
radius_top: Optional[float] = None,
radius_bottom: Optional[float] = None,
):
super().__init__()
if radiusTop is not None and radiusBottom is not None:
self.radiusTop = radiusTop
self.radiusBottom = radiusBottom
if radius_top is not None and radius_bottom is not None:
self.radius_top = radius_top
self.radius_bottom = radius_bottom
else:
self.radiusTop = radius
self.radiusBottom = radius
self.radius_top = radius
self.radius_bottom = radius
self.height = height
self.radialSegments = 50
self.radial_segments = 50
def lower(self, object_data):
return {
"uuid": self.uuid,
"type": "CylinderGeometry",
"radiusTop": self.radiusTop,
"radiusBottom": self.radiusBottom,
"radiusTop": self.radius_top,
"radiusBottom": self.radius_bottom,
"height": self.height,
"radialSegments": self.radialSegments,
"radialSegments": self.radial_segments,
}
class GenericMaterial(Material):
"""Generic Material base class
Args:
color: color of material. Defaults to 0xFFFFFF.
reflectivity: reflectivity index. Defaults to 0.5.
map: texture map of object. Defaults to None.
transparent: transparency value. Defaults to None.
opacity: opacity value. Defaults to 1.0.
linewidth: width of lines. Defaults to 1.0.
wireframe: whether to render wireframe around object. Defaults to False.
wireframe_linewidth: width of wireframe lines. Defaults to 1.0.
vertex_colors: whether to render vertex colors. Defaults to False.
"""
def __init__(
self,
color=0xFFFFFF,
reflectivity=0.5,
map=None,
side=2,
transparent=None,
opacity=1.0,
linewidth=1.0,
wireframe=False,
wireframeLinewidth=1.0,
vertexColors=False,
**kwargs
color: int = 0xFFFFFF,
reflectivity: float = 0.5,
map: Optional[Texture] = None, # pylint: disable=redefined-builtin
side: int = 2,
transparent: Optional[bool] = None,
opacity: float = 1.0,
linewidth: float = 1.0,
wireframe: bool = False,
wireframe_linewidth: float = 1.0,
vertex_colors: bool = False,
**kwargs,
):
super().__init__()
self.color = color
@@ -166,9 +243,10 @@ class GenericMaterial(Material):
self.opacity = opacity
self.linewidth = linewidth
self.wireframe = wireframe
self.wireframeLinewidth = wireframeLinewidth
self.vertexColors = vertexColors
self.wireframe_linewidth = wireframe_linewidth
self.vertex_colors = vertex_colors
self.properties = kwargs
self._type = self._type
def lower(self, object_data):
# Three.js allows a material to have an opacity which is != 1,
@@ -191,8 +269,8 @@ class GenericMaterial(Material):
"opacity": self.opacity,
"linewidth": self.linewidth,
"wireframe": bool(self.wireframe),
"wireframeLinewidth": self.wireframeLinewidth,
"vertexColors": (2 if self.vertexColors else 0), # three.js wants an enum
"wireframeLinewidth": self.wireframe_linewidth,
"vertexColors": (2 if self.vertex_colors else 0), # three.js wants an enum
}
data.update(self.properties)
if self.map is not None:
@@ -201,44 +279,63 @@ class GenericMaterial(Material):
class MeshBasicMaterial(GenericMaterial):
"""Basic material mesh class"""
_type = "MeshBasicMaterial"
class MeshPhongMaterial(GenericMaterial):
"""Phong material mesh class"""
_type = "MeshPhongMaterial"
class MeshLambertMaterial(GenericMaterial):
"""Lambert material mesh class"""
_type = "MeshLambertMaterial"
class MeshToonMaterial(GenericMaterial):
"""Toon material mesh class"""
_type = "MeshToonMaterial"
class LineBasicMaterial(GenericMaterial):
"""Basic Line Material class"""
_type = "LineBasicMaterial"
class PngImage(Image):
"""Png Image"""
def __init__(self, data):
super().__init__()
self.data = data
@staticmethod
def from_file(fname):
def from_file(fname: str):
"""Read in png image from file
Args:
fname: file name to read image from
"""
with open(fname, "rb") as f:
return PngImage(f.read())
def lower(self, object_data):
return {
"uuid": self.uuid,
"url": unicode("data:image/png;base64," + base64.b64encode(self.data).decode("ascii")),
"url": UNICODE("data:image/png;base64," + base64.b64encode(self.data).decode("ascii")),
}
class GenericTexture(Texture):
def __init__(self, properties):
"""Generic texture class"""
def __init__(self, properties: Iterable):
super().__init__()
self.properties = properties
@@ -252,8 +349,20 @@ class GenericTexture(Texture):
class ImageTexture(Texture):
def __init__(self, image, wrap=[1001, 1001], repeat=[1, 1], **kwargs):
"""Image Texture class
Args:
image: image represented as byte array
wrap: wrap format. Defaults to None.
repeat: repeat format. Defaults to None.
"""
def __init__(self, image: bytearray, wrap: List[int] = None, repeat: List[int] = None, **kwargs):
super().__init__()
if wrap is None:
wrap = [1001, 1001]
if repeat is None:
repeat = [1, 1]
self.image = image
self.wrap = wrap
self.repeat = repeat
@@ -271,12 +380,20 @@ class ImageTexture(Texture):
class Object(SceneElement):
def __init__(self, geometry, material=MeshPhongMaterial()):
"""Object element within scene
Args:
geometry: geometry of the object
material: material composition of object. Defaults to MeshPhongMaterial().
"""
def __init__(self, geometry: Geometry, material: GenericMaterial = MeshPhongMaterial()):
super().__init__()
self.geometry = geometry
self.material = material
self._type = self._type
def lower(self):
def lower(self, object_data):
data = {
"metadata": {
"version": 4.5,
@@ -298,11 +415,24 @@ class Object(SceneElement):
class Mesh(Object):
"""Mesh class"""
_type = "Mesh"
class OrthographicCamera(SceneElement):
def __init__(self, left, right, top, bottom, near, far, zoom=1):
"""Orthographic camera class
Args:
left: left bounds
right: right bounds
top: top bounds
bottom: bottom bounds
near: near plane
far: far plane
zoom: zoom param. Defaults to 1.
"""
def __init__(self, left: float, right: float, top: float, bottom: float, near: float, far: float, zoom: int = 1):
super(OrthographicCamera, self).__init__()
self.left = left
self.right = right
@@ -312,7 +442,7 @@ class OrthographicCamera(SceneElement):
self.far = far
self.zoom = zoom
def lower(self):
def lower(self, object_data):
data = {
"object": {
"uuid": self.uuid,
@@ -334,10 +464,8 @@ class PerspectiveCamera(SceneElement):
The PerspectiveCamera is the default camera used by the pyrad viewer. See
https://threejs.org/docs/#api/en/cameras/PerspectiveCamera for more
information.
"""
def __init__(self, fov=50, aspect=1, near=0.1, far=2000, zoom=1, filmGauge=35, filmOffset=0, focus=10):
"""
Args:
fov : Camera frustum vertical field of view, from bottom to top of view, in degrees. Default is 50.
aspect: Camera frustum aspect ratio, usually the canvas width / canvas height. Default is 1 (square canvas).
near : Camera frustum near plane. Default is 0.1. The valid range is greater than 0 and less than the current
@@ -345,31 +473,43 @@ class PerspectiveCamera(SceneElement):
PerspectiveCamera's near plane.
far : Camera frustum far plane. Default is 2000.
zoom : Gets or sets the zoom factor of the camera. Default is 1.
filmGauge: Film size used for the larger axis. Default is 35 (millimeters). This parameter does not influence
film_gauge: Film size used for the larger axis. Default is 35 (millimeters). This parameter does not influence
the projection matrix unless .filmOffset is set to a nonzero value.
filmOffset: Horizontal off-center offset in the same unit as .filmGauge. Default is 0.
film_offset: Horizontal off-center offset in the same unit as .filmGauge. Default is 0.
focus: Object distance used for stereoscopy and depth-of-field effects. This parameter does not influence
the projection matrix unless a StereoCamera is being used. Default is 10.
"""
"""
def __init__(
self,
fov: float = 50,
aspect: float = 1,
near: float = 0.1,
far: float = 2000,
zoom: int = 1,
film_gauge: float = 35,
film_offset: float = 0,
focus: float = 10,
):
super(PerspectiveCamera, self).__init__()
self.fov = fov
self.aspect = aspect
self.far = far
self.near = near
self.zoom = zoom
self.filmGauge = filmGauge
self.filmOffset = filmOffset
self.film_gauge = film_gauge
self.film_offset = film_offset
self.focus = focus
def lower(self):
def lower(self, object_data):
data = {
"object": {
"uuid": self.uuid,
"type": "PerspectiveCamera",
"aspect": self.aspect,
"far": self.far,
"filmGauge": self.filmGauge,
"filmOffset": self.filmOffset,
"filmGauge": self.film_gauge,
"filmOffset": self.film_offset,
"focus": self.focus,
"fov": self.fov,
"near": self.near,
@@ -379,31 +519,49 @@ class PerspectiveCamera(SceneElement):
return data
def item_size(array):
def item_size(array: np.ndarray) -> int:
"""Returns the size of the 1 or 2d numpy array
Args:
array: np array for which to get the size of
Raises:
ValueError: if n dimensions is not == 1 or 2
"""
if array.ndim == 1:
return 1
elif array.ndim == 2:
if array.ndim == 2:
return array.shape[0]
else:
raise ValueError(
"I can only pack 1- or 2-dimensional numpy arrays, but this one has {:d} dimensions".format(array.ndim)
)
raise ValueError(f"I can only pack 1- or 2-dimensional numpy arrays, but this one has {array.ndim:d} dimensions")
def threejs_type(dtype):
def threejs_type(dtype: type) -> Tuple[str, int]:
"""Converts the np type to 3js type, returns str name and hex of equivalent 3js type
Args:
dtype: np type
Raises:
ValueError: if unsupported datatype
"""
if dtype == np.uint8:
return "Uint8Array", 0x12
elif dtype == np.int32:
if dtype == np.int32:
return "Int32Array", 0x15
elif dtype == np.uint32:
if dtype == np.uint32:
return "Uint32Array", 0x16
elif dtype == np.float32:
if dtype == np.float32:
return "Float32Array", 0x17
else:
raise ValueError("Unsupported datatype: " + str(dtype))
raise ValueError("Unsupported datatype: " + str(dtype))
def pack_numpy_array(x):
def pack_numpy_array(x: np.ndarray) -> Dict[str, Any]:
"""convert numpy array to byte-based message with context, returns serialized message
Args:
x: array to pack into message format
"""
if x.dtype == np.float64:
x = x.astype(np.float32)
typename, extcode = threejs_type(x.dtype)
@@ -415,21 +573,36 @@ def pack_numpy_array(x):
}
def data_from_stream(stream):
def data_from_stream(stream: BinaryIO) -> str:
"""Read in data from some binary io stream and returns the serialized stream
Args:
stream: the stream in which data is being sent over
Raises:
ValueError: invalid stream type
"""
if sys.version_info >= (3, 0):
if isinstance(stream, BytesIO):
data = stream.read().decode(encoding="utf-8")
elif isinstance(stream, StringIO):
data = stream.read()
else:
raise ValueError("Stream must be instance of StringIO or BytesIO, not {}".format(type(stream)))
raise ValueError(f"Stream must be instance of StringIO or BytesIO, not {type(stream)}")
else:
data = stream.read()
return data
class MeshGeometry(Geometry):
def __init__(self, contents, mesh_format):
"""Basic mesh geometry class
Args:
contents: the stream of contents representing the mesh
mesh_format: specification of mesh format
"""
def __init__(self, contents: bytearray, mesh_format: str):
super().__init__()
self.contents = contents
self.mesh_format = mesh_format
@@ -439,39 +612,82 @@ class MeshGeometry(Geometry):
class ObjMeshGeometry(MeshGeometry):
def __init__(self, contents):
"""Basic mesh geometry class
Args:
contents: the stream of contents representing the mesh
"""
def __init__(self, contents: bytearray):
super().__init__(contents, "obj")
@staticmethod
def from_file(fname):
with open(fname, "r") as f:
def from_file(fname: str) -> MeshGeometry:
"""Reading mesh geometry from file. Returns mesh geometry object
Args:
fname: file name to read from
"""
with open(fname, "r", encoding="utf8") as f:
return MeshGeometry(f.read(), "obj")
@staticmethod
def from_stream(f):
def from_stream(f: BinaryIO) -> MeshGeometry:
"""Reads mesh geometry from io stream. Returns mesh geometry object
Args:
f: binary io stream to read from
"""
return MeshGeometry(data_from_stream(f), "obj")
class DaeMeshGeometry(MeshGeometry):
def __init__(self, contents):
"""Basic DAE mesh geometry class
Args:
contents: the stream of contents representing the mesh
"""
def __init__(self, contents: bytearray):
super().__init__(contents, "dae")
@staticmethod
def from_file(fname):
with open(fname, "r") as f:
def from_file(fname: str) -> MeshGeometry:
"""Reading mesh geometry from file. Returns mesh geometry object
Args:
fname: file name to read from
"""
with open(fname, "r", encoding="utf8") as f:
return MeshGeometry(f.read(), "dae")
@staticmethod
def from_stream(f):
def from_stream(f: BinaryIO) -> MeshGeometry:
"""Reads mesh geometry from io stream. Returns mesh geometry object
Args:
f: binary io stream to read from
"""
return MeshGeometry(data_from_stream(f), "dae")
class StlMeshGeometry(MeshGeometry):
def __init__(self, contents):
"""Basic STL mesh geometry class
Args:
contents: the stream of contents representing the mesh
"""
def __init__(self, contents: bytearray):
super().__init__(contents, "stl")
@staticmethod
def from_file(fname):
def from_file(fname: str) -> MeshGeometry:
"""Reading mesh geometry from file. Returns mesh geometry object
Args:
fname: file name to read from
"""
with open(fname, "rb") as f:
arr = np.frombuffer(f.read(), dtype=np.uint8)
_, extcode = threejs_type(np.uint8)
@@ -479,14 +695,19 @@ class StlMeshGeometry(MeshGeometry):
return MeshGeometry(encoded, "stl")
@staticmethod
def from_stream(f):
def from_stream(f: BinaryIO) -> MeshGeometry:
"""Reads mesh geometry from io stream. Returns mesh geometry object
Args:
f: binary io stream to read from
"""
if sys.version_info >= (3, 0):
if isinstance(f, BytesIO):
arr = np.frombuffer(f.read(), dtype=np.uint8)
elif isinstance(f, StringIO):
arr = np.frombuffer(bytes(f.read(), "utf-8"), dtype=np.uint8)
else:
raise ValueError("Stream must be instance of StringIO or BytesIO, not {}".format(type(f)))
raise ValueError(f"Stream must be instance of StringIO or BytesIO, not {type(f)}")
else:
arr = np.frombuffer(f.read(), dtype=np.uint8)
_, extcode = threejs_type(np.uint8)
@@ -495,11 +716,22 @@ class StlMeshGeometry(MeshGeometry):
class PlyMeshGeometry(MeshGeometry):
def __init__(self, contents):
"""Basic PLY mesh geometry class
Args:
contents: the stream of contents representing the mesh
"""
def __init__(self, contents: bytearray):
super().__init__(contents, "ply")
@staticmethod
def from_file(fname):
def from_file(fname: str) -> MeshGeometry:
"""Reading mesh geometry from file. Returns mesh geometry object
Args:
fname: file name to read from
"""
with open(fname, "rb") as f:
arr = np.frombuffer(f.read(), dtype=np.uint8)
_, extcode = threejs_type(np.uint8)
@@ -507,14 +739,19 @@ class PlyMeshGeometry(MeshGeometry):
return MeshGeometry(encoded, "ply")
@staticmethod
def from_stream(f):
def from_stream(f: BinaryIO) -> MeshGeometry:
"""Reads mesh geometry from io stream. Returns mesh geometry object
Args:
f: binary io stream to read from
"""
if sys.version_info >= (3, 0):
if isinstance(f, BytesIO):
arr = np.frombuffer(f.read(), dtype=np.uint8)
elif isinstance(f, StringIO):
arr = np.frombuffer(bytes(f.read(), "utf-8"), dtype=np.uint8)
else:
raise ValueError("Stream must be instance of StringIO or BytesIO, not {}".format(type(f)))
raise ValueError(f"Stream must be instance of StringIO or BytesIO, not {type(f)}")
else:
arr = np.frombuffer(f.read(), dtype=np.uint8)
_, extcode = threejs_type(np.uint8)
@@ -544,7 +781,7 @@ class TriangularMeshGeometry(Geometry):
__slots__ = ["vertices", "faces"]
def __init__(self, vertices, faces):
def __init__(self, vertices: np.ndarray, faces: np.ndarray):
super().__init__()
vertices = np.asarray(vertices, dtype=np.float32)
@@ -554,7 +791,7 @@ class TriangularMeshGeometry(Geometry):
self.vertices = vertices
self.faces = faces
def lower(self, object_data):
def lower(self, object_data) -> Dict[str, Any]:
return {
"uuid": self.uuid,
"type": "BufferGeometry",
@@ -566,12 +803,19 @@ class TriangularMeshGeometry(Geometry):
class PointsGeometry(Geometry):
def __init__(self, position, color=None):
"""Points Geometry class
Args:
position: position of the point to draw
color: color to render the point
"""
def __init__(self, position: np.ndarray, color: Optional[np.ndarray] = None):
super().__init__()
self.position = position
self.color = color
def lower(self, object_data):
def lower(self, object_data) -> Dict[str, Any]:
attrs = {"position": pack_numpy_array(self.position)}
if self.color is not None:
attrs["color"] = pack_numpy_array(self.color)
@@ -579,49 +823,74 @@ class PointsGeometry(Geometry):
class PointsMaterial(Material):
def __init__(self, size=0.001, color=0xFFFFFF, sizeAttenuation=True):
"""Points Material class
Args:
size: size of point to render
color: color to render the point
sizeAttenuation: whether to attenuate size
"""
def __init__(self, size: float = 0.001, color: int = 0xFFFFFF, size_attenuation: bool = True):
super().__init__()
self.size = size
self.color = color
self.sizeAttenuation = sizeAttenuation
self.size_attenuation = size_attenuation
def lower(self, object_data):
def lower(self, object_data) -> Dict[str, Any]:
return {
"uuid": self.uuid,
"type": "PointsMaterial",
"color": self.color,
"size": self.size,
"sizeAttenuation": bool(self.sizeAttenuation),
"sizeAttenuation": bool(self.size_attenuation),
"vertexColors": 2,
}
class Points(Object):
"""Points object class"""
_type = "Points"
def PointCloud(position, color, **kwargs):
def PointCloud(position: np.ndarray, color: np.ndarray, **kwargs) -> Points: # pylint: disable=invalid-name
"""Creates a point cloud with the specified position of points
Args:
position: position of points
color: color to render point cloud
"""
return Points(PointsGeometry(position, color), PointsMaterial(**kwargs))
class Line(Object):
"""Line class"""
_type = "Line"
class LineSegments(Object):
"""Line Segment class"""
_type = "LineSegments"
class LineLoop(Object):
"""Line Loop class"""
_type = "LineLoop"
def triad(scale=1.0):
def triad(scale: float = 1.0) -> LineSegments:
"""
A visual representation of the origin of a coordinate system, drawn as three
lines in red, green, and blue along the x, y, and z axes. The `scale` parameter
controls the length of the three lines.
Returns an `Object` which can be passed to `set_object()`
Args:
scale: scale size of triad
"""
return LineSegments(
PointsGeometry(
@@ -636,12 +905,15 @@ def triad(scale=1.0):
)
def camera(scale=1.0):
def camera(scale: float = 1.0) -> LineSegments:
"""
A visual representation of the origin of a coordinate system, drawn as three
lines in red, green, and blue along the x, y, and z axes. The `scale` parameter
controls the length of the three lines.
Returns an `Object` which can be passed to `set_object()`
Args:
scale: scale size of camera
"""
return LineSegments(
PointsGeometry(