Viewer refactor with state sync (#212)

* initial commit for viewer refactor

* updating name change to nerfactory

* adding headers

* making the rendering fix which broke from a merge

* things are starting to work. removing old commands now

* removed prints

* cleanup

* updating state works now even for nested dictionaries

* updating state in redux. listening for state changes. trying to draw three.js now

* added drawing functionality. need to fix translation of frustums and image planes

* images and frustums drawn correctly

* fixing lint

* github actions

* back to npm

* fixing eslint

* remove package.json from root

* new favicon

* some viewer cleanup

* notebook

* fixed camera drawings speed to avoid redraw

* trying to get Leva to update

* quick fix

* synced config panel

* adding notebook

* fixing output print error
This commit is contained in:
Ethan Weber authored and GitHub committed 2022-08-02 16:02:07 -05:00
1 parent 966374474d
commit 73fedc7593
67 files changed
+2510 -14057

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
# Python Kernel and Client Viewer App communication
> The purpose of this document is to explain how to communicate from Python with the Client Viewer app. We will eventually move this into the read the docs.
- Python Kernel (nerfactory code)
- Bridge Server
- Client Viewer App
We have two types of components that we want to keep state updated in both locations.
- Widgets
- The widgets are used to keep track of the
- SceneNode
- The scene nodes are used to represent the three.js objects. The properties relevant to these objects are the following: `"object", "transform", "properties"`.
# Checklist
- [ ] Currently using request-reply (REQ, REP with zmq). I.e., Python Kernel -> Bridge Server <-> Client Viewer App. We want a way to update the Python Kernel when the Bridge Server is updated. This requries some form of binding with callbacks. When the Bridge Server is updated, we want to update the binded Python variable. We can take inspiration from [ipywidgets](https://ipywidgets.readthedocs.io/en/stable/examples/Widget%20Basics.html).
- [ ]
-137
View File
@@ -1,137 +0,0 @@
# Copyright 2022 The Plenoptix Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Logic to render Camera objects in the Viewer"""
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):
"""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(
map=g.ImageTexture(image=g.PngImage(cv2.imencode(".png", self.image[:, :, ::-1])[1].tobytes()))
)
super().__init__(geometry, material)
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:
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])
ll = np.array([-w, -h, -f])
lr = np.array([w, -h, -f])
C = np.zeros(3)
camera_points = [C, ul, C, ur, C, ll, C, lr, C, ul, ur, ul, lr, ur, lr, ll, ll, ul]
lines = np.stack(camera_points) * scale
return lines
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,
image_size[1] / 2 * camera_scale,
image_size[0] / 2 * camera_scale,
-image_size[1] / 2 * camera_scale,
)
# scale image to plane such that it can go outside of the x0x1 range.
W, H = X1 - X0, Y0 - Y1
w, h = image_size
ratio = min(w / W, h / H)
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)
Ys, Xs = np.meshgrid(
np.linspace(Y0, Y1, num=hsteps),
np.linspace(X0, X1, num=wsteps),
indexing="ij",
)
Zs = np.ones_like(Xs) * Z
plane_pts = np.stack([Xs, Ys, Zs], axis=-1)
return plane_pts
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)
colors = np.array([color for _ in range(N)])
line_segments = LineSegments(
PointsGeometry(position=camera_wireframe_lines.astype(np.float32).T, color=colors.astype(np.float32).T),
LineBasicMaterial(vertexColors=True),
)
return line_segments
-144
View File
@@ -1,144 +0,0 @@
# Copyright 2022 The Plenoptix Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# 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
import numpy as np
from nerfactory.viewer.server.geometry import (
Mesh,
MeshPhongMaterial,
Object,
OrthographicCamera,
PerspectiveCamera,
Points,
PointsMaterial,
)
from nerfactory.viewer.server.path import Path
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: 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
"""
__slots__ = ["object", "path"]
def __init__(self, geometry_or_object, material=None, path=None):
if isinstance(geometry_or_object, Object):
if material is not None:
raise ValueError("Please supply either an Object OR a Geometry and a Material")
self.object = geometry_or_object
elif isinstance(geometry_or_object, (OrthographicCamera, PerspectiveCamera)):
self.object = geometry_or_object
else:
if material is None:
material = MeshPhongMaterial()
if isinstance(material, PointsMaterial):
self.object = Points(geometry_or_object, material)
else:
self.object = Mesh(geometry_or_object, material)
if path is not None:
self.path = path
else:
self.path = Path()
def lower(self) -> Dict[str, Any]:
"""creates properly formatted json"""
return {"type": "set_object", "object": self.object.lower(), "path": self.path.lower()}
@dataclass
class GetObject:
"""Get object command class
Args:
path: path of object in tree. Defaults to None.
"""
__slots__ = ["path"]
path: str
def lower(self) -> Dict[str, Any]:
"""creates properly formatted json with object"""
return {"type": "get_object", "path": self.path.lower()}
@dataclass
class SetTransform:
"""Set transform command class"""
__slots__ = ["matrix", "path"]
matrix: np.ndarray
path: str
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())}
@dataclass
class SetOutputOptions:
"""Set output options command class"""
__slots__ = ["output_options", "path"]
output_options: List[str]
path: str
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)}
@dataclass
class Delete:
"""Delete current state command class"""
__slots__ = ["path"]
path: str
def lower(self) -> Dict[str, Any]:
"""creates properly formatted json updating tree"""
return {"type": "delete", "path": self.path.lower()}
@dataclass
class SetProperty:
"""Set property command class"""
__slots__ = ["path", "key", "value"]
key: str
value: list
path: str
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}
-914
View File
@@ -1,914 +0,0 @@
# Copyright 2022 The Plenoptix Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Geometry to render meshes, textures, etc.
"""
import base64
import sys
import uuid
from typing import Any, BinaryIO, Dict, Iterable, List, Optional, Tuple
import numpy as np
import umsgpack
UNICODE = str
from io import BytesIO, StringIO
class SceneElement:
"""Base class for objects in the scene"""
def __init__(self):
self.uuid = UNICODE(uuid.uuid1())
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):
"""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):
"""Box object
Args:
lengths: length of side of box
"""
def __init__(self, lengths: List[float]):
super().__init__()
self.lengths = lengths
def lower(self, object_data):
return {
"uuid": self.uuid,
"type": "BoxGeometry",
"width": self.lengths[0],
"height": self.lengths[1],
"depth": self.lengths[2],
}
class Sphere(Geometry):
"""Sphere object
Args:
radius: radius of sphere
"""
def __init__(self, radius: float):
super().__init__()
self.radius = radius
def lower(self, object_data):
return {
"uuid": self.uuid,
"type": "SphereGeometry",
"radius": self.radius,
"widthSegments": 20,
"heightSegments": 20,
}
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: List[float]):
super().__init__(1.0)
self.radii = radii
def intrinsic_transform(self):
return np.diag(np.hstack((self.radii, 1.0)))
class PlaneGeometry(Geometry):
"""Plane Class
Args:
lengths: the height and width of plane
"""
def __init__(self, lengths: List[float]):
super().__init__()
self.lengths = lengths
def lower(self, object_data):
return {"uuid": self.uuid, "type": "PlaneGeometry", "width": self.lengths[0], "height": self.lengths[1]}
class Cylinder(Geometry):
"""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 radius_top is not None and radius_bottom is not None:
self.radius_top = radius_top
self.radius_bottom = radius_bottom
else:
self.radius_top = radius
self.radius_bottom = radius
self.height = height
self.radial_segments = 50
def lower(self, object_data):
return {
"uuid": self.uuid,
"type": "CylinderGeometry",
"radiusTop": self.radius_top,
"radiusBottom": self.radius_bottom,
"height": self.height,
"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: 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
self.reflectivity = reflectivity
self.map = map
self.side = side
self.transparent = transparent
self.opacity = opacity
self.linewidth = linewidth
self.wireframe = wireframe
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,
# but to still be non-transparent, in which case the opacity only
# serves to desaturate the material's color. That's a pretty odd
# combination of things to want, so by default we just use the
# opacity value to decide whether to set transparent to True or
# False.
if self.transparent is None:
transparent = bool(self.opacity != 1)
else:
transparent = self.transparent
data = {
"uuid": self.uuid,
"type": self._type,
"color": self.color,
"reflectivity": self.reflectivity,
"side": self.side,
"transparent": transparent,
"opacity": self.opacity,
"linewidth": self.linewidth,
"wireframe": bool(self.wireframe),
"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:
data["map"] = self.map.lower_in_object(object_data)
return data
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: 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")),
}
class GenericTexture(Texture):
"""Generic texture class"""
def __init__(self, properties: Iterable):
super().__init__()
self.properties = properties
def lower(self, object_data):
data = {"uuid": self.uuid}
data.update(self.properties)
if "image" in data:
image = data["image"]
data["image"] = image.lower_in_object(object_data)
return data
class ImageTexture(Texture):
"""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
self.properties = kwargs
def lower(self, object_data):
data = {
"uuid": self.uuid,
"wrap": self.wrap,
"repeat": self.repeat,
"image": self.image.lower_in_object(object_data),
}
data.update(self.properties)
return data
class Object(SceneElement):
"""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
# pylint: arguments-differ
def lower(self):
data = {
"metadata": {
"version": 4.5,
"type": "Object",
},
"geometries": [],
"materials": [],
"object": {
"uuid": self.uuid,
"type": self._type,
"geometry": self.geometry.uuid,
"material": self.material.uuid,
"matrix": list(self.geometry.intrinsic_transform().flatten()),
},
}
self.geometry.lower_in_object(data)
self.material.lower_in_object(data)
return data
class Mesh(Object):
"""Mesh class"""
_type = "Mesh"
class OrthographicCamera(SceneElement):
"""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().__init__()
self.left = left
self.right = right
self.top = top
self.bottom = bottom
self.near = near
self.far = far
self.zoom = zoom
def lower(self, object_data):
data = {
"object": {
"uuid": self.uuid,
"type": "OrthographicCamera",
"left": self.left,
"right": self.right,
"top": self.top,
"bottom": self.bottom,
"near": self.near,
"far": self.far,
"zoom": self.zoom,
}
}
return data
class PerspectiveCamera(SceneElement):
"""
The PerspectiveCamera is the default camera used by the nerfactory viewer. See
https://threejs.org/docs/#api/en/cameras/PerspectiveCamera for more
information.
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
value of the far plane. Note that, unlike for the OrthographicCamera, 0 is not a valid value for a
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.
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.
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().__init__()
self.fov = fov
self.aspect = aspect
self.far = far
self.near = near
self.zoom = zoom
self.film_gauge = film_gauge
self.film_offset = film_offset
self.focus = focus
def lower(self, object_data):
data = {
"object": {
"uuid": self.uuid,
"type": "PerspectiveCamera",
"aspect": self.aspect,
"far": self.far,
"filmGauge": self.film_gauge,
"filmOffset": self.film_offset,
"focus": self.focus,
"fov": self.fov,
"near": self.near,
"zoom": self.zoom,
}
}
return data
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
if array.ndim == 2:
return array.shape[0]
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: 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
if dtype == np.int32:
return "Int32Array", 0x15
if dtype == np.uint32:
return "Uint32Array", 0x16
if dtype == np.float32:
return "Float32Array", 0x17
raise ValueError("Unsupported datatype: " + str(dtype))
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)
return {
"itemSize": item_size(x),
"type": typename,
"array": umsgpack.Ext(extcode, x.tobytes("F")),
"normalized": False,
}
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 isinstance(stream, BytesIO):
data = stream.read().decode(encoding="utf-8")
elif isinstance(stream, StringIO):
data = stream.read()
else:
raise ValueError(f"Stream must be instance of StringIO or BytesIO, not {type(stream)}")
return data
class MeshGeometry(Geometry):
"""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
def lower(self, object_data):
return {"type": "_meshfile", "uuid": self.uuid, "format": self.mesh_format, "data": self.contents}
class ObjMeshGeometry(MeshGeometry):
"""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: str) -> MeshGeometry:
"""Reading mesh geometry from file. Returns mesh geometry object
Args:
fname: file name to read from
"""
with open(fname, encoding="utf8") as f:
return MeshGeometry(f.read(), "obj")
@staticmethod
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):
"""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: str) -> MeshGeometry:
"""Reading mesh geometry from file. Returns mesh geometry object
Args:
fname: file name to read from
"""
with open(fname, encoding="utf8") as f:
return MeshGeometry(f.read(), "dae")
@staticmethod
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):
"""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: 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)
encoded = umsgpack.Ext(extcode, arr.tobytes())
return MeshGeometry(encoded, "stl")
@staticmethod
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 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(f"Stream must be instance of StringIO or BytesIO, not {type(f)}")
_, extcode = threejs_type(np.uint8)
encoded = umsgpack.Ext(extcode, arr.tobytes())
return MeshGeometry(encoded, "stl")
class PlyMeshGeometry(MeshGeometry):
"""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: 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)
encoded = umsgpack.Ext(extcode, arr.tobytes())
return MeshGeometry(encoded, "ply")
@staticmethod
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 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(f"Stream must be instance of StringIO or BytesIO, not {type(f)}")
_, extcode = threejs_type(np.uint8)
encoded = umsgpack.Ext(extcode, arr.tobytes())
return MeshGeometry(encoded, "stl")
class TriangularMeshGeometry(Geometry):
"""
A mesh consisting of an arbitrary collection of triangular faces.
To construct one, you need to pass in a collection of vertices as an Nx3 array
and a collection of faces as an Mx3 array. Each element of `faces`
should be a collection of 3 indices into the `vertices` array.
For example, to create a square made out of two adjacent triangles, we could do:
vertices = np.array([
[0, 0, 0], # the first vertex is at [0, 0, 0]
[1, 0, 0],
[1, 0, 1],
[0, 0, 1]
])
faces = np.array([
[0, 1, 2], # The first face consists of vertices 0, 1, and 2
[3, 0, 2]
])
mesh = TriangularMeshGeometry(vertices, faces)
"""
__slots__ = ["vertices", "faces"]
def __init__(self, vertices: np.ndarray, faces: np.ndarray):
super().__init__()
vertices = np.asarray(vertices, dtype=np.float32)
faces = np.asarray(faces, dtype=np.uint32)
assert vertices.shape[1] == 3, "`vertices` must be an Nx3 array"
assert faces.shape[1] == 3, "`faces` must be an Mx3 array"
self.vertices = vertices
self.faces = faces
def lower(self, object_data) -> Dict[str, Any]:
return {
"uuid": self.uuid,
"type": "BufferGeometry",
"data": {
"attributes": {"position": pack_numpy_array(self.vertices.T)},
"index": pack_numpy_array(self.faces.T),
},
}
class PointsGeometry(Geometry):
"""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) -> Dict[str, Any]:
attrs = {"position": pack_numpy_array(self.position)}
if self.color is not None:
attrs["color"] = pack_numpy_array(self.color)
return {"uuid": self.uuid, "type": "BufferGeometry", "data": {"attributes": attrs}}
class PointsMaterial(Material):
"""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.size_attenuation = size_attenuation
def lower(self, object_data) -> Dict[str, Any]:
return {
"uuid": self.uuid,
"type": "PointsMaterial",
"color": self.color,
"size": self.size,
"sizeAttenuation": bool(self.size_attenuation),
"vertexColors": 2,
}
class Points(Object):
"""Points object class"""
_type = "Points"
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: 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(
position=np.array([[0, 0, 0], [scale, 0, 0], [0, 0, 0], [0, scale, 0], [0, 0, 0], [0, 0, scale]])
.astype(np.float32)
.T,
color=np.array([[1, 0, 0], [1, 0.6, 0], [0, 1, 0], [0.6, 1, 0], [0, 0, 1], [0, 0.6, 1]])
.astype(np.float32)
.T,
),
LineBasicMaterial(vertexColors=True),
)
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(
position=np.array([[0, 0, 0], [scale, 0, 0], [0, 0, 0], [0, scale, 0], [0, 0, 0], [0, 0, scale]])
.astype(np.float32)
.T,
color=np.array([[1, 0, 0], [1, 0.6, 0], [0, 1, 0], [0.6, 1, 0], [0, 0, 1], [0, 0.6, 1]])
.astype(np.float32)
.T,
),
LineBasicMaterial(vertexColors=True),
)
-1
View File
@@ -16,7 +16,6 @@
"""
import sys
from typing import Tuple
UNICODE = str
+65 -88
View File
@@ -16,7 +16,7 @@
import sys
from typing import Callable, List, Optional
from typing import Callable, List, Optional, Tuple
import msgpack
import msgpack_numpy
@@ -31,24 +31,14 @@ from aiortc import RTCPeerConnection, RTCSessionDescription
from aiortc.rtcrtpsender import RTCRtpSender
from zmq.eventloop.zmqstream import ZMQStream
from nerfactory.viewer.server.tree import SceneTree, find_node, walk
from nerfactory.viewer.server.state.node import find_node, get_tree, walk
from nerfactory.viewer.server.state.state_node import StateNode
from nerfactory.viewer.server.video_stream import SingleFrameStreamTrack
MAX_ATTEMPTS = 1000
DEFAULT_ZMQ_METHOD = "tcp"
DEFAULT_ZMQ_PORT = 6000
DEFAULT_WEBSOCKET_PORT = 8051
WEBSOCKET_COMMANDS = [
"set_transform",
"set_object",
"set_output_options",
"set_output_type",
"set_training_state",
"get_object",
"set_property",
"delete",
]
WEBRTC_COMMANDS = ["set_image"]
def find_available_port(func: Callable, default_port: int, max_attempts: int = MAX_ATTEMPTS, **kwargs) -> None:
@@ -105,7 +95,8 @@ class WebSocketHandler(tornado.websocket.WebSocketHandler): # pylint: disable=a
self.bridge.send_scene(self)
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
"""On reception of message from the websocket,
parses the message and calls the appropriate function based on the type of command
Args:
message: byte message to parse
@@ -115,22 +106,23 @@ class WebSocketHandler(tornado.websocket.WebSocketHandler): # pylint: disable=a
type_ = m["type"]
path = list(filter(lambda x: len(x) > 0, m["path"].split("/")))
if type_ == "set_transform":
find_node(self.bridge.tree, path).transform = data
elif type_ == "set_object":
find_node(self.bridge.tree, path).object = data
find_node(self.bridge.tree, path).properties = []
elif type_ == "set_output_options":
find_node(self.bridge.tree, path).object = data
elif type_ == "set_output_type":
find_node(self.bridge.tree, path).object = data
elif type_ == "set_max_resolution":
find_node(self.bridge.tree, path).object = data
elif type_ == "set_min_resolution":
find_node(self.bridge.tree, path).object = data
elif type_ == "set_training_state":
find_node(self.bridge.tree, path).object = data
if type_ == "write":
# writes the data coming from the websocket
find_node(self.bridge.state_tree, path).data = m["data"]
if m["path"] != "renderingState/camera":
# dispatch to the websockets if not a camera update!
# TODO(ethan): handle the camera properly!
# TODO: but don't update the current websocket
command = {"type": "write", "path": m["path"], "data": m["data"]}
packed_data = umsgpack.packb(command)
frames = ["write".encode("utf-8"), m["path"].encode("utf-8"), packed_data]
self.bridge.forward_to_websockets(frames, websocket_to_skip=self)
elif type_ == "read":
# reads and returns the data
data = find_node(self.bridge.state_tree, path).data
self.write_message(data, binary=True)
elif type_ == "offer":
# returns the description to for WebRTC to the specific websocket connection
offer = RTCSessionDescription(m["data"]["sdp"], m["data"]["type"])
pc = RTCPeerConnection()
@@ -139,7 +131,7 @@ class WebSocketHandler(tornado.websocket.WebSocketHandler): # pylint: disable=a
video = SingleFrameStreamTrack()
self.bridge.video_tracks.add(video)
_ = pc.addTrack(video)
# TODO(eventually do something with the codec)
# TODO: do something with the codec
# video_sender = pc.addTrack(video)
# force_codec(pc, video_sender, video_codec)
@@ -154,6 +146,14 @@ class WebSocketHandler(tornado.websocket.WebSocketHandler): # pylint: disable=a
}
data = umsgpack.packb(cmd_data)
self.write_message(data, binary=True)
else:
cmd_data = {
"type": "error",
"path": "",
"data": {"error": "Unknown command type: " + type_},
}
data = umsgpack.packb(cmd_data)
self.write_message(data, binary=True)
def on_close(self):
self.bridge.websocket_pool.remove(self)
@@ -196,7 +196,7 @@ class ZMQWebSocketBridge:
self.app.listen(websocket_port, **listen_kwargs)
self.websocket_port = websocket_port
self.tree = SceneTree()
self.state_tree = get_tree(StateNode)
def __str__(self) -> str:
class_name = self.__class__.__name__
@@ -212,61 +212,37 @@ class ZMQWebSocketBridge:
Args:
frames: the list containing command + object to be placed in tree
"""
cmd = frames[0].decode("utf-8")
print(cmd)
if len(frames) != 3:
self.zmq_socket.send(b"error: expected 3 frames")
return
type_ = frames[0].decode("utf-8")
path = list(filter(lambda x: len(x) > 0, frames[1].decode("utf-8").split("/")))
data = frames[2]
if cmd in WEBSOCKET_COMMANDS:
if cmd != "get_object":
self.forward_to_websockets(frames)
if cmd == "set_transform":
find_node(self.tree, path).transform = data
elif cmd == "set_object":
find_node(self.tree, path).object = data
find_node(self.tree, path).properties = []
elif cmd == "set_output_options":
find_node(self.tree, path).object = data
elif cmd == "set_output_type":
find_node(self.tree, path).object = data
elif cmd == "set_max_resolution":
find_node(self.tree, path).object = data
elif cmd == "set_min_resolution":
find_node(self.tree, path).object = data
elif cmd == "set_training_state":
find_node(self.tree, path).object = data
elif cmd == "get_object":
data = find_node(self.tree, path).object
if isinstance(data, type(None)):
data = umsgpack.packb("error: object not found")
self.zmq_socket.send(data)
return
elif cmd == "set_property":
find_node(self.tree, path).properties.append(data)
elif cmd == "delete":
if len(path) > 0:
parent = find_node(self.tree, path[:-1])
child = path[-1]
if child in parent:
del parent[child]
else:
self.tree = SceneTree()
elif cmd in WEBRTC_COMMANDS:
if cmd == "set_image":
image = msgpack.unpackb(
data, object_hook=msgpack_numpy.decode, use_list=False, max_bin_len=50000000, raw=False
)
for video_track in self.video_tracks:
video_track.put_frame(image)
else:
self.zmq_socket.send(b"error: unknown command")
return
self.zmq_socket.send(b"ok")
return
def forward_to_websockets(self, frames: List[bytes]):
if type_ == "write":
# TODO: use state_tree name
unpacked_data = umsgpack.unpackb(data)
find_node(self.state_tree, path).data = unpacked_data["data"]
self.forward_to_websockets(frames)
self.zmq_socket.send(umsgpack.packb(b"ok"))
elif type_ == "read":
# walk the node from the specified to get the full state dictionary
# TODO(ethan): handle the "data" key...
read_data = find_node(self.state_tree, path).data
self.zmq_socket.send(umsgpack.packb(read_data))
elif type_ == "set_image":
image = msgpack.unpackb(
data, object_hook=msgpack_numpy.decode, use_list=False, max_bin_len=50000000, raw=False
)
for video_track in self.video_tracks:
video_track.put_frame(image)
self.zmq_socket.send(umsgpack.packb(b"ok"))
else:
self.zmq_socket.send(umsgpack.packb(b"error: unknown command"))
def forward_to_websockets(
self, frames: Tuple[str, str, bytes], websocket_to_skip: Optional[WebSocketHandler] = None
):
"""Forward a zmq message to all websockets.
Args:
@@ -274,7 +250,10 @@ class ZMQWebSocketBridge:
"""
_, _, data = frames # cmd, path, data
for websocket in self.websocket_pool:
websocket.write_message(data, binary=True)
if websocket_to_skip and websocket == websocket_to_skip:
pass
else:
websocket.write_message(data, binary=True)
def setup_zmq(self, url: str):
"""Setup a zmq socket and connect it to the given url.
@@ -294,13 +273,11 @@ class ZMQWebSocketBridge:
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)
for p in node.properties:
websocket.write_message(p, binary=True)
if node.transform is not None:
websocket.write_message(node.transform, binary=True)
print("Sending entire scene state on websocket connect (i.e,. a page refresh).")
for path, node in walk("", self.state_tree):
if node.data is not None:
command = {"type": "write", "path": path, "data": node.data}
websocket.write_message(umsgpack.packb(command), binary=True)
def run(self):
"""starts and runs the websocket bridge"""
@@ -13,49 +13,53 @@
# limitations under the License.
"""
Functions for traversing server bridge tree nodes (storage)
For tree logic code.
"""
from collections import defaultdict
from typing import List
from typing import Callable
class TreeNode(defaultdict):
"""Tree Node object"""
__slots__ = ["object", "transform", "properties", "animation"]
class Node(defaultdict):
"""
The base class Node.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.object = None
self.properties = []
self.transform = None
self.animation = None
SceneTree = lambda: TreeNode(SceneTree)
def walk(tree: TreeNode) -> None:
"""Walk the entire tree and return the values
Args:
tree: the root of the tree to start search
def get_tree(node_class: Callable) -> Callable:
"""
yield tree
for v in tree.values():
yield from walk(v)
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
Get a tree from a node class.
This allows one to do tree["path"]["to"]["node"]
and it will return a new node if it doesn't exist
or the current node if it does.
"""
assert isinstance(node_class(), Node)
tree = lambda: node_class(tree)
return tree()
def find_node(tree, path):
if len(path) == 0:
return tree
else:
return find_node(tree[path[0]], path[1:])
def set_node_value(tree, path, value):
if len(path) == 0:
tree.data = value
else:
set_node_value(tree[path[0]], path[1:], value)
def walk(path, tree):
"""Walk the entire tree and return the values
Args:
tree: the root of the tree to start search
"""
yield path, tree
for k, v in tree.items():
yield from walk(path + "/" + k, v)
@@ -0,0 +1,28 @@
# Copyright 2022 The Plenoptix Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import List
from nerfactory.viewer.server.state.node import Node
class StateNode(Node):
"""Node that holds a hierarchy of state nodes"""
__slots__ = ["data"]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.path = None
self.data = None
@@ -1,89 +0,0 @@
# Copyright 2022 The Plenoptix Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Some helpful functions for creating geometric transformations.
"""
import math
from typing import List, Optional
import numpy as np
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:
data /= math.sqrt(np.dot(data, data))
return data
else:
if out is not data:
out[:] = np.array(data, copy=False)
data = out
length = np.atleast_1d(np.sum(data * data, axis))
np.sqrt(length, length)
if axis is not None:
length = np.expand_dims(length, axis)
data /= length
if out is None:
return data
return None
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: 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])
# rotation matrix around unit vector
R = np.diag([cosa, cosa, cosa])
R += np.outer(direction, direction) * (1.0 - cosa)
direction *= sina
R += np.array(
[[0.0, -direction[2], direction[1]], [direction[2], 0.0, -direction[0]], [-direction[1], direction[0], 0.0]]
)
M = np.identity(4)
M[:3, :3] = R
if point is not None:
# rotation not around origin
point = np.array(point[:3], dtype=np.float64, copy=False)
M[:3, 3] = point - np.dot(R, point)
return M
-29
View File
@@ -20,13 +20,6 @@ from typing import Any, Dict, List, Optional, Tuple
import numpy as np
import torch
from nerfactory.cameras.cameras import (
Camera,
get_camera,
get_intrinsics_from_intrinsics_matrix,
)
from nerfactory.viewer.server.visualizer import Viewer
def get_chunks(
lst: List[float], num_chunks: Optional[int] = None, size_of_chunk: Optional[int] = None
@@ -80,25 +73,3 @@ def get_intrinsics_matrix_and_camera_to_world_h(
)
return intrinsics_matrix, camera_to_world_h
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
camera_object = data["object"]["object"]
intrinsics_matrix, camera_to_world_h = get_intrinsics_matrix_and_camera_to_world_h(
camera_object, image_height=image_height
)
camera_to_world = camera_to_world_h[:3, :]
intrinsics = get_intrinsics_from_intrinsics_matrix(intrinsics_matrix)
camera = get_camera(intrinsics, camera_to_world)
return camera
+1 -1
View File
@@ -79,7 +79,7 @@ class SingleFrameStreamTrack(VideoStreamTrack):
def __init__(self):
super().__init__()
self.background_frame = np.zeros((480, 640, 3), dtype="uint8") * 255
self.background_frame = np.ones((480, 640, 3), dtype="uint8") * 255 # white background
self.frame = None
self.put_frame(self.background_frame)
+52 -251
View File
@@ -15,24 +15,16 @@
"""Code to interface with the `vis/` (the JS visualizer).
"""
import copy
import logging
import random
import sys
import threading
import time
from typing import Any, Dict, List, Optional
from typing import Any, Dict
import numpy as np
import torch
import nerfactory.viewer.server.cameras as c
import nerfactory.viewer.server.geometry as g
from nerfactory.cameras.cameras import (
Camera,
get_camera,
get_intrinsics_from_intrinsics_matrix,
)
from nerfactory.cameras.cameras import get_camera, get_intrinsics_from_intrinsics_matrix
from nerfactory.cameras.rays import RayBundle
from nerfactory.data.image_dataset import ImageDataset
from nerfactory.data.structs import DatasetInputs
@@ -40,7 +32,6 @@ from nerfactory.graphs.base import Graph
from nerfactory.utils import profiler
from nerfactory.utils.config import ViewerConfig
from nerfactory.utils.decorators import check_visualizer_enabled, decorate_all
from nerfactory.viewer.server.transformations import get_translation_matrix
from nerfactory.viewer.server.utils import get_intrinsics_matrix_and_camera_to_world_h
from nerfactory.viewer.server.visualizer import Viewer
@@ -117,15 +108,17 @@ class CheckThread(threading.Thread):
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.
"""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
data = self.state.vis["/Cameras/Main Camera"].get_object()
data = self.state.vis["renderingState/camera"].read()
if data is not None:
camera_object = data["object"]["object"]
camera_object = data["object"]
if self.state.prev_camera_matrix is None or not np.allclose(
camera_object["matrix"], self.state.prev_camera_matrix
):
@@ -133,27 +126,23 @@ class CheckThread(threading.Thread):
return
# check output type
data = self.state.vis["/Output Type"].get_object()
if data is None:
output_type = self.state.vis["renderingState/output_choice"].read()
if output_type is None:
output_type = "default"
else:
output_type = data["output_type"]
if self.state.prev_output_type != output_type:
self.state.check_interrupt_vis = True
return
# check max render
data = self.state.vis["/Max Resolution"].get_object()
if data is not None:
max_resolution = int(data["max_resolution"])
max_resolution = self.state.vis["renderingState/maxResolution"].read()
if max_resolution is not None:
if self.state.max_resolution != max_resolution:
self.state.check_interrupt_vis = True
return
# check min render
data = self.state.vis["/Min Resolution"].get_object()
if data is not None:
min_resolution = int(data["min_resolution"])
min_resolution = self.state.vis["renderingState/minResolution"].read()
if min_resolution is not None:
if self.state.min_resolution != min_resolution:
self.state.check_interrupt_vis = True
return
@@ -174,7 +163,6 @@ class VisualizerState:
if self.config.enable:
zmq_url = self.config.zmq_url
self.vis = Viewer(zmq_url=zmq_url)
self.vis.delete()
else:
logging.info("Continuing without viewer.")
@@ -198,28 +186,29 @@ class VisualizerState:
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:
# clear the current scene
self.vis["sceneState/sceneBounds"].delete()
self.vis["sceneState/cameras"].delete()
# draw the training cameras and images
image_indices = range(len(image_dataset))
for idx in image_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")
bgr = image[..., [2, 1, 0]]
self.vis[f"sceneState/cameras/{idx:06d}"].write(camera.to_json(image=bgr, resize_shape=(100, 100)))
# draw the scene bounds (i.e., the bounding box)
json_ = dataset_inputs.scene_bounds.to_json()
self.vis["sceneState/sceneBounds"].write(json_)
# set the properties of the camera
# self.vis["renderingState/camera"].write(json_)
# set the main camera intrinsics to one from the dataset
K = camera.get_intrinsics_matrix()
set_persp_intrinsics_matrix(self.vis, K.double().numpy())
# 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
@@ -228,21 +217,22 @@ class VisualizerState:
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"]:
is_training = self.vis["renderingState/isTraining"].read()
if is_training is None or is_training:
# in training mode, render every few steps
if self._is_render_step(step):
self._render_image_in_viewer(graph)
else:
# in pause training mode, enter render loop with set graph
local_step = step
run_loop = data["training_state"]
run_loop = not is_training
while run_loop:
if self._is_render_step(local_step):
self._render_image_in_viewer(graph)
data = self.vis["/Training State"].get_object()
run_loop = data["training_state"]
is_training = self.vis["renderingState/isTraining"].read()
run_loop = not is_training
local_step += 1
def check_interrupt(self, frame, event, arg): # pylint: disable=unused-argument
@@ -279,14 +269,15 @@ class VisualizerState:
outputs: the dictionary of outputs to choose from, from the graph
"""
if not self.outputs_set:
set_output_options(self.vis, list(outputs.keys()))
# set_output_options(self.vis, list(outputs.keys()))
self.vis["renderingState/output_options"].write(list(outputs.keys()))
self.outputs_set = True
# gross hack to get the image key, depending on which keys the graph uses
if self.prev_output_type == "default":
self.prev_output_type = "rgb" if "rgb" in outputs else "rgb_fine"
image_output = outputs[self.prev_output_type].cpu().numpy() * 255
image = (image_output).astype("uint8")
self.vis["/Cameras/Main Camera"].set_image(image)
self.vis.set_image(image)
@profiler.time_function
def _render_image_in_viewer(self, graph: Graph) -> None:
@@ -295,10 +286,10 @@ class VisualizerState:
The image is sent of a TCP connection and then uses WebRTC to send it to the viewer.
"""
# check and perform camera updates
data = self.vis["/Cameras/Main Camera"].get_object()
data = self.vis["renderingState/camera"].read()
if data is None:
return
camera_object = data["object"]["object"]
camera_object = data["object"]
# hacky way to prevent overflow check to see if < 100; TODO(make less hacky)
if self.prev_camera_matrix is not None and np.allclose(camera_object["matrix"], self.prev_camera_matrix):
self.res_upscale_factor = min(self.res_upscale_factor * 2, 100)
@@ -307,21 +298,19 @@ class VisualizerState:
self.res_upscale_factor = 1
# check and perform output type updates
data = self.vis["/Output Type"].get_object()
if data is None:
output_type = self.vis["renderingState/output_choice"].read()
if output_type is None:
output_type = "default"
else:
output_type = data["output_type"]
self.prev_output_type = output_type
# check and perform min/max update
data = self.vis["/Max Resolution"].get_object()
if data is not None:
self.max_resolution = int(data["max_resolution"])
max_resolution = self.vis["renderingState/maxResolution"].read()
if max_resolution:
self.max_resolution = max_resolution
data = self.vis["/Min Resolution"].get_object()
if data is not None:
self.min_resolution = int(data["min_resolution"])
min_resolution = self.vis["renderingState/minResolution"].read()
if min_resolution:
self.min_resolution = min_resolution
image_height = min(
self.min_resolution * self.res_upscale_factor,
@@ -368,191 +357,3 @@ def get_default_vis() -> Viewer:
zmq_url = "tcp://0.0.0.0:6000"
viewer = Viewer(zmq_url=zmq_url)
return viewer
def set_output_options(vis: Viewer, output_options: List[str]):
"""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.
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: 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)
else:
material = g.MeshPhongMaterial(vertexColors=True)
vis[name].set_object(g.PlyMeshGeometry.from_file(ply_path), material)
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)
else:
material = g.MeshPhongMaterial(vertexColors=True)
vis[name].set_object(g.ObjMeshGeometry.from_file(obj_path), material)
def draw_camera_frustum(
vis: Viewer,
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.
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]
pp_w = K[0, 2]
pp_h = K[1, 2]
if displayed_focal_length:
assert height is None or not realistic
if height:
assert displayed_focal_length is None or not realistic
if height:
dfl = height / (2.0 * (pp_h / focal_length))
width = 2.0 * (pp_w / focal_length) * dfl
if displayed_focal_length is None:
displayed_focal_length = dfl
elif displayed_focal_length:
width = 2.0 * (pp_w / focal_length) * displayed_focal_length
height = 2.0 * (pp_h / focal_length) * displayed_focal_length
else:
assert not realistic
if pose.shape == (3, 4):
pose = np.concatenate([pose, np.zeros_like(pose[:1])], axis=0)
pose[3, 3] = 1.0
# draw the frustum
g_frustum = c.frustum(scale=1.0, focal_length=displayed_focal_length, width=width, height=height)
vis[name + "/frustum"].set_object(g_frustum)
if not realistic:
vis[name + "/frustum"].set_transform(get_translation_matrix([0, 0, displayed_focal_length]))
# draw the image plane
g_image_plane = c.ImagePlane(image, width=width, height=height)
vis[name + "/image_plane"].set_object(g_image_plane)
if realistic:
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, -1.0 * shift_forward])
vis[name + "/frustum"].set_transform(matrix2 @ matrix)
vis[name + "/image_plane"].set_transform(matrix2)
# set the transform of the camera
vis[name].set_transform(pose)
def set_persp_intrinsics_matrix(vis, K):
pp_w = K[0, 2]
pp_h = K[1, 2]
assert K[0, 0] == K[1, 1]
focal_length = K[0, 0]
x = pp_h / (focal_length)
fov = 2.0 * np.arctan(x) * (180.0 / np.pi)
vis["/Cameras/Main Camera/<object>"].set_property("fov", fov)
vis["/Cameras/Main Camera/<object>"].set_property("aspect", float(pp_w / pp_h)) # three.js expects width/height
def set_persp_pose(vis, pose, colmap=True):
pose_processed = copy.deepcopy(pose)
if colmap:
pose_processed[:, 1:3] *= -1
vis["/Cameras/Main Camera/<object>"].set_transform(pose_processed)
def set_persp_camera(vis, pose, K, colmap=True):
"""Assumes simple pinhole model for intrinsics.
Args:
colmap: whether to use the colmap camera coordinate convention or not
"""
set_persp_intrinsics_matrix(vis, K)
set_persp_pose(vis, pose, colmap=colmap)
def set_camera(vis, camera: Camera):
pose = camera.get_camera_to_world_h()
K = camera.get_intrinsics_matrix()
set_persp_camera(vis, pose=pose.double().numpy(), K=K.double().numpy())
def draw_aabb(vis, aabb, name="aabb"):
"""Draw the axis-aligned bounding box."""
lengths = aabb[1] - aabb[0]
w = 1
aaa = np.array([w, w, w])
aab = np.array([w, w, -w])
aba = np.array([w, -w, w])
baa = np.array([-w, w, w])
abb = np.array([w, -w, -w])
bba = np.array([-w, -w, w])
bab = np.array([-w, w, -w])
bbb = np.array([-w, -w, -w])
camera_points = [aaa, aab, aaa, aba, aab, abb, aba, abb]
camera_points.extend([baa, bab, baa, bba, bab, bbb, bba, bbb])
camera_points.extend([aaa, baa, aab, bab, aba, bba, abb, bbb])
lines = np.stack(camera_points)
lines = lines * np.array(lengths) / 2.0
line_segments = g.LineSegments(
g.PointsGeometry(position=lines.astype(np.float32).T),
g.LineBasicMaterial(vertexColors=True),
)
vis[name].set_object(line_segments)
center = aabb[0] + lengths / 2.0
vis[name].set_transform(get_translation_matrix(center.tolist()))
+32 -59
View File
@@ -12,28 +12,25 @@
# See the License for the specific language governing permissions and
# limitations under the License.
"""Code to connect and send commands to the viewer.
"""
import logging
import signal
import sys
from typing import Dict, Optional
import msgpack
import msgpack_numpy
import numpy as np
import umsgpack
import zmq
from nerfactory.viewer.server.commands import (
Delete,
GetObject,
SetObject,
SetOutputOptions,
SetProperty,
SetTransform,
)
from nerfactory.viewer.server.path import Path
class ViewerWindow:
"""The viewer window has the ZMQ connection to the viewer bridge server."""
context = zmq.Context()
def __init__(self, zmq_url):
@@ -43,15 +40,15 @@ class ViewerWindow:
self.assert_connected()
def send(self, command):
cmd_data = command.lower()
"""Sends a command to the viewer bridge server."""
self.client.send_multipart(
[
cmd_data["type"].encode("utf-8"),
cmd_data["path"].encode("utf-8"),
umsgpack.packb(cmd_data),
command["type"].encode("utf-8"),
command["path"].encode("utf-8"),
umsgpack.packb(command),
]
)
return self.client.recv()
return umsgpack.unpackb(self.client.recv())
def send_ping(self):
"""Tries to contact the viewer bridge server."""
@@ -65,7 +62,7 @@ class ViewerWindow:
data,
]
)
return self.client.recv()
return umsgpack.unpackb(self.client.recv())
def assert_connected(self, timeout_in_sec: int = 5):
"""Check if the connection was established properly within some time.
@@ -84,7 +81,7 @@ class ViewerWindow:
_ = self.send_ping()
logging.info("Successfully connected.")
signal.alarm(0) # cancel the alarm
except Exception as e:
except Exception as e: # pylint: disable=broad-except
logging.info(e)
sys.exit()
@@ -93,19 +90,18 @@ class Viewer:
"""Visualizer class for connecting to the bridge server.
Args:
zmq_url (str, optional): _description_. Defaults to None.
window (ViewerWindow, optional): _description_. Defaults to None.
timeout (str, optional): _description_. Defaults to None.
zmq_url: Where to connect with ZMQ. Defaults to None.
window: An already existing ViewerWindow. Defaults to None.
"""
def __init__(self, zmq_url: str = None, window: ViewerWindow = None):
def __init__(self, zmq_url: Optional[str] = None, window: Optional[ViewerWindow] = None):
if zmq_url is None and window is None:
raise ValueError("Must specify either zmq_url or window.")
if window is None:
self.window = ViewerWindow(zmq_url=zmq_url)
else:
self.window = window
self.path = Path(("nerfactory",))
self.path = Path(())
@staticmethod
def view_into(window: ViewerWindow, path: Path):
@@ -117,28 +113,25 @@ class Viewer:
def __getitem__(self, path):
return Viewer.view_into(self.window, self.path.append(path))
def set_object(self, geometry, material=None):
"""Set the object at the current path
Args:
geometry (_type_): _description_
material (_type_, optional): _description_. Defaults to None.
def __repr__(self):
return f"<Viewer using: {self.window} at path: {self.path}>"
Returns:
_type_: _description_
"""
return self.window.send(SetObject(geometry, material, self.path))
def write(self, data: Optional[Dict] = None):
"""Write data."""
path = self.path.lower()
return self.window.send({"type": "write", "path": path, "data": data})
def get_object(self):
"""Get the object at the current path."""
data = self.window.send(GetObject(self.path))
data = umsgpack.unpackb(data)
if isinstance(data, str) and data.find("error") == 0:
# some error meaning that the object does not exist
return None
return data
def read(self):
"""Read data."""
path = self.path.lower()
return self.window.send({"type": "read", "path": path})
def delete(self):
"""Delete data."""
return self.write(data=None)
def set_image(self, image):
"""Set the image"""
"""Sends an image to the viewer with WebRTC."""
type_ = "set_image"
path = self.path.lower()
data = msgpack.packb(image, default=msgpack_numpy.encode, use_bin_type=True)
@@ -150,23 +143,3 @@ class Viewer:
]
)
return self.window.client.recv()
def set_transform(self, matrix=np.eye(4)):
"""Set the transform"""
assert matrix.shape == (4, 4)
return self.window.send(SetTransform(matrix, self.path))
def set_property(self, key, value):
"""Set the property"""
return self.window.send(SetProperty(key, value, self.path))
def set_output_options(self, options):
"""Set the output options"""
return self.window.send(SetOutputOptions(options, self.path))
def delete(self):
"""Delete the contents of the window"""
return self.window.send(Delete(self.path))
def __repr__(self):
return f"<Viewer using: {self.window} at path: {self.path}>"