[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

+62 -16
View File
@@ -12,17 +12,27 @@
# See the License for the specific language governing permissions and
# limitations under the License.
from .geometry import SceneElement, Geometry, Object, LineSegments, PointsGeometry, LineBasicMaterial
"""Logic to render Camera objects in the Viewer"""
# import geometry as g
from . import geometry as g
import numpy as np
from typing import List, Optional, Tuple
import cv2
import numpy as np
from . import geometry as g
from .geometry import LineBasicMaterial, LineSegments, PointsGeometry
class ImagePlane(g.Mesh):
def __init__(self, image, height=1, width=1):
"""TODO(ethan): decide how to deal with the height and width"""
"""Returns an image rendered within a specified plane
Args:
image: image to be displayed
height: height of image. Defaults to 1.
width: width of image. Defaults to 1.
"""
def __init__(self, image: np.ndarray, height: int = 1, width: int = 1):
# TODO(ethan): decide how to deal with the height and width
self.image = image
geometry = g.PlaneGeometry([width, height])
material = g.MeshBasicMaterial(
@@ -31,12 +41,18 @@ class ImagePlane(g.Mesh):
super().__init__(geometry, material)
def get_camera_wireframe(scale: float = 0.3, f=4, w=1.5, h=2):
"""
Returns a wireframe of a 3D line-plot of a camera symbol.
def get_camera_wireframe(scale: float = 0.3, f: int = 4, w: int = 1.5, h: int = 2) -> np.ndarray:
"""Returns a wireframe of a 3D line-plot of a camera symbol.
At https://github.com/hangg7/mvs_visual/blob/275d382a824733a3187a8e3147be184dd6f14795/mvs_visual.py#L54.
Args:
f (focal length): this is the focal length
scale: scale of rendering
f: this is the focal length
w: width
h: height
Returns:
np.ndarray: stack of points corresponding to wireframe of camera
"""
ul = np.array([-w, h, -f])
ur = np.array([w, h, -f])
@@ -44,11 +60,24 @@ def get_camera_wireframe(scale: float = 0.3, f=4, w=1.5, h=2):
lr = np.array([w, -h, -f])
C = np.zeros(3)
camera_points = [C, ul, C, ur, C, ll, C, lr, C]
lines = np.stack([x for x in camera_points]) * scale
lines = np.stack(camera_points) * scale
return lines
def get_plane_pts(focal_length=(1.0, 1.0), image_size=(10, 10), camera_scale=1, scale_factor=1 / 4):
def get_plane_pts(
focal_length: Tuple[float, float] = (1.0, 1.0),
image_size: Tuple[int, int] = (10, 10),
camera_scale: int = 1,
scale_factor: float = 1 / 4,
) -> np.ndarray:
"""Returns points on the image plane given camera intrinsics
Args:
focal_length: focal length of camera. Defaults to (1.0, 1.0).
image_size: height and width of image. Defaults to (10, 10).
camera_scale: camera intrinsics scale. Defaults to 1.
scale_factor: image scale. Defaults to 1/4.
"""
Z = -(focal_length[0] + focal_length[1]) / 2 * camera_scale
X0, Y0, X1, Y1 = (
-image_size[0] / 2 * camera_scale,
@@ -61,7 +90,7 @@ def get_plane_pts(focal_length=(1.0, 1.0), image_size=(10, 10), camera_scale=1,
W, H = X1 - X0, Y0 - Y1
w, h = image_size
ratio = min(w / W, h / H)
oW, oH = w / ratio, h / ratio
oW, oH = w / ratio, h / ratio # pylint: disable=invalid-name
X0, Y0, X1, Y1 = -oW / 2, oH / 2, oW / 2, -oH / 2
wsteps, hsteps = int(w * scale_factor), int(h * scale_factor)
@@ -75,10 +104,27 @@ def get_plane_pts(focal_length=(1.0, 1.0), image_size=(10, 10), camera_scale=1,
return plane_pts
def frustum(scale=1.0, color=[0, 0, 0], focal_length=4, width=1.5, height=2):
"""TODO(ethan): make the scale adjustable depending on the camera size
color - color of lines using R, G, B. default is black
def frustum(
scale: float = 1.0,
color: Optional[List[float]] = None,
focal_length: int = 4,
width: float = 1.5,
height: int = 2,
) -> LineSegments:
"""Draws the camera frustums, returning line segments representing the frustums
Args:
scale: scale of the rendering. Defaults to 1.0.
color: color of lines. Defaults to [0, 0, 0].
focal_length: focal length of camera. Defaults to 4.
width: width of wireframe. Defaults to 1.5.
height: height of wireframe. Defaults to 2.
"""
# color - color of lines using R, G, B. default is black
if color is None:
color = [0, 0, 0]
# TODO(ethan): make the scale adjustable depending on the camera size
# print("linewidth")
camera_wireframe_lines = get_camera_wireframe(scale=scale, f=focal_length, w=width / 2.0, h=height / 2.0)
N = len(camera_wireframe_lines)
+17 -38
View File
@@ -12,6 +12,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
"""Commands callable from WebSocket Server bridge
"""
from dataclasses import dataclass
from typing import Any, Dict, List
@@ -33,9 +36,9 @@ class SetObject: # pylint: disable=too-few-public-methods
"""Set object command class: Instantiates and sets the object according to object type
Args:
geometry_or_object (_type_): object to be set
material (_type_, optional): material to be set. Defaults to None.
path (str): path of object in tree. Defaults to None.
geometry_or_object: object to be set
material: material to be set. Defaults to None.
path: path of object in tree. Defaults to None.
Raises:
ValueError: error if material is not set for object
@@ -63,11 +66,7 @@ class SetObject: # pylint: disable=too-few-public-methods
self.path = Path()
def lower(self) -> Dict[str, Any]:
"""creates properly formatted json
Returns:
Dict[str, Any]: json in proper format
"""
"""creates properly formatted json"""
return {"type": "set_object", "object": self.object.lower(), "path": self.path.lower()}
@@ -76,7 +75,7 @@ class GetObject:
"""Get object command class
Args:
path (str): path of object in tree. Defaults to None.
path: path of object in tree. Defaults to None.
"""
__slots__ = ["path"]
@@ -84,11 +83,7 @@ class GetObject:
path: str
def lower(self) -> Dict[str, Any]:
"""creates properly formatted json with object
Returns:
Dict[str, Any]: json in proper format
"""
"""creates properly formatted json with object"""
return {"type": "get_object", "path": self.path.lower()}
@@ -101,12 +96,8 @@ class SetTransform:
matrix: np.ndarray
path: str
def lower(self):
"""creates properly formatted json with transform matrix
Returns:
Dict[str, Any]: json in proper format
"""
def lower(self) -> Dict[str, Any]:
"""creates properly formatted json with transform matrix"""
return {"type": "set_transform", "path": self.path.lower(), "matrix": list(self.matrix.T.flatten())}
@@ -119,12 +110,8 @@ class SetOutputOptions:
output_options: List[str]
path: str
def lower(self):
"""creates properly formatted json with list of possible output options
Returns:
Dict[str, Any]: json in proper format
"""
def lower(self) -> Dict[str, Any]:
"""creates properly formatted json with list of possible output options"""
return {"type": "set_output_options", "path": self.path.lower(), "output_options": list(self.output_options)}
@@ -136,12 +123,8 @@ class Delete:
path: str
def lower(self):
"""creates properly formatted json updating tree
Returns:
Dict[str, Any]: json in proper format
"""
def lower(self) -> Dict[str, Any]:
"""creates properly formatted json updating tree"""
return {"type": "delete", "path": self.path.lower()}
@@ -155,10 +138,6 @@ class SetProperty:
value: list
path: str
def lower(self):
"""creates properly formatted json setting property
Returns:
Dict[str, Any]: json in proper format
"""
def lower(self) -> Dict[str, Any]:
"""creates properly formatted json setting property"""
return {"type": "set_property", "path": self.path.lower(), "property": self.key.lower(), "value": self.value}
+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(
+21 -5
View File
@@ -12,21 +12,36 @@
# See the License for the specific language governing permissions and
# limitations under the License.
"""Path class
"""
from __future__ import absolute_import, division, print_function
import sys
from typing import Tuple
if sys.version_info >= (3, 0):
unicode = str
UNICODE = str
class Path(object):
class Path:
"""Path class
Args:
entries: component parts of the path
"""
__slots__ = ["entries"]
def __init__(self, entries=tuple()):
def __init__(self, entries: Tuple = tuple()):
self.entries = entries
def append(self, other):
def append(self, other: str) -> "Path":
"""Methodthat appends a new component and returns new Path
Args:
other: _description_
"""
new_path = self.entries
for element in other.split("/"):
if len(element) == 0:
@@ -36,7 +51,8 @@ class Path(object):
return Path(new_path)
def lower(self):
return unicode("/" + "/".join(self.entries))
"""Convert path object to serializable format"""
return UNICODE("/" + "/".join(self.entries))
def __hash__(self):
return hash(self.entries)
+73 -27
View File
@@ -12,11 +12,13 @@
# See the License for the specific language governing permissions and
# limitations under the License.
"""Server bridge to faciliate interactions between python backend and javascript front end"""
from __future__ import absolute_import, division, print_function
import sys
from typing import Callable, List, Optional
import numpy as np
import tornado.gen
import tornado.ioloop
import tornado.web
@@ -50,50 +52,65 @@ WEBSOCKET_COMMANDS = [
WEBRTC_COMMANDS = ["set_image"]
def find_available_port(func, default_port, max_attempts=MAX_ATTEMPTS, **kwargs):
def find_available_port(func: Callable, default_port: int, max_attempts: int = MAX_ATTEMPTS, **kwargs) -> None:
"""Finds and attempts to connect to a port
Args:
func: function used on connecting to port
default_port: the default port
max_attempts: max number of attempts to try connection. Defaults to MAX_ATTEMPTS.
"""
for i in range(max_attempts):
port = default_port + i
try:
return func(port, **kwargs), port
except (OSError, zmq.error.ZMQError):
print("Port: {:d} in use, trying another...".format(port), file=sys.stderr)
print(f"Port: {port:d} in use, trying another...", file=sys.stderr)
except Exception as e:
print(type(e))
raise
else:
raise (
Exception(
"Could not find an available port in the range: [{:d}, {:d})".format(
default_port, max_attempts + default_port
)
)
)
raise (
Exception(f"Could not find an available port in the range: [{default_port:d}, {max_attempts + default_port:d})")
)
def force_codec(pc, sender, forced_codec):
def force_codec(pc: RTCPeerConnection, sender: RTCRtpSender, forced_codec: str) -> None:
"""Sets the codec preferences on a connection between sender and reciever
Args:
pc: peer connection point
sender: sender that will send to connection point
forced_codec: codec to set
"""
kind = forced_codec.split("/")[0]
codecs = RTCRtpSender.getCapabilities(kind).codecs
transceiver = next(t for t in pc.getTransceivers() if t.sender == sender)
transceiver.setCodecPreferences([codec for codec in codecs if codec.mimeType == forced_codec])
class WebSocketHandler(tornado.websocket.WebSocketHandler):
class WebSocketHandler(tornado.websocket.WebSocketHandler): # pylint: disable=abstract-method
"""Tornado websocket handler for receiving and sending commands from/to the viewer."""
def __init__(self, *args, **kwargs):
self.bridge = kwargs.pop("bridge")
super(WebSocketHandler, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
def check_origin(self, origin):
"""This disables CORS."""
return True
def open(self):
def open(self, *args: str, **kwargs: str):
"""open websocket bridge"""
self.bridge.websocket_pool.add(self)
print("opened:", self, file=sys.stderr)
self.bridge.send_scene(self)
async def on_message(self, message):
async def on_message(self, message: bytearray): # pylint: disable=invalid-overridden-method
"""On reception of message, parses the message and calls the appropriate function based on the type of command
Args:
message: byte message to parse
"""
data = message
m = umsgpack.unpackb(message)
type_ = m["type"]
@@ -122,7 +139,9 @@ class WebSocketHandler(tornado.websocket.WebSocketHandler):
video = SingleFrameStreamTrack()
self.bridge.video_tracks.add(video)
video_sender = pc.addTrack(video)
_ = pc.addTrack(video)
# TODO(eventually do something with the codec)
# video_sender = pc.addTrack(video)
# force_codec(pc, video_sender, video_codec)
await pc.setRemoteDescription(offer)
@@ -142,10 +161,18 @@ class WebSocketHandler(tornado.websocket.WebSocketHandler):
print("closed:", self, file=sys.stderr)
class ZMQWebSocketBridge(object):
class ZMQWebSocketBridge:
"""ZMQ web socket bridge class
Args:
zmq_url: zmq url to connect to. Defaults to None.
host: host of server. Defaults to "127.0.0.1".
websocket_port: websocket port to connect to. Defaults to None.
"""
context = zmq.Context()
def __init__(self, zmq_url=None, host="127.0.0.1", websocket_port=None):
def __init__(self, zmq_url: Optional[str] = None, host: str = "127.0.0.1", websocket_port: Optional[int] = None):
self.host = host
self.websocket_pool = set()
self.app = self.make_app()
@@ -156,7 +183,7 @@ class ZMQWebSocketBridge(object):
if zmq_url is None:
def f(port):
return self.setup_zmq("{:s}://{:s}:{:d}".format(DEFAULT_ZMQ_METHOD, self.host, port))
return self.setup_zmq(f"{DEFAULT_ZMQ_METHOD:s}://{self.host:s}:{port:d}")
(self.zmq_socket, self.zmq_stream, self.zmq_url), _ = find_available_port(f, DEFAULT_ZMQ_PORT)
else:
@@ -180,7 +207,12 @@ class ZMQWebSocketBridge(object):
"""Create a tornado application for the websocket server."""
return tornado.web.Application([(r"/", WebSocketHandler, {"bridge": self})])
def handle_zmq(self, frames):
def handle_zmq(self, frames: List[bytes]):
"""Switch function that places commands in tree based on websocket command
Args:
frames: the list containing command + object to be placed in tree
"""
cmd = frames[0].decode("utf-8")
print(cmd)
if len(frames) != 3:
@@ -235,21 +267,34 @@ class ZMQWebSocketBridge(object):
self.zmq_socket.send(b"ok")
return
def forward_to_websockets(self, frames):
"""Forward a zmq message to all websockets."""
def forward_to_websockets(self, frames: List[bytes]):
"""Forward a zmq message to all websockets.
Args:
frames: byte messages to be sent over
"""
_, _, data = frames # cmd, path, data
for websocket in self.websocket_pool:
websocket.write_message(data, binary=True)
def setup_zmq(self, url):
"""Setup a zmq socket and connect it to the given url."""
zmq_socket = self.context.socket(zmq.REP)
def setup_zmq(self, url: str):
"""Setup a zmq socket and connect it to the given url.
Args:
url: point of connection
"""
zmq_socket = self.context.socket(zmq.REP) # pylint: disable=no-member
zmq_socket.bind(url)
zmq_stream = ZMQStream(zmq_socket)
zmq_stream.on_recv(self.handle_zmq)
return zmq_socket, zmq_stream, url
def send_scene(self, websocket):
def send_scene(self, websocket: WebSocketHandler):
"""Sends entire tree of information over the specified websocket
Args:
websocket: websocket to send information over
"""
for node in walk(self.tree):
if node.object is not None:
websocket.write_message(node.object, binary=True)
@@ -259,6 +304,7 @@ class ZMQWebSocketBridge(object):
websocket.write_message(node.transform, binary=True)
def run(self):
"""starts and runs the websocket bridge"""
self.ioloop.start()
+26 -6
View File
@@ -17,12 +17,21 @@ Some helpful functions for creating geometric transformations.
"""
import math
from typing import List, Optional
import numpy as np
def get_unit_vector(data, axis=None, out=None):
"""Return ndarray normalized by length, i.e. Euclidean norm, along axis."""
def get_unit_vector(
data: List[float], axis: Optional[List[float]] = None, out: Optional[List[float]] = None
) -> Optional[np.ndarray]:
"""Return ndarray normalized by length, i.e. Euclidean norm, along axis.
Args:
data: direction in which we want to calculate the unit vector for
axis: the axis along which to get the unit vector
out: buffer in which we write the unit vector out to (if not returning)
"""
if out is None:
data = np.array(data, dtype=np.float64, copy=True)
if data.ndim == 1:
@@ -39,17 +48,28 @@ def get_unit_vector(data, axis=None, out=None):
data /= length
if out is None:
return data
return None
def get_translation_matrix(direction):
"""Return matrix to translate by direction vector."""
def get_translation_matrix(direction: List[float]) -> np.ndarray:
"""Return matrix to translate by direction vector.
Args:
direction: specifying direction of translation
"""
M = np.identity(4)
M[:3, 3] = direction[:3]
return M
def get_rotation_matrix(angle, direction, point=None):
"""Return matrix to rotate about axis defined by point and direction."""
def get_rotation_matrix(angle: float, direction: List[float], point: Optional[List[float]] = None) -> np.ndarray:
"""Return matrix to rotate about axis defined by point and direction.
Args:
angle: angle of rotation
direction: specifying axis of rotation
point: if specified, rotation not around origin
"""
sina = math.sin(angle)
cosa = math.cos(angle)
direction = get_unit_vector(direction[:3])
+20 -2
View File
@@ -12,12 +12,19 @@
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Functions for traversing server bridge tree nodes (storage)
"""
from __future__ import absolute_import, division, print_function
from collections import defaultdict
from typing import List
class TreeNode(defaultdict):
"""Tree Node object"""
__slots__ = ["object", "transform", "properties", "animation"]
def __init__(self, *args, **kwargs):
@@ -31,14 +38,25 @@ class TreeNode(defaultdict):
SceneTree = lambda: TreeNode(SceneTree)
def walk(tree):
def walk(tree: TreeNode) -> None:
"""Walk the entire tree and return the values
Args:
tree: the root of the tree to start search
"""
yield tree
for v in tree.values():
for t in walk(v): # could use `yield from` if we didn't need python2
yield t
def find_node(tree, path):
def find_node(tree: TreeNode, path: List[str]) -> TreeNode:
"""Find the node associated with the path
Args:
tree: the root of the tree to start search
path: the path we are searching for
"""
if len(path) == 0:
return tree
else:
+27 -5
View File
@@ -12,14 +12,27 @@
# See the License for the specific language governing permissions and
# limitations under the License.
"""Generic utility functions
"""
from typing import Any, Dict, List, Optional, Tuple
import numpy as np
import torch
from pyrad.cameras.cameras import get_camera, get_intrinsics_from_intrinsics_matrix
from pyrad.cameras.cameras import Camera, get_camera, get_intrinsics_from_intrinsics_matrix
from pyrad.viewer.server.visualizer import Viewer
def get_chunks(lst, num_chunks=None, size_of_chunk=None):
"""Returns list of n elements, constaining a sublist."""
def get_chunks(
lst: List[float], num_chunks: Optional[int] = None, size_of_chunk: Optional[int] = None
) -> List[List[float]]:
"""Returns list of n elements, constaining a sublist.
Args:
lst: List to be chunked up
num_chunks: number of chunks to split list into
size_of_chunk: size of each chunk
"""
if num_chunks:
assert not size_of_chunk
size = len(lst) // num_chunks
@@ -32,7 +45,9 @@ def get_chunks(lst, num_chunks=None, size_of_chunk=None):
return chunks
def get_intrinsics_matrix_and_camera_to_world_h(camera_object, image_height):
def get_intrinsics_matrix_and_camera_to_world_h(
camera_object: Dict[str, Any], image_height: int
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Returns the camera intrinsics matrix and the camera to world homogeneous matrix.
Args:
camera_object: a Camera object.
@@ -62,7 +77,14 @@ def get_intrinsics_matrix_and_camera_to_world_h(camera_object, image_height):
return intrinsics_matrix, camera_to_world_h
def get_camera_from_vis(vis, name="/Cameras/Main Camera", image_height=100):
def get_camera_from_vis(vis: Viewer, name: str = "/Cameras/Main Camera", image_height: int = 100) -> Camera:
"""Caculates the specified camera object's parameters (extrinsics/intrinsics); returns associated Camera Object.
Args:
vis: viewer object
name: name of camera to calculate for. Defaults to "/Cameras/Main Camera".
image_height: height of image. Defaults to 100.
"""
data = vis[name].get_object()
if data is None:
return None
+23 -15
View File
@@ -12,19 +12,19 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
import queue
"""Video Stream objects for WebRTC"""
import math
import cv2
import numpy
import numpy as np
from aiortc import VideoStreamTrack
from av import VideoFrame
class FlagVideoStreamTrack(VideoStreamTrack):
"""
A video track that returns an animated flag.
A video track that returns an animated flag. For debugging purposes :')
"""
def __init__(self):
@@ -33,7 +33,7 @@ class FlagVideoStreamTrack(VideoStreamTrack):
height, width = 480, 640
# generate flag
data_bgr = numpy.hstack(
data_bgr = np.hstack(
[
self._create_rectangle(width=213, height=480, color=(255, 0, 0)), # blue
self._create_rectangle(width=214, height=480, color=(255, 255, 255)), # white
@@ -42,19 +42,19 @@ class FlagVideoStreamTrack(VideoStreamTrack):
)
# shrink and center it
M = numpy.float32([[0.5, 0, width / 4], [0, 0.5, height / 4]])
M = np.float32([[0.5, 0, width / 4], [0, 0.5, height / 4]])
data_bgr = cv2.warpAffine(data_bgr, M, (width, height))
# compute animation
omega = 2 * math.pi / height
id_x = numpy.tile(numpy.array(range(width), dtype=numpy.float32), (height, 1))
id_y = numpy.tile(numpy.array(range(height), dtype=numpy.float32), (width, 1)).transpose()
id_x = np.tile(np.array(range(width), dtype=np.float32), (height, 1))
id_y = np.tile(np.array(range(height), dtype=np.float32), (width, 1)).transpose()
self.frames = []
for k in range(30):
phase = 2 * k * math.pi / 30
map_x = id_x + 10 * numpy.cos(omega * id_x + phase)
map_y = id_y + 10 * numpy.sin(omega * id_x + phase)
map_x = id_x + 10 * np.cos(omega * id_x + phase)
map_y = id_y + 10 * np.sin(omega * id_x + phase)
frame = cv2.remap(data_bgr, map_x, map_y, cv2.INTER_LINEAR)
self.frames.append(VideoFrame.from_ndarray(frame, format="bgr24"))
@@ -67,24 +67,32 @@ class FlagVideoStreamTrack(VideoStreamTrack):
self.counter += 1
return frame
def _create_rectangle(self, width, height, color):
data_bgr = numpy.zeros((height, width, 3), numpy.uint8)
@staticmethod
def _create_rectangle(width, height, color):
data_bgr = np.zeros((height, width, 3), np.uint8)
data_bgr[:, :] = color
return data_bgr
class SingleFrameStreamTrack(VideoStreamTrack):
"""Single Frame stream class: pushes single frames to a stream"""
def __init__(self):
super().__init__()
self.background_frame = numpy.zeros((480, 640, 3), dtype="uint8") * 255
self.background_frame = np.zeros((480, 640, 3), dtype="uint8") * 255
self.frame = None
self.put_frame(self.background_frame)
def put_frame(self, frame):
def put_frame(self, frame: np.ndarray) -> None:
"""Sets the current viewing frame
Args:
frame: image to be viewed
"""
self.frame = VideoFrame.from_ndarray(frame)
async def recv(self):
"""Async method to grab and wait on frame"""
pts, time_base = await self.next_timestamp()
frame = self.frame
+131 -58
View File
@@ -21,7 +21,7 @@ import random
import sys
import threading
import time
from typing import List
from typing import Any, Dict, List, Optional
import numpy as np
import torch
@@ -60,7 +60,13 @@ class SetTrace:
class RenderThread(threading.Thread):
"""Thread that does all the rendering calls while listening for interrupts"""
"""Thread that does all the rendering calls while listening for interrupts
Args:
state: current visualizer state object
graph: current checkpoint of model
camera_ray_bundle: input rays to pass through the graph to render out
"""
def __init__(self, state: "VisualizerState", graph: Graph, camera_ray_bundle: RayBundle):
threading.Thread.__init__(self)
@@ -70,6 +76,10 @@ class RenderThread(threading.Thread):
self.exc = None
def run(self):
"""run function that renders out images given the current graph and ray bundles.
Interlaced with a trace function that checks to see if any I/O changes were registered.
Exits and continues program if IOChangeException thrown.
"""
outputs = None
try:
with SetTrace(self.state.check_interrupt):
@@ -90,13 +100,20 @@ class RenderThread(threading.Thread):
class CheckThread(threading.Thread):
"""Thread the constantly checks for io changes and sets a flag indicating interrupt"""
"""Thread the constantly checks for io changes and sets a flag indicating interrupt
Args:
state: current visualizer state object
"""
def __init__(self, state):
threading.Thread.__init__(self)
self.state = state
def run(self):
"""Run function that checks to see if any of the existing state has changed (e.g. camera pose/output type/resolutions).
Sets the visualizer state flag to true to signal to render thread that an interrupt was registered.
"""
self.state.check_done_render = False
while not self.state.check_done_render:
# check camera
@@ -138,7 +155,11 @@ class CheckThread(threading.Thread):
@decorate_all([check_visualizer_enabled])
class VisualizerState:
"""Class to hold state for visualizer variables"""
"""Class to hold state for visualizer variables
Args:
config: viewer setup configuration
"""
def __init__(self, config: ViewerConfig):
self.config = config
@@ -165,11 +186,42 @@ class VisualizerState:
self.outputs_set = False
def init_scene(self, image_dataset: ImageDataset, dataset_inputs: DatasetInputs) -> None:
"""initializes the scene with the datasets"""
self._draw_scene_in_viewer(image_dataset, dataset_inputs)
"""Draw some images and the scene aabb in the viewer.
Args:
image_dataset: dataset to render in the scene
dataset_inputs: inputs to the image dataset and ray generator
"""
indices = random.sample(range(len(image_dataset)), k=10)
for idx in indices:
image = image_dataset[idx]["image"]
camera = get_camera(dataset_inputs.intrinsics[idx], dataset_inputs.camera_to_world[idx], None)
pose = camera.get_camera_to_world().double().numpy()
K = camera.get_intrinsics_matrix().double().numpy()
draw_camera_frustum(
self.vis,
image=(image.double().numpy() * 255.0),
pose=pose,
K=K,
height=1.0,
name=f"image_dataset/{idx:06d}",
displayed_focal_length=0.5,
realistic=False,
)
aabb = dataset_inputs.scene_bounds.aabb
draw_aabb(self.vis, aabb, name="dataset_inputs_train/scene_bounds/aabb")
# set the main camera intrinsics to one from the dataset
K = camera.get_intrinsics_matrix()
set_persp_intrinsics_matrix(self.vis, K.double().numpy())
def update_scene(self, step: int, graph: Graph) -> None:
"""updates the scene based on the graph weights"""
"""updates the scene based on the graph weights
Args:
step: iteration step of training
graph: the current checkpoint of the model
"""
data = self.vis["/Training State"].get_object()
if data is None or not data["training_state"]:
@@ -187,8 +239,10 @@ class VisualizerState:
run_loop = data["training_state"]
local_step += 1
def check_interrupt(self, frame, event, arg):
"""raises interrupt when flag has been set and not already on lowest resolution"""
def check_interrupt(self, frame, event, arg): # pylint: disable=unused-argument
"""Raises interrupt when flag has been set and not already on lowest resolution.
Used in conjunction with SetTrace.
"""
if event == "line":
if self.check_interrupt_vis and self.res_upscale_factor > 1:
self.res_upscale_factor = 1
@@ -212,30 +266,21 @@ class VisualizerState:
return True # if not higher res, but steps met
return False # if init
def _draw_scene_in_viewer(self, image_dataset: ImageDataset, dataset_inputs: DatasetInputs) -> None:
"""Draw some images and the scene aabb in the viewer."""
indices = random.sample(range(len(image_dataset)), k=10)
for idx in indices:
image = image_dataset[idx]["image"]
camera = get_camera(dataset_inputs.intrinsics[idx], dataset_inputs.camera_to_world[idx], None)
pose = camera.get_camera_to_world().double().numpy()
K = camera.get_intrinsics_matrix().double().numpy()
draw_camera_frustum(
self.vis,
image=(image.double().numpy() * 255.0),
pose=pose,
K=K,
height=1.0,
name=f"image_dataset/{idx:06d}",
displayed_focal_length=0.5,
realistic=False,
)
aabb = dataset_inputs.scene_bounds.aabb
draw_aabb(self.vis, aabb, name="dataset_inputs_train/scene_bounds/aabb")
def _send_output_to_viewer(self, outputs: Dict[str, Any]):
"""Chooses the correct output and sends it to the viewer
# set the main camera intrinsics to one from the dataset
K = camera.get_intrinsics_matrix()
set_persp_intrinsics_matrix(self.vis, K.double().numpy())
Args:
outputs: the dictionary of outputs to choose from, from the graph
"""
if not self.outputs_set:
set_output_options(self.vis, list(outputs.keys()))
self.outputs_set = True
# gross hack to get the image key, depending on which keys the graph uses
if output_type == "default":
output_type = "rgb" if "rgb" in outputs else "rgb_fine"
image_output = outputs[output_type].cpu().numpy() * 255
image = (image_output).astype("uint8")
self.vis["/Cameras/Main Camera"].set_image(image)
@profiler.time_function
def _render_image_in_viewer(self, graph: Graph) -> None:
@@ -309,15 +354,7 @@ class VisualizerState:
graph.train()
outputs = graph.vis_outputs
if outputs is not None:
if not self.outputs_set:
set_output_options(self.vis, list(outputs.keys()))
self.outputs_set = True
# gross hack to get the image key, depending on which keys the graph uses
if output_type == "default":
output_type = "rgb" if "rgb" in outputs else "rgb_fine"
image_output = outputs[output_type].cpu().numpy() * 255
image = (image_output).astype("uint8")
self.vis["/Cameras/Main Camera"].set_image(image)
self._send_output_to_viewer(outputs)
def get_default_vis() -> Viewer:
@@ -328,17 +365,33 @@ def get_default_vis() -> Viewer:
def set_output_options(vis: Viewer, output_options: List[str]):
"""Sets the possible list of output options for user to toggle"""
"""Sets the possible list of output options for user to toggle
Args:
vis: current Viewer
output_options: list of possible output types to select from
"""
vis["output_options"].set_output_options(output_options)
def show_box_test(vis: Viewer):
"""Simple test to draw a box and make sure everything is working."""
"""Simple test to draw a box and make sure everything is working.
Args:
vis: current Viewer
"""
vis["box"].set_object(g.Box([1.0, 1.0, 1.0]), material=g.MeshPhongMaterial(color=0xFF0000))
def show_ply(vis: Viewer, ply_path: str, name: str = "ply", color=None):
"""Show the PLY file in the 3D viewer. Specify the full filename as input."""
def show_ply(vis: Viewer, ply_path: str, name: str = "ply", color: Optional[int] = None):
"""Show the PLY file in the 3D viewer. Specify the full filename as input.
Args:
vis: current Viewer
ply_path: path to ply to load in
name: reference name within viewer storage
color: color to render the ply in
"""
assert ply_path.endswith(".ply")
if color:
material = g.MeshPhongMaterial(color=color)
@@ -347,8 +400,15 @@ def show_ply(vis: Viewer, ply_path: str, name: str = "ply", color=None):
vis[name].set_object(g.PlyMeshGeometry.from_file(ply_path), material)
def show_obj(vis: Viewer, obj_path: str, name: str = "obj", color=None):
"""Show the PLY file in the 3D viewer. Specify the full filename as input."""
def show_obj(vis: Viewer, obj_path: str, name: str = "obj", color: Optional[int] = None):
"""Show the PLY file in the 3D viewer. Specify the full filename as input.
Args:
vis: current Viewer
obj_path: path to obj to load in
name: reference name within viewer storage
color: color to render the obj in
"""
assert obj_path.endswith(".obj")
if color:
material = g.MeshPhongMaterial(color=color)
@@ -359,16 +419,28 @@ def show_obj(vis: Viewer, obj_path: str, name: str = "obj", color=None):
def draw_camera_frustum(
vis: Viewer,
image=np.random.rand(100, 100, 3) * 255.0,
pose=get_translation_matrix([0, 0, 0]),
K=None,
name="0000000",
displayed_focal_length=None,
shift_forward=None,
height=None,
realistic=True,
image: np.ndarray = np.random.rand(100, 100, 3) * 255.0,
pose: np.ndarray = get_translation_matrix([0, 0, 0]),
K: Optional[np.ndarray] = None,
name: str = "0000000",
displayed_focal_length: Optional[float] = None,
shift_forward: Optional[float] = None,
height: Optional[float] = None,
realistic: bool = True,
):
"""Draw the camera in the scene."""
"""Draw the camera in the scene.
Args:
vis: current Viewer
image: image associated with the current camera
pose: pose of the camera
K: camera matrix
name: reference name within viewer storage
displayed_focal_length: the focal length to be displayed
shift_forward: how much to shift the drawn camera forward
height: height of the associated image plane
realistic: whether to render the image plane at the "realistic" focal length
"""
assert K[0, 0] == K[1, 1]
focal_length = K[0, 0]
@@ -405,11 +477,12 @@ def draw_camera_frustum(
g_image_plane = c.ImagePlane(image, width=width, height=height)
vis[name + "/image_plane"].set_object(g_image_plane)
if realistic:
vis[name + "/image_plane"].set_transform(get_translation_matrix([0, 0, -displayed_focal_length]))
assert displayed_focal_length is not None, "Need to set displayed focal length"
vis[name + "/image_plane"].set_transform(get_translation_matrix([0, 0, -1.0 * displayed_focal_length]))
if shift_forward:
matrix = get_translation_matrix([0, 0, displayed_focal_length])
matrix2 = get_translation_matrix([0, 0, -shift_forward])
matrix2 = get_translation_matrix([0, 0, -1.0 * shift_forward])
vis[name + "/frustum"].set_transform(matrix2 @ matrix)
vis[name + "/image_plane"].set_transform(matrix2)