Rename repo to nerfactory (#204)

* Rename to nerfactory

* Fix missing files
This commit is contained in:
Matthew Tancik authored and GitHub committed 2022-07-25 13:52:20 -07:00
1 parent 8db05d8299
commit 6dc704c551
187 files changed
+259775 -259761

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
# 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.
+4
View File
@@ -0,0 +1,4 @@
BROWSER=none
FAST_REFRESH=false
HOST=localhost
PORT=4000
+14
View File
@@ -0,0 +1,14 @@
.idea/
.vscode/
node_modules/
build/
.DS_Store
*.tgz
my-app*
template/src/__tests__/__snapshots__/
lerna-debug.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
/.changelog
.npm/
+56
View File
@@ -0,0 +1,56 @@
{
"name": "viewer",
"homepage": "https://ethanweber.me/nerfactory-private/",
"version": "0.0.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^14.2.0",
"ccapture.js": "github:aceslowman/ccapture.js#npm-fix",
"dat.gui": "^0.7.9",
"leva": "^0.9.29",
"msgpack-lite": "^0.1.26",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-scripts": "^5.0.1",
"socket.io-client": "^4.5.1",
"three": "^0.142.0",
"three-wtm": "^1.0",
"websocket": "^1.0.34",
"wwobjloader2": "^4.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"electron": "electron ."
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"main": "public/electron.js",
"author": "",
"license": "ISC",
"description": "",
"devDependencies": {
"concurrently": "^7.2.1",
"electron": "^19.0.4",
"electron-is-dev": "^2.0.0",
"typescript": "^4.7.3",
"wait-on": "^6.0.1"
}
}
+47
View File
@@ -0,0 +1,47 @@
const path = require("path");
const { app, BrowserWindow } = require("electron");
const isDev = require("electron-is-dev");
function createWindow() {
// Create the browser window.
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
},
});
// and load the index.html of the app.
// win.loadFile("index.html");
win.loadURL(
isDev
? "http://localhost:3000"
: `file://${path.join(__dirname, "../build/index.html")}`
);
// Open the DevTools.
if (isDev) {
win.webContents.openDevTools({ mode: "detach" });
}
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(createWindow);
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

+44
View File
@@ -0,0 +1,44 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>nerfactory Viewer</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

@@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
+3
View File
@@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

@@ -0,0 +1,282 @@
import * as THREE from "three";
import { OBJLoader } from "three/examples/jsm/loaders/OBJLoader.js";
import { ColladaLoader } from "three/examples/jsm/loaders/ColladaLoader.js";
import { MTLLoader } from "three/examples/jsm/loaders/MTLLoader.js";
import { MtlObjBridge } from "wwobjloader2";
import { STLLoader } from "three/examples/jsm/loaders/STLLoader.js";
import { PLYLoader } from "three/examples/jsm/loaders/PLYLoader.js";
import * as BufferGeometryUtils from "three/examples/jsm/utils/BufferGeometryUtils.js";
// Merges a hierarchy of collada mesh geometries into a single
// `BufferGeometry` object:
// * A new merged `BufferGeometry` if the input contains meshes
// * empty `BufferGeometry` otherwise
function merge_geometries(object, preserve_materials = false) {
let materials = [];
let geometries = [];
let root_transform = object.matrix.clone();
function collectGeometries(node, parent_transform) {
let transform = parent_transform.clone().multiply(node.matrix);
if (node.type === "Mesh") {
node.geometry.applyMatrix(transform);
geometries.push(node.geometry);
materials.push(node.material);
}
for (let child of node.children) {
collectGeometries(child, transform);
}
}
collectGeometries(object, root_transform);
let result = null;
if (geometries.length === 1) {
result = geometries[0];
if (preserve_materials) {
result.material = materials[0];
}
} else if (geometries.length > 1) {
result = BufferGeometryUtils.mergeBufferGeometries(geometries, true);
if (preserve_materials) {
result.material = materials;
}
} else {
result = new THREE.BufferGeometry();
}
return result;
}
// Handler for special texture types that we want to support
// in addition to whatever three.js supports. This function
// takes a json object representing a single texture, and should
// return either:
// * A new `THREE.Texture` if that json represents a special texture
// * `null` otherwise
function handle_special_texture(json) {
if (json.type === "_text") {
let canvas = document.createElement("canvas");
// canvas width and height should be in the power of 2; otherwise although
// the page usually loads successfully, WebGL does complain/warn
canvas.width = 256;
canvas.height = 256;
let ctx = canvas.getContext("2d");
ctx.textAlign = "center";
let font_size = json.font_size;
// auto-resing the font_size to fit in the canvas
ctx.font = font_size + "px " + json.font_face;
while (ctx.measureText(json.text).width > canvas.width) {
font_size--;
ctx.font = font_size + "px " + json.font_face;
}
ctx.fillText(json.text, canvas.width / 2, canvas.height / 2);
let canvas_texture = new THREE.CanvasTexture(canvas);
canvas_texture.uuid = json.uuid;
return canvas_texture;
} else {
return null;
}
}
// Handler for special geometry types that we want to support
// in addition to whatever three.js supports. This function
// takes a json object representing a single geometry, and should
// return either:
// * A new `THREE.Mesh` if that json represents a special geometry
// * `null` otherwise
function handle_special_geometry(geom) {
if (geom.type === "_meshfile") {
console.warn(
"_meshfile is deprecated. Please use _meshfile_geometry for geometries and _meshfile_object for objects with geometry and material"
);
geom.type = "_meshfile_geometry";
}
if (geom.type === "_meshfile_geometry") {
if (geom.format === "obj") {
let loader = new OBJLoader();
let obj = loader.parse(geom.data + "\n");
let loaded_geom = merge_geometries(obj);
loaded_geom.uuid = geom.uuid;
return loaded_geom;
} else if (geom.format === "dae") {
let loader = new ColladaLoader();
let obj = loader.parse(geom.data);
let result = merge_geometries(obj.scene);
result.uuid = geom.uuid;
return result;
} else if (geom.format === "stl") {
let loader = new STLLoader();
let loaded_geom = loader.parse(geom.data.buffer);
loaded_geom.uuid = geom.uuid;
return loaded_geom;
} else if (geom.format === "ply") {
let loader = new PLYLoader();
let loaded_geom = loader.parse(geom.data.buffer);
loaded_geom.uuid = geom.uuid;
return loaded_geom;
} else {
console.error("Unsupported mesh type:", geom);
return null;
}
}
return null;
}
// The ExtensibleObjectLoader extends the THREE.ObjectLoader
// interface, while providing some hooks for us to perform some
// custom loading for things other than three.js native JSON.
//
// We currently use this class to support some extensions to
// three.js JSON for objects which are easy to construct in
// javascript but hard to construct in Python and/or Julia.
// For example, we perform the following transformations:
//
// * Converting "_meshfile" geometries into actual meshes
// using the THREE.js native mesh loaders
// * Converting "_text" textures into text by drawing the
// requested text onto a canvas.
export class ExtensibleObjectLoader extends THREE.ObjectLoader {
delegate(special_handler, base_handler, json, additional_objects) {
let result = {};
if (json === undefined) {
return result;
}
let remaining_json = [];
for (let data of json) {
let x = special_handler(data);
if (x !== null) {
result[x.uuid] = x;
} else {
remaining_json.push(data);
}
}
return Object.assign(
result,
base_handler(remaining_json, additional_objects)
);
}
parseTextures(json, images) {
return this.delegate(
handle_special_texture,
super.parseTextures,
json,
images
);
}
parseGeometries(json, shapes) {
return this.delegate(
handle_special_geometry,
super.parseGeometries,
json,
shapes
);
}
parseObject(json, geometries, materials) {
if (json.type === "_meshfile_object") {
let geometry;
let material;
let manager = new THREE.LoadingManager();
let path =
json.url === undefined
? undefined
: THREE.LoaderUtils.extractUrlBase(json.url);
manager.setURLModifier((url) => {
if (json.resources[url] !== undefined) {
return json.resources[url];
}
return url;
});
if (json.format === "obj") {
let loader = new OBJLoader(manager);
if (json.mtl_library) {
let mtl_loader = new MTLLoader(manager);
let mtl_parse_result = mtl_loader.parse(json.mtl_library + "\n", "");
let materials =
MtlObjBridge.addMaterialsFromMtlLoader(mtl_parse_result);
loader.setMaterials(materials);
this.onTextureLoad();
}
let obj = loader.parse(json.data + "\n", path);
geometry = merge_geometries(obj, true);
geometry.uuid = json.uuid;
material = geometry.material;
} else if (json.format === "dae") {
let loader = new ColladaLoader(manager);
loader.onTextureLoad = this.onTextureLoad;
let obj = loader.parse(json.data, path);
geometry = merge_geometries(obj.scene, true);
geometry.uuid = json.uuid;
material = geometry.material;
} else if (json.format === "stl") {
let loader = new STLLoader();
geometry = loader.parse(json.data.buffer, path);
geometry.uuid = json.uuid;
material = geometry.material;
} else {
console.error("Unsupported mesh type:", json);
return null;
}
let object = new THREE.Mesh(geometry, material);
// Copied from ObjectLoader
object.uuid = json.uuid;
if (json.name !== undefined) object.name = json.name;
if (json.matrix !== undefined) {
object.matrix.fromArray(json.matrix);
if (json.matrixAutoUpdate !== undefined)
object.matrixAutoUpdate = json.matrixAutoUpdate;
if (object.matrixAutoUpdate)
object.matrix.decompose(
object.position,
object.quaternion,
object.scale
);
} else {
if (json.position !== undefined)
object.position.fromArray(json.position);
if (json.rotation !== undefined)
object.rotation.fromArray(json.rotation);
if (json.quaternion !== undefined)
object.quaternion.fromArray(json.quaternion);
if (json.scale !== undefined) object.scale.fromArray(json.scale);
}
if (json.castShadow !== undefined) object.castShadow = json.castShadow;
if (json.receiveShadow !== undefined)
object.receiveShadow = json.receiveShadow;
if (json.shadow) {
if (json.shadow.bias !== undefined)
object.shadow.bias = json.shadow.bias;
if (json.shadow.radius !== undefined)
object.shadow.radius = json.shadow.radius;
if (json.shadow.mapSize !== undefined)
object.shadow.mapSize.fromArray(json.shadow.mapSize);
if (json.shadow.camera !== undefined)
object.shadow.camera = this.parseObject(json.shadow.camera);
}
if (json.visible !== undefined) object.visible = json.visible;
if (json.frustumCulled !== undefined)
object.frustumCulled = json.frustumCulled;
if (json.renderOrder !== undefined) object.renderOrder = json.renderOrder;
if (json.userjson !== undefined) object.userjson = json.userData;
if (json.layers !== undefined) object.layers.mask = json.layers;
return object;
} else if (json.type === "CameraHelper") {
console.log("processing CameraHelper");
console.log(json);
console.log(geometries);
console.log(materials);
return super.parseObject(json, geometries, materials);
} else {
return super.parseObject(json, geometries, materials);
}
}
}
+144
View File
@@ -0,0 +1,144 @@
import * as THREE from "three";
const dat = require("dat.gui");
function remove_folders(gui) {
for (let name of Object.keys(gui.__folders)) {
let folder = gui.__folders[name];
remove_folders(folder);
dat.dom.dom.unbind(window, "resize", folder.__resizeHandler);
gui.removeFolder(folder);
}
}
function dispose(object) {
if (!object) {
return;
}
if (object.geometry) {
object.geometry.dispose();
}
if (object.material) {
if (Array.isArray(object.material)) {
for (let material of object.material) {
if (material.map) {
material.map.dispose();
}
material.dispose();
}
} else {
if (object.material.map) {
object.material.map.dispose();
}
object.material.dispose();
}
}
}
export class SceneNode {
constructor(object, folder) {
this.object = object;
this.folder = folder;
this.children = {};
this.create_controls();
for (let c of this.object.children) {
this.add_child(c);
}
}
add_child(object) {
let f = this.folder.addFolder(object.name);
let node = new SceneNode(object, f);
this.children[object.name] = node;
return node;
}
create_child(name) {
let obj = new THREE.Group();
obj.name = name;
this.object.add(obj);
return this.add_child(obj);
}
find(path) {
if (path.length == 0) {
return this;
} else {
let name = path[0];
let child = this.children[name];
if (child === undefined) {
child = this.create_child(name);
}
return child.find(path.slice(1));
}
}
create_controls() {
if (this.vis_controller !== undefined) {
this.folder.domElement.removeChild(this.vis_controller.domElement);
}
this.vis_controller = new dat.controllers.BooleanController(
this.object,
"visible"
);
this.folder.domElement.prepend(this.vis_controller.domElement);
this.vis_controller.domElement.style.height = "0";
this.vis_controller.domElement.style.float = "right";
}
set_property(property, value) {
if (property === "position") {
this.object.position.set(value[0], value[1], value[2]);
} else if (property === "quaternion") {
this.object.quaternion.set(value[0], value[1], value[2], value[3]);
} else if (property === "scale") {
this.object.scale.set(value[0], value[1], value[2]);
} else {
this.object[property] = value;
}
this.vis_controller.updateDisplay();
}
set_transform(matrix) {
let mat = new THREE.Matrix4();
mat.fromArray(matrix);
mat.decompose(
this.object.position,
this.object.quaternion,
this.object.scale
);
}
set_object(object) {
let parent = this.object.parent;
this.dispose_recursive();
this.object.parent.remove(this.object);
this.object = object;
parent.add(object);
this.create_controls();
}
dispose_recursive() {
for (let name of Object.keys(this.children)) {
this.children[name].dispose_recursive();
}
dispose(this.object);
}
delete(path) {
if (path.length == 0) {
console.error("Can't delete an empty path");
} else {
let parent = this.find(path.slice(0, path.length - 1));
let name = path[path.length - 1];
let child = parent.children[name];
if (child !== undefined) {
child.dispose_recursive();
parent.object.remove(child.object);
remove_folders(child.folder);
parent.folder.removeFolder(child.folder);
delete parent.children[name];
}
}
}
}
+461
View File
@@ -0,0 +1,461 @@
import React, { Component } from "react";
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import Stats from "three/examples/jsm/libs/stats.module.js";
import { GUI } from "dat.gui";
import { split_path } from "./utils";
import { SceneNode } from "./SceneNode";
import { ExtensibleObjectLoader } from "./ExtensibleObjectLoader";
function websocket_endpoint_from_url(url) {
let endpoint = url.split("?").pop();
if (endpoint == "") {
let message =
"Please set the websocket endpoint. E.g., a correct URL may be: http://localhost:4000?localhost:8051";
window.alert(message);
return null;
}
return endpoint;
}
function findCameraObjectUnderObject3D(object) {
// seach the tree for the camera
if (object instanceof THREE.Camera) {
return object;
}
for (let name of Object.keys(object.children)) {
return findCameraObjectUnderObject3D(object.children[name]);
}
return null;
}
var msgpack = require("msgpack-lite");
export class ViewerState extends Component {
constructor(props) {
super(props);
this.state = {
scene: null,
controls: null,
renderer: null,
gui: null,
scene_tree: null,
viewport_width: null,
viewport_height: null,
};
this.update = this.update.bind(this);
this.set_object = this.set_object.bind(this);
this.handle_command = this.handle_command.bind(this);
this.threejs_ref = React.createRef();
this.props = props;
}
handleResize() {
this.state.viewport_width = this.getViewportWidth();
this.state.viewport_height = this.getViewportHeight();
this.state.camera_main.aspect =
this.state.viewport_width / this.state.viewport_height;
this.state.camera_main.updateProjectionMatrix();
this.state.renderer_main.setSize(
this.state.viewport_width,
this.state.viewport_height
);
}
update() {
requestAnimationFrame(this.update);
this.handleResize();
let camera_main = findCameraObjectUnderObject3D(
this.state.scene_tree.find(["Cameras", "Main Camera"]).object
);
camera_main.updateProjectionMatrix();
if (this.state.controls_main != null) {
this.state.controls_main.update();
}
this.state.renderer_main.render(this.state.scene, camera_main);
this.send_camera_over_websocket();
}
send_camera_over_websocket() {
/* update the camera information in the python server
if the websocket is connected */
// console.log("send_camera_over_websocket");
if (this.state.websocket.readyState === WebSocket.OPEN) {
// update the camera information in the python server
let camera_main = findCameraObjectUnderObject3D(
this.state.scene_tree.find(["Cameras", "Main Camera"]).object
);
// console.log(camera_main.toJSON());
let cmd = "set_object";
let path = "Cameras/Main Camera";
let data = {
type: cmd,
path: path,
object: camera_main.toJSON(),
};
let message = msgpack.encode(data);
this.state.websocket.send(message);
}
}
send_training_state_over_websocket(value) {
if (this.state.websocket.readyState === WebSocket.OPEN) {
let cmd = "set_training_state";
let path = "Training State";
let data = {
type: cmd,
path: path,
training_state: value,
};
let message = msgpack.encode(data);
this.state.websocket.send(message);
}
}
send_output_type_over_websocket(value) {
/* update the output option in the python server
if the user changes selection */
if (this.state.websocket.readyState === WebSocket.OPEN) {
let cmd = "set_output_type";
let path = "Output Type";
let data = {
type: cmd,
path: path,
output_type: value,
};
let message = msgpack.encode(data);
this.state.websocket.send(message);
}
}
send_min_resolution_over_websocket(value) {
if (this.state.websocket.readyState === WebSocket.OPEN) {
let cmd = "set_min_resolution";
let path = "Min Resolution";
let data = {
type: cmd,
path: path,
min_resolution: value,
};
let message = msgpack.encode(data);
this.state.websocket.send(message);
}
}
send_max_resolution_over_websocket(value) {
if (this.state.websocket.readyState === WebSocket.OPEN) {
let cmd = "set_max_resolution";
let path = "Max Resolution";
let data = {
type: cmd,
path: path,
max_resolution: value,
};
let message = msgpack.encode(data);
this.state.websocket.send(message);
}
}
set_object(path, object) {
if (!(object instanceof THREE.Camera)) {
this.state.scene_tree.find(path.concat(["<object>"])).set_object(object);
}
}
set_object_from_json(path, object_json) {
let loader = new ExtensibleObjectLoader();
loader.parse(object_json, (obj) => {
if (
obj.geometry !== undefined &&
obj.geometry.type === "BufferGeometry"
) {
if (
obj.geometry.attributes.normal === undefined ||
obj.geometry.attributes.normal.count === 0
) {
obj.geometry.computeVertexNormals();
}
}
obj.castShadow = true;
obj.receiveShadow = true;
this.set_object(path, obj);
});
}
set_transform(path, matrix) {
this.state.scene_tree.find(path).set_transform(matrix);
}
delete_path(path) {
if (path.length === 0) {
console.error("Deleting the entire scene is not implemented.");
} else {
this.state.scene_tree.delete(path);
}
}
set_property(path, property, value) {
this.state.scene_tree.find(path).set_property(property, value);
// TODO(ethan): handle this issue
if (path[0] === "Background") {
// The background is not an Object3d, so needs a little help.
this.state.scene_tree.find(path).on_update();
}
}
handle_command(cmd) {
// convert binary serialization format back to JSON
cmd = msgpack.decode(new Uint8Array(cmd));
// console.log(cmd);
// three js scene commands
if (cmd.type === "set_object") {
let path = split_path(cmd.path);
this.set_object_from_json(path, cmd.object);
} else if (cmd.type === "set_transform") {
let path = split_path(cmd.path);
this.set_transform(path, cmd.matrix);
} else if (cmd.type === "delete") {
let path = split_path(cmd.path);
this.delete_path(path);
} else if (cmd.type === "set_property") {
let path = split_path(cmd.path);
this.set_property(path, cmd.property, cmd.value);
} else if (cmd.type == "set_output_options") {
this.props.setOutputOptions(cmd.output_options);
this.props.setControls({ output_options: 1 });
}
// web rtc commands
else if (cmd.type === "answer") {
let answer = cmd.data;
this.state.pc.setRemoteDescription(answer);
}
// possibly update the camera information in the python server
// this.send_camera_over_websocket();
}
getViewportWidth() {
return window.innerWidth - (window.innerWidth % 2);
}
getViewportHeight() {
return window.innerHeight;
}
setupWebRTC() {
console.log("setting up WebRTC");
// The iceServers config comes from the following URL:
// https://www.metered.ca/tools/openrelay/
this.state.pc = new RTCPeerConnection({
iceServers: [
{
urls: "stun:openrelay.metered.ca:80",
},
{
urls: "turn:openrelay.metered.ca:80",
username: "openrelayproject",
credential: "openrelayproject",
},
{
urls: "turn:openrelay.metered.ca:443",
username: "openrelayproject",
credential: "openrelayproject",
},
{
urls: "turn:openrelay.metered.ca:443?transport=tcp",
username: "openrelayproject",
credential: "openrelayproject",
},
],
});
// connect video
this.state.pc.addEventListener("track", function (evt) {
if (evt.track.kind == "video") {
console.log("setting event stream");
document.getElementById("WebRTCVideo-video").srcObject = evt.streams[0];
}
});
this.state.pc.addTransceiver("video", { direction: "recvonly" });
this.state.pc
.createOffer()
.then((offer) => {
return this.state.pc.setLocalDescription(offer);
})
.then(() => {
// wait for ICE gathering to complete
return new Promise((resolve) => {
if (this.state.pc.iceGatheringState === "complete") {
resolve();
} else {
var checkState = () => {
if (this.state.pc.iceGatheringState === "complete") {
this.state.pc.removeEventListener(
"icegatheringstatechange",
checkState
);
resolve();
}
};
this.state.pc.addEventListener(
"icegatheringstatechange",
checkState
);
}
});
})
.then(() => {
var offer = this.state.pc.localDescription;
console.log("sending the offer");
let cmd = "offer";
let path = "";
let data = {
type: cmd,
path: path,
data: {
sdp: offer.sdp,
type: offer.type,
},
};
let message = msgpack.encode(data);
this.state.websocket.send(message);
});
}
componentDidMount() {
// Open the websocket
let endpoint = websocket_endpoint_from_url(window.location.href);
this.state.websocket = new WebSocket("ws://" + endpoint + "/");
this.state.websocket.onopen = () => {
console.log("websocket connected");
this.setupWebRTC();
};
this.state.websocket.binaryType = "arraybuffer";
// 'command' for updates to Viewer
this.state.websocket.onmessage = (cmd) => this.handle_command(cmd.data);
this.state.websocket.onclose = function (evt) {
console.log("onclose:", evt);
};
// Get size of screen
this.state.viewport_width = this.getViewportWidth();
this.state.viewport_height = this.getViewportHeight();
// Scene
this.state.scene = new THREE.Scene();
// GUI
this.state.gui = new GUI();
let scene_folder = this.state.gui.addFolder("Scene");
scene_folder.open();
this.state.scene_tree = new SceneNode(this.state.scene, scene_folder);
// Renderer main
this.state.renderer_main = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
});
this.state.renderer_main.setPixelRatio(window.devicePixelRatio);
this.state.renderer_main.setSize(
this.state.viewport_width,
this.state.viewport_height
);
this.state.renderer_main.domElement.style.border = "1px solid black";
let domElement = document.getElementById("canvas-container-main");
domElement.append(this.state.renderer_main.domElement);
// Camera main
this.state.camera_main = new THREE.PerspectiveCamera(
120,
this.state.viewport_width / this.state.viewport_height,
0.01,
100
);
this.state.camera_main.position.x = 5;
this.state.camera_main.position.y = -5;
this.state.camera_main.position.z = 5;
this.state.camera_main.up = new THREE.Vector3(0, 0, 1);
this.state.controls_main = new OrbitControls(
this.state.camera_main,
this.state.renderer_main.domElement
);
this.state.controls_main.rotateSpeed = 2.0;
this.state.controls_main.zoomSpeed = 0.3;
this.state.controls_main.panSpeed = 0.2;
this.state.controls_main.target.set(0, 0, 0); // focus point of the controls
this.state.controls_main.autoRotate = false;
this.state.controls_main.enableDamping = true;
this.state.controls_main.dampingFactor = 1.0;
this.state.controls_main.update();
let path = ["Cameras", "Main Camera"];
this.state.scene_tree
.find(path.concat(["<object>"]))
.set_object(this.state.camera_main);
// Axes display
let axes = new THREE.AxesHelper(5);
this.set_object(["Axes"], axes);
// Grid
let grid = new THREE.GridHelper(20, 20);
grid.rotateX(Math.PI / 2); // now on xy plane
this.set_object(["Grid"], grid);
// Lights
let color = 0xffffff;
let intensity = 1;
let light = new THREE.AmbientLight(color, intensity);
this.set_object(["Light"], light);
// Stats
var stats = new Stats();
let domElement_stats = document.getElementById("canvas-container-main");
domElement_stats.append(stats.dom);
this.update();
}
componentDidUpdate(prevProps, prevState) {
// Pause training
if (prevProps.paused !== this.props.paused) {
this.send_training_state_over_websocket(this.props.paused);
}
// Choose render type
if (prevProps.output_options !== this.props.output_options) {
console.log(this.props.output_options);
this.send_output_type_over_websocket(this.props.output_options);
}
// Set minimum render resolution
if (prevProps.min_resolution !== this.props.min_resolution) {
this.send_min_resolution_over_websocket(
this.props.min_resolution.slice(0, -2)
);
}
// Set maximum render resolution
if (prevProps.max_resolution !== this.props.max_resolution) {
this.send_max_resolution_over_websocket(
this.props.max_resolution.slice(0, -2)
);
}
}
render() {
return (
<div>
<div className="WebRTCVideo">
<video id="WebRTCVideo-video" autoPlay playsInline muted></video>
</div>
<div id="canvas-container-main"> </div>
<div id="stats-container"> </div>
</div>
);
}
}
+68
View File
@@ -0,0 +1,68 @@
import React from "react";
import { Leva, button, buttonGroup, useControls } from "leva";
export function PanelConfig() {
let params = { titleBar: false };
let panel = (
<div style={{ position: "relative", width: 250, top: 60 }}>
<Leva fill oneLineLabels {...params} />
</div>
);
return panel;
}
export function RenderControls() {
const [outputOptions, setOutputOptions] = React.useState([]);
const [paused, setPaused] = React.useState(false);
const toggle = () => {
setPaused((current) => !current);
};
const [controls, setControls] = useControls(
"Render Options",
() => ({
"Resume Training": button(toggle, {
disabled: !paused,
}),
"Pause Training": button(toggle, {
disabled: paused,
}),
output_options: {
label: "Output Render",
options: outputOptions,
},
min_resolution: {
label: "Min Res.",
value: 50,
min: 10,
max: 100,
step: 1,
suffix: "px",
},
" ": buttonGroup({
"25px": () => setControls({ min_resolution: 25 }),
"50px": () => setControls({ min_resolution: 50 }),
"75px": () => setControls({ min_resolution: 75 }),
"100px": () => setControls({ min_resolution: 100 }),
}),
max_resolution: {
label: "Max Res.",
min: 10,
max: 2048,
step: 1,
value: 512,
suffix: "px",
},
" ": buttonGroup({
"128px": () => setControls({ max_resolution: 128 }),
"256px": () => setControls({ max_resolution: 256 }),
"512px": () => setControls({ max_resolution: 512 }),
"1024px": () => setControls({ max_resolution: 1024 }),
}),
}),
[outputOptions, paused]
);
return [controls, paused, setControls, setOutputOptions];
}
+43
View File
@@ -0,0 +1,43 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
monospace;
}
.BackgroundDiv,
.WebRTCVideo {
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
}
#BackgroundDiv-video,
#WebRTCVideo-video {
width: 100%;
height: 100%;
object-fit: fill;
}
#canvas-container-main {
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
}
#canvas-container-main canvas {
position: relative;
height: 100%;
width: 100%;
}
+32
View File
@@ -0,0 +1,32 @@
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import * as serviceWorker from "./serviceWorker";
import { ViewerState } from "./Viewer";
import { PanelConfig, RenderControls } from "./controlPanel";
function App() {
let [controls, paused, setControls, setOutputOptions] = RenderControls();
console.log(controls);
return (
<div>
<ViewerState
{...controls}
paused={paused}
setControls={setControls}
setOutputOptions={setOutputOptions}
/>
<button id="demo">Button 1</button>
<PanelConfig />
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
+7
View File
@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3">
<g fill="#61DAFB">
<path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/>
<circle cx="420.9" cy="296.5" r="45.7"/>
<path d="M520.5 78.1z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

+141
View File
@@ -0,0 +1,141 @@
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === "localhost" ||
// [::1] is the IPv6 localhost address.
window.location.hostname === "[::1]" ||
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === "production" && "serviceWorker" in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener("load", () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
"This web app is being served cache-first by a service " +
"worker. To learn more, visit https://bit.ly/CRA-PWA"
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then((registration) => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === "installed") {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
"New content is available and will be used when all " +
"tabs for this page are closed. See https://bit.ly/CRA-PWA."
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log("Content is cached for offline use.");
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch((error) => {
console.error("Error during service worker registration:", error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: { "Service-Worker": "script" },
})
.then((response) => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get("content-type");
if (
response.status === 404 ||
(contentType != null && contentType.indexOf("javascript") === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then((registration) => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
"No internet connection found. App is running in offline mode."
);
});
}
export function unregister() {
if ("serviceWorker" in navigator) {
navigator.serviceWorker.ready
.then((registration) => {
registration.unregister();
})
.catch((error) => {
console.error(error.message);
});
}
}
+5
View File
@@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import "@testing-library/jest-dom/extend-expect";
+3
View File
@@ -0,0 +1,3 @@
export function split_path(path_str) {
return path_str.split("/").filter((x) => x.length > 0);
}
File diff suppressed because it is too large. Load diff
+13
View File
@@ -0,0 +1,13 @@
# 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.
+136
View File
@@ -0,0 +1,136 @@
# 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
+143
View File
@@ -0,0 +1,143 @@
# 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}
+929
View File
@@ -0,0 +1,929 @@
# 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.
"""
from __future__ import absolute_import, division, print_function
import base64
import sys
import uuid
from typing import Any, BinaryIO, Dict, Iterable, List, Optional, Tuple
import numpy as np
import umsgpack
if sys.version_info >= (3, 0):
UNICODE = str
from io import BytesIO, StringIO
else:
from StringIO import StringIO
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(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, 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(PerspectiveCamera, self).__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 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(f"Stream must be instance of StringIO or BytesIO, not {type(stream)}")
else:
data = stream.read()
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, "r", 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, "r", 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 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(f"Stream must be instance of StringIO or BytesIO, not {type(f)}")
else:
arr = np.frombuffer(f.read(), dtype=np.uint8)
_, extcode = threejs_type(np.uint8)
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 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(f"Stream must be instance of StringIO or BytesIO, not {type(f)}")
else:
arr = np.frombuffer(f.read(), dtype=np.uint8)
_, extcode = threejs_type(np.uint8)
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),
)
+61
View File
@@ -0,0 +1,61 @@
# 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.
"""Path class
"""
from __future__ import absolute_import, division, print_function
import sys
from typing import Tuple
if sys.version_info >= (3, 0):
UNICODE = str
class Path:
"""Path class
Args:
entries: component parts of the path
"""
__slots__ = ["entries"]
def __init__(self, entries: Tuple = tuple()):
self.entries = entries
def append(self, other: str) -> "Path":
"""Methodthat appends a new component and returns new Path
Args:
other: _description_
"""
new_path = self.entries
for element in other.split("/"):
if len(element) == 0:
new_path = tuple()
else:
new_path = new_path + (element,)
return Path(new_path)
def lower(self):
"""Convert path object to serializable format"""
return UNICODE("/" + "/".join(self.entries))
def __hash__(self):
return hash(self.entries)
def __eq__(self, other):
return self.entries == other.entries
+313
View File
@@ -0,0 +1,313 @@
# 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.
"""Server bridge to faciliate interactions between python backend and javascript front end"""
from __future__ import absolute_import, division, print_function
import sys
from typing import Callable, List, Optional
import tornado.gen
import tornado.ioloop
import tornado.web
import tornado.websocket
import msgpack
import msgpack_numpy
import umsgpack
import zmq
import zmq.eventloop.ioloop
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.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:
"""Finds and attempts to connect to a port
Args:
func: function used on connecting to port
default_port: the default port
max_attempts: max number of attempts to try connection. Defaults to MAX_ATTEMPTS.
"""
for i in range(max_attempts):
port = default_port + i
try:
return func(port, **kwargs), port
except (OSError, zmq.error.ZMQError):
print(f"Port: {port:d} in use, trying another...", file=sys.stderr)
except Exception as e:
print(type(e))
raise
raise (
Exception(f"Could not find an available port in the range: [{default_port:d}, {max_attempts + default_port:d})")
)
def force_codec(pc: RTCPeerConnection, sender: RTCRtpSender, forced_codec: str) -> None:
"""Sets the codec preferences on a connection between sender and reciever
Args:
pc: peer connection point
sender: sender that will send to connection point
forced_codec: codec to set
"""
kind = forced_codec.split("/")[0]
codecs = RTCRtpSender.getCapabilities(kind).codecs
transceiver = next(t for t in pc.getTransceivers() if t.sender == sender)
transceiver.setCodecPreferences([codec for codec in codecs if codec.mimeType == forced_codec])
class WebSocketHandler(tornado.websocket.WebSocketHandler): # pylint: disable=abstract-method
"""Tornado websocket handler for receiving and sending commands from/to the viewer."""
def __init__(self, *args, **kwargs):
self.bridge = kwargs.pop("bridge")
super().__init__(*args, **kwargs)
def check_origin(self, origin):
"""This disables CORS."""
return True
def open(self, *args: str, **kwargs: str):
"""open websocket bridge"""
self.bridge.websocket_pool.add(self)
print("opened:", self, file=sys.stderr)
self.bridge.send_scene(self)
async def on_message(self, message: bytearray): # pylint: disable=invalid-overridden-method
"""On reception of message, parses the message and calls the appropriate function based on the type of command
Args:
message: byte message to parse
"""
data = message
m = umsgpack.unpackb(message)
type_ = m["type"]
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
elif type_ == "offer":
offer = RTCSessionDescription(m["data"]["sdp"], m["data"]["type"])
pc = RTCPeerConnection()
self.bridge.pcs.add(pc)
video = SingleFrameStreamTrack()
self.bridge.video_tracks.add(video)
_ = pc.addTrack(video)
# TODO(eventually do something with the codec)
# video_sender = pc.addTrack(video)
# force_codec(pc, video_sender, video_codec)
await pc.setRemoteDescription(offer)
answer = await pc.createAnswer()
await pc.setLocalDescription(answer)
cmd_data = {
"type": "answer",
"path": "",
"data": {"sdp": pc.localDescription.sdp, "type": pc.localDescription.type},
}
data = umsgpack.packb(cmd_data)
self.write_message(data, binary=True)
def on_close(self):
self.bridge.websocket_pool.remove(self)
print("closed:", self, file=sys.stderr)
class ZMQWebSocketBridge:
"""ZMQ web socket bridge class
Args:
zmq_url: zmq url to connect to. Defaults to None.
host: host of server. Defaults to "127.0.0.1".
websocket_port: websocket port to connect to. Defaults to None.
"""
context = zmq.Context()
def __init__(self, zmq_url: Optional[str] = None, host: str = "127.0.0.1", websocket_port: Optional[int] = None):
self.host = host
self.websocket_pool = set()
self.app = self.make_app()
self.ioloop = tornado.ioloop.IOLoop.current()
self.pcs = set()
self.video_tracks = set()
if zmq_url is None:
def f(port):
return self.setup_zmq(f"{DEFAULT_ZMQ_METHOD:s}://{self.host:s}:{port:d}")
(self.zmq_socket, self.zmq_stream, self.zmq_url), _ = find_available_port(f, DEFAULT_ZMQ_PORT)
else:
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):
"""Create a tornado application for the websocket server."""
return tornado.web.Application([(r"/", WebSocketHandler, {"bridge": self})])
def handle_zmq(self, frames: List[bytes]):
"""Switch function that places commands in tree based on websocket command
Args:
frames: the list containing command + object to be placed in tree
"""
cmd = frames[0].decode("utf-8")
print(cmd)
if len(frames) != 3:
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]
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]):
"""Forward a zmq message to all websockets.
Args:
frames: byte messages to be sent over
"""
_, _, data = frames # cmd, path, data
for websocket in self.websocket_pool:
websocket.write_message(data, binary=True)
def setup_zmq(self, url: str):
"""Setup a zmq socket and connect it to the given url.
Args:
url: point of connection
"""
zmq_socket = self.context.socket(zmq.REP) # pylint: disable=no-member
zmq_socket.bind(url)
zmq_stream = ZMQStream(zmq_socket)
zmq_stream.on_recv(self.handle_zmq)
return zmq_socket, zmq_stream, url
def send_scene(self, websocket: WebSocketHandler):
"""Sends entire tree of information over the specified websocket
Args:
websocket: websocket to send information over
"""
for node in walk(self.tree):
if node.object is not None:
websocket.write_message(node.object, binary=True)
for p in node.properties:
websocket.write_message(p, binary=True)
if node.transform is not None:
websocket.write_message(node.transform, binary=True)
def run(self):
"""starts and runs the websocket bridge"""
self.ioloop.start()
def start_server_as_subprocess(zmq_url=None):
"""Starts the ZMQWebSocketBridge server as a subprocess."""
raise NotImplementedError()
@@ -0,0 +1,89 @@
# 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
+63
View File
@@ -0,0 +1,63 @@
# 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.
"""
Functions for traversing server bridge tree nodes (storage)
"""
from __future__ import absolute_import, division, print_function
from collections import defaultdict
from typing import List
class TreeNode(defaultdict):
"""Tree Node object"""
__slots__ = ["object", "transform", "properties", "animation"]
def __init__(self, *args, **kwargs):
super(TreeNode, self).__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
"""
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: TreeNode, path: List[str]) -> TreeNode:
"""Find the node associated with the path
Args:
tree: the root of the tree to start search
path: the path we are searching for
"""
if len(path) == 0:
return tree
else:
return find_node(tree[path[0]], path[1:])
+99
View File
@@ -0,0 +1,99 @@
# 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.
"""Generic utility functions
"""
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
) -> List[List[float]]:
"""Returns list of n elements, constaining a sublist.
Args:
lst: List to be chunked up
num_chunks: number of chunks to split list into
size_of_chunk: size of each chunk
"""
if num_chunks:
assert not size_of_chunk
size = len(lst) // num_chunks
if size_of_chunk:
assert not num_chunks
size = size_of_chunk
chunks = []
for i in range(0, len(lst), size):
chunks.append(lst[i : i + size])
return chunks
def get_intrinsics_matrix_and_camera_to_world_h(
camera_object: Dict[str, Any], image_height: int
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Returns the camera intrinsics matrix and the camera to world homogeneous matrix.
Args:
camera_object: a Camera object.
image_size: the size of the image (height, width)
"""
# intrinsics
fov = camera_object["fov"]
aspect = camera_object["aspect"]
image_width = aspect * image_height
pp_w = image_width / 2.0
pp_h = image_height / 2.0
focal_length = pp_h / np.tan(fov * (np.pi / 180.0) / 2.0)
intrinsics_matrix = torch.tensor([[focal_length, 0, pp_w], [0, focal_length, pp_h], [0, 0, 1]]).float()
# extrinsics
camera_to_world_h = torch.tensor(get_chunks(camera_object["matrix"], size_of_chunk=4)).T.float()
camera_to_world_h = torch.stack(
[
camera_to_world_h[0, :],
camera_to_world_h[2, :],
camera_to_world_h[1, :],
camera_to_world_h[3, :],
],
dim=0,
)
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
+101
View File
@@ -0,0 +1,101 @@
# 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.
"""Video Stream objects for WebRTC"""
import math
import cv2
import numpy as np
from aiortc import VideoStreamTrack
from av import VideoFrame
class FlagVideoStreamTrack(VideoStreamTrack):
"""
A video track that returns an animated flag. For debugging purposes :')
"""
def __init__(self):
super().__init__() # don't forget this!
self.counter = 0
height, width = 480, 640
# generate flag
data_bgr = np.hstack(
[
self._create_rectangle(width=213, height=480, color=(255, 0, 0)), # blue
self._create_rectangle(width=214, height=480, color=(255, 255, 255)), # white
self._create_rectangle(width=213, height=480, color=(0, 0, 255)), # red
]
)
# shrink and center it
M = np.float32([[0.5, 0, width / 4], [0, 0.5, height / 4]])
data_bgr = cv2.warpAffine(data_bgr, M, (width, height))
# compute animation
omega = 2 * math.pi / height
id_x = np.tile(np.array(range(width), dtype=np.float32), (height, 1))
id_y = np.tile(np.array(range(height), dtype=np.float32), (width, 1)).transpose()
self.frames = []
for k in range(30):
phase = 2 * k * math.pi / 30
map_x = id_x + 10 * np.cos(omega * id_x + phase)
map_y = id_y + 10 * np.sin(omega * id_x + phase)
frame = cv2.remap(data_bgr, map_x, map_y, cv2.INTER_LINEAR)
self.frames.append(VideoFrame.from_ndarray(frame, format="bgr24"))
async def recv(self):
pts, time_base = await self.next_timestamp()
frame = self.frames[self.counter % 30]
frame.pts = pts
frame.time_base = time_base
self.counter += 1
return frame
@staticmethod
def _create_rectangle(width, height, color):
data_bgr = np.zeros((height, width, 3), np.uint8)
data_bgr[:, :] = color
return data_bgr
class SingleFrameStreamTrack(VideoStreamTrack):
"""Single Frame stream class: pushes single frames to a stream"""
def __init__(self):
super().__init__()
self.background_frame = np.zeros((480, 640, 3), dtype="uint8") * 255
self.frame = None
self.put_frame(self.background_frame)
def put_frame(self, frame: np.ndarray) -> None:
"""Sets the current viewing frame
Args:
frame: image to be viewed
"""
self.frame = VideoFrame.from_ndarray(frame)
async def recv(self):
"""Async method to grab and wait on frame"""
pts, time_base = await self.next_timestamp()
frame = self.frame
frame.pts = pts
frame.time_base = time_base
return frame
+552
View File
@@ -0,0 +1,552 @@
# 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 logging
import random
import sys
import threading
import time
from typing import Any, Dict, List, Optional
import numpy as np
import torch
from nerfactory.utils.decorators import check_visualizer_enabled, decorate_all
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.rays import RayBundle
from nerfactory.data.image_dataset import ImageDataset
from nerfactory.data.structs import DatasetInputs
from nerfactory.graphs.base import Graph
from nerfactory.utils import profiler
from nerfactory.utils.config import ViewerConfig
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
class IOChangeException(Exception):
"""Basic camera exception to interrupt visualizer"""
class SetTrace:
"""Basic trace function"""
def __init__(self, func):
self.func = func
def __enter__(self):
sys.settrace(self.func)
return self
def __exit__(self, ext_type, exc_value, traceback):
sys.settrace(None)
class RenderThread(threading.Thread):
"""Thread that does all the rendering calls while listening for interrupts
Args:
state: current visualizer state object
graph: current checkpoint of model
camera_ray_bundle: input rays to pass through the graph to render out
"""
def __init__(self, state: "VisualizerState", graph: Graph, camera_ray_bundle: RayBundle):
threading.Thread.__init__(self)
self.state = state
self.graph = graph
self.camera_ray_bundle = camera_ray_bundle
self.exc = None
def run(self):
"""run function that renders out images given the current graph and ray bundles.
Interlaced with a trace function that checks to see if any I/O changes were registered.
Exits and continues program if IOChangeException thrown.
"""
outputs = None
try:
with SetTrace(self.state.check_interrupt):
outputs = self.graph.get_outputs_for_camera_ray_bundle(self.camera_ray_bundle)
except IOChangeException as e:
self.exc = e
if outputs:
self.graph.process_outputs_as_images(outputs)
self.state.check_done_render = True
self.state.check_interrupt_vis = False
def join(self, timeout=None):
threading.Thread.join(self)
if self.exc:
raise self.exc
class CheckThread(threading.Thread):
"""Thread the constantly checks for io changes and sets a flag indicating interrupt
Args:
state: current visualizer state object
"""
def __init__(self, state):
threading.Thread.__init__(self)
self.state = state
def run(self):
"""Run function that checks to see if any of the existing state has changed (e.g. camera pose/output type/resolutions).
Sets the visualizer state flag to true to signal to render thread that an interrupt was registered.
"""
self.state.check_done_render = False
while not self.state.check_done_render:
# check camera
data = self.state.vis["/Cameras/Main Camera"].get_object()
if data is not None:
camera_object = data["object"]["object"]
if self.state.prev_camera_matrix is None or not np.allclose(
camera_object["matrix"], self.state.prev_camera_matrix
):
self.state.check_interrupt_vis = True
return
# check output type
data = self.state.vis["/Output Type"].get_object()
if data 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"])
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"])
if self.state.min_resolution != min_resolution:
self.state.check_interrupt_vis = True
return
@decorate_all([check_visualizer_enabled])
class VisualizerState:
"""Class to hold state for visualizer variables
Args:
config: viewer setup configuration
"""
def __init__(self, config: ViewerConfig):
self.config = config
self.vis = None
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.")
# visualizer specific variables
self.prev_camera_matrix = None
self.prev_output_type = "default"
self.min_resolution = 50
self.max_resolution = 1000
self.res_upscale_factor = 1
self.check_interrupt_vis = False
self.check_done_render = True
self.last_render_time = time.time()
self.min_wait_time = 0.5 # 1.0 is on high side and will cause lag
self.outputs_set = False
def init_scene(self, image_dataset: ImageDataset, dataset_inputs: DatasetInputs) -> None:
"""Draw some images and the scene aabb in the viewer.
Args:
image_dataset: dataset to render in the scene
dataset_inputs: inputs to the image dataset and ray generator
"""
indices = random.sample(range(len(image_dataset)), k=10)
for idx in indices:
image = image_dataset[idx]["image"]
camera = get_camera(dataset_inputs.intrinsics[idx], dataset_inputs.camera_to_world[idx], None)
pose = camera.get_camera_to_world().double().numpy()
K = camera.get_intrinsics_matrix().double().numpy()
draw_camera_frustum(
self.vis,
image=(image.double().numpy() * 255.0),
pose=pose,
K=K,
height=1.0,
name=f"image_dataset/{idx:06d}",
displayed_focal_length=0.5,
realistic=False,
)
aabb = dataset_inputs.scene_bounds.aabb
draw_aabb(self.vis, aabb, name="dataset_inputs_train/scene_bounds/aabb")
# set the main camera intrinsics to one from the dataset
K = camera.get_intrinsics_matrix()
set_persp_intrinsics_matrix(self.vis, K.double().numpy())
def update_scene(self, step: int, graph: Graph) -> None:
"""updates the scene based on the graph weights
Args:
step: iteration step of training
graph: the current checkpoint of the model
"""
data = self.vis["/Training State"].get_object()
if data is None or not data["training_state"]:
# 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"]
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"]
local_step += 1
def check_interrupt(self, frame, event, arg): # pylint: disable=unused-argument
"""Raises interrupt when flag has been set and not already on lowest resolution.
Used in conjunction with SetTrace.
"""
if event == "line":
if self.check_interrupt_vis and self.res_upscale_factor > 1:
self.res_upscale_factor = 1
raise IOChangeException
return self.check_interrupt
def _is_render_step(self, step: int, default_steps: int = 2, max_steps: int = 10) -> bool:
"""dynamically calculate when to render grapic based on resolution of image"""
if step != 0:
if self.res_upscale_factor == 1:
return True
steps_per_render_image = min(default_steps * self.res_upscale_factor, max_steps)
steps_condition = step % steps_per_render_image == 0
if steps_condition:
if self.res_upscale_factor > 3:
if time.time() - self.last_render_time >= self.min_wait_time:
self.last_render_time = time.time()
return True # if higher res, and minimum wait time achieved
return False # if higher res, and minimum wait time NOT achieved
self.last_render_time = time.time()
return True # if not higher res, but steps met
return False # if init
def _send_output_to_viewer(self, outputs: Dict[str, Any]):
"""Chooses the correct output and sends it to the viewer
Args:
outputs: the dictionary of outputs to choose from, from the graph
"""
if not self.outputs_set:
set_output_options(self.vis, list(outputs.keys()))
self.outputs_set = True
# gross hack to get the image key, depending on which keys the graph uses
if 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)
@profiler.time_function
def _render_image_in_viewer(self, graph: Graph) -> None:
"""
Draw an image using the current camera pose from the viewer.
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()
if data is None:
return
camera_object = data["object"]["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)
else:
self.prev_camera_matrix = camera_object["matrix"]
self.res_upscale_factor = 1
# check and perform output type updates
data = self.vis["/Output Type"].get_object()
if data 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"])
data = self.vis["/Min Resolution"].get_object()
if data is not None:
self.min_resolution = int(data["min_resolution"])
image_height = min(
self.min_resolution * self.res_upscale_factor,
self.max_resolution,
)
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, :]
camera_to_world = torch.stack(
[
camera_to_world[0, :],
camera_to_world[2, :],
camera_to_world[1, :],
],
dim=0,
)
intrinsics = get_intrinsics_from_intrinsics_matrix(intrinsics_matrix)
camera = get_camera(intrinsics, camera_to_world)
camera_ray_bundle = camera.get_camera_ray_bundle(device=graph.get_device())
camera_ray_bundle.num_rays_per_chunk = self.config.num_rays_per_chunk
graph.eval()
check_thread = CheckThread(state=self)
render_thread = RenderThread(state=self, graph=graph, camera_ray_bundle=camera_ray_bundle)
check_thread.start()
render_thread.start()
try:
render_thread.join()
check_thread.join()
except Exception: # pylint: disable=broad-except
pass
graph.train()
outputs = graph.vis_outputs
if outputs is not None:
self._send_output_to_viewer(outputs)
def get_default_vis() -> Viewer:
"""Returns the default Visualizer."""
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()))
+172
View File
@@ -0,0 +1,172 @@
# 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 logging
import signal
import sys
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:
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)
self.assert_connected()
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),
]
)
return self.client.recv()
def send_ping(self):
"""Tries to contact the viewer bridge server."""
type_ = "ping"
path = ""
data = umsgpack.packb({"type": type_, "path": path})
self.client.send_multipart(
[
type_.encode("utf-8"),
path.encode("utf-8"),
data,
]
)
return self.client.recv()
def assert_connected(self, timeout_in_sec: int = 5):
"""Check if the connection was established properly within some time.
Args:
timeout_in_sec (int): The maximum time to wait for the connection to be established.
"""
def timeout_handler(signum, frame):
raise Exception(f"Couldn't connect to the viewer Bridge Server in {timeout_in_sec} seconds. Exiting.")
signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(timeout_in_sec)
try:
logging.info("Sending ping to the viewer Bridge Server...")
_ = self.send_ping()
logging.info("Successfully connected.")
signal.alarm(0) # cancel the alarm
except Exception as e:
logging.info(e)
sys.exit()
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.
"""
def __init__(self, zmq_url: str = None, window: 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",))
@staticmethod
def view_into(window: ViewerWindow, path: Path):
"""Returns a new Viewer but keeping the same ViewerWindow."""
vis = Viewer(window=window)
vis.path = path
return vis
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.
Returns:
_type_: _description_
"""
return self.window.send(SetObject(geometry, material, self.path))
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 set_image(self, image):
"""Set the image"""
type_ = "set_image"
path = self.path.lower()
data = msgpack.packb(image, default=msgpack_numpy.encode, use_bin_type=True)
self.window.client.send_multipart(
[
type_.encode("utf-8"),
path.encode("utf-8"),
data,
]
)
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}>"