Initial viewer (visualizer) code (#52)

* some initial code for viewer. copying from other repos

* adding electron support

* moving some test files around. need to rewrite these

* camera traj. test cases. starting to transmit images

* still working on vis

* reorganized viewer and figured out websocket sending from client. need to do with camera pose

* black

* temporarily ignore pylinting for viewer

* ignore viewer

* fixed array

* license and fixed ignore in pyproject.toml

* improved syntax
This commit is contained in:
Ethan Weber authored and GitHub committed 2022-06-16 12:11:40 -07:00
1 parent 91ef54963c
commit 1e22984d87
50 files changed
+16946 -919

No files matched your search

+26
View File
@@ -0,0 +1,26 @@
# 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.
import os
from . import commands
from . import geometry
from . import visualizer
from . import transformations
from . import animation
from .visualizer import ViewerWindow, Visualizer
def viewer_assets_path():
return os.path.abspath(os.path.join(os.path.dirname(__file__), "viewer"))
+184
View File
@@ -0,0 +1,184 @@
# 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 __future__ import absolute_import, division, print_function
import tempfile
import tarfile
import sys
import os.path
import subprocess
if sys.version_info >= (3, 0):
unicode = str
import bisect
from . import transformations as tf
class AnimationTrack(object):
__slots__ = ["name", "jstype", "frames", "values"]
def __init__(self, name, jstype, frames=None, values=None):
self.name = name
self.jstype = jstype
if frames is None:
self.frames = []
else:
self.frames = frames
if values is None:
self.values = []
else:
self.values = values
def set_property(self, frame, value):
i = bisect.bisect(self.frames, frame)
self.frames.insert(i, frame)
self.values.insert(i, value)
def lower(self):
return {
"name": unicode("." + self.name),
"type": unicode(self.jstype),
"keys": [{"time": self.frames[i], "value": self.values[i]} for i in range(len(self.frames))],
}
class AnimationClip(object):
__slots__ = ["tracks", "fps", "name"]
def __init__(self, tracks=None, fps=30, name="default"):
if tracks is None:
self.tracks = {}
else:
self.tracks = tracks
self.fps = fps
self.name = name
def set_property(self, frame, property, jstype, value):
if property not in self.tracks:
self.tracks[property] = AnimationTrack(property, jstype)
track = self.tracks[property]
track.set_property(frame, value)
def lower(self):
return {"fps": self.fps, "name": unicode(self.name), "tracks": [t.lower() for t in self.tracks.values()]}
class Animation(object):
__slots__ = ["clips", "default_framerate"]
def __init__(self, clips=None, default_framerate=30):
if clips is None:
self.clips = {}
else:
self.clips = clips
self.default_framerate = default_framerate
def lower(self):
return [{"path": path.lower(), "clip": clip.lower()} for (path, clip) in self.clips.items()]
def at_frame(self, visualizer, frame):
return AnimationFrameVisualizer(self, visualizer.path, frame)
def js_position(matrix):
return list(matrix[:3, 3])
def js_quaternion(matrix):
quat = tf.quaternion_from_matrix(matrix)
return [quat[1], quat[2], quat[3], quat[0]]
class AnimationFrameVisualizer(object):
__slots__ = ["animation", "path", "current_frame"]
def __init__(self, animation, path, current_frame):
self.animation = animation
self.path = path
self.current_frame = current_frame
def get_clip(self):
if self.path not in self.animation.clips:
self.animation.clips[self.path] = AnimationClip(fps=self.animation.default_framerate)
return self.animation.clips[self.path]
def set_transform(self, matrix):
assert matrix.shape == (4, 4)
clip = self.get_clip()
clip.set_property(self.current_frame, "position", "vector3", js_position(matrix))
clip.set_property(self.current_frame, "quaternion", "quaternion", js_quaternion(matrix))
def set_property(self, prop, jstype, value):
clip = self.get_clip()
clip.set_property(self.current_frame, prop, jstype, value)
def __getitem__(self, path):
return AnimationFrameVisualizer(self.animation, self.path.append(path), self.current_frame)
def __enter__(self):
return self
def __exit__(self, *arg):
pass
def convert_frames_to_video(tar_file_path, output_path="output.mp4", framerate=60, overwrite=False):
"""
Try to convert a tar file containing a sequence of frames saved by the
pyrad viewer into a single video file.
This relies on having `ffmpeg` installed on your system.
"""
output_path = os.path.abspath(output_path)
if os.path.isfile(output_path) and not overwrite:
raise ValueError(
"The output path {:s} already exists. To overwrite that file, you can pass overwrite=True to this function.".format(
output_path
)
)
with tempfile.TemporaryDirectory() as tmp_dir:
with tarfile.open(tar_file_path) as tar:
tar.extractall(tmp_dir)
args = [
"ffmpeg",
"-r",
str(framerate),
"-i",
r"%07d.png",
"-vcodec",
"libx264",
"-preset",
"slow",
"-crf",
"18",
]
if overwrite:
args.append("-y")
args.append(output_path)
try:
subprocess.check_call(args, cwd=tmp_dir)
except subprocess.CalledProcessError as e:
print(
"""
Could not call `ffmpeg` to convert your frames into a video.
If you want to convert the frames manually, you can extract the
.tar archive into a directory, cd to that directory, and run:
ffmpeg -r 60 -i %07d.png \\\n\t -vcodec libx264 \\\n\t -preset slow \\\n\t -crf 18 \\\n\t output.mp4
"""
)
raise
print("Saved output as {:s}".format(output_path))
return output_path
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python
import os
import sys
import subprocess
import time
def file_filter(name):
return (not name.startswith(".")) and (not name.endswith(".swp"))
def file_times(path):
for top_level in filter(file_filter, os.listdir(path)):
for root, dirs, files in os.walk(top_level):
for file in filter(file_filter, files):
yield os.stat(os.path.join(root, file)).st_mtime
def print_stdout(process):
stdout = process.stdout
if stdout != None:
print(stdout)
# We concatenate all of the arguments together, and treat that as the command to run
command = " ".join(sys.argv[1:])
# The path to watch
path = "."
# How often we check the filesystem for changes (in seconds)
wait = 1
# The process to autoreload
process = subprocess.Popen(command, shell=True)
# The current maximum file modified time under the watched directory
last_mtime = max(file_times(path))
while True:
max_mtime = max(file_times(path))
print_stdout(process)
if max_mtime > last_mtime:
last_mtime = max_mtime
process.kill()
print("Restarting process.")
process = subprocess.Popen(command, shell=True)
time.sleep(wait)
+167
View File
@@ -0,0 +1,167 @@
# 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 .geometry import SceneElement, Geometry, Object, LineSegments, PointsGeometry, LineBasicMaterial
# import geometry as g
from . import geometry as g
import numpy as np
import cv2
"""
TODO(ethan): add some notes about the coordinate conventions of the cameras
"""
class Camera(SceneElement):
def __init__(self):
super().__init__()
class OrthographicCamera(Camera):
def __init__(self, left, right, top, bottom, near, far, zoom=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):
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(Camera):
def __init__(self, aspect, fov, near, far, zoom=1):
super().__init__()
self.aspect = aspect
self.fov = fov
self.near = near
self.far = far
@staticmethod
def from_intrinsics(focal_length, aspect_ratio):
"""TODO(ethan): finish this"""
# convert the intrinsics matrix into three.js compatible format
return PerspectiveCamera(aspect, fov, near, far)
def lower(self):
data = {
"object": {
"uuid": self.uuid,
"type": "PerspectiveCamera",
"aspect": self.aspect,
"fov": self.fov,
"near": self.near,
"far": self.far,
}
}
return data
class CameraHelper(Camera):
"""NOTE(ethan): Camera parent class might not make sense here?"""
def __init__(self, camera):
super().__init__()
self.camera = camera
def lower(self):
data = {"object": {"uuid": self.uuid, "type": "CameraHelper", "camera": self.camera.lower()}}
return data
class ImagePlane(g.Mesh):
def __init__(self, image, height=1, width=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=4, w=1.5, h=2):
"""
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
"""
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]
lines = np.stack([x for x in 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):
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
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=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
"""
# 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, linewidth=10.0),
)
return line_segments
+120
View File
@@ -0,0 +1,120 @@
# 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 __future__ import absolute_import, division, print_function
import sys
if sys.version_info >= (3, 0):
unicode = str
from .geometry import (
Geometry,
Object,
Mesh,
MeshPhongMaterial,
OrthographicCamera,
PerspectiveCamera,
PointsMaterial,
Points,
)
from .cameras import Camera, CameraHelper
from .path import Path
class SetObject:
__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):
return {"type": "set_object", "object": self.object.lower(), "path": self.path.lower()}
class SetTransform:
__slots__ = ["matrix", "path"]
def __init__(self, matrix, path):
self.matrix = matrix
self.path = path
def lower(self):
return {"type": "set_transform", "path": self.path.lower(), "matrix": list(self.matrix.T.flatten())}
class Delete:
__slots__ = ["path"]
def __init__(self, path):
self.path = path
def lower(self):
return {"type": "delete", "path": self.path.lower()}
class SetProperty:
__slots__ = ["path", "key", "value"]
def __init__(self, key, value, path):
self.key = key
self.value = value
self.path = path
def lower(self):
return {"type": "set_property", "path": self.path.lower(), "property": self.key.lower(), "value": self.value}
class SetAnimation:
__slots__ = ["animation", "play", "repetitions"]
def __init__(self, animation, play=True, repetitions=1):
self.animation = animation
self.play = play
self.repetitions = repetitions
def lower(self):
return {
"type": "set_animation",
"animations": self.animation.lower(),
"options": {"play": self.play, "repetitions": self.repetitions},
"path": "",
}
class SetImage:
__slots__ = ["image", "path"]
def __init__(self, image, path):
self.image = image
self.path = path
def lower(self):
return {"type": "set_image", "image": self.image, "path": self.path.lower()}
+658
View File
@@ -0,0 +1,658 @@
# 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 __future__ import absolute_import, division, print_function
import sys
import base64
import uuid
if sys.version_info >= (3, 0):
unicode = str
from io import StringIO, BytesIO
else:
from StringIO import StringIO
BytesIO = StringIO
import umsgpack
import numpy as np
from . import transformations as tf
class SceneElement(object):
def __init__(self):
self.uuid = unicode(uuid.uuid1())
def intrinsic_transform(self):
return tf.identity_matrix()
class ReferenceSceneElement(SceneElement):
def lower_in_object(self, object_data):
object_data.setdefault(self.field, []).append(self.lower(object_data))
return self.uuid
class Geometry(ReferenceSceneElement):
field = "geometries"
class Material(ReferenceSceneElement):
field = "materials"
class Texture(ReferenceSceneElement):
field = "textures"
class Image(ReferenceSceneElement):
field = "images"
class Box(Geometry):
def __init__(self, lengths):
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):
def __init__(self, radius):
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
"""
def __init__(self, radii):
super().__init__(1.0)
self.radii = radii
def intrinsic_transform(self):
return np.diag(np.hstack((self.radii, 1.0)))
class PlaneGeometry(Geometry):
def __init__(self, lengths):
super().__init__()
self.lengths = lengths
def lower(self, object_data):
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):
super().__init__()
if radiusTop is not None and radiusBottom is not None:
self.radiusTop = radiusTop
self.radiusBottom = radiusBottom
else:
self.radiusTop = radius
self.radiusBottom = radius
self.height = height
self.radialSegments = 50
def lower(self, object_data):
return {
"uuid": self.uuid,
"type": "CylinderGeometry",
"radiusTop": self.radiusTop,
"radiusBottom": self.radiusBottom,
"height": self.height,
"radialSegments": self.radialSegments,
}
class GenericMaterial(Material):
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
):
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.wireframeLinewidth = wireframeLinewidth
self.vertexColors = vertexColors
self.properties = kwargs
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.wireframeLinewidth,
"vertexColors": (2 if self.vertexColors 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):
_type = "MeshBasicMaterial"
class MeshPhongMaterial(GenericMaterial):
_type = "MeshPhongMaterial"
class MeshLambertMaterial(GenericMaterial):
_type = "MeshLambertMaterial"
class MeshToonMaterial(GenericMaterial):
_type = "MeshToonMaterial"
class LineBasicMaterial(GenericMaterial):
_type = "LineBasicMaterial"
class PngImage(Image):
def __init__(self, data):
super().__init__()
self.data = data
@staticmethod
def from_file(fname):
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):
def __init__(self, properties):
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):
def __init__(self, image, wrap=[1001, 1001], repeat=[1, 1], **kwargs):
super().__init__()
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):
def __init__(self, geometry, material=MeshPhongMaterial()):
super().__init__()
self.geometry = geometry
self.material = material
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):
_type = "Mesh"
class OrthographicCamera(SceneElement):
def __init__(self, left, right, top, bottom, near, far, zoom=1):
super(OrthographicCamera, self).__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):
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 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):
"""
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.
filmGauge: 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.
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.
"""
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.focus = focus
def lower(self):
data = {
"object": {
"uuid": self.uuid,
"type": "PerspectiveCamera",
"aspect": self.aspect,
"far": self.far,
"filmGauge": self.filmGauge,
"filmOffset": self.filmOffset,
"focus": self.focus,
"fov": self.fov,
"near": self.near,
"zoom": self.zoom,
}
}
return data
def item_size(array):
if array.ndim == 1:
return 1
elif 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)
)
def threejs_type(dtype):
if dtype == np.uint8:
return "Uint8Array", 0x12
elif dtype == np.int32:
return "Int32Array", 0x15
elif dtype == np.uint32:
return "Uint32Array", 0x16
elif dtype == np.float32:
return "Float32Array", 0x17
else:
raise ValueError("Unsupported datatype: " + str(dtype))
def pack_numpy_array(x):
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):
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)))
else:
data = stream.read()
return data
class MeshGeometry(Geometry):
def __init__(self, contents, mesh_format):
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):
def __init__(self, contents):
super().__init__(contents, "obj")
@staticmethod
def from_file(fname):
with open(fname, "r") as f:
return MeshGeometry(f.read(), "obj")
@staticmethod
def from_stream(f):
return MeshGeometry(data_from_stream(f), "obj")
class DaeMeshGeometry(MeshGeometry):
def __init__(self, contents):
super().__init__(contents, "dae")
@staticmethod
def from_file(fname):
with open(fname, "r") as f:
return MeshGeometry(f.read(), "dae")
@staticmethod
def from_stream(f):
return MeshGeometry(data_from_stream(f), "dae")
class StlMeshGeometry(MeshGeometry):
def __init__(self, contents):
super().__init__(contents, "stl")
@staticmethod
def from_file(fname):
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):
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)))
else:
arr = np.frombuffer(f.read(), dtype=np.uint8)
_, extcode = threejs_type(np.uint8)
encoded = umsgpack.Ext(extcode, arr.tobytes())
return MeshGeometry(encoded, "stl")
class PlyMeshGeometry(MeshGeometry):
def __init__(self, contents):
super().__init__(contents, "ply")
@staticmethod
def from_file(fname):
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):
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)))
else:
arr = np.frombuffer(f.read(), dtype=np.uint8)
_, 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, faces):
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):
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):
def __init__(self, position, color=None):
super().__init__()
self.position = position
self.color = color
def lower(self, object_data):
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):
def __init__(self, size=0.001, color=0xFFFFFF, sizeAttenuation=True):
super().__init__()
self.size = size
self.color = color
self.sizeAttenuation = sizeAttenuation
def lower(self, object_data):
return {
"uuid": self.uuid,
"type": "PointsMaterial",
"color": self.color,
"size": self.size,
"sizeAttenuation": bool(self.sizeAttenuation),
"vertexColors": 2,
}
class Points(Object):
_type = "Points"
def PointCloud(position, color, **kwargs):
return Points(PointsGeometry(position, color), PointsMaterial(**kwargs))
class Line(Object):
_type = "Line"
class LineSegments(Object):
_type = "LineSegments"
class LineLoop(Object):
_type = "LineLoop"
def triad(scale=1.0):
"""
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()`
"""
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=1.0):
"""
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()`
"""
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),
)
+45
View File
@@ -0,0 +1,45 @@
# 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 __future__ import absolute_import, division, print_function
import sys
if sys.version_info >= (3, 0):
unicode = str
class Path(object):
__slots__ = ["entries"]
def __init__(self, entries=tuple()):
self.entries = entries
def append(self, other):
new_path = self.entries
for element in other.split("/"):
if len(element) == 0:
new_path = tuple()
else:
new_path = new_path + (element,)
return Path(new_path)
def lower(self):
return unicode("/" + "/".join(self.entries))
def __hash__(self):
return hash(self.entries)
def __eq__(self, other):
return self.entries == other.entries
+233
View File
@@ -0,0 +1,233 @@
# 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 __future__ import absolute_import, division, print_function
import base64
import re
import sys
if sys.version_info >= (3, 0):
ADDRESS_IN_USE_ERROR = OSError
else:
import socket
ADDRESS_IN_USE_ERROR = socket.error
import tornado.gen
import tornado.ioloop
import tornado.web
import tornado.websocket
import zmq
import zmq.eventloop.ioloop
from pyrad.viewer.backend.tree import SceneTree, find_node, walk
from zmq.eventloop.zmqstream import ZMQStream
def capture(pattern, s):
match = re.match(pattern, s)
if not match:
raise ValueError("Could not match {:s} with pattern {:s}".format(s, pattern))
else:
return match.groups()[0]
def match_zmq_url(line):
return capture(r"^zmq_url=(.*)$", line)
def _zmq_install_ioloop():
# For pyzmq<17, install ioloop instead of a tornado ioloop
# http://zeromq.github.com/pyzmq/eventloop.html
try:
pyzmq_major = int(zmq.__version__.split(".")[0])
except ValueError:
# Development version?
return
if pyzmq_major < 17:
zmq.eventloop.ioloop.install()
_zmq_install_ioloop()
MAX_ATTEMPTS = 1000
DEFAULT_ZMQ_METHOD = "tcp"
DEFAULT_ZMQ_PORT = 6000
DEFAULT_WEBSOCKET_PORT = 8051
MESHCAT_COMMANDS = ["set_transform", "set_object", "delete", "set_property", "set_animation", "set_image"]
def find_available_port(func, default_port, max_attempts=MAX_ATTEMPTS, **kwargs):
for i in range(max_attempts):
port = default_port + i
try:
return func(port, **kwargs), port
except (ADDRESS_IN_USE_ERROR, zmq.error.ZMQError):
print("Port: {:d} in use, trying another...".format(port), 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
)
)
)
class WebSocketHandler(tornado.websocket.WebSocketHandler):
def __init__(self, *args, **kwargs):
self.bridge = kwargs.pop("bridge")
super(WebSocketHandler, self).__init__(*args, **kwargs)
# this disables CORS
def check_origin(self, origin):
return True
def open(self):
self.bridge.websocket_pool.add(self)
print("opened:", self, file=sys.stderr)
self.bridge.send_scene(self)
def on_message(self, message):
print(message)
def on_close(self):
self.bridge.websocket_pool.remove(self)
print("closed:", self, file=sys.stderr)
def create_command(data):
"""Encode the drawing command into a Javascript fetch() command for display."""
return """
fetch("data:application/octet-binary;base64,{}")
.then(res => res.arrayBuffer())
.then(buffer => viewer.handle_command_bytearray(new Uint8Array(buffer)));
""".format(
base64.b64encode(data).decode("utf-8")
)
class ZMQWebSocketBridge(object):
context = zmq.Context()
def __init__(self, zmq_url=None, host="127.0.0.1", websocket_port=None):
self.host = host
self.websocket_pool = set()
self.app = self.make_app()
self.ioloop = tornado.ioloop.IOLoop.current()
if zmq_url is None:
def f(port):
return self.setup_zmq("{:s}://{:s}:{:d}".format(DEFAULT_ZMQ_METHOD, self.host, port))
(self.zmq_socket, self.zmq_stream, self.zmq_url), _ = find_available_port(f, DEFAULT_ZMQ_PORT)
else:
self.zmq_socket, self.zmq_stream, self.zmq_url = self.setup_zmq(zmq_url)
listen_kwargs = {}
if websocket_port is None:
_, self.websocket_port = find_available_port(self.app.listen, DEFAULT_WEBSOCKET_PORT, **listen_kwargs)
else:
self.app.listen(websocket_port, **listen_kwargs)
self.websocket_port = websocket_port
self.tree = SceneTree()
def __str__(self) -> str:
class_name = self.__class__.__name__
return f"{class_name} using zmq_url={self.zmq_url} and websocket_port={self.websocket_port}"
def make_app(self):
return tornado.web.Application([(r"/", WebSocketHandler, {"bridge": self})])
def handle_zmq(self, frames):
cmd = frames[0].decode("utf-8")
if cmd not in MESHCAT_COMMANDS:
print(f"{cmd} not in MESHCAT_COMMANDS! Proceeding anyways.")
# self.zmq_socket.send(b"error: unrecognized comand")
if len(frames) != 3:
self.zmq_socket.send(b"error: expected 3 frames")
return
path = list(filter(lambda x: len(x) > 0, frames[1].decode("utf-8").split("/")))
data = frames[2]
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_property":
find_node(self.tree, path).properties.append(data)
elif cmd == "set_animation":
find_node(self.tree, path).animation = 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()
self.zmq_socket.send(b"ok")
def forward_to_websockets(self, frames):
cmd, path, data = frames
for websocket in self.websocket_pool:
websocket.write_message(data, binary=True)
def setup_zmq(self, url):
zmq_socket = self.context.socket(zmq.REP)
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):
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)
if node.animation is not None:
websocket.write_message(node.animation, binary=True)
def run(self):
self.ioloop.start()
def main():
import argparse
parser = argparse.ArgumentParser(description="Serve the MeshCat HTML files and listen for ZeroMQ commands")
parser.add_argument("--zmq-url", "-z", type=str, nargs="?", default=None)
parser.add_argument("--websocket-port", "-wp", type=str, nargs="?", default=None)
args = parser.parse_args()
bridge = ZMQWebSocketBridge(zmq_url=args.zmq_url, websocket_port=args.websocket_port)
print(bridge)
try:
bridge.run()
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()
File diff suppressed because it is too large. Load diff
+45
View File
@@ -0,0 +1,45 @@
# 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 __future__ import absolute_import, division, print_function
from collections import defaultdict
class TreeNode(defaultdict):
__slots__ = ["object", "transform", "properties", "animation"]
def __init__(self, *args, **kwargs):
super(TreeNode, self).__init__(*args, **kwargs)
self.object = None
self.properties = []
self.transform = None
self.animation = None
SceneTree = lambda: TreeNode(SceneTree)
def walk(tree):
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):
if len(path) == 0:
return tree
else:
return find_node(tree[path[0]], path[1:])
+219
View File
@@ -0,0 +1,219 @@
# 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.
"""Code to interface with the `vis/` (the JS visualizer).
"""
import copy
import random
import cv2
import matplotlib.pyplot as plt
import numpy as np
from pyrad.cameras.cameras import Camera
import pyrad.viewer.backend.cameras as c
import pyrad.viewer.backend.geometry as g
import pyrad.viewer.backend.transformations as tf
from pyrad.viewer.backend import ViewerWindow, Visualizer
def get_vis(zmq_url="tcp://0.0.0.0:6000"):
"""Returns the vis object."""
window = ViewerWindow(zmq_url)
vis = Visualizer(window=window)
return vis
def show_box_test(vis):
"""Simple test to draw a box and make sure everything is working."""
vis["box"].set_object(g.Box([1.0, 1.0, 1.0]), material=g.MeshPhongMaterial(color=0xFF0000))
def get_random_color():
color = np.random.rand(3) * 255.0
color = tuple([int(x) for x in color])
return color
def plot_correspondences(pair, plot=True):
"""Draw what the pair looks like, with the correspondences as lines."""
image0 = (pair["data0"]["image"] * 255).astype("uint8").transpose((1, 2, 0))
image1 = (pair["data1"]["image"] * 255).astype("uint8").transpose((1, 2, 0))
original_image = np.hstack([image0, image1])
h, w, _ = image0.shape
matches_image = original_image.copy()
# draw lines
correspondences = list(pair["correspondences"])
num = min(20, len(correspondences))
for x0, y0, x1, y1 in np.array(random.sample(correspondences, k=num)).astype("uint64"):
color = get_random_color()
thickness = 2
matches_image = cv2.line(matches_image, (x0, y0), (int(w + x1), y1), color, thickness)
# show image
if plot:
print("Correspondences:")
plt.figure(figsize=(20, 10))
plt.imshow(matches_image)
plt.show()
# ----------
# example training data
equal_distances_image = original_image.copy()
for i in range(num):
c0, c1 = np.array(random.sample(correspondences, k=2)).astype("uint64")
color = get_random_color()
thickness = 2
p0, p1 = c0[:2], c1[:2]
equal_distances_image = cv2.line(equal_distances_image, tuple(p0), tuple(p1), color, thickness)
p0, p1 = c0[2:], c1[2:]
p0[0] += w
p1[0] += w
equal_distances_image = cv2.line(equal_distances_image, tuple(p0), tuple(p1), color, thickness)
if plot:
print("Example training data:")
plt.figure(figsize=(20, 10))
plt.imshow(equal_distances_image)
plt.show()
return matches_image, equal_distances_image
def show_ply(vis, ply_path, name="ply", color=None):
"""Show the PLY file in the 3D viewer. Specify the full filename as input."""
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, obj_path, name="obj", color=None):
"""Show the PLY file in the 3D viewer. Specify the full filename as input."""
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,
image=np.random.rand(100, 100, 3) * 255.0,
pose=tf.translation_matrix([0, 0, 0]),
K=None,
name="0000000",
displayed_focal_length=None,
shift_forward=None,
height=None,
realistic=True,
):
"""Draw the camera in the scene."""
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(tf.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:
vis[name + "/image_plane"].set_transform(tf.translation_matrix([0, 0, -displayed_focal_length]))
if shift_forward:
matrix = tf.translation_matrix([0, 0, displayed_focal_length])
matrix2 = tf.translation_matrix([0, 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_camera_render(vis, intrinsics=None, pose=None, name="renderer"):
"""Place a three.js camera in the scene.
This can be used to render an image from.
"""
full_name_str = f"/Cameras/{name}/rotated"
g_camera = c.PerspectiveCamera(fov=120, aspect=1.0, near=0.01, far=1000)
g_camera_helper = c.CameraHelper(g_camera)
# vis[full_name_str].set_object(g_camera)
vis[full_name_str].set_object(g_camera_helper)
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
"""
pose_processed = copy.deepcopy(pose)
if colmap:
pose_processed[:, 1:3] *= -1
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 R/<object>"].set_property("fov", fov)
vis["/Cameras/Main Camera R/<object>"].set_property("aspect", float(pp_w / pp_h)) # three.js expects width/height
vis["/Cameras/Main Camera R"].set_transform(pose_processed)
def set_orth_camera(vis, pose, width, height, colmap=True):
""" """
pose_processed = copy.deepcopy(pose)
if colmap:
pose_processed[:, 1:3] *= -1
vis["/Cameras/Main Camera Orth"].set_transform(pose_processed)
vis["/Cameras/Main Camera Orth/<object>"].set_property("left", -width / 2.0)
vis["/Cameras/Main Camera Orth/<object>"].set_property("right", width / 2.0)
vis["/Cameras/Main Camera Orth/<object>"].set_property("top", height / 2.0)
vis["/Cameras/Main Camera Orth/<object>"].set_property("bottom", -height / 2.0)
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())
+84
View File
@@ -0,0 +1,84 @@
# 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 __future__ import absolute_import, division, print_function
import sys
import time
import numpy as np
import umsgpack
import zmq
from .commands import Delete, SetAnimation, SetImage, SetObject, SetProperty, SetTransform
from .path import Path
class ViewerWindow(object):
context = zmq.Context()
def __init__(self, zmq_url):
self.zmq_url = zmq_url
self.client = self.context.socket(zmq.REQ)
self.client.connect(self.zmq_url)
def send(self, command):
cmd_data = command.lower()
self.client.send_multipart(
[
cmd_data["type"].encode("utf-8"),
cmd_data["path"].encode("utf-8"),
umsgpack.packb(cmd_data),
]
)
self.client.recv()
class Visualizer(object):
__slots__ = ["window", "path"]
def __init__(self, window):
self.window = window
self.path = Path(("pyrad",)) # TODO(ethan): change this
@staticmethod
def view_into(window, path):
vis = Visualizer(window=window)
vis.path = path
return vis
def __getitem__(self, path):
return Visualizer.view_into(self.window, self.path.append(path))
def set_object(self, geometry, material=None):
return self.window.send(SetObject(geometry, material, self.path))
def set_transform(self, matrix=np.eye(4)):
assert matrix.shape == (4, 4)
return self.window.send(SetTransform(matrix, self.path))
def set_property(self, key, value):
return self.window.send(SetProperty(key, value, self.path))
def set_animation(self, animation, play=True, repetitions=1):
return self.window.send(SetAnimation(animation, play=play, repetitions=repetitions))
def set_image(self, image):
return self.window.send(SetImage(image, self.path))
def delete(self):
return self.window.send(Delete(self.path))
def __repr__(self):
return "<Visualizer using: {window} at path: {path}>".format(window=self.window, path=self.path)